Files
gitea ca9d87e13f Group CLI modules into parse, run, output, and help
Move parser, tokenize, and area-aliases under cli/parse; runner and read-only under cli/run; printer under cli/output; help plus the docs/naming contract tests under cli/help. types.ts and helpers.ts stay at the cli root. Update imports, the app-root depth calculation, test fixtures, and the CLI doc generator path. No behavior change.
2026-11-19 16:38:14 +08:00

8.0 KiB
Raw Permalink Blame History

description, globs, trigger
description globs trigger
CLI stdout/stderr stream contract, exit codes, SWR caching, and preview safety for seal-use commands src/cli/**/*.ts manual

CLI Stream, Performance & Exit Code Protocol

When developing or refactoring CLI commands under src/cli/:

1. Dual Stream Protocol (stdout vs stderr)

  • Machine Channel (stdout):
    • Data commands MUST output pure, parseable JSON on stdout.
    • NEVER output human text, logs, spinners, progress banners, or update notices to stdout. The Agent Harness parses stdout directly into typed payloads.
    • Documented exceptions: seal-use --help / seal-use help <area> (src/cli/output/printer.ts), seal-use doctor guide (src/cli/commands/doctor.ts), and seal-use skill dump (src/cli/commands/skill.ts) intentionally output Markdown documents on stdout because their output is the requested document payload (e.g. seal-use skill dump > SKILL.md). Never add new stdout-prose commands outside this list.
  • Diagnostics & Guidance Channel (stderr):
    • Use stderr for runtime logs, network probing status, self-healing notifications, and human tips.
    • Explicit Next-Step Command Suggestions MUST follow the format:
      👉 Next action: seal-use <command>
      

2. Performance Contract & SWR Architecture

  • Sub-70ms Local Execution:
    • Read-only discovery commands (e.g. seal-use version, seal-use doctor paths, seal-use corps list) MUST return in under 70ms wall clock (Bun interpreter startup is ~7ms on its own, so this leaves ~60ms for the module graph).
    • Achieved by keeping src/cli/run/runner.ts free of static command-module imports: dispatch branches load their handler with await import("./commands/<area>.js") on demand, so seal-use version never loads the Excel/zip tool chain.
    • Never trigger synchronous external HTTP requests during routine discovery or inspection invocations. Measured on the maintainer's machine (2026-09): version 45ms, help 41ms, corps list 41ms, bare bun -e 7ms.
  • Stale-While-Revalidate (SWR) Pattern:
    1. Synchronously read local cache from ~/.config/seal-use/*.json (<0.2ms).
    2. Return the local cached state immediately on stdout.
    3. If cache is missing or older than TTL (e.g. 24 hours), trigger a background refresh:
      const child = spawn(launcher.command, [...launcher.args, "subcommand", "--bg-save"], {
        detached: true,
        stdio: "ignore"
      });
      child.unref(); // Detach completely so parent exits immediately
      
    4. Always respect test/CI guards (SEAL_DISABLE_BG_UPDATE=1, NODE_ENV=test, CI=true) to keep automated test suites deterministic.

3. High-Risk Mutation & Preview Contract (--dry-run)

  • All potentially destructive or state-mutating commands (e.g. rules push/clear/create/update/delete/publish, corps sync-test, corps mark, preference update, users create/delete/reset-password/delegation, simulation delete, analytics analyze, auth link revoke, webhook create/update/delete) MUST support --dry-run.
  • Preview Output:
    • When --dry-run is present, the command performs read-only discovery, simulates the mutation, and returns structured JSON with:
      {
        "preview": true,
        "targetUrl": "...",
        "changesDiff": { "before": "...", "after": "..." },
        "impactCount": 5
      }
      
    • Live execution requires explicit --yes or --confirm. If neither is provided on a live mutation, block execution with exit code 10.

4. Semantic Exit Codes

Exit Code Meaning Example Scenario
0 Success Successful query, preview, or completed mutation
1 Domain / Upstream Failure Upstream HTTP 500, business logic rejection, quota insufficient, lint score below threshold
2 Usage / Syntax Error Unknown subcommand, invalid --flag value, malformed --json payload
10 Confirmation Required Mutating command invoked without --confirm or --yes
11 Authentication Missing / Invalid Upstream HTTP 401/403, or an expired/missing/invalid token/bearer/session (classified in classifyCliError)
12 Output Protection Response exceeds the size limit (PayloadTooLargeError from printer.ts); use --summary/--fields/--count/--output-file, or --full when the full payload is genuinely required
13 Config / Input Validation Well-formed command with an unusable value: missing --corp in stateless mode, unparseable enterprise JSON, missing required parameter (Chinese-language usage wording), Zod/schema validation failure
14 Safety Guard Block Target environment forbids the action: replay into a production tenant, regression matrix outside a test tenant. Requires a different target or an explicit override flag

Rule: Never call process.exit() deep in domain functions. Throw structured errors (usageError → 2, validationError → 13, safetyBlocked → 14, confirmationRequired → 10) and let src/cli/run/runner.ts handle error classification, stream routing, and exit code assignment. Domain failures and quality gates stay at 1.


5. Argument Parsing Conventions

  • Use helpers from src/cli/parse/parser.ts:
    • booleanOption(args.options.flag)
    • stringOption(args.options.param)
    • numberOption(args.options.limit)
  • Support kebab-case and camelCase options gracefully.
  • Positional arguments should fall back to option flags when natural (e.g. corps get <corpId> and corps get --corp <corpId>).

6. Silent Compatibility

  • Compatibility command spellings and options may remain accepted for existing scripts, but they are implementation-only.
  • Do not expose them in help, Skill, references, README guidance, generated suggestions, or normal runtime notices.
  • Agent-generated commands and all new documentation MUST use the current canonical spelling.

7. Naming Charter (跨域命名宪章)

同一语义操作在不同业务域必须使用同一个词。命名决策顺序:语义类别 → 宪章词表 → 旧名一律转为静默 alias(见 §6)。允许域内风格化命名(如 rules pull/push 的 git 配对隐喻),前提是该域 help summary 写明其导出/导入语义,形成可见桥接。横切概念一览:

7.1 子命令动词词表

语义 Canonical 静默兼容 / 备注
分页列表 list 关键字过滤用 --query/--search flag
读单条 get
关键字检索 search search 是 list 别名的场景仅限历史兼容(approval-runs)
计数 count
创建 create add 退役为 alias
更新 update
删除 delete 批量语义在 summary/usage 说明;clean/clear/remove 退役为 alias
导出/下载 export rules pull 是该域 canonical 名,summary 必须写明 Export 语义
上传/导入 push / import
重放 replay

7.2 横切 Flag 词表

语义 Canonical 静默兼容拼写
写入本地文件 --out --output、-o、--output-file、--outputFile
存到 ~/Downloads --downloads --download、--to-downloads、--toDownloads
明文揭示密钥 --reveal(短名 -r) --show-secret
时间范围 --start-date / --end-date --start/--end、--startDate/--endDate;--since/--until 仅用于 simulation 的相对时间窗
列表页大小 --limit --max-results 仅用于 search 命中数
本地扫描上限 --max-scan

7.3 机械约束

  • Flag 一律 lowercase kebab-case;camelCase 拼写只作为静默兼容,永不出现在 help/Skill/README(src/cli/naming-charter.test.ts 强制)。
  • 每个横切 flag 的 canonical 拼写在所有同类命令中必须被实际读取;accept-set 不齐 = 静默忽略 bug(宪章测试有专项回归)。
  • 新命令落地时实现可以双收新旧拼写,但 help 注册表只写 canonical;旧名退役永远走 alias,不做硬切断。