# @master4n/master-cli (`mfn`)

> 50 headless, JSON-first commands for AI agents and developers: extract instead
> of dump (token savers), compute instead of guess (hallucination killers),
> one-call system/code/network facts, and cross-platform OS actions (clipboard,
> notifications, trash, processes). Every command behaves identically for a
> human at a terminal and an agent reading stdout.

## Agent contract (read this first)

- **Zero-install:** `npx -y @master4n/master-cli <command> --json` works without a
  global install; with it installed, the binary is `mfn`.
- **Discover commands:** `mfn capabilities --json` returns the full manifest
  (`{ name, version, bin, conventions, docs, categories, commands:[{name,category,summary,examples}] }`).
- **Machine output:** pass `--json`, OR just pipe the command (when stdout is not
  a TTY the CLI auto-emits JSON). Output is exactly one object on stdout:
  success → `{ "ok": true, ... }`, failure → `{ "ok": false, "error", "message" }`.
- **Exit codes:** `0` success · `1` runtime error · `2` usage error.
- **Clean channels:** banners/spinners/logs go to **stderr**; **stdout carries only
  the JSON result**, so `mfn <cmd> --json | jq` always works.
- **No prompts in headless mode:** with `--json` or when piped, commands never block.
- **Strict parsing:** unknown commands/flags and missing args → `{ok:false, error:"UsageError"}`, exit 2.
- **Fast:** ~60ms per invocation; heavy/TTY-only deps load lazily.

## Token savers (read less, extract exactly)

- `mfn json [query] [-f file] [--keys] [--length] --json` — one value from JSON by
  dot/bracket path (`scripts.build`, `users[0].name`); stdin or file. Don't read the document.
- `mfn schema [query] [-f file] --json` — infer JSON shape (dot-paths → types, arrays
  sampled). A 10MB payload becomes ~20 lines.
- `mfn count [text] [-f file] --json` — lines/words/chars/bytes + `tokensEstimate`
  (~4 chars/token heuristic). Know the cost before reading.
- `mfn lines <file> [-s start] [-e end | -n count] --json` — exact 1-based line range,
  capped at 2000 lines. Returns `totalLines` too.
- `mfn outline <file> [-k kind] [-e] --json` — symbols + line numbers for
  .ts/.tsx/.js/.jsx/.py/.go/.md. Pair with `lines` to read only what matters.
- `mfn diff <a> <b> [-s] --json` — structured hunks `{aStart,aLines,bStart,bLines,removed,added}`;
  `-s` for locations/counts only.
- `mfn freq [file] [-t top] [-m min] --json` — most repeated lines (log triage in one call).
- `mfn imports [file] | --who <module> --json` — a file's imports (grouped
  relative/packages/builtin), or every file importing a module.
- `mfn repo [-n commits] --json` — git branch, staged/unstaged/untracked counts,
  ahead/behind, remotes, recent commits. Replaces 4-5 git calls.
- `mfn sys --json` — OS, arch, node, CPU, memory, user, shell, timezone, cwd in one object.
- `mfn have <tools...> --json` — which tools exist, their path + version, in one call.
- `mfn size [dir] [-t top] --json` / `mfn ext [dir] --json` / `mfn recent [dir] [-t top] --json`
  — disk usage, project composition by extension, newest files.
- `mfn ports [--min N] --json` — ALL listening TCP ports with pid/command.
- `mfn ip [-a] --json` — local interfaces/addresses; `primaryIPv4` convenience field.
- `mfn pkg [name] --json` — declared vs installed dependency versions; `missing` list.
- `mfn env [names...] [-p prefix] --json` — env vars; secret-looking values are
  ALWAYS redacted; no names → name list only.
- `mfn dotenv [-f .env] [-e .env.example] --json` — missing/extra keys; values never read.

## Exact computation (never guess)

- `mfn calc <expr> --json` — `+ - * / % ^` with parens; integer math in BigInt
  (`2^53 + 1` → `9007199254740993`, exact). `exact:true|false` flag in output.
- `mfn base <value> [-f hex|dec|bin|oct] --json` — 0xff/0b1010/0o755/decimal → all bases, BigInt-safe.
- `mfn semver <versions...> [-b major|minor|patch] [-s] --json` — validate/compare/sort/bump
  per semver.org (prerelease ordering correct).
- `mfn cron <expr> [-n next] --json` — validate 5-field cron (+ @daily etc.), plain-English
  description, next run times (local + ISO + epochMs).
- `mfn regex <pattern> [text] [-f file] [--flags imsuvy] --json` — all matches with
  line/index/groups. Test, don't assume.
- `mfn url <value> --json` — components + decoded query params (repeats → arrays).
- `mfn escape [text] [-a shell|json|regex|html|url|string] --json` — context-exact escaping.
- `mfn case [text] [-t camel|snake|kebab|pascal|constant|dot|path|title|sentence|lower|upper] --json`
  — identifier style conversion; omit `-t` for all styles.
- `mfn epoch <value> --json` / `mfn epoch --from <date> --json` — epoch ↔ date
  (unit auto-detected s/ms/µs/ns).
- `mfn date [from] [--tz] [--format] --json` — date across timezones (IANA), defaults to now.
- `mfn decode -t <jwt> --json` — JWT header+payload+expiry (signature NOT verified).

## Actions (do, don't script)

- `mfn replace <search> <replacement> -g <glob> [--write] --json` — literal find/replace
  across files; DRY-RUN by default, `--write` to apply; per-file counts.
- `mfn wait [-p port | -u url | -f file] [-t seconds] --json` — block until ready;
  replaces sleep-and-retry loops. Exit 1 on timeout.
- `mfn kill -p <ports...> [-y] --json` — kill listeners on ports (headless: needs explicit -p).
- `mfn http <url> [-m GET|HEAD] [-H "Name: value"] --json` — status/headers/timing
  + body preview capped at 2KB (never a full dump). Exit 1 on non-2xx.
- `mfn port [-c port | -n count] --json` — find free port(s) / check one.
- `mfn id [-t uuid|uuid7|nano] [-n count] --json` — UUID v4, time-ordered v7 (RFC 9562), nano.
- `mfn hash [text] [-a md5|sha1|sha256|sha512] [-f file] --json` — digest of string/file/stdin.
- `mfn encode [text] [--as base64|base64url|hex|url] [-d] --json` — encode/decode (strict charset).
- `mfn random [-b bytes] | [-p [-l length]] --json` — CSPRNG bytes / unbiased password.
- `mfn sc [pattern] [--depth] [--limit] --json` — fuzzy file find under cwd.
- `mfn cts [--type text|svg|png|jpeg] --json` — directory tree.
- `mfn update [package] --json` — global npm update of the CLI (or named package).

## OS-level (cross-platform: macOS / Windows / Linux)

- `mfn clip [text] [-r] --json` — read/write the system clipboard. Write via arg or
  stdin (`git diff | mfn clip`); read returns `{chars, text}`. Headless sessions fail
  cleanly with `ClipboardUnavailable`.
- `mfn notify <message> [-t title] --json` — desktop notification (osascript /
  notify-send / WinRT toast). Ping the user when a long task finishes.
- `mfn open <target> --json` — open an http(s) URL or existing file in the default
  app/browser. Non-http schemes and missing paths are rejected (exit 2).
- `mfn procs [pattern] [-t top] --json` — search processes by name: pid/cpu/memMB,
  sorted by cpu. One call instead of ps|grep (or tasklist parsing).
- `mfn disk [-a] --json` — per-mount totals/free/used% (df -kP / Win32_LogicalDisk).
- `mfn trash <paths...> --json` — move to the OS trash (reversible; ~/.Trash, XDG
  spec, Recycle Bin). Refuses root/home/cwd and parents of cwd. Use instead of rm.
- `mfn dns <hostname> [-t a|aaaa|cname|mx|txt|ns] --json` — system resolver +
  record sweep; missing record types are null, not errors.

## Guardrails (always on — there are no bypass flags)

- File-content commands (`lines` `json` `schema` `diff` `freq` `regex -f`) refuse
  credential/secret paths (`~/.ssh`, `.env*`, `*.pem`, `.npmrc`, …) → `SensitivePath`, exit 2.
- `clip` read redacts secret-shaped content (keys/JWTs/tokens) → `redacted:true`.
- `env` redacts by name AND value shape; `dotenv` never reads values at all.
- `http`/`wait -u` refuse cloud metadata endpoints (169.254.169.254 etc.) → `BlockedTarget`;
  `http` redacts `set-cookie` response headers.
- `open` allows only http(s)/existing paths; `trash` is reversible and refuses
  root/home/cwd; `kill` validates ports and PIDs; `replace` is dry-run unless `--write`.
- Full threat model: SECURITY.md (shipped in this package).

## Notes

- Time/date powered by `@master4n/temporal-transformer` v2 (Luxon-backed, integer epochs).
- Zero shell interpolation: every subprocess uses `execFile` (no shell) — inputs cannot
  inject commands. See SECURITY.md (shipped in this package) for the full threat model.
- `count.tokensEstimate` is a ~4-chars/token heuristic, not a model tokenizer.
