@letterstory/cli 0.168.2 → 0.174.1

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/lib/cli.mjs CHANGED
@@ -75,7 +75,7 @@ import {
75
75
  } from "./commands.mjs";
76
76
 
77
77
  // Matches cli/package.json; publish-cli.yml rewrites both to the published version.
78
- export const VERSION = "0.168.2";
78
+ export const VERSION = "0.174.1";
79
79
 
80
80
  /** The exit code for a gate refusal (CARD_REQUIRED, PAYMENT_FAILED, OUT_OF_TOKENS): 1 is a plain error. */
81
81
  export const EXIT_PAYMENT_REQUIRED = 3;
@@ -88,6 +88,8 @@ export const BOOLEAN_FLAGS = new Set([
88
88
  "start",
89
89
  // site research-builds: run now even when the stored pass is under an hour old.
90
90
  "fresh",
91
+ // admin letterpress telemetry: every org, test and demo orgs included.
92
+ "all-orgs",
91
93
  // admin letterpress status | gaps: the customers' reading (no test or demo orgs).
92
94
  "customers",
93
95
  // build: repeat an open build's ask; post its progress in the org's Slack channel.
@@ -333,6 +335,8 @@ export const BOOLEAN_FLAGS = new Set([
333
335
  // admin billing lago payments --open / payments run --dry
334
336
  "open",
335
337
  "dry",
338
+ // admin billing emails --bounced
339
+ "bounced",
336
340
  ]);
337
341
 
338
342
  // Tiny argv parser: `--flag value`, `--flag=value`, boolean `--flag`, and positionals.
@@ -1045,9 +1049,26 @@ Admin (STAFF key — --staff-key / LETTERSTORY_STAFF_API_KEY; acts before an org
1045
1049
  Mark legacy orgs: free until migrated, never gated
1046
1050
  by the free paywall (--all: everyone who pays today)
1047
1051
  admin billing legacy unmark <org-id> --why "…" No longer legacy; kept with who, when and why
1052
+ admin billing legacy review | decide <org-id> keep|free|test --why "…" [--tokens N]
1053
+ The legacy orgs no rule decided, most used first;
1054
+ decide each (free: a staff grant; test: a test org)
1048
1055
  admin billing free exposure | backfill --why "…" [--apply]
1049
1056
  Who the free paywall would stop today; the one-time
1050
1057
  signup grant for self-serve orgs with none
1058
+ admin billing free grant <org-id> <tokens> --why "…" [--key k] | grants [--org <org-id>] | revoke <org-id> <ref> --why "…"
1059
+ Give an org free tokens (a Lago org: a one-off wallet),
1060
+ list staff grants, take one back; posted to #billing
1061
+ admin billing visitors opt-out --why "…" [--apply] Turn off identification switched on automatically on
1062
+ billing-gated orgs (owners opt back in); a dry run first
1063
+ admin billing desk [--json] The Billing desk: switches, failed payments, the
1064
+ nightly reconcile, refusals, signups, grants
1065
+ admin billing free preflight [--json] Who the paywall stops the moment it is enforced:
1066
+ out of tokens, low, paying but covered, undecided
1067
+ admin billing emails [--bounced] [--org <org-id>] [--limit N]
1068
+ The invoice and receipt emails we sent for Lago and
1069
+ what became of each, bounced first (--bounced: only
1070
+ bounced, marked as spam or failed). Read only.
1071
+ Needs spend:read.
1051
1072
  admin billing lago catalog [--apply] [--include-drafts]
1052
1073
  | provision <org-id> --plan starter|growth|scale [--ratio 1|2|4|8 (8 needs --why "…")] [--complimentary N] [--stripe-customer cus_…] [--start ISO] [--review D]
1053
1074
  | reconcile [--org <org-id>] | forward
@@ -1088,6 +1109,7 @@ Admin (STAFF key — --staff-key / LETTERSTORY_STAFF_API_KEY; acts before an org
1088
1109
  | collections [--org-ids a,b | --account-stages won,active]
1089
1110
  | delivery-flags [--org-ids a,b | --account-stages won,active] [--include collections] [--since 2026-10-19T20:00:00Z]
1090
1111
  | pulse [--ids a,b] [--since 2026-10-19T20:00:00Z] how each client is doing, worst churn risk first
1112
+ | client-health [--since 2026-10-19T20:00:00Z] can we reach each fleet client in Slack, problems first
1091
1113
  | case <account-id> [--outcome <outcome-id>]
1092
1114
  | onboard <account-id> --domain acme.com [--name "Acme"] [--site "<direction>"]… [--sites N]
1093
1115
  [--slack a@acme.com,b@acme.com] [--invite a@acme.com[:admin]]… [--no-checklist]
@@ -14,7 +14,7 @@
14
14
  // The old names — evals, eval-add, eval-set, proposals, propose-eval, capture-eval, reject-eval — still work.)
15
15
  // admin evals scoreboard|cases|runs|run|triage|guard|retire … (fleet:read / tuning:experiment)
16
16
  // admin fleet-experiments list|articles|clients|mark|unmark|new|assign|assign-eligible|assign-orgs|spin-up|apply|start|stop|decide … (fleet:read / fleet:experiment)
17
- // admin crm import|capture|outreach|signals|record|signal|add|accounts|account|score|slack-channels|link-slack|white-glove|set-white-glove|churn|revenue|reach-outs|replies|record-churn|draft-churn-reason|undo-churn|outcomes|record-outcome|renewals|track-record|weekly-note|at-risk|expansion-signals|collections|delivery-flags|pulse|case|onboard|onboarding|retry-onboarding|onboard-plan|payment-link … (crm:read / crm:write)
17
+ // admin crm import|capture|outreach|signals|record|signal|add|accounts|account|score|slack-channels|link-slack|white-glove|set-white-glove|churn|revenue|reach-outs|replies|record-churn|draft-churn-reason|undo-churn|outcomes|record-outcome|renewals|track-record|weekly-note|at-risk|expansion-signals|collections|delivery-flags|pulse|client-health|case|onboard|onboarding|retry-onboarding|onboard-plan|payment-link … (crm:read / crm:write)
18
18
  // admin spend summary|reconcile|pnl|margin|pricing|entries|add|import|usage|remove|reference|stripe-sync|services|service … (spend:read / spend:write)
19
19
  // admin brand-detection <org-id> (fleet:read)
20
20
  // admin brand-detection <org-id> [--term t]... [--exact t]... [--exclude p]... [--note "…"] | --clear [--note "…"] (fleet:instrument)
@@ -3463,7 +3463,7 @@ async function cmdAdminCrm(ctx) {
3463
3463
  r.headline
3464
3464
  ? `${r.headline.month}: NRR ${pct(r.headline.nrr)} · GRR ${pct(r.headline.grr)} · expansion ${usd(r.headline.expansionCents)} · avg ${r.headline.avgCents == null ? "—" : usd(r.headline.avgCents)}/client`
3465
3465
  : "No complete month yet.",
3466
- `Clients counted: ${r.coverage.counted} (${r.coverage.stripe} Stripe, ${r.coverage.deal} deal) · comp ${r.coverage.comp} · ${usd(r.coverage.countedCents)}/mo`,
3466
+ `Clients counted: ${r.coverage.counted} (${r.coverage.lago ?? 0} Lago plan, ${r.coverage.stripe} Stripe, ${r.coverage.deal} deal) · comp ${r.coverage.comp} · ${usd(r.coverage.countedCents)}/mo`,
3467
3467
  "",
3468
3468
  ...r.periods.map(
3469
3469
  (p) =>
@@ -3737,6 +3737,33 @@ async function cmdAdminCrm(ctx) {
3737
3737
  );
3738
3738
  });
3739
3739
  }
3740
+ case "client-health": {
3741
+ // admin crm client-health [--since <ISO time, e.g. 2026-10-19T20:00:00Z>]
3742
+ // — can we reach each fleet client in Slack? Clients with something wrong first,
3743
+ // then every client without a channel. From a snapshot (~10 min); --since skips one older than that.
3744
+ const params = new URLSearchParams(compact({ since: flagStr(flags.since) }));
3745
+ return out(await staffRequest(ctx, "GET", `/api/superadmin/client-health?${params}`), (r) => {
3746
+ const flag = (f) =>
3747
+ f.kind === "invite_expired"
3748
+ ? `invitation expired (${f.emails.join(", ")})`
3749
+ : f.kind === "invite_pending"
3750
+ ? `invitation unanswered ${f.oldestDays}d (${f.emails.join(", ")})`
3751
+ : f.kind === "nobody_joined"
3752
+ ? "nobody from the client has joined"
3753
+ : `everyone left (${f.emails.join(", ")})`;
3754
+ const asOf = r.snapshot
3755
+ ? `(as of ${r.snapshot.computedAt}${r.snapshot.stale ? ", STALE: the refresh is failing" : ""})\n`
3756
+ : "";
3757
+ return [
3758
+ `${asOf}${r.covered} of ${r.total} fleet clients have a Slack channel`,
3759
+ ...r.atRisk.map((a) => `risk ${a.orgName} ${a.flags.map(flag).join("; ")} ${a.orgId}`),
3760
+ ...r.channels
3761
+ .filter((c) => c.state === "bot_missing")
3762
+ .map((c) => `no bot ${c.orgName} the Watchdog has never seen ${c.channelId} ${c.orgId}`),
3763
+ ...r.missingChannel.map((m) => `no room ${m.orgName} ${m.orgId}`),
3764
+ ].join("\n");
3765
+ });
3766
+ }
3740
3767
  case "case": {
3741
3768
  // admin crm case <account-id> [--outcome <id>] — the 90 days before an outcome, or before today.
3742
3769
  if (!id) throw new CliError("Usage: admin crm case <account-id> [--outcome <outcome-id>]");
@@ -3851,7 +3878,7 @@ async function cmdAdminCrm(ctx) {
3851
3878
  }
3852
3879
  default:
3853
3880
  throw new CliError(
3854
- "Usage: admin crm import|capture|outreach|signals|record|signal|accounts|account|score|slack-channels|link-slack|white-glove|set-white-glove|churn|revenue|reach-outs|replies|record-churn|draft-churn-reason|undo-churn|outcomes|record-outcome|renewals|track-record|weekly-note|at-risk|expansion-signals|collections|delivery-flags|pulse|case|onboard|onboarding|retry-onboarding|onboard-plan|prospect-org|prospect-orgs|payment-link … (see --help)"
3881
+ "Usage: admin crm import|capture|outreach|signals|record|signal|accounts|account|score|slack-channels|link-slack|white-glove|set-white-glove|churn|revenue|reach-outs|replies|record-churn|draft-churn-reason|undo-churn|outcomes|record-outcome|renewals|track-record|weekly-note|at-risk|expansion-signals|collections|delivery-flags|pulse|client-health|case|onboard|onboarding|retry-onboarding|onboard-plan|prospect-org|prospect-orgs|payment-link … (see --help)"
3855
3882
  );
3856
3883
  }
3857
3884
  }
@@ -4988,6 +5015,7 @@ const RECIPES = "/api/superadmin/recipes";
4988
5015
  /** The fields a recipe file carries: what import_recipes reads back. */
4989
5016
  const RECIPE_FILE_FIELDS = [
4990
5017
  "id",
5018
+ "kind",
4991
5019
  "name",
4992
5020
  "description",
4993
5021
  "recipe",
@@ -4998,7 +5026,7 @@ const RECIPE_FILE_FIELDS = [
4998
5026
  "variations",
4999
5027
  ];
5000
5028
  const RECIPES_USAGE =
5001
- "Usage: admin recipes list [--approach seo|geo|agent_conviction|inbound_conversion|outbound|other] | show <id|name> | runs <id|name> [--days 1..90] [--limit n] | vocab | stats | export [--out <file>] | import <file> [--dry-run] | save [<id>] [--file <recipe.json>] [--name …] [--description …] [--recipe …] [--when-to-use …] [--when-not-to-use …] [--weight 1..10] [--approaches seo,geo,…] | delete <id> --yes";
5029
+ "Usage: admin recipes list [--kind recipe|known_issue] [--approach seo|geo|agent_conviction|inbound_conversion|outbound|other] | show <id|name> | runs <id|name> [--days 1..90] [--limit n] | vocab | stats | export [--out <file>] | import <file> [--dry-run] | save [<id>] [--file <recipe.json>] [--kind recipe|known_issue] [--name …] [--description …] [--recipe …] [--when-to-use …] [--when-not-to-use …] [--weight 1..10] [--approaches seo,geo,…] | delete <id> --yes";
5002
5030
 
5003
5031
  const recipeForFile = (r) => Object.fromEntries(RECIPE_FILE_FIELDS.map((k) => [k, r[k]]));
5004
5032
 
@@ -5013,7 +5041,8 @@ const recipeVariations = (r) => [
5013
5041
 
5014
5042
  function recipeLine(r) {
5015
5043
  const more = r.variations?.length ? ` ${r.variations.length + 1} variations` : "";
5016
- return `${String(r.weight).padStart(2)}/10 ${r.name} [${recipeApproaches(r)}]${more} ${r.id}`;
5044
+ const kind = r.kind === "known_issue" ? " (known issue)" : "";
5045
+ return `${String(r.weight).padStart(2)}/10 ${r.name}${kind} [${recipeApproaches(r)}]${more} ${r.id}`;
5017
5046
  }
5018
5047
 
5019
5048
  function recipeDetail(r) {
@@ -5026,6 +5055,7 @@ function recipeDetail(r) {
5026
5055
  ];
5027
5056
  return [
5028
5057
  `${r.name} weight ${r.weight}/10 ${r.id}`,
5058
+ ` kind: ${r.kind === "known_issue" ? "known issue (Fix's list)" : "recipe (the Plan's)"}`,
5029
5059
  ` approaches: ${recipeApproaches(r)}`,
5030
5060
  ...(variations.length > 1
5031
5061
  ? variations.flatMap((v, i) => [` variation ${i + 1}: ${v.name}`, ...fields(v, " ")])
@@ -5059,6 +5089,7 @@ function recipeFromFlags(flags) {
5059
5089
  }
5060
5090
  return compact({
5061
5091
  ...compact(recipeForFile(base)),
5092
+ kind: flagStr(flags.kind),
5062
5093
  name: flagStr(flags.name),
5063
5094
  description: flagStr(flags.description),
5064
5095
  recipe: flagStr(flags.recipe),
@@ -5075,8 +5106,9 @@ function recipeFromFlags(flags) {
5075
5106
 
5076
5107
  const ENGINE = "/api/superadmin/engine-settings";
5077
5108
  const LETTERPRESS = "/api/superadmin/letterpress";
5109
+ const CODING_TELEMETRY = "/api/superadmin/coding-telemetry";
5078
5110
  const ENGINE_USAGE =
5079
- "Usage: admin letterpress status | gaps | replay <run-id> | mark <run-id> <item-id> <right|weak|wrong|lead|clear> [--note …] | settings | set <weights.<ask>.<reading>|lenses.<lens>.bar.<reading>|lenses.<lens>.bar|lenses.<lens>.research.turns|lenses.<lens>.research.ms|asks.<lens>.ask|asks.<lens>.guidance|dismissals.block_days|explore.ask|explore.research.turns|explore.research.ms|explore.every_days> <value>";
5111
+ "Usage: admin letterpress status | gaps | telemetry [--days N] [--harness h] [--all-orgs] | runs [--status s] [--error-code c] [--pr merged|closed|open|none] [--harness h] [--days N] | replay <run-id> | mark <run-id> <item-id> <right|weak|wrong|lead|clear> [--note …] | settings | set <weights.<ask>.<reading>|lenses.<lens>.bar.<reading>|lenses.<lens>.bar|lenses.<lens>.research.turns|lenses.<lens>.research.ms|asks.<lens>.ask|asks.<lens>.guidance|dismissals.block_days|explore.ask|explore.research.turns|explore.research.ms|explore.every_days> <value>";
5080
5112
 
5081
5113
  /** One number of the settings from a dotted path and a value: the PUT body save_engine_settings reads. */
5082
5114
  function engineSettingsPatch(path, value) {
@@ -5187,10 +5219,73 @@ async function cmdAdminLetterpress(ctx) {
5187
5219
  ? `asks from: ${s.surfaces.map((x) => `${x.surface} ${x.runs}`).join(", ")}`
5188
5220
  : "no runs yet",
5189
5221
  `turns ${s.turns.runs}${s.turns.by_action.length ? ` (${s.turns.by_action.map((a) => `${a.action} ${a.runs}`).join(", ")})` : ""}; builds ${s.turns.merge.builds}, merged ${s.turns.merge.merged}, closed ${s.turns.merge.closed}${s.customer_only ? " [customers only]" : ""}`,
5222
+ ...(s.harness_evals ?? []).map(
5223
+ (p) =>
5224
+ `harness eval ${p.at.slice(0, 10)} (${p.version}, ${p.pairs} pairs): ${p.harnesses
5225
+ .map(
5226
+ (h) =>
5227
+ `${h.harness} ${h.checks_passed}/${h.checks_total} checks, ${h.succeeded}/${h.tasks} succeeded${h.median_cost_usd !== null ? `, $${h.median_cost_usd.toFixed(2)}` : ""}${h.median_agent_minutes !== null ? `, ${h.median_agent_minutes.toFixed(1)} min` : ""}`
5228
+ )
5229
+ .join("; ")}; judge ${p.judge.wins}–${p.judge.losses}–${p.judge.ties}`
5230
+ ),
5231
+ ].join("\n")
5232
+ );
5233
+ return 0;
5234
+ }
5235
+ case "telemetry": {
5236
+ // get_coding_telemetry with fleet: the coding agent's numbers (docs/architecture/coding-telemetry.md).
5237
+ const q = new URLSearchParams({ view: "summary", days: String(flags.days ?? 7) });
5238
+ if (flags.harness) q.set("harness", String(flags.harness));
5239
+ if (flagBool(flags["all-orgs"])) q.set("customers", "0");
5240
+ const r = await staffRequest(ctx, "GET", `${CODING_TELEMETRY}?${q}`);
5241
+ const pct = (x) => (x.rate == null ? "—" : `${Math.round(100 * x.rate)}% (${x.hits}/${x.n})`);
5242
+ const usd = (v) => (v == null ? "—" : `$${v.toFixed(2)}`);
5243
+ const min = (v) => (v == null ? "—" : `${(v / 60_000).toFixed(1)}m`);
5244
+ printResult(io, flags, r, (t) =>
5245
+ [
5246
+ `Coding agent, last ${t.days} days${t.customer_only ? " (customers only)" : ""}: ${t.all.runs} runs (${t.previous.runs} the period before)`,
5247
+ ...[t.all, ...t.by_harness].map(
5248
+ (h) =>
5249
+ `${h.harness.padEnd(13)} ${String(h.runs).padStart(4)} runs first-try merge ${pct(h.first_try_merge)} failed ${pct(h.failed)} per merged PR ${usd(h.cost.per_merged_pr_usd)} agent ${min(h.time.agent_ms.p50)}`
5250
+ ),
5251
+ t.moved.length
5252
+ ? `moved beyond chance: ${t.moved.map((m) => `${m.measure} ${m.direction}`).join(", ")}`
5253
+ : "nothing moved beyond chance",
5254
+ t.failures.length
5255
+ ? `failures: ${t.failures.map((f) => `${f.error_code} ${f.count} (was ${f.previous}, ${f.fault})`).join(", ")}`
5256
+ : "no failures",
5257
+ `lost to timeouts/memory/crashes: ${pct(t.resilience)}${t.resilience.over_bar ? " OVER 3%" : ""}`,
5190
5258
  ].join("\n")
5191
5259
  );
5192
5260
  return 0;
5193
5261
  }
5262
+ case "runs": {
5263
+ // list_coding_runs with fleet.
5264
+ const q = new URLSearchParams({
5265
+ view: "runs",
5266
+ days: String(flags.days ?? 30),
5267
+ limit: String(flags.limit ?? 50),
5268
+ });
5269
+ for (const [flag, key] of [
5270
+ ["status", "status"],
5271
+ ["error-code", "error_code"],
5272
+ ["harness", "harness"],
5273
+ ["pr", "pr"],
5274
+ ])
5275
+ if (flags[flag]) q.set(key, String(flags[flag]));
5276
+ const r = await staffRequest(ctx, "GET", `${CODING_TELEMETRY}?${q}`);
5277
+ printResult(io, flags, r, (x) =>
5278
+ x.runs.length
5279
+ ? x.runs
5280
+ .map(
5281
+ (run) =>
5282
+ `${run.started_at.slice(0, 16)} ${run.harness.padEnd(13)} ${(run.status === "failed" ? (run.error_code ?? "failed") : run.status).padEnd(16)} pr ${run.pr.padEnd(6)} $${run.cost_usd.toFixed(2).padStart(6)} ${run.org_name ?? run.org_id} ${run.id}`
5283
+ )
5284
+ .join("\n")
5285
+ : "No runs match."
5286
+ );
5287
+ return 0;
5288
+ }
5194
5289
  case "gaps": {
5195
5290
  const r = await staffRequest(
5196
5291
  ctx,
@@ -5298,9 +5393,12 @@ async function cmdAdminRecipes(ctx) {
5298
5393
  }
5299
5394
  case "list": {
5300
5395
  const approach = flagStr(flags.approach);
5301
- const recipes = approach
5302
- ? ((await staffRequest(ctx, "GET", `${RECIPES}?approach=${encodeURIComponent(approach)}`)).recipes ??
5303
- [])
5396
+ const kind = flagStr(flags.kind);
5397
+ const query = new URLSearchParams();
5398
+ if (approach) query.set("approach", approach);
5399
+ if (kind) query.set("kind", kind);
5400
+ const recipes = query.size
5401
+ ? ((await staffRequest(ctx, "GET", `${RECIPES}?${query}`)).recipes ?? [])
5304
5402
  : await all();
5305
5403
  printResult(io, flags, { recipes }, (r) =>
5306
5404
  r.recipes.length ? r.recipes.map(recipeLine).join("\n") : "No recipes yet."
@@ -5410,7 +5508,8 @@ async function cmdAdminRecipes(ctx) {
5410
5508
  }
5411
5509
 
5412
5510
  const LAGO = "/api/superadmin/billing/lago";
5413
- const LAGO_USAGE = `Usage: admin billing lago <command>
5511
+ const LAGO_USAGE = `Usage: admin billing desk [--json] the Billing desk: switches, failed payments, reconcile, refusals, grants
5512
+ admin billing lago <command>
5414
5513
  catalog [--apply] [--include-drafts] what the plan catalog would change in Lago; --apply makes it so
5415
5514
  provision <org-id> --plan starter [--ratio 4] [--why "…" above 4x] [--complimentary 20000] [--stripe-customer cus_…] [--start 2026-11-02T00:00:00Z] [--review 2027-05-01]
5416
5515
  reconcile [--org <org-id>] Lago's tokens this period and last invoice against what we forwarded
@@ -5431,7 +5530,9 @@ const LAGO_USAGE = `Usage: admin billing lago <command>
5431
5530
 
5432
5531
  const LEGACY_USAGE = `Usage: admin billing legacy mark <org-id> --why "…" mark one org legacy (free until migrated)
5433
5532
  admin billing legacy mark --all --why "…" [--apply] every org that pays today; a dry run unless --apply
5434
- admin billing legacy unmark <org-id> --why "…" no longer legacy (kept with who, when and why)`;
5533
+ admin billing legacy unmark <org-id> --why "…" no longer legacy (kept with who, when and why)
5534
+ admin billing legacy review [--json] legacy orgs no rule decided, most used first, and the date they're decided by
5535
+ admin billing legacy decide <org-id> keep|free|test --why "…" [--tokens N] decide one (free: on free tokens; test: a test org)`;
5435
5536
 
5436
5537
  /**
5437
5538
  * admin billing legacy mark … — legacy orgs (decisions 2026-10-27): free until migrated, never gated
@@ -5441,6 +5542,36 @@ const LEGACY_USAGE = `Usage: admin billing legacy mark <org-id> --why "…"
5441
5542
  async function cmdAdminBillingLegacy(ctx) {
5442
5543
  const { flags, positionals, io } = ctx;
5443
5544
  if (positionals[1] === "unmark") return cmdAdminBillingLegacyUnmark(ctx);
5545
+ if (positionals[1] === "review") {
5546
+ const r = await staffRequest(ctx, "GET", "/api/superadmin/billing/legacy/review");
5547
+ printResult(io, flags, r, (x) => {
5548
+ const lines = [
5549
+ `${x.pending.length} legacy org(s) to decide by ${x.by} (${x.reviewed} reviewed so far), most used first:`,
5550
+ ];
5551
+ for (const o of x.pending)
5552
+ lines.push(
5553
+ ` ${o.orgId.slice(0, 8)} ${o.name ?? "(no name)"} ${o.events30d.toLocaleString("en-US")} events/30d${o.lastUsedAt ? `, last ${o.lastUsedAt.slice(0, 10)}` : ""} revenue=${o.revenueSource ?? "-"}`
5554
+ );
5555
+ return lines.join("\n");
5556
+ });
5557
+ return 0;
5558
+ }
5559
+ if (positionals[1] === "decide") {
5560
+ const [orgId, decision] = [positionals[2], positionals[3]];
5561
+ if (!orgId || !["keep", "free", "test"].includes(decision)) throw new CliError(LEGACY_USAGE);
5562
+ const why = flagStr(flags.why);
5563
+ if (!why) throw new CliError(`Say why (--why "…"): it is kept with the decision.\n${LEGACY_USAGE}`);
5564
+ const tokens = flagStr(flags.tokens);
5565
+ const r = await staffPost(ctx, "/api/superadmin/billing/legacy/review", {
5566
+ orgId,
5567
+ decision,
5568
+ why,
5569
+ ...(tokens ? { tokens: Number(tokens.replace(/[,_]/g, "")) } : {}),
5570
+ });
5571
+ const words = { keep: "kept legacy", free: "on free tokens", test: "marked a test org" };
5572
+ printResult(io, flags, r, (x) => `${orgId}: ${words[x.decision]}${x.grantRef ? ` (${x.grantRef})` : ""}.`);
5573
+ return 0;
5574
+ }
5444
5575
  if (positionals[1] !== "mark") throw new CliError(LEGACY_USAGE);
5445
5576
  const why = flagStr(flags.why);
5446
5577
  if (!why) throw new CliError(`Say why (--why "…"): it is kept with the mark.\n${LEGACY_USAGE}`);
@@ -5478,9 +5609,45 @@ async function cmdAdminBillingLegacyUnmark(ctx) {
5478
5609
  return 0;
5479
5610
  }
5480
5611
 
5612
+ const VISITORS_USAGE = `Usage: admin billing visitors opt-out --why "…" [--apply] turn off identification switched on automatically on billing-gated orgs (owners opt back in); a dry run unless --apply`;
5613
+
5614
+ /**
5615
+ * admin billing visitors opt-out — identification is billed per person, so sites switched on
5616
+ * automatically on an org on free tokens or billed on Lago are turned off once, as staff with who and
5617
+ * why; legacy, internal, unassigned and demo orgs and every owner-set site are left alone. A dry run
5618
+ * lists them unless --apply (lib/visitors/identification-opt-out.ts).
5619
+ */
5620
+ async function cmdAdminBillingVisitors(ctx) {
5621
+ const { flags, positionals, io } = ctx;
5622
+ if (positionals[1] !== "opt-out") throw new CliError(VISITORS_USAGE);
5623
+ const why = flagStr(flags.why);
5624
+ if (!why) throw new CliError(`Say why (--why "…").\n${VISITORS_USAGE}`);
5625
+ const r = await staffPost(ctx, "/api/superadmin/billing/visitors/opt-out", { dry: !flagBool(flags.apply), why });
5626
+ printResult(io, flags, r, (x) => {
5627
+ const row = (s) => ` ${s.domain ?? s.siteId} ${s.orgName ?? s.orgId.slice(0, 8)} (${s.standing})`;
5628
+ const lines = [
5629
+ `${x.dry ? "Would turn off" : "Turned off"} ${x.changed.length} site(s):`,
5630
+ ...x.changed.map(row),
5631
+ ];
5632
+ if (x.failed.length) lines.push(`Failed ${x.failed.length}:`, ...x.failed.map((f) => `${row(f)} ${f.error}`));
5633
+ if (x.kept.length)
5634
+ lines.push(
5635
+ `Left on ${x.kept.length} (auto, not billing-gated or a demo):`,
5636
+ ...x.kept.map((k) => `${row(k)} ${k.why}`)
5637
+ );
5638
+ if (x.dry) lines.push("Nothing written. Run again with --apply.");
5639
+ return lines.join("\n");
5640
+ });
5641
+ return 0;
5642
+ }
5643
+
5481
5644
  const FREE_USAGE = `Usage: admin billing free exposure [--json] who the free paywall covers, and who is unassigned
5482
5645
  admin billing free backfill --why "…" [--apply] signup grant for self-serve orgs with none; a dry run unless --apply
5483
- admin billing free repair-subjects --why "…" [--apply] staff-address signup subjects fixed, refused orgs granted (R1); a dry run unless --apply`;
5646
+ admin billing free repair-subjects --why "…" [--apply] staff-address signup subjects fixed, refused orgs granted (R1); a dry run unless --apply
5647
+ admin billing free grant <org-id> <tokens> --why "…" [--key k] give an org free tokens (a Lago org: a one-off wallet); the same key is one grant
5648
+ admin billing free grants [--org <org-id>] [--limit n] staff grants, newest first, live and revoked
5649
+ admin billing free revoke <org-id> <ref> --why "…" take a staff grant back (ref from the list: grant:<id> or wallet:staff_…)
5650
+ admin billing free preflight [--json] who the paywall stops the moment it is enforced, and whether it is ready`;
5484
5651
 
5485
5652
  const EXPOSURE_WORDS = {
5486
5653
  needs_legacy: "pay today: need a legacy mark (admin billing legacy mark --all)",
@@ -5493,7 +5660,7 @@ const EXPOSURE_WORDS = {
5493
5660
  /**
5494
5661
  * admin billing free … — before LETTERBRACE_FREE_TOKENS is set: who the free paywall would stop
5495
5662
  * (exposure, reads only) and the one-time signup grant for self-serve orgs that predate it (backfill,
5496
- * a dry run unless --apply).
5663
+ * a dry run unless --apply). grant / grants / revoke: staff grants of free tokens (lib/billing/staff-grant.ts).
5497
5664
  */
5498
5665
  async function cmdAdminBillingFree(ctx) {
5499
5666
  const { flags, positionals, io } = ctx;
@@ -5513,6 +5680,37 @@ async function cmdAdminBillingFree(ctx) {
5513
5680
  });
5514
5681
  return 0;
5515
5682
  }
5683
+ if (positionals[1] === "preflight") {
5684
+ const r = await staffRequest(ctx, "GET", "/api/superadmin/billing/free-tokens/preflight");
5685
+ printResult(io, flags, r, (x) => {
5686
+ const n = (v) => Number(v).toLocaleString("en-US");
5687
+ const row = (o) =>
5688
+ ` ${o.orgId.slice(0, 8)} ${o.name ?? "(no name)"} ${n(o.availableTokens)} left of ${n(o.grantedTokens)} (used ${n(o.usedTokens)}${o.heldTokens ? `, held ${n(o.heldTokens)}` : ""})`;
5689
+ const lines = [
5690
+ `Free paywall: ${x.mode}. ${x.ready ? "READY to enforce." : "NOT ready to enforce:"}`,
5691
+ ...x.blockers.map((b) => ` - ${b}`),
5692
+ `Covered: ${n(x.covered)} free org(s).`,
5693
+ `Refused the moment it's enforced (0 or less left): ${x.refusedNow.length}`,
5694
+ ...x.refusedNow.map(row),
5695
+ `Running low: ${x.low.length}`,
5696
+ ...x.low.map(row),
5697
+ ];
5698
+ if (x.wronglyCovered.length) {
5699
+ lines.push(`Pay us but covered: ${x.wronglyCovered.length}`);
5700
+ for (const o of x.wronglyCovered)
5701
+ lines.push(
5702
+ ` ${o.orgId.slice(0, 8)} ${o.name ?? "(no name)"} revenue=${o.revenueSource ?? "-"}${o.paying ? " paying" : ""}`
5703
+ );
5704
+ }
5705
+ if (x.undecided.length) {
5706
+ lines.push(`Undecided: ${x.undecided.length}`);
5707
+ for (const o of x.undecided)
5708
+ lines.push(` ${o.orgId.slice(0, 8)} ${o.name ?? "(no name)"} origin=${o.origin ?? "-"}`);
5709
+ }
5710
+ return lines.join("\n");
5711
+ });
5712
+ return 0;
5713
+ }
5516
5714
  if (positionals[1] === "backfill") {
5517
5715
  const why = flagStr(flags.why);
5518
5716
  if (!why) throw new CliError(`Say why (--why "…"): it is kept with each grant.\n${FREE_USAGE}`);
@@ -5551,14 +5749,176 @@ async function cmdAdminBillingFree(ctx) {
5551
5749
  });
5552
5750
  return 0;
5553
5751
  }
5752
+ if (positionals[1] === "grant") {
5753
+ const [orgId, tokensArg] = [positionals[2], positionals[3]];
5754
+ const tokens = Number(String(tokensArg ?? "").replace(/[,_]/g, ""));
5755
+ if (!orgId || !Number.isInteger(tokens) || tokens <= 0) throw new CliError(FREE_USAGE);
5756
+ const why = flagStr(flags.why);
5757
+ if (!why) throw new CliError(`Say why (--why "…"): it is kept with the grant.\n${FREE_USAGE}`);
5758
+ const key = flagStr(flags.key);
5759
+ const r = await staffPost(ctx, "/api/superadmin/billing/free-tokens/grants", {
5760
+ orgId,
5761
+ tokens,
5762
+ why,
5763
+ ...(key ? { key } : {}),
5764
+ });
5765
+ printResult(io, flags, r, (x) => {
5766
+ const what = x.kind === "wallet" ? "as a one-off wallet on Lago" : "as a free-token grant";
5767
+ const lines = [
5768
+ x.granted
5769
+ ? `Gave ${x.tokens.toLocaleString("en-US")} tokens ${what} (${x.ref}).`
5770
+ : `Already given under this key (${x.ref}); nothing new.`,
5771
+ ];
5772
+ if (x.standing.before !== x.standing.after)
5773
+ lines.push(`Standing: ${x.standing.before} -> ${x.standing.after} (now on the free paywall).`);
5774
+ return lines.join("\n");
5775
+ });
5776
+ return 0;
5777
+ }
5778
+ if (positionals[1] === "grants") {
5779
+ const org = flagStr(flags.org);
5780
+ const limit = flagStr(flags.limit);
5781
+ const qs = new URLSearchParams({ ...(org ? { orgId: org } : {}), ...(limit ? { limit } : {}) });
5782
+ const r = await staffRequest(
5783
+ ctx,
5784
+ "GET",
5785
+ `/api/superadmin/billing/free-tokens/grants${qs.size ? `?${qs}` : ""}`
5786
+ );
5787
+ printResult(io, flags, r, (x) => {
5788
+ if (!x.grants.length) return "No staff grants.";
5789
+ return x.grants
5790
+ .map(
5791
+ (g) =>
5792
+ `${g.createdAt.slice(0, 10)} ${g.ref.padEnd(24)} ${String(g.tokens.toLocaleString("en-US")).padStart(9)} ${g.orgName ?? g.orgId.slice(0, 8)} by ${g.grantedBy}: ${g.reason ?? "-"}` +
5793
+ (g.revokedAt
5794
+ ? ` [revoked ${g.revokedAt.slice(0, 10)} by ${g.revokedBy}: ${g.revokeReason}]`
5795
+ : "")
5796
+ )
5797
+ .join("\n");
5798
+ });
5799
+ return 0;
5800
+ }
5801
+ if (positionals[1] === "revoke") {
5802
+ const [orgId, ref] = [positionals[2], positionals[3]];
5803
+ if (!orgId || !ref) throw new CliError(FREE_USAGE);
5804
+ const why = flagStr(flags.why);
5805
+ if (!why) throw new CliError(`Say why (--why "…"): it is kept with the revoke.\n${FREE_USAGE}`);
5806
+ const r = await staffRequest(ctx, "DELETE", "/api/superadmin/billing/free-tokens/grants", { orgId, ref, why });
5807
+ printResult(
5808
+ io,
5809
+ flags,
5810
+ r,
5811
+ (x) =>
5812
+ `Took back ${x.revoked.tokens.toLocaleString("en-US")} tokens (${x.revoked.ref}) from ${x.revoked.orgName ?? orgId}.`
5813
+ );
5814
+ return 0;
5815
+ }
5554
5816
  throw new CliError(FREE_USAGE);
5555
5817
  }
5556
5818
 
5819
+ /**
5820
+ * admin billing desk [--json] — the Billing desk in one read (lib/billing/desk.ts, docs/billing/billing-desk.md):
5821
+ * the switches, what needs a person now, and the week's numbers. The same as GET /api/superadmin/billing/desk
5822
+ * and MCP billing_desk.
5823
+ */
5824
+ async function cmdAdminBillingDesk(ctx) {
5825
+ const { flags, io } = ctx;
5826
+ const r = await staffRequest(ctx, "GET", "/api/superadmin/billing/desk");
5827
+ printResult(io, flags, r, (d) => {
5828
+ const n = (x) => Number(x ?? 0).toLocaleString("en-US");
5829
+ const sw = d.switches;
5830
+ const signup = sw.lagoSignup.active ? "on" : sw.lagoSignup.from ? `from ${sw.lagoSignup.from}` : "off";
5831
+ const forward = sw.forwarding.on ? "on" : "off";
5832
+ const lines = [
5833
+ `Switches: spend cap ${sw.tokenGate}${sw.enforcedOrgs ? ` (+${sw.enforcedOrgs} enforced)` : ""} · free paywall ${sw.freeTokens} · Lago signups ${signup} · forwarding ${forward} · failed payments ${sw.dunning}${sw.lagoConfigured ? "" : " · Lago NOT configured"}`,
5834
+ `Signups: ${n(d.signups.grants.today)} today, ${n(d.signups.grants.week)} this week (${n(d.signups.grants.agentWeek)} by an agent) · Lago this week: ${
5835
+ Object.entries(d.signups.lagoWeek)
5836
+ .filter(([, c]) => c > 0)
5837
+ .map(([s, c]) => `${c} ${s}`)
5838
+ .join(", ") || "none"
5839
+ }`,
5840
+ ];
5841
+ const rec = d.reconcile;
5842
+ const recWhen = rec.meta.computedAt ? rec.meta.computedAt.slice(0, 16).replace("T", " ") : "never";
5843
+ const drifting = (rec.result?.orgs ?? []).filter((o) => o.status !== "ok" && o.status !== "not_started");
5844
+ lines.push(
5845
+ `Reconcile (${recWhen}${rec.meta.stale ? ", STALE" : ""}): ${rec.result ? (rec.result.ok ? `all ${rec.result.orgs.length} agree` : `${drifting.length} need a look`) : "no result yet"}`
5846
+ );
5847
+ for (const o of drifting) lines.push(` ${o.orgId.slice(0, 8)} ${o.status} drift ${o.drift ?? "-"}`);
5848
+ lines.push(`Failed payments open: ${d.payments.length}`);
5849
+ for (const p of d.payments)
5850
+ lines.push(
5851
+ ` ${p.orgName ?? p.orgId.slice(0, 8)} ${p.invoiceNumber ?? p.invoiceId} $${(p.amountCents / 100).toFixed(2)} ${p.status} ${p.attempts} tries${p.lastError ? `: ${p.lastError}` : ""}`
5852
+ );
5853
+ if (d.signups.stuck.length) lines.push(`Stuck signups: ${d.signups.stuck.length}`);
5854
+ for (const s of d.signups.stuck)
5855
+ lines.push(
5856
+ ` ${s.orgName ?? s.orgId.slice(0, 8)} ${s.planCode} ${s.status}${s.lastError ? `: ${s.lastError}` : ""}`
5857
+ );
5858
+ const refusalWords = Object.entries(d.refusals.byReason)
5859
+ .map(([k, c]) => `${c} ${k}`)
5860
+ .join(", ");
5861
+ lines.push(`Gate refusals this week: ${n(d.refusals.total)}${refusalWords ? ` (${refusalWords})` : ""}`);
5862
+ for (const o of d.refusals.orgs.slice(0, 5))
5863
+ lines.push(` ${o.orgName ?? o.orgId.slice(0, 8)} ${o.count} ${o.reasons.join(", ")}`);
5864
+ lines.push(
5865
+ `Free paywall: ${n(d.exposure.counts.granted)} granted · ${d.exposure.waiting.length} waiting on a person (admin billing free exposure)`
5866
+ );
5867
+ if (d.capRequests.length) lines.push(`Cap requests this week: ${d.capRequests.length}`);
5868
+ if (d.termChanges.length)
5869
+ lines.push(`Scheduled term changes: ${d.termChanges.length} (admin billing lago changes)`);
5870
+ const live = d.grants.filter((g) => !g.revokedAt);
5871
+ lines.push(`Staff grants: ${live.length} live of the last ${d.grants.length} (admin billing free grants)`);
5872
+ if (d.emails)
5873
+ lines.push(
5874
+ `Invoice emails: ${d.emails.on ? "ours" : "Lago's"} · ${d.emails.problems.length} didn't arrive${d.emails.problems.length ? " (admin billing emails --bounced)" : ""}`
5875
+ );
5876
+ return lines.join("\n");
5877
+ });
5878
+ return 0;
5879
+ }
5880
+
5881
+ const EMAILS_USAGE = `Usage: admin billing emails [--bounced] [--org <org-id>] [--limit N]
5882
+ the invoice and receipt emails we sent for Lago and what became of each, bounced first
5883
+ (--bounced: only the ones that bounced, were marked as spam or failed)`;
5884
+
5885
+ /**
5886
+ * admin billing emails — the invoice and receipt emails we send for Lago (lib/billing/lago/invoice-emails.ts)
5887
+ * and what Resend said of each. Read only.
5888
+ */
5889
+ async function cmdAdminBillingEmails(ctx) {
5890
+ const { flags, positionals, io } = ctx;
5891
+ if (positionals.length > 1) throw new CliError(EMAILS_USAGE);
5892
+ const params = new URLSearchParams(
5893
+ compact({
5894
+ orgId: flagStr(flags.org),
5895
+ bounced: flagBool(flags.bounced) ? "true" : undefined,
5896
+ limit: flagNum(flags.limit) !== undefined ? String(flagNum(flags.limit)) : undefined,
5897
+ })
5898
+ );
5899
+ const result = await staffRequest(ctx, "GET", `/api/superadmin/billing/emails${params.size ? `?${params}` : ""}`);
5900
+ printResult(io, flags, result, (r) =>
5901
+ [
5902
+ `Invoice and receipt emails: ${r.on ? "on (we send them)" : "off (Lago sends them)"}`,
5903
+ ...(r.emails.length
5904
+ ? r.emails.map(
5905
+ (e) =>
5906
+ ` ${e.status.padEnd(10)} ${e.kind.padEnd(7)} ${e.invoiceNumber ?? e.invoiceId} ${e.orgName ?? e.orgId} $${(e.amountCents / 100).toFixed(2)} ${e.to.join(", ") || "(nobody)"} ${e.sentAt ?? e.createdAt}${e.error ? ` (${e.error})` : ""}`
5907
+ )
5908
+ : [flagBool(flags.bounced) ? " None bounced." : " None sent yet."]),
5909
+ ].join("\n")
5910
+ );
5911
+ return 0;
5912
+ }
5913
+
5557
5914
  /** admin billing lago … — staff operations on Lago (docs/billing/lago-integration.md). */
5558
5915
  async function cmdAdminBilling(ctx) {
5559
5916
  const { flags, positionals, io } = ctx;
5560
5917
  if (positionals[0] === "legacy") return cmdAdminBillingLegacy(ctx);
5561
5918
  if (positionals[0] === "free") return cmdAdminBillingFree(ctx);
5919
+ if (positionals[0] === "desk") return cmdAdminBillingDesk(ctx);
5920
+ if (positionals[0] === "emails") return cmdAdminBillingEmails(ctx);
5921
+ if (positionals[0] === "visitors") return cmdAdminBillingVisitors(ctx);
5562
5922
  if (positionals[0] !== "lago") throw new CliError(LAGO_USAGE);
5563
5923
  const sub = positionals[1];
5564
5924
  switch (sub) {
@@ -26,6 +26,8 @@ const ARGS = {
26
26
  notify_slack: { flag: "notify-slack", type: "bool" },
27
27
  harness: { flag: "harness", enum: ["claude-code", "letterpress-1"] },
28
28
  again: { flag: "again", type: "bool" },
29
+ // --recipe <id>: the recipe the build carries out (a Plan row's), recorded on it.
30
+ recipe: "recipe",
29
31
  },
30
32
  send_build_message: {
31
33
  message: {
@@ -87,7 +87,8 @@ const ARGS = {
87
87
  // --with-preview: the PR opens straight away and a preview of the change stays up next to it.
88
88
  with_preview: { flag: "with-preview", type: "bool" },
89
89
  // --harness claude-code|letterpress-1: the coding agent; omitted, the deployment's default.
90
- harness: { flag: "harness", enum: ["claude-code", "letterpress-1"] },
90
+ // codex (OpenAI's Codex CLI) runs only on a test organization, for the harness evals.
91
+ harness: { flag: "harness", enum: ["claude-code", "letterpress-1", "codex"] },
91
92
  // --again: start it even when an open change already asks for the same thing.
92
93
  again: { flag: "again", type: "bool" },
93
94
  // --verifier / --no-verifier: review the change before it goes out; omitted, the deployment's choice.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@letterstory/cli",
3
- "version": "0.168.2",
3
+ "version": "0.174.1",
4
4
  "description": "Spin up and manage Letter phantom blogs from your terminal.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",