@foleo/cli 0.1.24 → 0.1.26

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.
package/dist/index.js CHANGED
@@ -99,6 +99,8 @@ export async function runCli(argv, deps = {
99
99
  return await update(rest, commandDeps);
100
100
  if (command === "name")
101
101
  return await nameCommand(rest, commandDeps);
102
+ if (command === "names")
103
+ return await namesCommand(rest, commandDeps);
102
104
  if (command === "unpublish")
103
105
  return await unpublish(rest, commandDeps);
104
106
  if (command === "delete")
@@ -215,12 +217,19 @@ function describeArgvToken(raw) {
215
217
  * centrally, so a command added later cannot silently inherit a plan flag it
216
218
  * does not implement — the failure mode that let `html-update --dry-run`
217
219
  * perform a real update.
220
+ *
221
+ * `name` covers `name attach|set|release` (spec 090 §I5). `names` (the list
222
+ * command) and `name-check` are already read-only and take no `--dry-run` of
223
+ * their own — they stay off this set deliberately, so passing `--dry-run` to
224
+ * either still hits the central refusal below rather than being silently
225
+ * accepted and ignored.
218
226
  */
219
227
  const DRY_RUN_AWARE_COMMANDS = new Set([
220
228
  "publish",
221
229
  "html-publish",
222
230
  "update",
223
231
  "html-update",
232
+ "name",
224
233
  ]);
225
234
  const ARTIFACT_NAME_MIN_LENGTH = 3;
226
235
  const ARTIFACT_NAME_MAX_LENGTH = 63;
@@ -257,9 +266,9 @@ function validateArtifactName(raw) {
257
266
  const NAME_MISSING_MESSAGE = [
258
267
  "Missing --name.",
259
268
  "",
260
- "HTML artifacts get their own subdomain, and the name is permanent — Foleo has",
261
- "no rename. Choose it now, or changing the URL later means republishing under a",
262
- "new id and the old link stops working.",
269
+ "HTML artifacts get their own subdomain, and the name is their address. Choose",
270
+ "it with the human now: renaming later (`foleo name set`) has to decide whether",
271
+ "links already shared keep working.",
263
272
  "",
264
273
  " foleo name-check leadtube --json # free, no quota cost",
265
274
  " foleo publish ./site --accept-hosting-risk --name leadtube --dry-run",
@@ -661,12 +670,47 @@ async function nameCheck(args, deps) {
661
670
  return 1;
662
671
  }
663
672
  const result = await requestJson(deps, `/subdomains/${encodeURIComponent(validated.label)}`, { method: "GET", body: undefined });
664
- const payload = { label: validated.label, status: result.status };
673
+ // Spec 090 O5/D5: a name this account released is `cooldown` and
674
+ // reclaimable, and using it succeeds — so it must not read as unavailable.
675
+ const reclaimable = isReclaimableByCaller(result);
676
+ const payload = {
677
+ label: validated.label,
678
+ status: result.status,
679
+ ...(typeof result.availableAt === "string"
680
+ ? { availableAt: result.availableAt }
681
+ : {}),
682
+ ...(reclaimable ? { reclaimableByCaller: true } : {}),
683
+ };
665
684
  if (parsed.json)
666
685
  deps.stdout(`${JSON.stringify(payload, null, 2)}\n`);
686
+ else if (reclaimable)
687
+ deps.stdout(`cooldown ${payload.label} (released by this account; using it reclaims it)\n`);
667
688
  else
668
689
  deps.stdout(`${payload.status} ${payload.label}\n`);
669
- return payload.status === "available" ? 0 : 1;
690
+ return payload.status === "available" || reclaimable ? 0 : 1;
691
+ }
692
+ /** Only ever true for the organization that released the name (spec 090 O5). */
693
+ function isReclaimableByCaller(result) {
694
+ return result.status === "cooldown" && result.reclaimableByCaller === true;
695
+ }
696
+ /**
697
+ * Shared by `publish --dry-run` and `name attach|set --dry-run`: a `taken` or
698
+ * `reserved` label is a failure, not a plan, and both dry runs report it with
699
+ * the same stable error object a real create/attach/rename would fail with —
700
+ * never a buried plan field. `cooldown` (this org's own reclaimable release)
701
+ * and `available` both fall through without throwing.
702
+ */
703
+ function refuseUnavailableName(label, availability, next) {
704
+ if (availability !== "taken" && availability !== "reserved")
705
+ return;
706
+ throw new FoleoError({
707
+ code: availability === "taken" ? "name_taken" : "name_reserved",
708
+ message: `The name "${label}" is ${availability}.`,
709
+ source: "api",
710
+ retryable: false,
711
+ next,
712
+ context: { name: label, availability },
713
+ });
670
714
  }
671
715
  /**
672
716
  * `publish --dry-run` — plan without consuming product quota.
@@ -711,23 +755,16 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
711
755
  let checkedAt = null;
712
756
  let cost = null;
713
757
  let executable = false;
758
+ let reclaimable = false;
714
759
  try {
715
760
  const result = await requestJson(deps, `/subdomains/${encodeURIComponent(derived)}`, { method: "GET", body: undefined });
716
761
  availability = result.status;
762
+ reclaimable = isReclaimableByCaller(result);
717
763
  checkedAt = new Date((deps.now ?? Date.now)()).toISOString();
718
- if (availability === "taken" || availability === "reserved") {
719
- // Spec 089 L859: an unavailable name is a failure, not a plan — it gets
720
- // the same stable error object a real create would fail with, not a
721
- // buried `plan.name.availability` field an agent has to know to check.
722
- throw new FoleoError({
723
- code: availability === "taken" ? "name_taken" : "name_reserved",
724
- message: `The name "${derived}" is ${availability}.`,
725
- source: "api",
726
- retryable: false,
727
- next: "Choose a different --name and check it first: foleo name-check <label> --json",
728
- context: { name: derived, availability },
729
- });
730
- }
764
+ // Spec 089 L859: an unavailable name is a failure, not a plan — it gets
765
+ // the same stable error object a real create would fail with, not a
766
+ // buried `plan.name.availability` field an agent has to know to check.
767
+ refuseUnavailableName(derived, availability, "Choose a different --name and check it first: foleo name-check <label> --json");
731
768
  const usage = await requestJson(deps, "/usage", {
732
769
  method: "GET",
733
770
  body: undefined,
@@ -750,7 +787,9 @@ async function htmlPublishDryRun(root, name, parsed, deps) {
750
787
  context: { htmlArtifacts: htmlAccess },
751
788
  });
752
789
  }
753
- executable = availability === "available";
790
+ // A create reclaims this account's own released name in place, so a
791
+ // reclaimable cooldown is as executable as an available name.
792
+ executable = availability === "available" || reclaimable;
754
793
  }
755
794
  catch (error) {
756
795
  // Only a missing credential may degrade to a bundle-only plan (D2). An
@@ -2017,42 +2056,395 @@ async function unpublish(args, deps) {
2017
2056
  * the server's guarded revision bump still rejects anything that changed in
2018
2057
  * between. Pass `--revision` explicitly to pin a specific known state.
2019
2058
  */
2059
+ const NAME_USAGE = [
2060
+ "Usage:",
2061
+ " foleo name attach <id> <label> [--revision <etag>] [--dry-run] [--json]",
2062
+ " foleo name set <id> <label> --previous keep-as-alias|release [--revision <etag>] [--dry-run] [--json]",
2063
+ " foleo name release <id> <label> --acknowledge-link-breakage [--revision <etag>] [--dry-run] [--json]",
2064
+ ].join("\n");
2065
+ /**
2066
+ * Spec 090 — `foleo name attach|set|release`. Each is an explicit operation
2067
+ * (ADR 0033): a name is never changed as a side effect of `settings`.
2068
+ */
2020
2069
  async function nameCommand(args, deps) {
2021
2070
  const sub = args[0];
2022
- if (sub !== "attach") {
2023
- throw new UsageError("Usage: foleo name attach <id> <label> [--revision <etag>] [--json]");
2024
- }
2025
2071
  const parsed = parseFlags(args.slice(1));
2026
2072
  const [id, rawLabel] = parsed.positionals;
2027
- if (!id || !rawLabel || parsed.positionals.length !== 2) {
2028
- throw new UsageError("Usage: foleo name attach <id> <label> [--revision <etag>] [--json]");
2073
+ if ((sub !== "attach" && sub !== "set" && sub !== "release") ||
2074
+ !id ||
2075
+ !rawLabel ||
2076
+ parsed.positionals.length !== 2) {
2077
+ throw new UsageError(NAME_USAGE);
2029
2078
  }
2030
2079
  const label = requireArtifactName(rawLabel);
2031
- let revision = artifactRevision(parsed.revision);
2032
- if (revision === null) {
2033
- if (parsed.revision !== undefined) {
2034
- throw new UsageError("--revision must be an opaque artifact ETag, e.g. --revision '\"artifact:...\"'.", "revision_invalid");
2035
- }
2036
- const current = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, { method: "GET", body: undefined });
2037
- const etag = typeof current.etag === "string"
2038
- ? current.etag
2039
- : typeof current.artifact
2040
- ?.etag === "string"
2041
- ? current.artifact.etag
2042
- : null;
2043
- if (etag === null) {
2044
- throw new LocalError("revision_unavailable", "Could not read the artifact's current revision.", { next: "Run `foleo get <id> --json` and pass --revision explicitly." });
2045
- }
2046
- revision = etag;
2047
- }
2048
- const result = await withRateLimitRetry(deps, "attaching the name", () => requestJson(deps, `/artifacts/${encodeURIComponent(id)}/name`, {
2049
- method: "POST",
2050
- body: { name: label },
2051
- headers: artifactMutationHeaders(revision, randomUUID()),
2080
+ if (sub === "set") {
2081
+ // No default, locally as on the server: which links keep working is the
2082
+ // human's decision, and an agent must not guess it.
2083
+ if (parsed.previous !== "keep-as-alias" && parsed.previous !== "release") {
2084
+ throw new UsageError("`foleo name set` needs --previous keep-as-alias (the old URL keeps working) or --previous release (the old URL stops working). There is no default; ask the human which.", "previous_label_required");
2085
+ }
2086
+ }
2087
+ if (sub === "release" && !parsed.acknowledgeLinkBreakage) {
2088
+ throw new UsageError(`Releasing ${label} stops its URL working immediately. Re-run with --acknowledge-link-breakage once the human has agreed.`, "acknowledgement_required");
2089
+ }
2090
+ if (parsed.dryRun) {
2091
+ return nameDryRun(sub, id, label, parsed, deps);
2092
+ }
2093
+ const snapshot = await resolveArtifactSnapshot(parsed.revision, id, deps);
2094
+ const revision = snapshot.etag;
2095
+ // One key for the whole command, so a rate-limit retry replays rather than
2096
+ // re-issuing the mutation under a fresh identity.
2097
+ const idempotencyKey = randomUUID();
2098
+ const encodedId = encodeURIComponent(id);
2099
+ const request = sub === "attach"
2100
+ ? {
2101
+ activity: "attaching the name",
2102
+ path: `/artifacts/${encodedId}/name`,
2103
+ method: "POST",
2104
+ body: { name: label },
2105
+ }
2106
+ : sub === "set"
2107
+ ? {
2108
+ activity: "renaming the artifact",
2109
+ path: `/artifacts/${encodedId}/name`,
2110
+ method: "PATCH",
2111
+ // Bind the rename to the address this run actually read, so a
2112
+ // rename made elsewhere in between is refused rather than applied
2113
+ // to an address the caller never saw. With an explicit --revision
2114
+ // the ETag already binds that state.
2115
+ body: {
2116
+ name: label,
2117
+ previousLabel: parsed.previous,
2118
+ ...(typeof snapshot.name === "string"
2119
+ ? { expectedPreviousLabel: snapshot.name }
2120
+ : {}),
2121
+ },
2122
+ }
2123
+ : {
2124
+ activity: "releasing the name",
2125
+ path: `/artifacts/${encodedId}/names/${encodeURIComponent(label)}/release`,
2126
+ method: "POST",
2127
+ body: { acknowledgeLinkBreakage: true },
2128
+ };
2129
+ const result = await withRateLimitRetry(deps, request.activity, () => requestJson(deps, request.path, {
2130
+ method: request.method,
2131
+ body: request.body,
2132
+ headers: artifactMutationHeaders(revision, idempotencyKey),
2052
2133
  }));
2053
2134
  writeResult(deps, result, parsed.json);
2054
2135
  return 0;
2055
2136
  }
2137
+ /** The two dimensions a name-lifecycle `quota_exceeded` can name (spec 090 D10/O8). */
2138
+ const NAME_QUOTA_DIMENSIONS = {
2139
+ claimsPerDay: "publish.subdomain_claims",
2140
+ activeNames: "publish.subdomain_names.active",
2141
+ };
2142
+ function nameHostnameUrl(hostname) {
2143
+ return `https://${hostname}/`;
2144
+ }
2145
+ /** `GET /v1/artifacts/{id}` is `{ artifact: {...} }`; tolerate a flat body too. */
2146
+ function currentArtifactSummary(body) {
2147
+ const record = nestedRecord(body, "artifact") ?? (isRecord(body) ? body : null);
2148
+ return {
2149
+ name: record ? stringField(record, "name") : null,
2150
+ url: record ? stringField(record, "url") : null,
2151
+ };
2152
+ }
2153
+ function nameAlreadySetRefusal(existingName) {
2154
+ return new FoleoError({
2155
+ code: "name_already_set",
2156
+ message: `This artifact already has the name "${existingName}".`,
2157
+ source: "api",
2158
+ retryable: false,
2159
+ next: "`foleo name set` renames it.",
2160
+ context: { name: existingName },
2161
+ });
2162
+ }
2163
+ function nameNotSetRefusal() {
2164
+ return new FoleoError({
2165
+ code: "name_not_set",
2166
+ message: "This artifact has no name yet.",
2167
+ source: "api",
2168
+ retryable: false,
2169
+ next: "`foleo name attach` attaches a first name.",
2170
+ });
2171
+ }
2172
+ function nameUnchangedRefusal(label) {
2173
+ return new FoleoError({
2174
+ code: "name_unchanged",
2175
+ message: `"${label}" is already this artifact's name.`,
2176
+ source: "api",
2177
+ retryable: false,
2178
+ context: { name: label },
2179
+ });
2180
+ }
2181
+ function nameNotFoundRefusal(label) {
2182
+ return new FoleoError({
2183
+ code: "name_not_found",
2184
+ message: `"${label}" is not one of this artifact's active names.`,
2185
+ source: "api",
2186
+ retryable: false,
2187
+ context: { name: label },
2188
+ });
2189
+ }
2190
+ function lastNameReleaseRefusal(label) {
2191
+ return new FoleoError({
2192
+ code: "last_name_release_refused",
2193
+ message: `Releasing "${label}" would leave the artifact with no address; an artifact must keep one.`,
2194
+ source: "api",
2195
+ retryable: false,
2196
+ next: "Rename it with --previous release instead, or unpublish it.",
2197
+ context: { name: label },
2198
+ });
2199
+ }
2200
+ function nameQuotaExceededRefusal(dimension) {
2201
+ const next = dimension === NAME_QUOTA_DIMENSIONS.activeNames
2202
+ ? "This organization holds its maximum number of active names. Rename with --previous release (it does not add a name), or release a name you no longer need; foleo names lists them."
2203
+ : "The daily name-claim limit is used up. It resets at the start of the next UTC day.";
2204
+ return new FoleoError({
2205
+ code: "quota_exceeded",
2206
+ message: "This name operation would exceed the organization's quota.",
2207
+ source: "api",
2208
+ retryable: false,
2209
+ next,
2210
+ context: { dimension },
2211
+ });
2212
+ }
2213
+ /** Predicts the same `quota_exceeded` the batch would raise, before any write. */
2214
+ function checkNameQuota(quota, checks) {
2215
+ if (checks.claims) {
2216
+ const claimsToday = Number(quota.claimsToday ?? 0);
2217
+ const claimsPerDay = Number(quota.claimsPerDay ?? Number.POSITIVE_INFINITY);
2218
+ if (claimsToday + checks.claims > claimsPerDay) {
2219
+ throw nameQuotaExceededRefusal(NAME_QUOTA_DIMENSIONS.claimsPerDay);
2220
+ }
2221
+ }
2222
+ if (checks.active) {
2223
+ const active = Number(quota.active ?? 0);
2224
+ const activeLimit = Number(quota.activeLimit ?? Number.POSITIVE_INFINITY);
2225
+ if (active + checks.active > activeLimit) {
2226
+ throw nameQuotaExceededRefusal(NAME_QUOTA_DIMENSIONS.activeNames);
2227
+ }
2228
+ }
2229
+ }
2230
+ /** `GET /v1/subdomains/{label}`, refusing the same way a real claim would fail. */
2231
+ async function checkLabelAvailability(label, deps) {
2232
+ const availability = await requestJson(deps, `/subdomains/${encodeURIComponent(label)}`, { method: "GET", body: undefined });
2233
+ refuseUnavailableName(label, availability.status, "Choose a different label and check it first: foleo name-check <label> --json");
2234
+ return availability;
2235
+ }
2236
+ /**
2237
+ * `foleo name attach|set|release --dry-run` — plans a name-lifecycle mutation
2238
+ * with GET requests only (spec 090 §I5 — deferred in the original build,
2239
+ * built here). Mirrors `htmlPublishDryRun`'s philosophy: a predicted refusal
2240
+ * fails with the exact stable error object the real command would return,
2241
+ * never a buried plan field, and the plan only ever reads, never writes.
2242
+ */
2243
+ async function nameDryRun(sub, id, label, parsed, deps) {
2244
+ const artifactBody = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, { method: "GET", body: undefined });
2245
+ const current = currentArtifactSummary(artifactBody);
2246
+ const namesBody = await requestJson(deps, `/subdomains?artifactId=${encodeURIComponent(id)}`, {
2247
+ method: "GET",
2248
+ body: undefined,
2249
+ });
2250
+ const activeNames = (namesBody.names ?? []).map((entry) => ({
2251
+ label: String(entry.label),
2252
+ hostname: String(entry.hostname),
2253
+ isPrimary: entry.isPrimary === true,
2254
+ }));
2255
+ const quota = namesBody.quota ?? {};
2256
+ // Active names are every address the artifact has: ADR 0040 Phase 3 retired
2257
+ // generated a-<id> hosts, so there is no other host that could stop working.
2258
+ const beforeHostnames = new Set(activeNames.map((entry) => entry.hostname));
2259
+ let result;
2260
+ let addressesThatStopWorking = [];
2261
+ let promotedAlias = null;
2262
+ let claimsExistingAlias = false;
2263
+ let reclaimsReleasedName = false;
2264
+ let claimsDelta = 0;
2265
+ let activeDelta = 0;
2266
+ if (sub === "attach") {
2267
+ if (current.name !== null)
2268
+ throw nameAlreadySetRefusal(current.name);
2269
+ const availability = await checkLabelAvailability(label, deps);
2270
+ reclaimsReleasedName = isReclaimableByCaller(availability);
2271
+ checkNameQuota(quota, { claims: 1, active: 1 });
2272
+ claimsDelta = 1;
2273
+ activeDelta = 1;
2274
+ result = {
2275
+ primaryName: label,
2276
+ primaryUrl: artifactPreviewUrl(label, deps),
2277
+ };
2278
+ }
2279
+ else if (sub === "release") {
2280
+ const released = activeNames.find((entry) => entry.label === label);
2281
+ if (!released)
2282
+ throw nameNotFoundRefusal(label);
2283
+ if (activeNames.length === 1)
2284
+ throw lastNameReleaseRefusal(label);
2285
+ addressesThatStopWorking = [released.hostname];
2286
+ activeDelta = -1;
2287
+ if (released.isPrimary) {
2288
+ // Same order the server promotes by (D3): `names[]` is already
2289
+ // `claimed_at DESC, id ASC`, so the first survivor is the promotion.
2290
+ const promoted = activeNames.find((entry) => entry.label !== label);
2291
+ promotedAlias = promoted?.label ?? null;
2292
+ result = promoted
2293
+ ? {
2294
+ primaryName: promoted.label,
2295
+ primaryUrl: nameHostnameUrl(promoted.hostname),
2296
+ }
2297
+ : { primaryName: label, primaryUrl: null };
2298
+ }
2299
+ else {
2300
+ const primary = activeNames.find((entry) => entry.isPrimary);
2301
+ result = {
2302
+ primaryName: primary?.label ?? current.name ?? label,
2303
+ primaryUrl: primary ? nameHostnameUrl(primary.hostname) : current.url,
2304
+ };
2305
+ }
2306
+ }
2307
+ else {
2308
+ // sub === "set" (rename)
2309
+ if (current.name === null)
2310
+ throw nameNotSetRefusal();
2311
+ if (label === current.name)
2312
+ throw nameUnchangedRefusal(label);
2313
+ const disposition = parsed.previous === "release" ? "release" : "keep-as-alias";
2314
+ const alias = activeNames.find((entry) => entry.label === label);
2315
+ if (alias) {
2316
+ // D4: promoting a name the artifact already holds claims nothing.
2317
+ claimsExistingAlias = true;
2318
+ result = {
2319
+ primaryName: alias.label,
2320
+ primaryUrl: nameHostnameUrl(alias.hostname),
2321
+ };
2322
+ }
2323
+ else {
2324
+ const availability = await checkLabelAvailability(label, deps);
2325
+ reclaimsReleasedName = isReclaimableByCaller(availability);
2326
+ checkNameQuota(quota, disposition === "keep-as-alias"
2327
+ ? { claims: 1, active: 1 }
2328
+ : { claims: 1 });
2329
+ claimsDelta = 1;
2330
+ result = {
2331
+ primaryName: label,
2332
+ primaryUrl: artifactPreviewUrl(label, deps),
2333
+ };
2334
+ }
2335
+ // O8: a `release` disposition decrements the old primary in the same
2336
+ // batch as the new claim's increment, netting 0 for a new label and -1
2337
+ // when the new primary was already an active alias (D4 promote).
2338
+ activeDelta = disposition === "release" ? (alias ? -1 : 0) : alias ? 0 : 1;
2339
+ if (disposition === "release") {
2340
+ const oldPrimary = activeNames.find((entry) => entry.isPrimary);
2341
+ addressesThatStopWorking = oldPrimary ? [oldPrimary.hostname] : [];
2342
+ }
2343
+ }
2344
+ const resultHostname = result.primaryUrl
2345
+ ? new URL(result.primaryUrl).hostname
2346
+ : null;
2347
+ const addressesThatKeepWorking = [...beforeHostnames]
2348
+ .filter((hostname) => hostname !== resultHostname &&
2349
+ !addressesThatStopWorking.includes(hostname))
2350
+ .sort();
2351
+ const plan = {
2352
+ ok: true,
2353
+ plan: {
2354
+ operation: sub === "set" ? "rename" : sub,
2355
+ artifactId: id,
2356
+ current,
2357
+ result,
2358
+ addressesThatStopWorking,
2359
+ addressesThatKeepWorking,
2360
+ promotedAlias,
2361
+ claimsExistingAlias,
2362
+ reclaimsReleasedName,
2363
+ quota: {
2364
+ [NAME_QUOTA_DIMENSIONS.claimsPerDay]: claimsDelta,
2365
+ [NAME_QUOTA_DIMENSIONS.activeNames]: activeDelta,
2366
+ current: quota,
2367
+ },
2368
+ executable: true,
2369
+ },
2370
+ };
2371
+ if (parsed.json)
2372
+ deps.stdout(`${JSON.stringify(plan, null, 2)}\n`);
2373
+ else {
2374
+ deps.stdout(`plan: ${plan.plan.operation} ${id} ${label}\n` +
2375
+ `${current.name ?? "(none)"} -> ${plan.plan.result.primaryName}` +
2376
+ ` (${plan.plan.result.primaryUrl ?? "unknown"})\n` +
2377
+ `stops working: ${addressesThatStopWorking.join(", ") || "none"}\n` +
2378
+ `keeps working: ${addressesThatKeepWorking.join(", ") || "none"}\n` +
2379
+ `executable: true\n`);
2380
+ }
2381
+ return 0;
2382
+ }
2383
+ /**
2384
+ * The caller's `--revision`, or the artifact's current opaque ETag together
2385
+ * with the primary name read in the same response, so both describe one state.
2386
+ */
2387
+ async function resolveArtifactSnapshot(raw, id, deps) {
2388
+ const revision = artifactRevision(raw);
2389
+ if (revision !== null)
2390
+ return { etag: revision };
2391
+ if (raw !== undefined) {
2392
+ throw new UsageError("--revision must be an opaque artifact ETag, e.g. --revision '\"artifact:...\"'.", "revision_invalid");
2393
+ }
2394
+ const current = await requestJson(deps, `/artifacts/${encodeURIComponent(id)}`, {
2395
+ method: "GET",
2396
+ body: undefined,
2397
+ });
2398
+ const etag = typeof current.etag === "string"
2399
+ ? current.etag
2400
+ : typeof current.artifact?.etag === "string"
2401
+ ? current.artifact.etag
2402
+ : null;
2403
+ if (etag === null) {
2404
+ throw new LocalError("revision_unavailable", "Could not read the artifact's current revision.", { next: "Run `foleo get <id> --json` and pass --revision explicitly." });
2405
+ }
2406
+ const name = current.artifact?.name ?? current.name;
2407
+ return { etag, name: typeof name === "string" ? name : null };
2408
+ }
2409
+ /** Spec 090 Slice 2 — `foleo names`: the names this organization holds. */
2410
+ async function namesCommand(args, deps) {
2411
+ const parsed = parseFlags(args);
2412
+ if (parsed.positionals.length !== 0) {
2413
+ throw new UsageError("Usage: foleo names [--artifact <id>] [--limit <n>] [--cursor <cursor>] [--json]");
2414
+ }
2415
+ const query = new URLSearchParams();
2416
+ if (parsed.artifact)
2417
+ query.set("artifactId", parsed.artifact);
2418
+ if (parsed.limit !== undefined)
2419
+ query.set("limit", String(parsed.limit));
2420
+ if (parsed.cursor)
2421
+ query.set("cursor", parsed.cursor);
2422
+ const suffix = query.toString();
2423
+ const result = await requestJson(deps, `/subdomains${suffix ? `?${suffix}` : ""}`, {
2424
+ method: "GET",
2425
+ body: undefined,
2426
+ });
2427
+ if (parsed.json) {
2428
+ writeResult(deps, result, true);
2429
+ return 0;
2430
+ }
2431
+ const lines = (result.names ?? []).map((name) => {
2432
+ const label = String(name.label);
2433
+ if (name.status === "cooldown") {
2434
+ return `${label} released, reclaimable until ${String(name.availableAt)}`;
2435
+ }
2436
+ return `${label} ${String(name.hostname)}${name.isPrimary ? " (primary)" : " (alias)"}`;
2437
+ });
2438
+ const quota = result.quota;
2439
+ if (quota) {
2440
+ lines.push(`Active names: ${String(quota.active)}/${String(quota.activeLimit)} · claims today: ${String(quota.claimsToday)}/${String(quota.claimsPerDay)}`);
2441
+ }
2442
+ if (typeof result.nextCursor === "string") {
2443
+ lines.push(`More: foleo names --cursor ${result.nextCursor}`);
2444
+ }
2445
+ deps.stdout(`${lines.join("\n")}\n`);
2446
+ return 0;
2447
+ }
2056
2448
  async function deleteArtifact(args, deps) {
2057
2449
  const parsed = parseFlags(args);
2058
2450
  const id = parsed.positionals[0];
@@ -2774,6 +3166,10 @@ function parseFlags(args, options = {}) {
2774
3166
  let allowPurge = false;
2775
3167
  let name;
2776
3168
  let dryRun = false;
3169
+ let previous;
3170
+ let acknowledgeLinkBreakage = false;
3171
+ let artifact;
3172
+ let cursor;
2777
3173
  for (let i = 0; i < args.length; i++) {
2778
3174
  const arg = args[i];
2779
3175
  if (arg === "--json") {
@@ -2872,6 +3268,28 @@ function parseFlags(args, options = {}) {
2872
3268
  publishSeparately = true;
2873
3269
  continue;
2874
3270
  }
3271
+ if (arg === "--previous") {
3272
+ previous = args[++i];
3273
+ if (!previous)
3274
+ throw new UsageError("--previous requires keep-as-alias or release", "previous_label_required");
3275
+ continue;
3276
+ }
3277
+ if (arg === "--acknowledge-link-breakage") {
3278
+ acknowledgeLinkBreakage = true;
3279
+ continue;
3280
+ }
3281
+ if (arg === "--artifact") {
3282
+ artifact = args[++i];
3283
+ if (!artifact)
3284
+ throw new Error("--artifact requires an artifact id");
3285
+ continue;
3286
+ }
3287
+ if (arg === "--cursor") {
3288
+ cursor = args[++i];
3289
+ if (!cursor)
3290
+ throw new Error("--cursor requires a value");
3291
+ continue;
3292
+ }
2875
3293
  if (arg === "--allow-delete") {
2876
3294
  if (!options.allowLoginScopeFlags)
2877
3295
  throw new Error("--allow-delete is valid only with login");
@@ -2909,6 +3327,10 @@ function parseFlags(args, options = {}) {
2909
3327
  allowPurge,
2910
3328
  ...(name === undefined ? {} : { name }),
2911
3329
  dryRun,
3330
+ ...(previous === undefined ? {} : { previous }),
3331
+ acknowledgeLinkBreakage,
3332
+ ...(artifact === undefined ? {} : { artifact }),
3333
+ ...(cursor === undefined ? {} : { cursor }),
2912
3334
  };
2913
3335
  }
2914
3336
  function parseGlobalFlags(argv) {
@@ -2938,6 +3360,10 @@ function help() {
2938
3360
  " foleo update <id> <path> --revision <etag> [--json]",
2939
3361
  " foleo update <id> <file.md> --version <version> [--json] (compatibility)",
2940
3362
  " foleo name-check <label> [--json]",
3363
+ " foleo names [--artifact <id>] [--limit <n>] [--cursor <cursor>] [--json]",
3364
+ " foleo name attach <id> <label> [--revision <etag>] [--dry-run] [--json]",
3365
+ " foleo name set <id> <label> --previous keep-as-alias|release [--revision <etag>] [--dry-run] [--json]",
3366
+ " foleo name release <id> <label> --acknowledge-link-breakage [--revision <etag>] [--dry-run] [--json]",
2941
3367
  " foleo status <id> [--json]",
2942
3368
  " foleo settings <id> [--json]",
2943
3369
  " foleo settings <id> --set k=v [--set k=v ...] [--password-stdin] --revision <etag> [--json]",
@@ -2955,22 +3381,37 @@ function help() {
2955
3381
  " foleo html-unpublish <id> --revision <stateRevision> (deprecated alias of unpublish)",
2956
3382
  "",
2957
3383
  "Naming (HTML only):",
2958
- " --name <label> is REQUIRED on every real HTML publish, and is PERMANENT:",
2959
- " there is no rename, so a new URL means republishing under a new id and",
2960
- " the old link breaks. Choose it with the human.",
3384
+ " --name <label> is REQUIRED on every real HTML publish. Choose it with the",
3385
+ " human. `name set` renames later and must say what happens to the old URL:",
3386
+ " --previous keep-as-alias keeps it working (uses one of 25 active names);",
3387
+ " --previous release stops it working and holds the name for you 30 days.",
3388
+ " `name release` drops an extra name; an artifact's last name cannot be",
3389
+ " released. `names` lists what this organization holds.",
2961
3390
  " Labels are 3-63 chars, a-z 0-9 and hyphens, with no leading, trailing or",
2962
3391
  " doubled hyphen. Invalid labels fail locally, before any network call.",
2963
3392
  " Markdown never requires --name and ignores it; the requirement follows",
2964
3393
  " the format inferred from the path, not the command you typed.",
2965
3394
  " The chosen name is the artifact's only address; there is no generated",
2966
- " fallback. Artifacts created before 2026-09-11 also keep an a-<id> host.",
3395
+ " fallback, and the old generated a-<id> hosts no longer serve.",
2967
3396
  "",
2968
3397
  " --dry-run plans an HTML publish without uploading, creating, or spending",
2969
3398
  " quota. It reports the resolved name and availability, url, title with its",
2970
3399
  " resolvedFrom source, visibility, routes, largestFiles and skipped[].",
2971
3400
  " A taken or reserved name fails with name_taken / name_reserved.",
2972
- " Every other command refuses it with dry_run_unsupported and mutates",
2973
- " nothing — Markdown publish, update, settings, unpublish, delete, purge.",
3401
+ "",
3402
+ " name attach|set|release --dry-run plans a name-lifecycle change with GET",
3403
+ " requests only; nothing is attached, renamed, or released. It reports the",
3404
+ " plan.result primary name/url, addressesThatStopWorking/KeepWorking, any",
3405
+ " D3 promotedAlias (release of the primary) or D4 claimsExistingAlias",
3406
+ " (renaming to a name already held as an alias claims nothing), and the",
3407
+ " publish.subdomain_claims / publish.subdomain_names.active quota deltas",
3408
+ " next to the current quota. A predicted refusal (name_taken, name_reserved,",
3409
+ " name_unchanged, name_not_found, last_name_release_refused, quota_exceeded,",
3410
+ " ...) fails with the same stable error object the real command would.",
3411
+ "",
3412
+ " Every other command refuses --dry-run with dry_run_unsupported and",
3413
+ " mutates nothing — Markdown publish, update, settings, unpublish, delete,",
3414
+ " restore, purge, names.",
2974
3415
  " name-check <label> is free and checks availability without publishing.",
2975
3416
  "",
2976
3417
  "Secrets:",