@tokenoftrust/cli 1.4.0 → 1.5.0

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 (54) hide show
  1. package/README.md +5 -0
  2. package/bin/tot.mjs +148 -57
  3. package/package.json +6 -1
  4. package/src/activity.mjs +379 -0
  5. package/src/app-scaffold.mjs +4 -4
  6. package/src/auth.mjs +13 -5
  7. package/src/candidate-state.mjs +3 -3
  8. package/src/commands/accept.mjs +498 -59
  9. package/src/commands/app/dev.mjs +8 -4
  10. package/src/commands/app/index.mjs +3 -3
  11. package/src/commands/app/scaffold.mjs +1 -1
  12. package/src/commands/branches.mjs +297 -0
  13. package/src/commands/cleanup.mjs +264 -0
  14. package/src/commands/clone.mjs +307 -25
  15. package/src/commands/dev.mjs +440 -156
  16. package/src/commands/doctor.mjs +4 -4
  17. package/src/commands/git-credential.mjs +180 -0
  18. package/src/commands/go-live.mjs +9 -5
  19. package/src/commands/grants.mjs +7 -5
  20. package/src/commands/hotfix.mjs +428 -0
  21. package/src/commands/ideas.mjs +2 -2
  22. package/src/commands/link.mjs +2 -2
  23. package/src/commands/login.mjs +5 -6
  24. package/src/commands/pr.mjs +62 -25
  25. package/src/commands/preview-build.mjs +6 -6
  26. package/src/commands/preview-doctor.mjs +225 -0
  27. package/src/commands/preview-retry-evidence.mjs +156 -0
  28. package/src/commands/preview.mjs +19 -3
  29. package/src/commands/revert.mjs +322 -0
  30. package/src/commands/rollback.mjs +18 -16
  31. package/src/commands/ship.mjs +51 -14
  32. package/src/commands/start.mjs +101 -59
  33. package/src/commands/submit.mjs +1183 -169
  34. package/src/commands/sync.mjs +203 -0
  35. package/src/commands/validate.mjs +10 -4
  36. package/src/commands/whoami.mjs +1 -1
  37. package/src/dev-heartbeat.mjs +3 -2
  38. package/src/dev-logs.mjs +2 -2
  39. package/src/errors.mjs +11 -4
  40. package/src/git-credential.mjs +257 -0
  41. package/src/last-tenant.mjs +1 -1
  42. package/src/mcp.mjs +6 -1
  43. package/src/merge-doctor-report.mjs +208 -0
  44. package/src/no-gitea-links.test.mjs +55 -0
  45. package/src/oauth.mjs +18 -14
  46. package/src/obstacle-beacon.cjs +2 -2
  47. package/src/obstacle.mjs +1 -1
  48. package/src/plan.mjs +83 -15
  49. package/src/sample.mjs +4 -4
  50. package/src/validate.mjs +187 -15
  51. package/src/vendor/private-apps-devkit.mjs +3 -3
  52. package/src/viewer-session.mjs +118 -0
  53. package/template/private-app/README.md +12 -6
  54. package/src/commands/retire.mjs +0 -203
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `tot app dev` — the local Private App harness (PrivateApps epic D6 Chunk D).
2
+ * `tot app dev` — the local Private App harness (PrivateApps epic).
3
3
  * Everything here is OFFLINE: no network beyond the localhost URL you point
4
4
  * it at, no MCP, no real ToT credentials. It generates and reuses its own
5
5
  * throwaway RS256 keypair per app directory (`.tot/dev-keys.json`) so signing
@@ -49,7 +49,10 @@ function randHex(bytes) {
49
49
  return Buffer.from(crypto.getRandomValues(new Uint8Array(bytes))).toString("hex");
50
50
  }
51
51
 
52
- /** Load or create the app's throwaway RS256 keypair at `<appDir>/.tot/dev-keys.json`. */
52
+ /**
53
+ * Load or create the app's throwaway RS256 keypair at `<appDir>/.tot/dev-keys.json`.
54
+ * @param {string} appDir @param {{ kid?: string }} [opts]
55
+ */
53
56
  export async function ensureDevKeys(appDir, { kid } = {}) {
54
57
  const keysPath = join(appDir, ".tot", "dev-keys.json");
55
58
  const alg = { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" };
@@ -107,8 +110,9 @@ function runValidate(argv, { appDir }) {
107
110
  console.log(`✔ ${manifestPath} is a valid tot-app.json (contract v${result.manifest.contractVersion})`);
108
111
  return 0;
109
112
  }
110
- console.log(`✖ ${manifestPath} ${result.errors.length} error(s):`);
111
- for (const e of result.errors) console.log(` - ${e}`);
113
+ const errs = result.errors || [];
114
+ console.log(`✖ ${manifestPath} — ${errs.length} error(s):`);
115
+ for (const e of errs) console.log(` - ${e}`);
112
116
  return 1;
113
117
  }
114
118
 
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `tot app` — the Storefront Private App developer subcommand group
3
- * (PrivateApps epic D6 Chunks C+D): scaffold a new app, then exercise its
3
+ * (PrivateApps epic): scaffold a new app, then exercise its
4
4
  * webhook/manifest/widget-launch loop entirely offline.
5
5
  *
6
6
  * tot app scaffold <name> materialize a runnable Private App skeleton
@@ -23,11 +23,11 @@ export async function run(argv, ctx) {
23
23
 
24
24
  if (sub === "scaffold") {
25
25
  const { run: runScaffold } = await import("./scaffold.mjs");
26
- return runScaffold(rest, ctx);
26
+ return /** @type {any} */ (runScaffold)(rest, ctx);
27
27
  }
28
28
  if (sub === "dev") {
29
29
  const { run: runDev } = await import("./dev.mjs");
30
- return runDev(rest, ctx);
30
+ return /** @type {any} */ (runDev)(rest, ctx);
31
31
  }
32
32
 
33
33
  console.error(fail(`unknown \`tot app\` subcommand: ${sub}`, "tot app --help"));
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `tot app scaffold <name>` — materialize a runnable Storefront Private App
3
- * skeleton on disk (PrivateApps epic D6 Chunk C). See ../../app-scaffold.mjs
3
+ * skeleton on disk (PrivateApps epic). See ../../app-scaffold.mjs
4
4
  * for the offline, idempotent copy logic this wraps.
5
5
  *
6
6
  * tot app scaffold <name> scaffold ./<name>
@@ -0,0 +1,297 @@
1
+ /**
2
+ * `tot branches` — the full branch-cleanup REPORT for one tenant's repo (per
3
+ * the branch-lifecycle-and-integration-preview contract: "join
4
+ * branch, PR, candidate, head SHA, actor, full zoned timestamp, age, evidence,
5
+ * aggregate status, and cleanup eligibility"). Distinct from `tot pr list`,
6
+ * which only shows OPEN PRs — this shows EVERY branch on the repo (protected,
7
+ * active, stale, integrated, closed, orphaned), because that is what a
8
+ * cleanup decision needs.
9
+ *
10
+ * The report itself is server-side classification (the `candidate_list` MCP
11
+ * tool → `classifyBranches`); this command is presentation only — it never
12
+ * re-derives eligibility, an "aggregate" verdict, or a classification bucket
13
+ * client-side. The contract's complaint about a "truncated human table" (see
14
+ * "Candidate branch retirement") is about hidden precision, not columns — so
15
+ * every SHA and timestamp is printed in full, never shortened.
16
+ *
17
+ * KNOWN GAP: the contract asks for an "actor" column, but neither Gitea's
18
+ * branch record nor its PR record (see `../../gitea/gitea-rest.ts`) carries a
19
+ * PR author — `candidate_list` does not surface one. Rather than fabricate it
20
+ * client-side, every row prints `actor: —` and the report states the gap once
21
+ * up top. Fixing this is a tot-mcp follow-up (surface the PR author from
22
+ * Gitea), not something this CLI can honestly synthesize.
23
+ *
24
+ * `tot cleanup` (cleanup.mjs) reuses `resolveRepoAndTenant` from here so the
25
+ * two commands resolve "which repo" identically.
26
+ *
27
+ * Dependency-free (global fetch via mcp.mjs's client + `git`).
28
+ */
29
+ import { execFileSync } from "node:child_process";
30
+ import { createMcpClient } from "../mcp.mjs";
31
+ import { establishSession, AuthUnavailableError } from "../auth.mjs";
32
+ import { fail } from "../errors.mjs";
33
+ import { repoNameFromRemote } from "./submit.mjs";
34
+
35
+ const DEFAULT_MCP_URL = "https://mcp.tokenoftrust.com";
36
+
37
+ const USAGE = `tot branches — full branch-cleanup report (every branch, not just open PRs)
38
+
39
+ tot branches report for the current checkout's repo
40
+ tot branches --tenant <t> report for <t> (works without a checkout)
41
+ tot branches --json emit the raw classification report as JSON
42
+
43
+ Joins branch + PR (any state) + candidate ref + head SHA + full zoned
44
+ timestamp + age + evidence + aggregate status + cleanup eligibility for
45
+ EVERY branch on the repo — read-only, always safe to run, and the report
46
+ \`tot cleanup\` reuses before it deletes anything.
47
+
48
+ Options:
49
+ --tenant <appDomain> Target tenant/repo. Defaults to the current
50
+ checkout's tenant when run inside one.
51
+ --repo <name> Explicit repo name, if it differs from --tenant.
52
+ --stale-after-days <n> Idle-day threshold for the "stale-open" warn
53
+ bucket. Defaults to the server's policy (14).
54
+ --mcp <url> MCP base URL (default: env MCP_BASE_URL / TOT_MCP_URL)
55
+ --identity <id> Prefer this cached identity over the default.
56
+ --json Print the raw classification report as JSON.
57
+ --help, -h Show this help.`;
58
+
59
+ /** Parse `tot branches` argv. Pure — unit-testable. */
60
+ export function parseBranchesArgs(argv) {
61
+ /** @type {{ tenant: string|null, repo: string|null, staleAfterDays: number|null, mcp: string|null, identity: string|null, json: boolean, help: boolean }} */
62
+ const a = {
63
+ tenant: null,
64
+ repo: null,
65
+ staleAfterDays: null,
66
+ mcp: null,
67
+ identity: null,
68
+ json: false,
69
+ help: false,
70
+ };
71
+ for (let i = 0; i < argv.length; i++) {
72
+ const t = argv[i];
73
+ if (t === "--tenant") a.tenant = argv[++i];
74
+ else if (t === "--repo") a.repo = argv[++i];
75
+ else if (t === "--stale-after-days") a.staleAfterDays = Number(argv[++i]);
76
+ else if (t === "--mcp") a.mcp = argv[++i];
77
+ else if (t === "--identity") a.identity = argv[++i];
78
+ else if (t === "--json") a.json = true;
79
+ else if (t === "--help" || t === "-h") a.help = true;
80
+ }
81
+ return a;
82
+ }
83
+
84
+ /** Best-effort `git remote get-url origin` from a checkout ctx. Never throws. */
85
+ function defaultReadRemoteUrl(ctx) {
86
+ try {
87
+ return execFileSync("git", ["-C", ctx.workspacePath, "remote", "get-url", "origin"], {
88
+ stdio: ["ignore", "pipe", "pipe"],
89
+ })
90
+ .toString()
91
+ .trim();
92
+ } catch {
93
+ return "";
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Resolve which repo + tenant a branches/cleanup call targets: an explicit
99
+ * `--repo`/`--tenant` wins; otherwise, inside a checkout, the repo is derived
100
+ * from the checkout's forge remote (same derivation `tot pr` uses) and the
101
+ * tenant from the detected context. `repo` (the Gitea repo/tenant-appDomain
102
+ * name candidate_list expects) falls back to the tenant when neither an
103
+ * explicit `--repo` nor a checkout is available — this codebase's own naming
104
+ * convention is that the repo name IS the tenant appDomain. Pure given
105
+ * `deps.readRemoteUrl` — unit-testable with no real git/network.
106
+ * @param {{tenant?:string|null, repo?:string|null}} args
107
+ * @param {any} ctx
108
+ * @param {{ readRemoteUrl?: (ctx:any) => string }} [deps]
109
+ * @returns {{ repo: string|null, tenant: string|null, error: string|null }}
110
+ */
111
+ export function resolveRepoAndTenant(args, ctx, deps = {}) {
112
+ const readRemoteUrl = deps.readRemoteUrl || defaultReadRemoteUrl;
113
+ const tenant = (args.tenant || ctx?.tenant || "").trim() || null;
114
+ let repo = (args.repo || "").trim() || null;
115
+ if (!repo && ctx?.mode === "checkout" && ctx?.workspacePath) {
116
+ const remote = readRemoteUrl(ctx);
117
+ repo = remote ? repoNameFromRemote(remote) : null;
118
+ }
119
+ if (!repo) repo = tenant;
120
+ if (!repo) {
121
+ return {
122
+ repo: null,
123
+ tenant,
124
+ error: fail(
125
+ "no target repo/tenant.",
126
+ "pass --tenant <appDomain> (e.g. --tenant tokenoftrust.com), or run inside a store checkout.",
127
+ ),
128
+ };
129
+ }
130
+ return { repo, tenant: tenant || repo, error: null };
131
+ }
132
+
133
+ const COLUMNS = [
134
+ ["branch", "BRANCH"],
135
+ ["pr", "PR"],
136
+ ["candidate", "CANDIDATE"],
137
+ ["sha", "HEAD SHA"],
138
+ ["actor", "ACTOR"],
139
+ ["updated", "UPDATED (UTC)"],
140
+ ["age", "AGE"],
141
+ ["evidence", "EVIDENCE"],
142
+ ["status", "STATUS"],
143
+ ["aggregate", "AGGREGATE"],
144
+ ["cleanup", "CLEANUP"],
145
+ ];
146
+
147
+ /**
148
+ * Adapt one `candidate_list` `BranchCleanupRecord` to this table's row shape.
149
+ * Every value is printed in full — no truncated SHAs, no truncated
150
+ * timestamps (see module header re: the contract's "truncated human table"
151
+ * complaint). Pure — unit-tested.
152
+ * @param {any} b - a BranchCleanupRecord from the MCP `candidate_list` tool
153
+ */
154
+ export function formatBranchRow(b) {
155
+ const pr = typeof b.prNumber === "number" ? `#${b.prNumber}` : "#—";
156
+ const candidate = b.changeId || "—";
157
+ const sha = b.sha || "—";
158
+ // KNOWN GAP — see module header: candidate_list does not surface a PR
159
+ // author today, so this is honestly "—", never fabricated.
160
+ const actor = "—";
161
+ const updated = b.commitTimestampUtc || "(unknown)";
162
+ const age = b.idleDays != null ? `${b.idleDays}d` : "(unknown)";
163
+ const evidence = b.evidence
164
+ ? `${b.evidence.checksTotal} check(s) ${b.evidence.allPass ? "all pass" : "NOT all pass"} @ ${b.evidence.generatedAtUtc}`
165
+ : "no evidence";
166
+ const aggregate =
167
+ b.classification === "protected" ? "—" : b.integratedIntoAggregate ? "in preview aggregate" : "not in aggregate";
168
+ const cleanup = b.eligibleForDelete ? "ELIGIBLE" : b.quarantine ? "QUARANTINED" : "keep";
169
+ return {
170
+ branch: b.ref,
171
+ pr,
172
+ candidate,
173
+ sha,
174
+ actor,
175
+ updated,
176
+ age,
177
+ evidence,
178
+ status: b.classification ?? "?",
179
+ aggregate,
180
+ cleanup,
181
+ reason: b.reason ?? "",
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Render already-formatted rows as one padded, legible table (header + one
187
+ * row per branch + an indented `reason:` line — the reason text is often
188
+ * longer than any fixed column would comfortably hold). Pure — unit-tested.
189
+ * @param {ReturnType<typeof formatBranchRow>[]} rows
190
+ * @returns {string[]}
191
+ */
192
+ export function renderBranchesTable(rows) {
193
+ if (!rows.length) return ["(no branches)"];
194
+ const widths = COLUMNS.map(([key, label]) =>
195
+ Math.max(label.length, ...rows.map((r) => String(r[key] ?? "").length)),
196
+ );
197
+ const renderLine = (vals) =>
198
+ COLUMNS.map(([key], i) => String(vals[key] ?? "").padEnd(widths[i])).join(" ").trimEnd();
199
+ const lines = [renderLine(Object.fromEntries(COLUMNS.map(([key, label]) => [key, label])))];
200
+ for (const r of rows) {
201
+ lines.push(renderLine(r));
202
+ if (r.reason) lines.push(` reason: ${r.reason}`);
203
+ }
204
+ return lines;
205
+ }
206
+
207
+ /**
208
+ * Render the full `candidate_list` report: header, the table, then the
209
+ * server-computed summary/quarantine counts (never recomputed client-side —
210
+ * `candidate_list` already returns `summary` and `quarantined`). Pure —
211
+ * unit-tested.
212
+ * @param {any} report - the raw `candidate_list` result
213
+ * @returns {string[]}
214
+ */
215
+ export function renderBranchesReport(report) {
216
+ const lines = [];
217
+ const repoLabel = report?.repo || "(unknown repo)";
218
+ lines.push(
219
+ `Branches for ${repoLabel} (org ${report?.org || "?"}) — generated ${report?.generatedAtUtc || "(unknown)"} ` +
220
+ `(stale-after ${report?.staleAfterDays ?? "?"}d)`,
221
+ );
222
+ lines.push('NOTE: "actor" is not yet surfaced by the server\'s branch-cleanup report — shown as "—" below.');
223
+ lines.push("");
224
+ lines.push(...renderBranchesTable((report?.branches || []).map(formatBranchRow)));
225
+ lines.push("");
226
+ const summary = report?.summary || {};
227
+ const summaryParts = Object.entries(summary)
228
+ .map(([k, v]) => `${k}: ${v}`)
229
+ .join(", ");
230
+ lines.push(`Summary — ${report?.branches?.length ?? 0} branch(es): ${summaryParts || "(none)"}`);
231
+ if (Array.isArray(report?.quarantined) && report.quarantined.length) {
232
+ lines.push(
233
+ `Quarantined orphans (${report.quarantined.length}) — no PR record in any state; NEVER auto-deleted: ` +
234
+ report.quarantined.join(", "),
235
+ );
236
+ }
237
+ return lines;
238
+ }
239
+
240
+ /** @param {string[]} argv @param {any} ctx */
241
+ export async function run(argv, ctx) {
242
+ const env = process.env;
243
+ const args = parseBranchesArgs(argv);
244
+ if (args.help) {
245
+ console.log(USAGE);
246
+ return 0;
247
+ }
248
+
249
+ const { repo, tenant, error } = resolveRepoAndTenant(args, ctx);
250
+ if (error) {
251
+ console.error(error);
252
+ return 2;
253
+ }
254
+
255
+ const baseUrl = args.mcp || env.MCP_BASE_URL || env.TOT_MCP_URL || DEFAULT_MCP_URL;
256
+ const client = createMcpClient(baseUrl);
257
+ try {
258
+ await establishSession(client, { env, prefer: args.identity || undefined });
259
+ if (tenant) await client.callTool("client_switch", { tenant });
260
+
261
+ const report = await client.callTool("candidate_list", {
262
+ repo,
263
+ ...(args.staleAfterDays != null && Number.isFinite(args.staleAfterDays)
264
+ ? { staleAfterDays: args.staleAfterDays }
265
+ : {}),
266
+ });
267
+
268
+ if (report?.status === "error" || report?.status === "invalid_input" || report?.error) {
269
+ console.error(
270
+ fail(
271
+ `couldn't list branches for ${repo}: ${report.error || report.message || "unknown error"}`,
272
+ "check --tenant / --repo, then re-run",
273
+ ),
274
+ );
275
+ return 1;
276
+ }
277
+
278
+ if (args.json) {
279
+ console.log(JSON.stringify(report, null, 2));
280
+ return 0;
281
+ }
282
+ console.log(renderBranchesReport(report).join("\n"));
283
+ return 0;
284
+ } catch (e) {
285
+ if (e instanceof AuthUnavailableError) {
286
+ console.error(fail("sign in to list branches", e.hint || "run `tot login`, then re-run"));
287
+ return 1;
288
+ }
289
+ console.error(
290
+ fail(
291
+ `couldn't reach the candidate service: ${String(e?.message || e)}`,
292
+ "check your connection and that you're signed in, then re-run",
293
+ ),
294
+ );
295
+ return 1;
296
+ }
297
+ }
@@ -0,0 +1,264 @@
1
+ /**
2
+ * `tot cleanup` — owner-confirmed branch GC, per the
3
+ * branch-lifecycle-and-integration-preview contract's "Current gaps".
4
+ *
5
+ * `tot cleanup --dry-run` runs the SAME fresh server-side classification
6
+ * `tot branches` shows (the `candidate_list` MCP tool) and prints exactly
7
+ * which refs are eligible to delete and WHY — no writes, ever, no matter what
8
+ * else is passed. An owner-confirmed execution mode (`--yes`, or an
9
+ * interactive y/N via the shared plan affordance) then deletes ONLY that
10
+ * exact eligible set: one `candidate_delete` call per ref. The server
11
+ * RE-CLASSIFIES FRESH before every single delete (see branch-cleanup-tools.ts)
12
+ * — this CLI's dry-run read is a convenience for the human, never the source
13
+ * of truth the delete trusts.
14
+ *
15
+ * THE CONTRACT'S HARD RULES, ENFORCED SERVER-SIDE AND NEVER RELAXED HERE:
16
+ * - age alone NEVER makes an open candidate deletable (`stale-open` is a
17
+ * WARN bucket only);
18
+ * - `main`/`preview` classify as `protected` and are never eligible;
19
+ * - an `orphan` (no PR record in any state) is quarantined for owner
20
+ * review, never auto-deleted.
21
+ * This CLI does not re-derive eligibility — it only ever deletes a ref the
22
+ * server's `candidate_list` marked `eligibleForDelete: true` moments earlier,
23
+ * and the server independently re-checks that before acting.
24
+ *
25
+ * Dependency-free (global fetch via mcp.mjs's client + the shared plan module).
26
+ */
27
+ import { createMcpClient } from "../mcp.mjs";
28
+ import { establishSession, AuthUnavailableError } from "../auth.mjs";
29
+ import { fail } from "../errors.mjs";
30
+ import { planForAction, printPlanAndConfirm } from "../plan.mjs";
31
+ import { resolveRepoAndTenant, renderBranchesTable, formatBranchRow } from "./branches.mjs";
32
+
33
+ const DEFAULT_MCP_URL = "https://mcp.tokenoftrust.com";
34
+
35
+ const USAGE = `tot cleanup — owner-confirmed branch GC (deletes terminal candidate branches only)
36
+
37
+ tot cleanup --dry-run classify + print the eligible-to-delete set; delete nothing
38
+ tot cleanup classify, print the plan, then ask to confirm before deleting
39
+ tot cleanup --yes classify and delete the eligible set without prompting
40
+
41
+ Deletes ONLY branches the server just (re-)classified as "integrated" (PR
42
+ merged) or "closed-or-rejected" (PR closed without merging). NEVER deletes
43
+ by age alone, NEVER touches \`main\`/\`preview\`, and NEVER deletes an orphan
44
+ (no PR record) — orphans are reported, not removed. Reject closes the PR and
45
+ removes its hosted candidate artifact; cleanup deletes the terminal git ref.
46
+
47
+ Options:
48
+ --tenant <appDomain> Target tenant/repo. Defaults to the current
49
+ checkout's tenant when run inside one.
50
+ --repo <name> Explicit repo name, if it differs from --tenant.
51
+ --stale-after-days <n> Idle-day threshold for the "stale-open" warn
52
+ bucket. Defaults to the server's policy (14).
53
+ --ref <ref> Narrow deletion to exactly this one eligible ref
54
+ (still refused if it isn't eligible).
55
+ --dry-run Classify and print the eligible set; delete nothing.
56
+ --yes, -y Skip the confirmation prompt.
57
+ --mcp <url> MCP base URL (default: env MCP_BASE_URL / TOT_MCP_URL)
58
+ --identity <id> Prefer this cached identity over the default.
59
+ --help, -h Show this help.`;
60
+
61
+ /** Parse `tot cleanup` argv. Pure — unit-testable. */
62
+ export function parseCleanupArgs(argv) {
63
+ /** @type {{ tenant: string|null, repo: string|null, staleAfterDays: number|null, ref: string|null, dryRun: boolean, yes: boolean, mcp: string|null, identity: string|null, help: boolean }} */
64
+ const a = {
65
+ tenant: null,
66
+ repo: null,
67
+ staleAfterDays: null,
68
+ ref: null,
69
+ dryRun: false,
70
+ yes: false,
71
+ mcp: null,
72
+ identity: null,
73
+ help: false,
74
+ };
75
+ for (let i = 0; i < argv.length; i++) {
76
+ const t = argv[i];
77
+ if (t === "--tenant") a.tenant = argv[++i];
78
+ else if (t === "--repo") a.repo = argv[++i];
79
+ else if (t === "--stale-after-days") a.staleAfterDays = Number(argv[++i]);
80
+ else if (t === "--ref") a.ref = argv[++i];
81
+ else if (t === "--dry-run") a.dryRun = true;
82
+ else if (t === "--yes" || t === "-y") a.yes = true;
83
+ else if (t === "--mcp") a.mcp = argv[++i];
84
+ else if (t === "--identity") a.identity = argv[++i];
85
+ else if (t === "--help" || t === "-h") a.help = true;
86
+ }
87
+ return a;
88
+ }
89
+
90
+ /** Branches the fresh classification marked eligible. Pure. */
91
+ export function eligibleRefs(report) {
92
+ return (report?.branches || []).filter((b) => b.eligibleForDelete === true);
93
+ }
94
+
95
+ /** Branches the fresh classification quarantined (orphans). Pure. */
96
+ export function quarantinedRefs(report) {
97
+ return (report?.branches || []).filter((b) => b.quarantine === true);
98
+ }
99
+
100
+ /**
101
+ * Render the dry-run view: the same table `tot branches` renders, then the
102
+ * exact eligible set + why, then the quarantined orphans + why they are NOT
103
+ * in that set. Pure — unit-tested.
104
+ * @param {any} report
105
+ * @param {ReturnType<typeof eligibleRefs>} eligible
106
+ * @returns {string[]}
107
+ */
108
+ export function renderCleanupDryRun(report, eligible) {
109
+ const lines = [];
110
+ const repoLabel = report?.repo || "(unknown repo)";
111
+ lines.push(
112
+ `Branch cleanup classification for ${repoLabel} — generated ${report?.generatedAtUtc || "(unknown)"} ` +
113
+ `(stale-after ${report?.staleAfterDays ?? "?"}d)`,
114
+ );
115
+ lines.push("");
116
+ lines.push(...renderBranchesTable((report?.branches || []).map(formatBranchRow)));
117
+ lines.push("");
118
+ if (!eligible.length) {
119
+ lines.push("Eligible to delete: none.");
120
+ } else {
121
+ lines.push(`Eligible to delete (${eligible.length}):`);
122
+ for (const b of eligible) {
123
+ lines.push(` ${b.ref} (${b.sha || "—"})`);
124
+ lines.push(` reason: ${b.reason}`);
125
+ }
126
+ }
127
+ const quarantined = quarantinedRefs(report);
128
+ if (quarantined.length) {
129
+ lines.push("");
130
+ lines.push(
131
+ `Quarantined orphans (${quarantined.length}) — no PR record in any state; NOT deleted, needs owner review:`,
132
+ );
133
+ for (const b of quarantined) lines.push(` ${b.ref} (${b.sha || "—"})`);
134
+ }
135
+ return lines;
136
+ }
137
+
138
+ /** @param {string[]} argv @param {any} ctx */
139
+ export async function run(argv, ctx) {
140
+ const env = process.env;
141
+ const args = parseCleanupArgs(argv);
142
+ if (args.help) {
143
+ console.log(USAGE);
144
+ return 0;
145
+ }
146
+
147
+ const { repo, tenant, error } = resolveRepoAndTenant(args, ctx);
148
+ if (error) {
149
+ console.error(error);
150
+ return 2;
151
+ }
152
+
153
+ const baseUrl = args.mcp || env.MCP_BASE_URL || env.TOT_MCP_URL || DEFAULT_MCP_URL;
154
+ const client = createMcpClient(baseUrl);
155
+ try {
156
+ await establishSession(client, { env, prefer: args.identity || undefined });
157
+ if (tenant) await client.callTool("client_switch", { tenant });
158
+
159
+ const report = await client.callTool("candidate_list", {
160
+ repo,
161
+ ...(args.staleAfterDays != null && Number.isFinite(args.staleAfterDays)
162
+ ? { staleAfterDays: args.staleAfterDays }
163
+ : {}),
164
+ });
165
+
166
+ if (report?.status === "error" || report?.status === "invalid_input" || report?.error) {
167
+ console.error(
168
+ fail(
169
+ `couldn't classify branches for ${repo}: ${report.error || report.message || "unknown error"}`,
170
+ "check --tenant / --repo, then re-run",
171
+ ),
172
+ );
173
+ return 1;
174
+ }
175
+
176
+ let eligible = eligibleRefs(report);
177
+
178
+ if (args.ref) {
179
+ const only = eligible.find((b) => b.ref === args.ref);
180
+ if (!only) {
181
+ console.error(
182
+ fail(
183
+ `"${args.ref}" is not currently eligible for deletion`,
184
+ "run `tot cleanup --dry-run` to see the current eligible set",
185
+ ),
186
+ );
187
+ return 1;
188
+ }
189
+ eligible = [only];
190
+ }
191
+
192
+ console.log(renderCleanupDryRun(report, eligible).join("\n"));
193
+
194
+ if (args.dryRun) {
195
+ console.log("\nDry run — nothing was deleted.");
196
+ return 0;
197
+ }
198
+ if (!eligible.length) {
199
+ console.log("\nNothing eligible to delete.");
200
+ return 0;
201
+ }
202
+
203
+ const planLines = planForAction({
204
+ action: "cleanup",
205
+ tenant: /** @type {string} */ (tenant || repo),
206
+ refs: eligible.map((b) => ({ ref: b.ref, sha: b.sha, reason: b.reason })),
207
+ });
208
+ const { confirmed, reason } = await printPlanAndConfirm(planLines, {
209
+ yes: args.yes,
210
+ question: `Delete these ${eligible.length} eligible branch(es) now?`,
211
+ });
212
+ if (!confirmed) {
213
+ if (reason === "non-tty") {
214
+ console.error(
215
+ fail(
216
+ "refusing to delete branches without confirmation on a non-TTY.",
217
+ "re-run with --yes (an explicit human affirmative), or from an interactive terminal.",
218
+ ),
219
+ );
220
+ return 2;
221
+ }
222
+ console.log("Aborted — nothing was deleted.");
223
+ return 1;
224
+ }
225
+
226
+ let failures = 0;
227
+ for (const b of eligible) {
228
+ try {
229
+ const res = await client.callTool("candidate_delete", {
230
+ repo,
231
+ ref: b.ref,
232
+ expectedSha: b.sha,
233
+ });
234
+ if (res?.deleted) {
235
+ console.log(`✓ deleted ${b.ref}${res.alreadyAbsent ? " (already absent)" : ""}`);
236
+ } else {
237
+ failures++;
238
+ console.error(`✗ ${b.ref}: ${res?.error || res?.message || res?.status || "not deleted"}`);
239
+ }
240
+ } catch (e) {
241
+ failures++;
242
+ console.error(`✗ ${b.ref}: ${String(e?.message || e)}`);
243
+ }
244
+ }
245
+ if (failures) {
246
+ console.error(`\n${failures} of ${eligible.length} deletion(s) failed — see above.`);
247
+ return 1;
248
+ }
249
+ console.log(`\n✓ deleted ${eligible.length} branch(es).`);
250
+ return 0;
251
+ } catch (e) {
252
+ if (e instanceof AuthUnavailableError) {
253
+ console.error(fail("sign in to clean up branches", e.hint || "run `tot login`, then re-run"));
254
+ return 1;
255
+ }
256
+ console.error(
257
+ fail(
258
+ `couldn't reach the candidate service: ${String(e?.message || e)}`,
259
+ "check your connection and that you're signed in, then re-run",
260
+ ),
261
+ );
262
+ return 1;
263
+ }
264
+ }