Skip to main content

bynk/
cli.rs

1//! The `bynk` driver command-line interface.
2//!
3//! The developer front-end: `doctor` / `new` / `dev`, plus the everyday
4//! `check` / `fmt` / `test` (v0.138, #487). `check`, `compile`, `fmt` and `test` run the
5//! linked pipeline in-process.
6
7use std::path::PathBuf;
8
9use clap::{Args, Parser, Subcommand, ValueEnum};
10
11use crate::doctor::{Capability, DoctorOptions};
12use crate::report::Format;
13
14#[derive(Parser, Debug)]
15#[command(name = "bynk", version, about = "The Bynk driver", long_about = None)]
16pub struct Cli {
17    /// Don't print per-context progress from `build`, `dev` and `deploy`.
18    #[arg(short, long, global = true)]
19    pub quiet: bool,
20    /// When to colour output: `auto` colours a terminal unless `NO_COLOR` is
21    /// set, `always` colours a pipe or file too, and `never` doesn't colour.
22    /// Machine-readable formats are never coloured.
23    #[arg(
24        long = "color",
25        visible_alias = "colour",
26        value_name = "WHEN",
27        value_enum,
28        default_value_t,
29        global = true
30    )]
31    pub color: bynk_driver::colour::ColourChoice,
32    #[command(subcommand)]
33    pub command: Command,
34}
35
36/// The flags of `bynk eval` (#3585).
37#[derive(clap::Args, Debug, Clone)]
38pub struct EvalCommand {
39    /// Project directory. Defaults to the current directory.
40    #[arg(default_value = ".")]
41    pub input: PathBuf,
42    /// The unit (a `commons` or `context`, by dotted name) whose scope the
43    /// snippet is evaluated in.
44    #[arg(long)]
45    pub unit: String,
46    /// The snippet. When absent it is read from stdin.
47    #[arg(long)]
48    pub expr: Option<String>,
49    /// Evaluate against the unsaved buffers given as JSON on stdin, as
50    /// `bynk compile --sources-stdin` does: `{ "<absolute path>": "<text>" }`.
51    /// Stdin then holds the buffers, so the snippet must be `--expr`.
52    #[arg(long)]
53    pub sources_stdin: bool,
54    /// Build `--unit`'s own suite in, and evaluate the snippet inside it, so the
55    /// suite's `stub`s, `fn`s and fixtures apply. The value must be the unit
56    /// named by `--unit`. By default the project's own suites are left out.
57    #[arg(long, value_name = "UNIT")]
58    pub suite: Option<String>,
59    /// Kill the evaluation after this many seconds and report it timed out.
60    #[arg(long, value_name = "SECONDS", default_value_t = crate::eval::default_timeout_secs(), value_parser = clap::value_parser!(u64).range(1..))]
61    pub timeout: u64,
62}
63
64/// The headings `bynk --help` sorts its subcommands under, in order. clap has
65/// no subcommand headings of its own, so [`command`] renders this listing into
66/// the help template; every visible subcommand must appear exactly once.
67pub const COMMAND_GROUPS: &[(&str, &[&str])] = &[
68    (
69        "Project",
70        &[
71            "new", "check", "fmt", "test", "eval", "build", "compile", "openapi", "client", "token",
72        ],
73    ),
74    (
75        "Run and deploy",
76        &["dev", "deploy", "revert", "tail", "migrate"],
77    ),
78    (
79        "Dependencies",
80        &["add", "deps", "fetch", "update", "search", "approve"],
81    ),
82    (
83        "Publishing",
84        &["publish", "yank", "login", "logout", "org", "registry"],
85    ),
86    (
87        "Help and tooling",
88        &["doctor", "explain", "book", "mcp", "help"],
89    ),
90];
91
92/// The driver's clap command: [`Cli`]'s, with the top-level subcommands listed
93/// under [`COMMAND_GROUPS`] instead of in one flat block.
94pub fn command() -> clap::Command {
95    use clap::CommandFactory;
96
97    // Build first, so clap's implicit `help` subcommand is there to list.
98    let mut cmd = Cli::command();
99    cmd.build();
100    let styles = cmd.get_styles();
101    let (header, literal) = (*styles.get_header(), *styles.get_literal());
102    let width = COMMAND_GROUPS
103        .iter()
104        .flat_map(|(_, names)| names.iter())
105        .map(|name| name.len())
106        .max()
107        .unwrap_or(0);
108
109    let mut listing = String::new();
110    for (heading, names) in COMMAND_GROUPS {
111        listing.push_str(&format!("{header}{heading}:{header:#}\n"));
112        for name in *names {
113            let about = cmd
114                .find_subcommand(name)
115                .and_then(clap::Command::get_about)
116                .map(ToString::to_string)
117                .unwrap_or_default();
118            let pad = " ".repeat(width - name.len());
119            listing.push_str(&format!("  {literal}{name}{literal:#}{pad}  {about}\n"));
120        }
121        listing.push('\n');
122    }
123
124    cmd.help_template(format!(
125        "{{about-with-newline}}\n{{usage-heading}} {{usage}}\n\n{listing}\
126         {header}Options:{header:#}\n{{options}}{{after-help}}"
127    ))
128}
129
130#[derive(Subcommand, Debug)]
131pub enum Command {
132    /// Check this machine has the tools Bynk needs.
133    ///
134    /// Surveys what compiling, testing, and deploying need, and prints the
135    /// exact remedy for anything missing.
136    ///
137    /// Bare `bynk doctor` is informational: it surveys every capability and
138    /// exits 0 unless the compiler itself is unusable. `--only <capability>` gates on
139    /// one capability (exits non-zero if its tools are missing); `--strict`
140    /// turns every warning into a failure, for CI.
141    Doctor {
142        /// Project directory to inspect (for project-local `node_modules/.bin`
143        /// resolution). Defaults to the current directory.
144        #[arg(default_value = ".")]
145        input: PathBuf,
146        /// Scope the check — and the exit code — to one capability.
147        #[arg(long, value_enum)]
148        only: Option<CapabilityArg>,
149        /// Treat every warning (optional gaps, npx provisionability, minor
150        /// version skew) as a failure. For an all-green CI gate.
151        #[arg(long)]
152        strict: bool,
153        /// Output format. `human` (default) is a grouped table; `short` and
154        /// `json` are the stable scriptable surface.
155        #[arg(long, value_enum, default_value = "human")]
156        format: FormatArg,
157    },
158    /// Build and serve the project locally, rebuilding on save.
159    ///
160    /// One step in place of the manual compile + `cd` + `wrangler dev` recipe.
161    ///
162    /// Compiles into a managed `.bynk/dev/` build dir and runs one `wrangler
163    /// dev` per context from inside its worker dir, in local mode (Miniflare) —
164    /// no namespace provisioning needed. Every context is served by default and
165    /// the service bindings between them are wired (#552), so a cross-context
166    /// call resolves locally; `--context` narrows to a subset. While serving,
167    /// `.bynk` sources are watched (#524): saving a file rebuilds in place and
168    /// the running workers hot-reload; a failing rebuild reports errors and
169    /// keeps serving the last good build. Everything after `--` is forwarded to
170    /// `wrangler dev` verbatim.
171    ///
172    /// `bynk dev inspect` reads a running session (#3581): see its help.
173    #[command(args_conflicts_with_subcommands = true)]
174    Dev {
175        #[command(subcommand)]
176        sub: Option<DevSub>,
177        /// Project directory to serve from (anywhere inside the project; the
178        /// root is found by walking up for `bynk.toml`). Defaults to `.`.
179        #[arg(default_value = ".")]
180        path: PathBuf,
181        #[command(flatten)]
182        lock: LockArgs,
183        /// Which context to serve, repeatable. Omit to serve every context in
184        /// the project with the service bindings between them wired (#552);
185        /// pass one or more to narrow to a subset. Accepts the dotted name or
186        /// its dasherised worker-dir form.
187        #[arg(long = "context", value_name = "NAME")]
188        contexts: Vec<String>,
189        /// First port of the per-context allocation (context *i* gets
190        /// `--base-port` + *i*, in sorted order). Defaults to wrangler's 8787.
191        /// A single context left on the default keeps `-- --port N` working.
192        #[arg(long, value_name = "PORT")]
193        base_port: Option<u16>,
194        /// Serve with the V8 inspector enabled (slice 3, ADR 0104): `wrangler dev`
195        /// starts with `--inspector-port` so a JavaScript debugger can attach.
196        /// Breakpoints set in `.bynk` sources resolve through the emitted source
197        /// maps, composed into the worker bundle. Prints the inspector URL on start.
198        #[arg(long)]
199        inspect: bool,
200        /// First inspector port, allocated per context exactly as `--base-port`
201        /// is. Always honoured, even for one context. Without it the base is
202        /// 9229 under `--inspect` or with several contexts, and a single
203        /// context without `--inspect` gets a free port of its own, so
204        /// sessions started together do not collide on 9229.
205        #[arg(long, value_name = "PORT")]
206        inspect_port: Option<u16>,
207        /// Do not install the generated project's npm packages: stop, naming
208        /// the install command, when one is missing. For people who provision
209        /// `node_modules` themselves, and CI. Also set by `BYNK_NO_INSTALL=1`.
210        #[arg(long)]
211        no_install: bool,
212        /// Which `bynk.deploy.lock` environment `-- --remote` reads the KV id
213        /// from. `dev` never provisions, so this only selects among what
214        /// `bynk deploy --env NAME` already recorded — irrelevant without
215        /// `--remote`. Omit for today's single, unqualified default.
216        #[arg(long, default_value = "default", value_name = "NAME")]
217        env: String,
218        /// A Worker outside the project, named by a `Service` instance
219        /// (`@worker("NAME")`), to reach in your own locally running
220        /// `wrangler dev` of it rather than in the stand-in `dev` binds by
221        /// default. Repeatable.
222        #[arg(long = "local-worker", value_name = "NAME")]
223        local_workers: Vec<String>,
224        /// Output format. `human` (default) is the readable stream on stderr.
225        /// `json` adds one JSON event per line on stdout (`serving` with each
226        /// context's ports, `rebuilding`, `rebuild_ok`, `rebuild_failed`,
227        /// `stopped`), the stable scriptable surface for editors and CI.
228        #[arg(long, value_enum, default_value = "human")]
229        format: DevFormatArg,
230        /// Once every served context answers an HTTP probe, write
231        /// `{ "<worker>": "<url>" }` to FILE: the readiness signal for a test
232        /// runner or CI script. A stale FILE is removed at start, and FILE is
233        /// removed when the session stops.
234        #[arg(long, value_name = "FILE")]
235        ready_json: Option<PathBuf>,
236        #[command(flatten)]
237        stream: DevStreamArgs,
238        /// Arguments after `--`, forwarded to `wrangler dev` (e.g. `-- --remote`).
239        /// Ports are the driver's to allocate: use `--base-port` / `--inspect-port`.
240        #[arg(last = true)]
241        wrangler_args: Vec<String>,
242    },
243    /// Stream a deployed Worker's logs, mapped to `.bynk` sources.
244    ///
245    /// Runs `wrangler tail` with stack frames rewritten to `.bynk` locations,
246    /// as `bynk dev` does for the local server (#2546). The project is
247    /// compiled so the frames can be mapped through the emitter's source maps,
248    /// but nothing is deployed or provisioned. Everything after `--` is forwarded to `wrangler tail`.
249    Tail {
250        /// Project directory (anywhere inside the project). Defaults to `.`.
251        #[arg(default_value = ".")]
252        path: PathBuf,
253        #[command(flatten)]
254        lock: LockArgs,
255        /// Which context's Worker to tail. Optional when the project has one
256        /// context. Accepts the dotted name or its dasherised worker-dir form.
257        #[arg(long = "context", value_name = "NAME")]
258        context: Option<String>,
259        /// Which `bynk deploy --env` environment's Worker to tail.
260        #[arg(long, default_value = "default", value_name = "NAME")]
261        env: String,
262        /// Arguments after `--`, forwarded to `wrangler tail` (e.g.
263        /// `-- --status error`).
264        #[arg(last = true)]
265        wrangler_args: Vec<String>,
266    },
267    /// Provision Cloudflare resources and deploy every Worker.
268    ///
269    /// Each context's resources are provisioned and its Worker deployed; the
270    /// whole project ships in one command, in Service-Binding dependency
271    /// order — Cloudflare rejects a Worker uploaded before a Worker it binds
272    /// to. The generated configuration remains disposable: Cloudflare ids live
273    /// in the committed `bynk.deploy.lock`.
274    Deploy {
275        /// Project directory to deploy from. Defaults to the current directory.
276        #[arg(default_value = ".")]
277        path: PathBuf,
278        #[command(flatten)]
279        lock: LockArgs,
280        /// Deploy this context alone, assuming the contexts it consumes are
281        /// already live; a dependency that has never been deployed is reported
282        /// rather than pushed into. Accepts the dotted name or its dasherised
283        /// worker-dir form. Omit to deploy the whole project in order.
284        #[arg(long, value_name = "NAME", conflicts_with = "worker")]
285        context: Option<String>,
286        /// Deploy this Worker alone, by its directory name under `workers/`: a
287        /// `[deploy.workers.<key>]` group's key (the group is one Worker, so it
288        /// deploys, and rolls back, as a unit), or a context's dasherised name.
289        /// Like `--context`, it assumes the Workers it binds to are already live.
290        #[arg(long, value_name = "NAME")]
291        worker: Option<String>,
292        /// Target environment. Selects the `bynk.deploy.lock` section and,
293        /// for any value other than `default`, synthesises an environment-
294        /// scoped Wrangler config section (KV, queues, Service Bindings all
295        /// qualified) since Cloudflare does not inherit bindings into a named
296        /// environment. Omit to deploy today's single, unqualified default.
297        #[arg(long, default_value = "default", value_name = "NAME")]
298        env: String,
299        /// Print the provisioning and deploy plan without changing Cloudflare
300        /// or writing `bynk.deploy.lock`.
301        #[arg(long, visible_alias = "plan")]
302        dry_run: bool,
303        /// Do not install the generated project's npm packages: stop, naming
304        /// the install command, when one is missing. For people who provision
305        /// `node_modules` themselves, and CI. Also set by `BYNK_NO_INSTALL=1`.
306        #[arg(long)]
307        no_install: bool,
308        /// Plan output format. `short` is line-oriented; `json` is for CI.
309        #[arg(long, value_enum, default_value = "short")]
310        format: DeployFormatArg,
311        /// Skip the confirmation required before creating a namespace or
312        /// publishing a Worker. Required for non-interactive automation.
313        #[arg(long)]
314        yes: bool,
315        /// Read secret values from a dotenv-style `NAME=value` file. Supplies
316        /// both names and values; never committed, never persisted. Values move
317        /// to `wrangler secret put` and are dropped.
318        #[arg(long, value_name = "PATH")]
319        secrets_file: Option<PathBuf>,
320        /// Set this named secret, taking its value from the environment (or a
321        /// prompt). Repeatable. Use for a `bynk.Secrets` name, whose spelling
322        /// the compiler cannot know — an actor's declared `auth` secret needs no
323        /// flag. The environment is never scanned for names.
324        #[arg(long = "secret", value_name = "NAME")]
325        secrets: Vec<String>,
326        /// Overwrite a secret that is already set. The default sets only the
327        /// missing ones, so a re-deploy does not cut a fresh Cloudflare secret
328        /// version for every secret every time.
329        #[arg(long)]
330        force: bool,
331        /// Delete every reported orphan — a KV namespace or queue the ledger
332        /// remembers that the current build no longer declares. Never
333        /// deletes a Worker. Prompts separately from the creation
334        /// confirmation unless --yes is also given; omit to report only.
335        #[arg(long)]
336        prune: bool,
337        /// Confirm deleting this agent class's stored data, named as the plan
338        /// prints it (`<context>.<Class>`). Repeatable. A `removed agent`
339        /// declaration deletes data irreversibly, so `--yes` never stands in
340        /// for this.
341        #[arg(long = "confirm-delete", value_name = "CONTEXT.CLASS")]
342        confirm_delete: Vec<String>,
343        /// Let this context start with fresh agent state on another Worker script
344        /// than the one it was last deployed to (into or out of a
345        /// `[deploy.workers.<key>]` group, or after a group is renamed or re-keyed).
346        /// An agent's state belongs to its script, so without this such a move is
347        /// refused (`bynk.deploy.agent_move_refused`); with it the old state stays
348        /// in the old script, which the plan then reports as holding data.
349        /// Repeatable; each context is named, never a blanket.
350        #[arg(long = "accept-fresh-agent", value_name = "CONTEXT")]
351        accept_fresh_agent: Vec<String>,
352        /// With `--context`: deploy a callee ahead of live callers still on an
353        /// older contract, when every such change is compatible for them. The
354        /// older contracts are recorded in `bynk.contracts.lock` (commit it),
355        /// and the callee answers them until the callers are redeployed. A
356        /// breaking change, and a caller ahead of its live callee, are
357        /// refused as before.
358        #[arg(long, requires = "context")]
359        accept_compatible_skew: bool,
360        /// Arguments after `--`, forwarded to `wrangler deploy` verbatim.
361        #[arg(last = true)]
362        wrangler_args: Vec<String>,
363    },
364    /// Scaffold a new project.
365    ///
366    /// The project is a complete, runnable single-context HTTP service you can
367    /// serve immediately with `bynk dev`.
368    ///
369    /// Writes a `bynk.toml`, a `.gitignore`, and `src/<name>.bynk` into a new
370    /// directory. Pure offline file-writing — it shells nothing and needs no
371    /// toolchain, so you can run it before Node or `wrangler` are
372    /// installed. The project name defaults to the target directory's final
373    /// component; `--name` overrides it and must be a legal Bynk identifier.
374    New {
375        /// Directory to create for the new project (e.g. `hello` or `./hello`).
376        path: PathBuf,
377        /// Project name / context identifier. Defaults to PATH's final
378        /// component; must be a legal Bynk identifier (a letter followed by
379        /// letters, digits, or underscores).
380        #[arg(long)]
381        name: Option<String>,
382    },
383    /// Type-check a file or project.
384    ///
385    /// Writes no output.
386    ///
387    /// Runs the compiler pipeline in-process.
388    Check {
389        /// Input `.bynk` file or project root. Defaults to the current directory.
390        #[arg(default_value = ".")]
391        input: PathBuf,
392        /// Diagnostic output format. `rich` (default) is the ariadne
393        /// source-context rendering; `short` emits one terse
394        /// `path:line:col: severity[category]: message` line per diagnostic,
395        /// for tooling (the VS Code problem-matcher, CI, scripts).
396        /// In both, `path` is the file as you'd type it from the working
397        /// directory (the input you passed, joined with the file's place in
398        /// it), the same path `fmt` reports.
399        #[arg(long, value_enum, default_value = "rich")]
400        format: CheckFormatArg,
401        /// Apply the machine-applicable fix suggestions to the sources, in
402        /// place, before checking (#2642): the same fixes the editor's
403        /// "fix all" applies, repeated until none remain. Writes only files
404        /// that change, does not format, and writes nothing if applying the
405        /// fixes would leave a problem that needs a human. What remains is
406        /// reported as usual. `--fix=<code>[,<code>…]` takes only the fixes of
407        /// the named diagnostic codes (a hint's too, when named): for a single
408        /// migration, such as an upgrade note's one change. An unknown code is
409        /// an error that names the nearest real one (#3537).
410        #[arg(
411            long,
412            value_name = "CODE",
413            num_args = 0..,
414            require_equals = true,
415            value_delimiter = ','
416        )]
417        fix: Option<Vec<String>>,
418        /// After a passing check, generate the Workers TypeScript into a
419        /// temporary directory and type-check it with `tsc` (#3068). A failure
420        /// is reported as `bynk.codegen.tsc_failed` at the Bynk source the
421        /// failing line came from: it is a compiler bug. Needs `tsc` (with
422        /// Node.js); slower than a plain check, so off by default. Project
423        /// directories only.
424        #[arg(long)]
425        emit: bool,
426        /// Run over each project directly inside a directory that has no
427        /// `bynk.toml` of its own (#3274): as at a `[workspace]` root, one
428        /// report per project under a `── path ──` header, every project run,
429        /// and a non-zero exit if any fails. A subdirectory without a
430        /// `bynk.toml` is not a project and is skipped. At a workspace root
431        /// it changes nothing; at a project, or inside one, it is an error.
432        #[arg(long)]
433        each: bool,
434        #[command(flatten)]
435        lock: LockArgs,
436    },
437    /// Build a project from its `[build]` settings.
438    ///
439    /// Needs no flags: `out`, `target`, `platform` and `emit` come from the
440    /// `[build]` table, else the defaults (`out`, `bundle`, `cloudflare`,
441    /// `ts`), and a flag overrides its key. `build` infers from the project;
442    /// `bynk compile` is told, and never reads `[build]`.
443    Build {
444        /// Project directory. Defaults to the current directory.
445        #[arg(default_value = ".")]
446        input: PathBuf,
447        /// Output directory. Overrides `[build] out`.
448        #[arg(short, long)]
449        out: Option<PathBuf>,
450        /// Build target. Overrides `[build] target`.
451        #[arg(long, value_enum)]
452        target: Option<bynk_driver::CliTarget>,
453        /// Deploy platform. Overrides `[build] platform`.
454        #[arg(long, value_enum)]
455        platform: Option<bynk_driver::CliPlatform>,
456        /// Artefact language. Overrides `[build] emit`.
457        #[arg(long, value_enum)]
458        emit: Option<bynk_driver::EmitFormat>,
459        /// Build profile: `release` (the default, no contract checks) or `dev`
460        /// (contract checks on). `[profile.<name>]` overrides its defaults.
461        #[arg(long, value_enum)]
462        profile: Option<bynk_driver::CliProfile>,
463        #[command(flatten)]
464        lock: LockArgs,
465    },
466    /// Compile a project to TypeScript, settings as flags.
467    ///
468    /// Use `bynk build` for a project that takes its settings from `bynk.toml`.
469    /// Runs in-process (#2471, #2998).
470    ///
471    /// The compiler is linked in. With `--sources-stdin` it compiles unsaved editor buffers:
472    /// a JSON object `{ "<absolute path>": "<text>" }`
473    /// on stdin wins over the files on disk, and `bynk.schema.lock` is neither
474    /// read nor written. What "Bynk: Show Compiled Output" runs.
475    Compile {
476        /// Project directory, or one `.bynk` file. Defaults to the current
477        /// directory.
478        #[arg(default_value = ".")]
479        input: PathBuf,
480        /// Output root directory (the output file, for a single-file input).
481        #[arg(short, long)]
482        output: PathBuf,
483        /// Build target. `bundle` (default) produces a single deployment
484        /// unit; `workers` produces one Cloudflare Worker per context with
485        /// Service Binding plumbing.
486        #[arg(long, value_enum, default_value = "bundle")]
487        target: bynk_driver::CliTarget,
488        /// Deploy platform selecting the `bynk` surface binding: `cloudflare`
489        /// (default), `node`, or `browser` (`bundle` topology only).
490        #[arg(long, value_enum, default_value = "cloudflare")]
491        platform: bynk_driver::CliPlatform,
492        /// Artefact language. `ts` (default) writes typed TypeScript; `js`
493        /// writes the same modules with types stripped, runnable with no `tsc`
494        /// in the loop.
495        #[arg(long, value_enum, default_value = "ts")]
496        emit: bynk_driver::EmitFormat,
497        /// Compile the unsaved buffers given as JSON on stdin (see above).
498        #[arg(long)]
499        sources_stdin: bool,
500        #[command(flatten)]
501        lock: LockArgs,
502    },
503    /// Write a typed TypeScript client for the HTTP services.
504    ///
505    /// One module a front end (SvelteKit, Next.js, anything that can `fetch`)
506    /// imports (#3508): one function per `from http` route, the boundary types as
507    /// TypeScript types, and the same refinement checks the server runs, on the
508    /// way out and on the way in. Each call returns a union of the route's own
509    /// responses keyed by `status`, or a `CallFailure`; nothing is thrown for an
510    /// HTTP status. An optional value is `T | null`.
511    ///
512    /// The module carries a small browser-safe runtime, so it needs nothing
513    /// installed. Pass it your own `fetch`, a `baseUrl` and `headers`:
514    /// `createClient({ baseUrl, fetch, headers })`. Writes to stdout unless
515    /// `--out` is given. The project must check clean. Experimental: member names
516    /// may change in a minor version until it is stabilised.
517    ///
518    /// Routes the client cannot represent yet (raw bodies, raw and streamed
519    /// responses) are named on stderr and left out. `bynk openapi` is the language-neutral contract and stays.
520    Client {
521        /// Project directory (or any path inside it). Defaults to the current
522        /// directory.
523        #[arg(default_value = ".")]
524        input: PathBuf,
525        /// Write the client to PATH instead of stdout: a `.ts` file, or with
526        /// `--layout dir` a directory. Defaults to `[build.client]` `out` in
527        /// bynk.toml.
528        #[arg(short, long)]
529        out: Option<PathBuf>,
530        /// Generate only this `from http` service (`Name` or `unit.Name`); may be
531        /// given more than once. Defaults to `[build.client]` `service`, else every
532        /// one.
533        #[arg(long)]
534        service: Vec<String>,
535        /// `file` (default) writes one module; `dir` writes `index.ts`,
536        /// `types.ts`, `codecs.ts` and `runtime.ts` into `--out`. Defaults to
537        /// `[build.client]` `layout`.
538        #[arg(long, value_enum)]
539        layout: Option<ClientLayoutArg>,
540        /// Write nothing: compare the client at `--out` with the one the project
541        /// generates, and exit non-zero, naming where they differ, when it is
542        /// stale or missing. The CI drift gate.
543        #[arg(long)]
544        check: bool,
545        #[command(flatten)]
546        lock: LockArgs,
547    },
548    /// Write an OpenAPI document for the project's HTTP services.
549    ///
550    /// An OpenAPI 3.1 document for every `from http` service (#856): paths
551    /// and methods from the routes, parameters and request bodies from the
552    /// handler params, and responses keyed by the exact status codes
553    /// the handlers can return — the 2xx body and each error variant a handler
554    /// constructs, plus the `400` the boundary itself answers.
555    ///
556    /// Schemas come from the same boundary-shape derivation the emitted codecs
557    /// use, so a refinement (`String where NonEmpty`) becomes the JSON Schema
558    /// constraint it re-validates (`minLength: 1`) and the spec cannot drift
559    /// from the handlers. Writes to stdout unless `--out` is given, so it
560    /// composes in CI. The project must check clean.
561    Openapi {
562        /// Project directory (or any path inside it). Defaults to the current
563        /// directory.
564        #[arg(default_value = ".")]
565        input: PathBuf,
566        /// Document only this `from http` service (`Name` or `unit.Name`).
567        /// Defaults to every one.
568        #[arg(long)]
569        service: Option<String>,
570        /// Write the document to FILE instead of stdout.
571        #[arg(short, long)]
572        out: Option<PathBuf>,
573        /// Output format. Defaults to `yaml` when `--out` ends in `.yaml` or
574        /// `.yml`, otherwise `json`.
575        #[arg(long, value_enum)]
576        format: Option<OpenapiFormatArg>,
577        #[command(flatten)]
578        lock: LockArgs,
579    },
580    /// Mint a credential for the project's own Bearer actor.
581    ///
582    /// For calling a `Bearer`-guarded route by hand — `curl` under `bynk dev`,
583    /// or a smoke test against a deployment. Prints the token alone on stdout,
584    /// so `$(bynk token Reader --sub me)` works.
585    ///
586    /// This is not `bynk org token mint`, which mints a registry **publish**
587    /// token for `bynk publish`. `bynk token` signs an HS256 JWT for an `actor`
588    /// *this project* declares, exactly as that actor's emitted seam verifies it.
589    ///
590    /// The secret is read from the environment under the name the actor declares
591    /// (`auth = Bearer(secret = "API_TOKEN_SECRET")` → `$API_TOKEN_SECRET`),
592    /// never from an argument, and is never printed. `--sub` is checked against
593    /// the actor's identity type, refinements included, before signing. Only
594    /// `Bearer` actors are supported: a `Signature` actor signs a request body,
595    /// and an `Oidc` actor's tokens come from the identity provider. With no
596    /// actor, lists the project's Bearer actors and the secret each reads.
597    ///
598    /// A refinement actor (`actor Moderator = Reader where hasClaim("mod")`)
599    /// signs with its base's secret and carries the claims its predicate needs,
600    /// as the `system` test harness does for `by Moderator("x")`. A predicate
601    /// that no claims satisfy is refused. `--claim name[=value]` (repeatable)
602    /// adds claims to any actor's token, and replaces a claim the predicate
603    /// would have set, so the seam's `403` can be tested.
604    ///
605    /// The default lifetime is 1 hour; `--lifetime` (up to 365d) sets another.
606    /// `--expired` and `--not-before` mint tokens the seam must refuse, for
607    /// testing the refusals.
608    Token {
609        /// The actor to mint for (`Name` or `unit.Name`). Omit to list the
610        /// project's Bearer actors.
611        actor: Option<String>,
612        /// The identity the token names — its `sub` claim.
613        #[arg(long)]
614        sub: Option<String>,
615        /// How long the token is valid, like `15m`, `1h` or `30d` (default
616        /// `1h`, at most `365d`). Counted from `--not-before` when that is set.
617        #[arg(long, conflicts_with = "expired")]
618        lifetime: Option<String>,
619        /// Mint a token that expired an hour ago, to test that the seam
620        /// refuses it.
621        #[arg(long)]
622        expired: bool,
623        /// Start the token's validity this long from now, like `10m`, to test
624        /// that the seam refuses a token not yet valid.
625        #[arg(long, conflicts_with = "expired")]
626        not_before: Option<String>,
627        /// Add a claim to the token: `name` signs `true`, `name=value` signs
628        /// the string. Repeatable. Not `sub`, `iat`, `exp`, `nbf`, `iss` or
629        /// `aud`, which `bynk token` signs itself.
630        #[arg(long = "claim", value_name = "NAME[=VALUE]")]
631        claims: Vec<String>,
632        /// Project directory (or any path inside it). Defaults to the current
633        /// directory.
634        #[arg(long, default_value = ".")]
635        input: PathBuf,
636        #[command(flatten)]
637        lock: LockArgs,
638    },
639    /// Format `.bynk` source files.
640    ///
641    /// Formats in place. Passing `-` reads from stdin and writes to stdout.
642    ///
643    /// Runs the formatter in-process.
644    ///
645    /// `--indent`, `--indent-width`, `--max-line-width` and
646    /// `--no-trailing-comma` override the canonical style for this run; with
647    /// none of them the output is the canonical formatting.
648    Fmt {
649        #[command(flatten)]
650        args: bynk_driver::FmtArgs,
651    },
652    /// Run the project's tests.
653    ///
654    /// Discovers and runs test declarations.
655    ///
656    /// Runs in-process. Requires `tsc` (with Node.js) or `tsx` on PATH.
657    Test {
658        #[command(flatten)]
659        args: Box<bynk_driver::test_runner::TestArgs>,
660        #[command(flatten)]
661        lock: LockArgs,
662    },
663    /// Evaluate a snippet in a unit's scope; print its value.
664    ///
665    /// Compiles and runs the snippet as a synthetic test case in a suite for
666    /// `--unit`, under the test runtime, and prints
667    /// `{"value": <wire shape>, "type": "…", "diagnostics": […]}` (#3585). The
668    /// snippet is `--expr`, or stdin; its last expression is the value. Leading
669    /// `consumes` and `stub` lines belong to the suite, so a snippet that uses
670    /// another unit `consumes` it, as a suite does. A capability the snippet
671    /// calls needs a `stub`; nothing reaches the network. Each evaluation is
672    /// independent: send earlier cells' `let`s again ahead of the snippet.
673    ///
674    /// The project's own suites are left out of the build, so a suite that does
675    /// not compile cannot block an evaluation. `--suite <UNIT>` builds `--unit`'s
676    /// own suite in and puts the snippet inside it, so the suite's `stub`s
677    /// and `fn`s apply; its errors are then reported.
678    ///
679    /// Runs in-process, with the build and runner of `bynk test`; requires
680    /// `tsc` (with Node.js) or `tsx` on PATH. The exit status is zero only when
681    /// there is a value.
682    Eval {
683        #[command(flatten)]
684        args: EvalCommand,
685        #[command(flatten)]
686        lock: LockArgs,
687    },
688    /// Fetch dependencies and write `bynk.lock`.
689    ///
690    /// Resolves the project's dependencies, fetches the git ones missing from
691    /// the store, and writes `bynk.lock` (#2240). `check`, `test`, `dev` and
692    /// `deploy` do this first anyway; `fetch` does only this — warm the store
693    /// before an `--offline` CI step, or after editing `[dependencies]`.
694    Fetch {
695        /// Project (or workspace) directory. Defaults to `.`.
696        #[arg(default_value = ".")]
697        path: PathBuf,
698        #[command(flatten)]
699        lock: LockArgs,
700        /// Output format. `json` prints one document on stdout (#2472).
701        #[arg(long, value_enum, default_value_t)]
702        format: DeployFormatArg,
703    },
704    /// Move git dependencies to their latest revisions.
705    ///
706    /// Re-resolves git dependencies' revisions — a branch that moved upstream
707    /// — and rewrites `bynk.lock` (#2240). Name aliases or packages to update only
708    /// those; with none, every git dependency is re-resolved.
709    Update {
710        /// The aliases or `org/package` names to update. All when omitted.
711        #[arg(value_name = "DEPENDENCY")]
712        names: Vec<String>,
713        /// Project (or workspace) directory.
714        #[arg(long, default_value = ".")]
715        path: PathBuf,
716    },
717    /// Make a Worker's previous deployment live again.
718    ///
719    /// Needs no rebuild. Drives Cloudflare's version rollback after checking what makes it
720    /// unsafe: D1 migrations the live version applied, agent state stamped
721    /// with a newer schema version, contract skew against the other live
722    /// Workers, a replaced resource id, a secret change. Every unknown is a
723    /// refusal, and a refusal changes nothing. Reads Cloudflare even with
724    /// `--dry-run`, so it needs `CLOUDFLARE_API_TOKEN` (with D1 read access)
725    /// and `CLOUDFLARE_ACCOUNT_ID`. Only versions deployed by a `bynk` that
726    /// records deploy facts can be reverted; for any other, redeploy the tag.
727    Revert {
728        /// Project directory. Defaults to the current directory.
729        #[arg(default_value = ".")]
730        path: PathBuf,
731        /// Revert this context alone (dotted name or Worker directory).
732        /// Default: every Worker the ledger records for the environment.
733        #[arg(long, value_name = "NAME", conflicts_with = "worker")]
734        context: Option<String>,
735        /// Revert this Worker alone, by its directory name: a
736        /// `[deploy.workers.<key>]` group's key, or a context's dashed name. A
737        /// group is one script, so every member goes back together.
738        #[arg(long, value_name = "NAME")]
739        worker: Option<String>,
740        /// The environment to revert.
741        #[arg(long, default_value = "default", value_name = "NAME")]
742        env: String,
743        /// Go back to this Cloudflare Worker version id instead of the
744        /// deployment before the live release. Needs `--context`, since
745        /// a version id belongs to one Worker. The same checks apply.
746        #[arg(long, value_name = "VERSION")]
747        to: Option<String>,
748        /// Print each check's verdict and stop. Still reads Cloudflare.
749        #[arg(long, visible_alias = "plan")]
750        dry_run: bool,
751        /// Plan output format. `short` is line-oriented; `json` is for CI.
752        #[arg(long, value_enum, default_value = "short")]
753        format: DeployFormatArg,
754        /// Skip the confirmation. Required for non-interactive runs. Never
755        /// overrides a refusal.
756        #[arg(long)]
757        yes: bool,
758        /// Assert that the D1 migrations applied after the target was built
759        /// are additive, for this binding (`D1_ORDERS`). Repeatable.
760        #[arg(long = "accept-schema-ahead", value_name = "BINDING")]
761        accept_schema_ahead: Vec<String>,
762        /// Accept secret changes between the target and now (a `bynk migrate
763        /// sweep` makes two).
764        #[arg(long)]
765        accept_secret_changes: bool,
766    },
767    /// Inspect and migrate agents' stored state.
768    ///
769    /// `status` reports where each agent class's stored state stands; `sweep`
770    /// migrates every stored instance so old `migrate` steps can retire.
771    Migrate {
772        #[command(subcommand)]
773        command: MigrateCommand,
774    },
775    /// Add a registry dependency to `bynk.toml`.
776    ///
777    /// Adds (#2274) the highest version its registry offers (or one matching
778    /// `@<range>`), written as `<alias> = { package = "…", version = "^…" }`,
779    /// then resolved and locked.
780    Add {
781        /// `org/package`, optionally `@<range>` (`acme/money@^1.4`).
782        #[arg(value_name = "PACKAGE")]
783        package: String,
784        /// The alias to reach it by; defaults to the package segment.
785        #[arg(long = "as", value_name = "ALIAS")]
786        alias: Option<String>,
787        /// Project directory.
788        #[arg(long, default_value = ".")]
789        path: PathBuf,
790        /// Output format. `json` prints the entry written on stdout (#2472).
791        #[arg(long, value_enum, default_value_t)]
792        format: DeployFormatArg,
793    },
794    /// Look up a package's versions on its registry.
795    ///
796    /// Asks the registry its organisation routes to (#2472) for every version
797    /// its index lists, with the newest usable one. An exact `org/package`
798    /// lookup — a registry's index has no free-text search.
799    Search {
800        /// `org/package`.
801        #[arg(value_name = "PACKAGE")]
802        package: String,
803        /// The project whose `[registries]` route the organisation.
804        #[arg(long, default_value = ".")]
805        path: PathBuf,
806        /// Output format. `json` is for scripts and editors.
807        #[arg(long, value_enum, default_value_t)]
808        format: DeployFormatArg,
809    },
810    /// List dependencies and their locked versions.
811    ///
812    /// What `bynk.lock` resolved each of the project's dependencies to (#2472).
813    /// Offline.
814    Deps {
815        /// Project directory.
816        #[arg(long, default_value = ".")]
817        path: PathBuf,
818        /// Output format. `json` is for scripts and editors.
819        #[arg(long, value_enum, default_value_t)]
820        format: DeployFormatArg,
821    },
822    /// Publish this package to its registry.
823    ///
824    /// Publishes to the registry its organisation routes to (#2287): check it,
825    /// pack it, upload it through the registry's publish API, and verify the
826    /// signed line the registry returns.
827    Publish {
828        /// The package directory.
829        #[arg(long, default_value = ".")]
830        path: PathBuf,
831        /// Check and pack, and report what would be published, without
832        /// uploading.
833        #[arg(long)]
834        dry_run: bool,
835        /// Refuse, before uploading anything, unless the package packs to
836        /// exactly this checksum (the one a `--dry-run` reported).
837        #[arg(long, value_name = "CHECKSUM")]
838        expect_checksum: Option<String>,
839        /// Output format. `json` prints the package, version, registry and
840        /// file list on stdout (#2472).
841        #[arg(long, value_enum, default_value_t)]
842        format: DeployFormatArg,
843    },
844    /// Yank a published version.
845    ///
846    /// Yanks through the registry's publish API (#2287): the version is kept
847    /// for locked builds, but never newly chosen.
848    Yank {
849        /// `org/package`.
850        package: String,
851        /// The version.
852        version: String,
853        /// Clear the yank instead.
854        #[arg(long)]
855        undo: bool,
856        /// The project whose `[registries]` route the organisation.
857        #[arg(long, default_value = ".")]
858        path: PathBuf,
859    },
860    /// Sign in to a registry.
861    ///
862    /// Signs in to a registry's accounts (#2378) through GitHub's device flow,
863    /// and keeps the account token in the credentials file.
864    Login {
865        #[command(flatten)]
866        target: AccountTarget,
867    },
868    /// Sign out of a registry.
869    ///
870    /// Signs out of a registry's accounts (#2378), here and on the server.
871    Logout {
872        #[command(flatten)]
873        target: AccountTarget,
874    },
875    /// Manage a registry organisation, its members and tokens.
876    ///
877    /// For a registry with accounts (#2378): claim and block an organisation,
878    /// add and remove members, mint and revoke publish tokens.
879    Org {
880        #[command(subcommand)]
881        command: OrgCommand,
882    },
883    /// Approve the npm packages that dependencies bring in.
884    ///
885    /// Reviews and approves the npm packages that git and registry
886    /// dependencies' adapters bring into the build (#2296), recording each
887    /// approval in `bynk.lock`. With no package, asks about each pending one.
888    Approve {
889        /// Approve this npm package's pending requirements.
890        #[arg(conflicts_with_all = ["all", "list"])]
891        package: Option<String>,
892        /// Approve every pending requirement without asking.
893        #[arg(long, conflicts_with = "list")]
894        all: bool,
895        /// List pending and approved requirements; change nothing.
896        #[arg(long)]
897        list: bool,
898        /// With `--list`: `short` (default) is one line per requirement;
899        /// `json` is one document for tooling (the editor's review).
900        #[arg(long, value_enum, default_value = "short", requires = "list")]
901        format: DeployFormatArg,
902        /// Project (or workspace) directory.
903        #[arg(long, default_value = ".")]
904        path: PathBuf,
905    },
906    /// Build and maintain a static package registry.
907    ///
908    /// The registry lives in a directory (#2274), served by any static host
909    /// or read as a `file://` index.
910    Registry {
911        #[command(subcommand)]
912        command: RegistryCommand,
913    },
914    /// Explain a diagnostic code.
915    ///
916    /// Prints the longer-form "what the rule is, why it exists, and how to fix
917    /// it" behind a `bynk.*` error code (#853).
918    ///
919    /// Prints a curated blurb, a minimal before/after example, and a link to
920    /// the relevant Book concept page. The blurb is offline-complete, so the
921    /// substance is available without network. Codes without a curated
922    /// explanation report that gracefully; an unrecognised code exits non-zero.
923    /// The same explanations back the editor's clickable diagnostic-code links.
924    Explain {
925        /// The diagnostic code to explain, e.g. `bynk.resolve.unknown_type`.
926        #[arg(value_name = "CODE")]
927        code: String,
928    },
929    /// Serve toolchain answers to an AI agent over MCP.
930    ///
931    /// Read-only answers over the Model Context Protocol (#2466), on
932    /// stdin/stdout.
933    ///
934    /// Eight tools: diagnostics, a symbol's type and definition, a unit's
935    /// documentation, the project's architecture, a handler's wire contract,
936    /// a diagnostic explanation, a project check, and a search of the Book. Each answers in compact
937    /// Markdown with `path:line:column` locations relative to PATH. Nothing is
938    /// written, and `file` arguments cannot leave PATH. Point an MCP client at
939    /// `bynk mcp` (see the tooling docs for per-client set-up).
940    Mcp {
941        /// The workspace the tools may read. Defaults to the current directory.
942        #[arg(default_value = ".")]
943        path: PathBuf,
944    },
945    /// Print or search the Bynk Book.
946    ///
947    /// The whole Book, every page in reading order, is embedded in this build
948    /// (#2463), so it matches the `bynk` you run and works offline. With no arguments it
949    /// prints the Book, its first line naming the toolchain version. With
950    /// `--search <QUERY>` it prints the best-matching sections instead, each
951    /// with its page link. Used by the editor's `bynk_search_book`
952    /// language-model tool; a build made without the bundle says so and exits
953    /// non-zero.
954    Book {
955        /// Print the sections of the Book that best match these words.
956        #[arg(long, value_name = "QUERY")]
957        search: Option<String>,
958        /// With `--search`: `text` (Markdown, the default) or `json`.
959        #[arg(
960            long,
961            value_name = "FORMAT",
962            default_value = "text",
963            requires = "search"
964        )]
965        format: BookFormat,
966    },
967}
968
969/// `bynk migrate`'s subcommands (state-migrations S4, #2259).
970#[derive(Subcommand, Debug)]
971pub enum MigrateCommand {
972    /// Each agent class's recorded version and floor, its `migrate` steps and
973    /// the versions they cover, any version with no path forward, and the
974    /// environments a floor-raising sweep must cover. Offline: reads
975    /// `bynk.schema.lock`, the source, and `bynk.deploy.lock`.
976    Status {
977        /// Project directory. Defaults to the current directory.
978        #[arg(default_value = ".")]
979        path: PathBuf,
980        #[command(flatten)]
981        lock: LockArgs,
982        /// Output format. `json` is for scripts.
983        #[arg(long, value_enum, default_value = "short")]
984        format: DeployFormatArg,
985    },
986    /// Wake every stored instance of the project's agent classes in the
987    /// deployed Workers, so each migrates to its class's current version, and
988    /// raise each class's floor when the run covered every environment
989    /// `bynk.deploy.lock` records.
990    ///
991    /// Lists the instances through Cloudflare's API, so it needs
992    /// `CLOUDFLARE_API_TOKEN` (with "Workers Scripts: Edit") and
993    /// `CLOUDFLARE_ACCOUNT_ID`. Each Worker gets a temporary secret,
994    /// `BYNK_MIGRATE_KEY`, for the run; setting and deleting it each create a
995    /// Worker version.
996    Sweep {
997        /// Project directory. Defaults to the current directory.
998        #[arg(default_value = ".")]
999        path: PathBuf,
1000        /// Sweep this context's classes alone (dotted name or Worker
1001        /// directory). A floor rises only for the classes swept.
1002        #[arg(long, value_name = "NAME")]
1003        context: Option<String>,
1004        /// Sweep this environment. Repeatable. Omit to sweep every environment
1005        /// the ledger records; a narrower run migrates but raises no floor.
1006        #[arg(long = "env", value_name = "NAME")]
1007        environments: Vec<String>,
1008        /// Instances woken per request to a Worker. The default keeps within
1009        /// the Free plan's 50 subrequests per invocation.
1010        #[arg(long, default_value_t = 40, value_parser = clap::value_parser!(u16).range(1..=1000))]
1011        batch: u16,
1012        /// Where a Worker that does not serve on `workers.dev` is reached, as
1013        /// `<deployed Worker name>=https://<host>`. Repeatable.
1014        #[arg(long = "url", value_name = "WORKER=URL")]
1015        urls: Vec<String>,
1016        /// Skip the confirmation. Required for non-interactive runs.
1017        #[arg(long)]
1018        yes: bool,
1019    },
1020}
1021
1022/// `bynk check --format` selector (rich/short).
1023#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
1024pub enum CheckFormatArg {
1025    /// Ariadne rendering with full source context (the default).
1026    #[default]
1027    Rich,
1028    /// One terse `path:line:col: severity[category]: message` line per
1029    /// diagnostic — for the VS Code problem-matcher, CI, and scripts.
1030    Short,
1031}
1032
1033/// `--only` selector. Mirrors [`Capability`] minus the internal distinctions.
1034#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
1035pub enum CapabilityArg {
1036    /// Compile / check / fmt.
1037    Compile,
1038    /// `bynk test` — Node + tsc|tsx.
1039    Test,
1040    /// dev / deploy to Cloudflare — Node + wrangler.
1041    Deploy,
1042    /// Editor support — bynk-lsp.
1043    Editor,
1044    /// Build Bynk from source — a Rust toolchain.
1045    Build,
1046}
1047
1048impl From<CapabilityArg> for Capability {
1049    fn from(a: CapabilityArg) -> Self {
1050        match a {
1051            CapabilityArg::Compile => Capability::Compile,
1052            CapabilityArg::Test => Capability::Test,
1053            CapabilityArg::Deploy => Capability::Deploy,
1054            CapabilityArg::Editor => Capability::Editor,
1055            CapabilityArg::Build => Capability::BuildFromSource,
1056        }
1057    }
1058}
1059
1060#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
1061pub enum FormatArg {
1062    #[default]
1063    Human,
1064    Short,
1065    Json,
1066}
1067
1068/// Output choices for `bynk dev` (#2094).
1069#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
1070pub enum DevFormatArg {
1071    /// The readable stream on stderr.
1072    #[default]
1073    Human,
1074    /// Also one JSON lifecycle event per line on stdout.
1075    Json,
1076}
1077
1078impl From<DevFormatArg> for crate::dev::DevFormat {
1079    fn from(f: DevFormatArg) -> Self {
1080        match f {
1081            DevFormatArg::Human => crate::dev::DevFormat::Human,
1082            DevFormatArg::Json => crate::dev::DevFormat::Json,
1083        }
1084    }
1085}
1086
1087/// Scriptable output choices for `bynk deploy`'s plan.
1088#[derive(Copy, Clone, Debug, PartialEq, Eq, Default, ValueEnum)]
1089pub enum DeployFormatArg {
1090    #[default]
1091    Short,
1092    Json,
1093}
1094
1095impl From<DeployFormatArg> for crate::migrate::StatusFormat {
1096    fn from(arg: DeployFormatArg) -> Self {
1097        match arg {
1098            DeployFormatArg::Short => Self::Short,
1099            DeployFormatArg::Json => Self::Json,
1100        }
1101    }
1102}
1103
1104impl From<DeployFormatArg> for crate::deploy::DeployFormat {
1105    fn from(arg: DeployFormatArg) -> Self {
1106        match arg {
1107            DeployFormatArg::Short => Self::Short,
1108            DeployFormatArg::Json => Self::Json,
1109        }
1110    }
1111}
1112
1113impl From<FormatArg> for Format {
1114    fn from(f: FormatArg) -> Self {
1115        match f {
1116            FormatArg::Human => Format::Human,
1117            FormatArg::Short => Format::Short,
1118            FormatArg::Json => Format::Json,
1119        }
1120    }
1121}
1122
1123/// Build the [`DoctorOptions`] from the parsed flags.
1124pub fn doctor_options(only: Option<CapabilityArg>, strict: bool) -> DoctorOptions {
1125    DoctorOptions {
1126        only: only.map(Into::into),
1127        strict,
1128    }
1129}
1130
1131/// What `bynk dev` can do besides serve (#3581).
1132#[derive(Subcommand, Debug)]
1133pub enum DevSub {
1134    /// Read what a running `bynk dev` session holds. Prints JSON on stdout.
1135    ///
1136    /// A session built by `bynk dev` answers a signed, read-only route in each
1137    /// Worker; a deploy build has none. Needs a running session for the project.
1138    Inspect {
1139        #[command(subcommand)]
1140        what: InspectSub,
1141    },
1142}
1143
1144/// `bynk dev inspect`'s subjects.
1145#[derive(Subcommand, Debug)]
1146pub enum InspectSub {
1147    /// List the agent instances the session has seen, by class and key.
1148    ///
1149    /// An instance is listed once a handler has addressed it in this session.
1150    Agents {
1151        /// Project directory (anywhere inside the project). Defaults to `.`.
1152        #[arg(default_value = ".")]
1153        path: PathBuf,
1154        /// Only this context (dotted name or its worker-dir form).
1155        #[arg(long, value_name = "NAME")]
1156        context: Option<String>,
1157        /// Only this agent class.
1158        #[arg(long, value_name = "AGENT")]
1159        class: Option<String>,
1160    },
1161    /// Read one agent instance's stored state, its schema version and layout.
1162    ///
1163    /// The state is read as stored (the wire shape) and nothing is written: a
1164    /// record older than the build is reported, not migrated. Collections are
1165    /// paged: `--field` pages one, from the cursor `--after`.
1166    Agent {
1167        /// The agent class.
1168        class: String,
1169        /// The instance's key: a string as it is, any other key as JSON.
1170        key: String,
1171        /// Project directory (anywhere inside the project). Defaults to `.`.
1172        #[arg(long, default_value = ".")]
1173        path: PathBuf,
1174        /// Only this context (dotted name or its worker-dir form).
1175        #[arg(long, value_name = "NAME")]
1176        context: Option<String>,
1177        /// Page this collection field alone.
1178        #[arg(long, value_name = "FIELD")]
1179        field: Option<String>,
1180        /// The cursor a previous page returned as `next`.
1181        #[arg(long, value_name = "CURSOR", requires = "field")]
1182        after: Option<String>,
1183        /// Entries per page (at most 500).
1184        #[arg(long, value_name = "N")]
1185        limit: Option<u32>,
1186    },
1187}
1188
1189/// What `bynk dev` reads from the workers' output and writes as events: the
1190/// `--log-events`, `--trace-events` and `--rewrite-frames` flags, together so
1191/// `bynk dev`'s many flags stay manageable.
1192#[derive(Args, Debug, Clone, Copy, Default)]
1193pub struct DevStreamArgs {
1194    /// With `--format json`, also write each line a worker prints as a
1195    /// `log` event (`context`, `level`, `text`), so an editor can show the
1196    /// workers' logs per context and level. Implies `--rewrite-frames`.
1197    #[arg(long)]
1198    pub log_events: bool,
1199    /// Write one `request` event per request a worker serves (its route,
1200    /// status, duration and the steps it took: capability ops, cross-context
1201    /// calls and agent calls, each with its `.bynk` span), so an editor can show
1202    /// what a request did. Implies `--format json` and `--rewrite-frames`. Builds the workers with the
1203    /// recording on, and adds the `nodejs_als` compatibility flag unless the
1204    /// project already lists `nodejs_compat` or `nodejs_als`. Steps carry no
1205    /// argument values. Dev builds only: a deploy build never records.
1206    #[arg(long)]
1207    pub trace_events: bool,
1208    /// Rewrite stack frames in the workers' output to `.bynk` locations
1209    /// even on a terminal. Off a terminal (an editor task, CI) it is
1210    /// always done; on one, wrangler's output is left attached so its
1211    /// colour and hotkeys keep working.
1212    #[arg(long)]
1213    pub rewrite_frames: bool,
1214}
1215
1216/// #2240: how a command may change `bynk.lock` and the store.
1217#[derive(Args, Debug, Clone, Copy, Default)]
1218pub struct LockArgs {
1219    /// Fail instead of changing `bynk.lock` — for CI, which should build
1220    /// exactly what was committed.
1221    #[arg(long)]
1222    pub locked: bool,
1223    /// Fail instead of fetching: every git dependency must already be in the
1224    /// store.
1225    #[arg(long)]
1226    pub offline: bool,
1227}
1228
1229impl LockArgs {
1230    /// The fetch options these flags ask for.
1231    pub fn options(self) -> crate::fetch::FetchOptions {
1232        crate::fetch::FetchOptions {
1233            locked: self.locked,
1234            offline: self.offline,
1235            update: None,
1236        }
1237    }
1238}
1239
1240/// #2378: which registry an account command talks to.
1241#[derive(Args, Debug, Clone)]
1242pub struct AccountTarget {
1243    /// The registry, by its `[registries]` name: by default, the one the
1244    /// organisation routes to (the first-party registry for `login` and
1245    /// `logout`).
1246    #[arg(long)]
1247    pub registry: Option<String>,
1248    /// The project whose `[registries]` name and route the registry.
1249    #[arg(long, default_value = ".")]
1250    pub path: PathBuf,
1251}
1252
1253/// `bynk client --layout` (#3508).
1254#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
1255pub enum ClientLayoutArg {
1256    /// One module.
1257    File,
1258    /// `index.ts`, `types.ts`, `codecs.ts` and `runtime.ts`.
1259    Dir,
1260}
1261
1262/// #2378: `bynk org` subcommands.
1263/// `bynk openapi --format`.
1264#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
1265pub enum OpenapiFormatArg {
1266    Json,
1267    Yaml,
1268}
1269
1270#[derive(Subcommand, Debug)]
1271pub enum OrgCommand {
1272    /// Claim an organisation, first come: you become its owner.
1273    Claim {
1274        org: String,
1275        /// Hold the name without publishing: every publish is refused.
1276        #[arg(long)]
1277        block: bool,
1278        /// Claim it for this GitHub user (an operator token only).
1279        #[arg(long)]
1280        owner: Option<String>,
1281        #[command(flatten)]
1282        target: AccountTarget,
1283    },
1284    /// Show an organisation's owner, members, whether it is blocked, and its
1285    /// publish tokens (never the tokens themselves).
1286    Show {
1287        org: String,
1288        /// Output format.
1289        #[arg(long, value_enum, default_value_t)]
1290        format: DeployFormatArg,
1291        #[command(flatten)]
1292        target: AccountTarget,
1293    },
1294    /// Block an organisation: every publish to it is refused.
1295    Block {
1296        org: String,
1297        #[command(flatten)]
1298        target: AccountTarget,
1299    },
1300    /// Unblock an organisation.
1301    Unblock {
1302        org: String,
1303        #[command(flatten)]
1304        target: AccountTarget,
1305    },
1306    /// Add or remove members.
1307    Member {
1308        #[command(subcommand)]
1309        command: MemberCommand,
1310    },
1311    /// Mint or revoke publish tokens.
1312    Token {
1313        #[command(subcommand)]
1314        command: OrgTokenCommand,
1315    },
1316}
1317
1318/// #2378: `bynk org member` subcommands.
1319#[derive(Subcommand, Debug)]
1320pub enum MemberCommand {
1321    /// Add a GitHub user as a member: they may mint publish tokens.
1322    Add {
1323        org: String,
1324        /// Their GitHub login.
1325        login: String,
1326        #[command(flatten)]
1327        target: AccountTarget,
1328    },
1329    /// Remove a member, and every token they minted.
1330    Remove {
1331        org: String,
1332        /// Their GitHub login, or numeric id.
1333        member: String,
1334        #[command(flatten)]
1335        target: AccountTarget,
1336    },
1337}
1338
1339/// #2378: `bynk org token` subcommands.
1340#[derive(Subcommand, Debug)]
1341pub enum OrgTokenCommand {
1342    /// Mint a publish token, shown once on stdout (or saved with `--save`).
1343    Mint {
1344        org: String,
1345        /// What it may do: `publish`, `yank` (repeatable or comma-separated;
1346        /// both by default).
1347        #[arg(long = "can", value_delimiter = ',', default_values = ["publish", "yank"])]
1348        can: Vec<String>,
1349        /// How many days it lasts (1 to 365).
1350        #[arg(long, default_value_t = 90)]
1351        days: u32,
1352        /// A note to recognise it by in `bynk org show`.
1353        #[arg(long, default_value = "")]
1354        note: String,
1355        /// Save it as `[registries.<name>] token` in the credentials file,
1356        /// where `bynk publish` reads it, instead of printing it.
1357        #[arg(long)]
1358        save: bool,
1359        /// Let `--save` replace a different token.
1360        #[arg(long, requires = "save")]
1361        force: bool,
1362        #[command(flatten)]
1363        target: AccountTarget,
1364    },
1365    /// Revoke a publish token, by the id `bynk org show` prints.
1366    Revoke {
1367        org: String,
1368        /// The token's id, or a unique prefix of it.
1369        id: String,
1370        #[command(flatten)]
1371        target: AccountTarget,
1372    },
1373}
1374
1375/// #2274: `bynk registry` subcommands.
1376#[derive(Subcommand, Debug)]
1377pub enum RegistryCommand {
1378    /// Create a registry: its `config.json`, and a signing key written outside
1379    /// the directory. Prints the `key = "…"` line consumers pin.
1380    Init {
1381        /// The registry directory to create.
1382        dir: PathBuf,
1383        /// The registry's id, which every signed line binds.
1384        #[arg(long)]
1385        id: String,
1386        /// Where to write the signing key (default `./<id>.key`).
1387        #[arg(long = "key-out")]
1388        key_out: Option<PathBuf>,
1389    },
1390    /// Pack a package, sign its index line, and add it to the registry.
1391    Add {
1392        /// The registry directory.
1393        dir: PathBuf,
1394        /// The package's directory (holding its `bynk.toml`).
1395        package: PathBuf,
1396        /// The registry's signing key.
1397        #[arg(long)]
1398        key: PathBuf,
1399    },
1400    /// Serve a registry directory with the publish API (#2287): plain HTTP,
1401    /// loopback by default — put a TLS-terminating proxy in front to serve
1402    /// beyond this machine.
1403    Serve {
1404        /// The registry directory.
1405        dir: PathBuf,
1406        /// The registry's signing key (never inside the directory).
1407        #[arg(long)]
1408        key: PathBuf,
1409        /// The tokens file `bynk registry token` writes (never inside the
1410        /// directory).
1411        #[arg(long)]
1412        tokens: PathBuf,
1413        /// The address to listen on.
1414        #[arg(long, default_value = crate::registry::serve::DEFAULT_LISTEN)]
1415        listen: String,
1416    },
1417    /// Append a link to the registry's key chain (#2316): a new key, signed
1418    /// by the current chain key. Clients that trust an older key follow it.
1419    Rotate {
1420        /// The registry directory (or a copy holding its `config.json`).
1421        dir: PathBuf,
1422        /// The current (newest) chain key.
1423        #[arg(long)]
1424        key: PathBuf,
1425        /// Where to write the new key (never inside the directory).
1426        #[arg(long)]
1427        key_out: PathBuf,
1428    },
1429    /// Delegate signing to a new key (#2316): it may sign index lines, and
1430    /// nothing else. Use it as `serve`'s or `add`'s `--key`, keeping the chain
1431    /// key offline.
1432    Delegate {
1433        /// The registry directory (or a copy holding its `config.json`).
1434        dir: PathBuf,
1435        /// A chain key, which signs the delegation.
1436        #[arg(long)]
1437        key: PathBuf,
1438        /// Where to write the delegated key (never inside the directory).
1439        #[arg(long)]
1440        delegate_out: PathBuf,
1441    },
1442    /// Revoke a delegated key (#2316): lines it signed are refused from then
1443    /// on, so re-sign them with another key first (`resign`).
1444    Revoke {
1445        /// The registry directory (or a copy holding its `config.json`).
1446        dir: PathBuf,
1447        /// The delegate to revoke, `ed25519:…`.
1448        target: String,
1449        /// A chain key, which signs the revocation.
1450        #[arg(long)]
1451        key: PathBuf,
1452        /// Revoke even if some lines would be left with no valid signer.
1453        #[arg(long)]
1454        force: bool,
1455    },
1456    /// Re-sign every index line with a key (#2316): the newest chain key or a
1457    /// valid delegate. Only each line's `sig` changes.
1458    Resign {
1459        /// The registry directory.
1460        dir: PathBuf,
1461        /// The signing key.
1462        #[arg(long)]
1463        key: PathBuf,
1464    },
1465    /// Check a registry against the protocol (#2311): every observable rule a
1466    /// server must keep, run against its URL. A full run publishes one
1467    /// throwaway package under `--org` and leaves it yanked; `--read-only`
1468    /// publishes nothing.
1469    Conformance {
1470        /// The registry's index URL.
1471        index: String,
1472        /// The organisation the token may publish and yank under.
1473        #[arg(long, required_unless_present = "read_only")]
1474        org: Option<String>,
1475        /// The registry name the token is found under
1476        /// (`BYNK_REGISTRY_<NAME>_TOKEN`, or the credentials file).
1477        #[arg(long, default_value = "conformance")]
1478        name: String,
1479        /// The registry's key to pin (`ed25519:…`); trusted on first use for
1480        /// the run otherwise.
1481        #[arg(long)]
1482        key: Option<String>,
1483        /// Publish nothing: check `config.json`, and `--package` if given.
1484        #[arg(long)]
1485        read_only: bool,
1486        /// The existing `org/package` a `--read-only` run reads back.
1487        #[arg(long, requires = "read_only")]
1488        package: Option<String>,
1489        /// An environment variable holding a token that can't act for
1490        /// `--org`, for the `auth.scope` check (skipped without one).
1491        #[arg(long)]
1492        narrow_token_env: Option<String>,
1493        /// The upload cap, in bytes, to test `413` against.
1494        #[arg(long, default_value_t = 64 * 1024 * 1024)]
1495        max_upload: u64,
1496        /// Output format.
1497        #[arg(long, value_enum, default_value_t)]
1498        format: DeployFormatArg,
1499    },
1500    /// Mint a publish token for `bynk registry serve` (#2287): printed once;
1501    /// only its hash is stored in the tokens file.
1502    Token {
1503        /// The tokens file to add it to.
1504        tokens: PathBuf,
1505        /// An organisation it may act for (repeatable).
1506        #[arg(long = "org", required = true)]
1507        organisations: Vec<String>,
1508        /// What it may do: `publish`, `yank` (repeatable or comma-separated; both by default).
1509        #[arg(long = "can", value_delimiter = ',', default_values = ["publish", "yank"])]
1510        can: Vec<String>,
1511    },
1512    /// Mark a version yanked — kept for locked builds, never newly chosen.
1513    Yank {
1514        /// The registry directory.
1515        dir: PathBuf,
1516        /// `org/package`.
1517        package: String,
1518        /// The version to yank.
1519        version: String,
1520        /// Clear the yank instead.
1521        #[arg(long)]
1522        undo: bool,
1523    },
1524    /// Withdraw a version (#2330): a takedown. Yanks its line, records the
1525    /// reason clients print, and deletes its archive. Final — there is no undo.
1526    Withdraw {
1527        /// The registry directory.
1528        dir: PathBuf,
1529        /// `org/package`.
1530        package: String,
1531        /// The version to withdraw.
1532        version: String,
1533        /// Why, as clients will print it (one line, at most 500 characters).
1534        #[arg(long)]
1535        reason: String,
1536    },
1537}
1538
1539/// `bynk book --search`'s output formats.
1540#[derive(Clone, Copy, Debug, clap::ValueEnum)]
1541pub enum BookFormat {
1542    /// Markdown, for a person or a language model.
1543    Text,
1544    /// A JSON document: `version`, `query` and `results`.
1545    Json,
1546}
1547
1548impl From<ClientLayoutArg> for bynk_emit::emitter::http_client::Layout {
1549    fn from(l: ClientLayoutArg) -> Self {
1550        match l {
1551            ClientLayoutArg::File => Self::File,
1552            ClientLayoutArg::Dir => Self::Dir,
1553        }
1554    }
1555}
1556
1557#[cfg(test)]
1558mod tests {
1559    use super::*;
1560    use clap::Parser;
1561
1562    /// #3580: `--trace-events` implies `--format json`, so it needs no `--format`
1563    /// and goes with `--log-events` (which writes events too).
1564    #[test]
1565    fn trace_events_needs_no_format_and_goes_with_log_events() {
1566        let parse = |args: &[&str]| Cli::try_parse_from(["bynk", "dev"].iter().chain(args));
1567        assert!(parse(&["--trace-events"]).is_ok());
1568        assert!(parse(&["--trace-events", "--log-events"]).is_ok());
1569        assert!(parse(&["--trace-events", "--format", "json"]).is_ok());
1570    }
1571
1572    /// A subcommand left out of `COMMAND_GROUPS` would vanish from
1573    /// `bynk --help`; one listed twice, or not at all, is a typo.
1574    #[test]
1575    fn every_subcommand_is_grouped_once() {
1576        let mut cmd = command();
1577        cmd.build();
1578        let mut grouped: Vec<&str> = COMMAND_GROUPS
1579            .iter()
1580            .flat_map(|(_, names)| names.iter().copied())
1581            .collect();
1582        grouped.sort_unstable();
1583        let mut visible: Vec<&str> = cmd
1584            .get_subcommands()
1585            .filter(|sub| !sub.is_hide_set())
1586            .map(clap::Command::get_name)
1587            .collect();
1588        visible.sort_unstable();
1589        assert_eq!(grouped, visible);
1590    }
1591
1592    /// The rendered help keeps clap's own parts around the groups, so a typo in
1593    /// a template tag (`{usage-heading}` and the like) shows up here.
1594    #[test]
1595    fn help_renders_groups_between_usage_and_options() {
1596        let help = command().render_help().to_string();
1597        let usage = help
1598            .find("Usage: bynk [OPTIONS] <COMMAND>")
1599            .expect("usage line");
1600        let options = help.find("Options:\n  -q, --quiet").expect("options");
1601        let mut at = usage;
1602        for (heading, names) in COMMAND_GROUPS {
1603            let found = help[at..].find(&format!("\n{heading}:\n"));
1604            at += found.unwrap_or_else(|| panic!("heading {heading:?} out of order"));
1605            for name in *names {
1606                assert!(help.contains(&format!("\n  {name} ")), "{name} listed");
1607            }
1608        }
1609        assert!(at < options, "groups precede Options:");
1610        assert!(help.starts_with("The Bynk driver\n"));
1611        assert!(!help.contains('{'), "an unexpanded template tag:\n{help}");
1612    }
1613
1614    /// The top-level listing stays scannable: each summary fits on one line,
1615    /// with the detail left to `bynk <command> --help`.
1616    #[test]
1617    fn subcommand_summaries_are_short() {
1618        for sub in command().get_subcommands() {
1619            let about = sub.get_about().map(ToString::to_string).unwrap_or_default();
1620            assert!(
1621                !about.is_empty() && about.len() <= 60 && !about.contains('\n'),
1622                "`bynk {}` summary should be one line of at most 60 chars: {about:?}",
1623                sub.get_name()
1624            );
1625        }
1626    }
1627}