@autocodeflow/cli 1.8.0 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,10 @@
1
- import { Command } from 'commander';
1
+ import { Command, InvalidArgumentError } from 'commander';
2
2
  import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
- import { get, post, put, del, ANALYZE_TIMEOUT_MS } from '../client.js';
6
- import { emitError, UsageError, interruptExit } from '../ui.js';
5
+ import * as path from 'path';
6
+ import { get, post, put, del, ANALYZE_TIMEOUT_MS, UPLOAD_TIMEOUT_MS } from '../client.js';
7
+ import { emitError, emitUsageError, UsageError, confirmDestructive } from '../ui.js';
7
8
  function statusColor(s) {
8
9
  if (s === 'running')
9
10
  return chalk.green(s);
@@ -107,14 +108,27 @@ export function appsCommand() {
107
108
  }
108
109
  });
109
110
  // acf app create
111
+ // 2026-10-07 对齐 task create 的载荷旗标改名:--json <body> → --body。
112
+ //(task 侧先改,app 侧本轮补齐——--json 在其余命令都是「输出 JSON」布尔
113
+ // 旗标,载荷语义的 --json 是历史包袱,下一大版本收敛为布尔。)
110
114
  cmd.command('create')
111
- .description('Create an application (JSON payload via --json or --file; required: name, version, runtime)')
112
- .requiredOption('--json <body>', 'Application body as JSON string')
113
- .option('--file <path>', 'Read application body from a JSON file (overrides --json)')
115
+ .description('Create an application (JSON payload via --body or --file; required: name, version, runtime)')
116
+ .option('--body <json>', 'Application body as JSON string (required unless --file is given)')
117
+ .option('--json <body>', 'DEPRECATED (renamed to --body): Application body as JSON string. In the next major version --json becomes a boolean output flag')
118
+ .option('--file <path>', 'Read application body from a JSON file (overrides --body/--json)')
114
119
  .action(async (opts) => {
120
+ if (opts.body !== undefined && opts.json !== undefined) {
121
+ emitUsageError('--body and --json (deprecated alias) are mutually exclusive — pass only --body');
122
+ }
123
+ if (opts.body === undefined && opts.json === undefined && !opts.file) {
124
+ emitUsageError('Missing required application body — pass --body <json> (or --file <path>)');
125
+ }
115
126
  const spinner = ora('Creating application…').start();
116
127
  try {
117
- const body = await loadJsonBody(opts.json, opts.file);
128
+ if (opts.json !== undefined) {
129
+ process.stderr.write(chalk.yellow('⚠ --json <body> is deprecated and will be removed in the next major version (it will become a boolean output flag). Use --body <json> instead.\n'));
130
+ }
131
+ const body = await loadJsonBody(opts.json ?? opts.body, opts.file);
118
132
  const a = await post('/applications', body);
119
133
  spinner.succeed(`Application created: ${a.id}`);
120
134
  console.log(chalk.gray(` name: ${a.name} version: ${a.version ?? '-'} status: ${statusColor(a.status)}`));
@@ -123,17 +137,82 @@ export function appsCommand() {
123
137
  emitError('Failed to create application', e, { spinner });
124
138
  }
125
139
  });
140
+ // P2: acf app upload <zip> —— POST /applications/upload(multipart/form-data,
141
+ // 按名称 upsert:应用已存在只更新 packageUrl(可选 runtime/version),不存在
142
+ // 则创建)。入参白名单以服务端 UploadApplicationDto 为准:file/name 必填、
143
+ // runtime/version 可选——forbidNonWhitelisted 下多一个字段都 400,故可选字段
144
+ // 只在用户给出时才 append。zip 魔数/大小/zip 炸弹校验是服务端职责(400/503
145
+ // 契约语义),CLI 不复刻,只做廉价的扩展名/可读性预检(退出码 2,请求不发)。
146
+ cmd.command('upload <zip>')
147
+ .description('Upload an application package (.zip, max 200 MB) and upsert it by name: an existing app only gets its packageUrl (and runtime/version) updated, a new one is created. ZIP magic/size/zip-bomb checks are server-side')
148
+ .requiredOption('--name <name>', 'Application name (1-100 chars) — the upsert key')
149
+ .option('--runtime <runtime>', 'Runtime type (max 50 chars; a NEW app defaults to python when omitted)')
150
+ .option('--version <version>', 'Version to record for this upload (e.g. 1.2.0); omit to keep the current version')
151
+ .option('--json', 'Emit raw JSON (CI-consumable)')
152
+ .action(async (zip, opts) => {
153
+ const spinner = ora('Uploading package…').start();
154
+ try {
155
+ if (!/\.zip$/i.test(zip)) {
156
+ throw new UsageError(`Only .zip packages are accepted (got "${zip}") — the server validates both extension and ZIP magic`);
157
+ }
158
+ const fsPromises = await import('fs/promises');
159
+ let buf;
160
+ try {
161
+ buf = await fsPromises.readFile(zip);
162
+ }
163
+ catch (err) {
164
+ // 本地文件层错误 = 用法错误(退出码 2),与服务端拒绝(1)区分;
165
+ // 口径与 loadJsonBody / task import 一致。
166
+ throw new UsageError(`Cannot read package file: ${zip} (${err instanceof Error ? err.message : String(err)})`);
167
+ }
168
+ // Node 内置 FormData/Blob(undici,Node >=18 全局可用):axios 1.x 识别
169
+ // spec FormData 后自动补 multipart boundary 与 Content-Type,无需引入
170
+ // form-data 依赖。字段名 file/name/runtime/version 是服务端 multer +
171
+ // DTO 白名单;不手动设 Content-Type(会把 boundary 写死)。
172
+ const form = new FormData();
173
+ form.append('file', new Blob([buf], { type: 'application/zip' }), path.basename(zip));
174
+ form.append('name', opts.name);
175
+ if (opts.runtime)
176
+ form.append('runtime', opts.runtime);
177
+ if (opts.version)
178
+ form.append('version', opts.version);
179
+ // NETOPT-6④ 同款思路:200MB 上限下实例默认 30s 结构性不够,用
180
+ // UPLOAD_TIMEOUT_MS(300s)per-call 覆盖。
181
+ const a = await post('/applications/upload', form, UPLOAD_TIMEOUT_MS);
182
+ spinner.stop();
183
+ if (opts.json) {
184
+ // ECO-02:单对象形态 → pretty JSON
185
+ console.log(JSON.stringify(a, null, 2));
186
+ return;
187
+ }
188
+ spinner.succeed(`Package uploaded: ${a.name}`);
189
+ console.log(chalk.gray(` id: ${a.id} version: ${a.version ?? '-'} status: ${statusColor(a.status)} packageUrl: ${a.packageUrl ?? '-'}`));
190
+ }
191
+ catch (e) {
192
+ emitError('Failed to upload package', e, { spinner });
193
+ }
194
+ });
126
195
  // acf app update <id>
127
196
  cmd.command('update <id>')
128
- .description('Update an application (JSON payload via --json or --file). ' +
197
+ .description('Update an application (JSON payload via --body or --file). ' +
129
198
  'Accepted fields: description, version, runtime, status, gitRepo, gitBranch, gitCommit, manifest, env, entrypoint, packageUrl, webhookSecret. ' +
130
199
  'NOTE: the backend UpdateApplicationDto has no `name` field — renaming is not supported.')
131
- .requiredOption('--json <body>', 'Application patch body as JSON string')
132
- .option('--file <path>', 'Read application patch body from a JSON file (overrides --json)')
200
+ .option('--body <json>', 'Application patch body as JSON string (required unless --file is given)')
201
+ .option('--json <body>', 'DEPRECATED (renamed to --body): Application patch body as JSON string. In the next major version --json becomes a boolean output flag')
202
+ .option('--file <path>', 'Read application patch body from a JSON file (overrides --body/--json)')
133
203
  .action(async (id, opts) => {
204
+ if (opts.body !== undefined && opts.json !== undefined) {
205
+ emitUsageError('--body and --json (deprecated alias) are mutually exclusive — pass only --body');
206
+ }
207
+ if (opts.body === undefined && opts.json === undefined && !opts.file) {
208
+ emitUsageError('Missing required application patch body — pass --body <json> (or --file <path>)');
209
+ }
134
210
  const spinner = ora('Updating application…').start();
135
211
  try {
136
- const body = (await loadJsonBody(opts.json, opts.file));
212
+ if (opts.json !== undefined) {
213
+ process.stderr.write(chalk.yellow('⚠ --json <body> is deprecated and will be removed in the next major version (it will become a boolean output flag). Use --body <json> instead.\n'));
214
+ }
215
+ const body = (await loadJsonBody(opts.json ?? opts.body, opts.file));
137
216
  // UpdateApplicationDto has no `name` — with forbidNonWhitelisted the
138
217
  // API would answer 400 "property name should not exist". Fail early
139
218
  // with an actionable message instead.
@@ -155,19 +234,9 @@ export function appsCommand() {
155
234
  .description('Delete an application')
156
235
  .option('-y, --yes', 'Skip confirmation prompt', false)
157
236
  .action(async (id, opts) => {
158
- if (!opts.yes) {
159
- const readline = await import('readline/promises');
160
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
161
- // raw 模式下 Ctrl+C 触发 rl 'SIGINT' 而非进程信号;无监听只会 pause,
162
- // 确认提示处会假死。接住并走统一中断出口(130)。
163
- rl.on('SIGINT', () => interruptExit());
164
- const answer = await rl.question(`Delete application ${id}? [y/N] `);
165
- rl.close();
166
- if (!/^y(es)?$/i.test(answer)) {
167
- console.log(chalk.yellow('Aborted.'));
168
- return;
169
- }
170
- }
237
+ // P0(CLI-AGENT-UX-AUDIT):非交互 stdin 下必须显式拒绝,不能静默假绿。
238
+ if (!(await confirmDestructive(`Delete application ${id}?`, { yes: opts.yes })))
239
+ return;
171
240
  const spinner = ora('Deleting application…').start();
172
241
  try {
173
242
  await del(`/applications/${id}`);
@@ -203,22 +272,56 @@ export function appsCommand() {
203
272
  }
204
273
  });
205
274
  // acf app deploy <id>
275
+ //
276
+ // P0(2026-10 开发人员实测):`--run-mode` 的语义此前只列枚举值、不解释
277
+ // 行为差异,且默认值 `daemon` 恰好是"部署即立刻执行入口脚本"的模式——中台
278
+ // 定时触发场景(存量部署 11/12 是 scheduled)按"部署 = 待命"理解却不传 -m,
279
+ // 部署时自跑了一次完整任务,28s 后再 trigger 又跑一次,两边并发写同一云盘
280
+ // 目录。修复三管齐下:
281
+ // ① 默认值改为 `scheduled`(仅下发、由中台/定时触发,部署后不自跑);
282
+ // ② 帮助文本写清三档的真实行为(语义见 docs/deployment.md §runMode);
283
+ // ③ 显式传 once/daemon 时在发请求前打黄色预警"将立刻启动入口脚本"。
284
+ // `deploy-only` 是 scheduled 的自解释别名("仅部署、不自动运行")——服务端
285
+ // RunMode 枚举没有该值,CLI 在本地归一为 scheduled 后发送。
206
286
  cmd.command('deploy <id>')
207
287
  .description('Deploy an application to an executor (auto-selects the lowest-load online executor when --executor is omitted)')
208
288
  .option('-e, --executor <executorId>', 'Pin to a specific executor')
209
- .option('-m, --run-mode <mode>', 'Run mode: once | daemon | scheduled', 'daemon')
289
+ .option('-m, --run-mode <mode>', 'Run mode: once (run the entry script once, no restart) | daemon (resident process — the entry script STARTS at deploy and auto-restarts on crash) | scheduled (deploy-only — no process at deploy; middleware/cron triggers it later; default) | deploy-only (alias of scheduled)', (v) => {
290
+ const m = v.toLowerCase();
291
+ if (!['once', 'daemon', 'scheduled', 'deploy-only'].includes(m)) {
292
+ throw new InvalidArgumentError('must be one of: once | daemon | scheduled | deploy-only (deploy-only = scheduled — deploy without auto-run)');
293
+ }
294
+ return m;
295
+ }, 'scheduled')
210
296
  .option('--env <json>', 'Env var overrides as JSON, e.g. \'{"KEY":"value"}\'')
211
297
  .option('--start-command <cmd>', 'Startup command override (defaults to manifest entrypoint)')
212
298
  .action(async (id, opts) => {
299
+ // deploy-only → scheduled:本地别名归一(服务端 RunMode 枚举无 deploy-only)。
300
+ const runMode = opts.runMode === 'deploy-only' ? 'scheduled' : opts.runMode;
301
+ if (runMode === 'daemon' || runMode === 'once') {
302
+ // 预警在请求发出之前给出:once/daemon 会在部署时立刻启动入口脚本
303
+ //(daemon 异常退出还会自动重启)——"部署即跑"是双跑事故的根源。
304
+ process.stderr.write(chalk.yellow(`⚠ run-mode "${opts.runMode}" starts the entry script immediately at deploy — for deploy-only (middleware/cron triggers later), use --run-mode scheduled.\n`));
305
+ }
213
306
  const spinner = ora('Triggering deployment…').start();
214
307
  try {
215
- const body = { runMode: opts.runMode };
308
+ const body = { runMode };
216
309
  if (opts.executor)
217
310
  body.executorId = opts.executor;
218
- if (opts.env)
219
- body.env = JSON.parse(opts.env);
220
311
  if (opts.startCommand)
221
312
  body.startCommand = opts.startCommand;
313
+ // P2(CLI-AGENT-UX-AUDIT):--env 的 JSON 解析此前裸放在 try 里,坏 JSON
314
+ // 被当成「部署失败」报退出码 1——agent 会去查服务端日志,而实际是自己
315
+ // 参数写错了。与 `task trigger --params` 同口径:本地 payload 错误是
316
+ // 用法错误(退出码 2),且请求不发出。
317
+ if (opts.env) {
318
+ try {
319
+ body.env = JSON.parse(opts.env);
320
+ }
321
+ catch (err) {
322
+ throw new UsageError(`Invalid --env JSON: ${err instanceof Error ? err.message : String(err)}`);
323
+ }
324
+ }
222
325
  const dep = await post(`/app-deployments/applications/${id}/deploy`, body);
223
326
  spinner.succeed('Deployment triggered');
224
327
  console.log(chalk.gray(` deployment: ${dep?.id ?? '-'} status: ${dep?.status ?? '-'} executor: ${dep?.executorId ?? 'auto'}`));
@@ -227,6 +330,97 @@ export function appsCommand() {
227
330
  emitError('Deployment failed', e, { spinner });
228
331
  }
229
332
  });
333
+ // P2: acf app upgrade-all <appId> —— POST /applications/:id/upgrade-all(DEP-02
334
+ // 灰度)。契约:请求体全可选,缺省(不传 body)= all 全量升级,既有语义逐字节
335
+ // 保持;canary 传 { rollout: { strategy: 'canary', percentage? } }。
336
+ // 2026-10-07:UpgradeAllDto 增可选 version(版本定向灰度/渐进回滚)——
337
+ // --version <v> 时 body 带顶层 version;缺省不带(升级目标恒为应用当前版本)。
338
+ // 批次由服务端异步推进(心跳确认 → 健康探测 → 提升),受理 ≠ 完成。
339
+ cmd.command('upgrade-all <appId>')
340
+ .description("Trigger a rolling upgrade of all RUNNING deployments to the application's current version (or --version). Default = full upgrade (pre-DEP-02 semantics, no body). Canary batches advance asynchronously on the server — acceptance is not completion")
341
+ .option('--strategy <strategy>', 'Rollout strategy: all (default) | canary (first batch → heartbeat confirm → health probe → auto-promote the rest, DEP-02)')
342
+ .option('--percentage <n>', 'Canary first-batch percentage, int 1-100 (default 50 — first batch = ceil(N × p%), at least 1)', (v) => {
343
+ const n = Number.parseInt(v, 10);
344
+ if (!Number.isInteger(n) || n < 1 || n > 100) {
345
+ throw new InvalidArgumentError('must be an integer between 1 and 100');
346
+ }
347
+ return n;
348
+ })
349
+ .option('--version <version>', 'Target a historical released version (version string, not uuid) — enables gradual rollback. Default: the application\'s current version. The app record is restored from that version snapshot before the rollout starts')
350
+ .option('--json', 'Emit raw JSON (CI-consumable)')
351
+ .option('-y, --yes', 'Skip the confirmation prompt for a FULL upgrade (all strategy)', false)
352
+ .action(async (appId, opts) => {
353
+ const strategy = opts.strategy ?? 'all';
354
+ if (strategy !== 'all' && strategy !== 'canary') {
355
+ emitUsageError(`Unknown rollout strategy "${strategy}" — expected one of: all | canary`);
356
+ }
357
+ if (opts.percentage !== undefined && strategy !== 'canary') {
358
+ emitUsageError('--percentage only applies to --strategy canary (the full-upgrade path never reads it)');
359
+ }
360
+ // P1(CLI-AGENT-UX-AUDIT):全量滚动升级会重启该应用**所有 RUNNING 部署**,
361
+ // 此前零确认。canary 天然是低风险首步(且服务端会自动提升/回滚),不设门;
362
+ // all 是「一次性动全量」,需要显式表态——与三处 delete 共用同一套非交互语义。
363
+ if (strategy === 'all') {
364
+ if (!(await confirmDestructive(`Roll out the upgrade to ALL running deployments of ${appId}?`, { yes: opts.yes }))) {
365
+ return;
366
+ }
367
+ }
368
+ const spinner = ora('Triggering upgrade…').start();
369
+ try {
370
+ // all:不传 body —— 与既有全量升级语义逐字节一致;canary:rollout
371
+ // 白名单体,percentage 仅在给出时携带(服务端缺省 50)。
372
+ const body = strategy === 'canary'
373
+ ? {
374
+ ...(opts.version !== undefined ? { version: opts.version } : {}),
375
+ rollout: {
376
+ strategy,
377
+ ...(opts.percentage !== undefined ? { percentage: opts.percentage } : {}),
378
+ },
379
+ }
380
+ : opts.version !== undefined
381
+ ? { version: opts.version }
382
+ : undefined;
383
+ const r = await post(`/applications/${appId}/upgrade-all`, body);
384
+ spinner.stop();
385
+ if (opts.json) {
386
+ // ECO-02:响应对象直出(含 rollout 批次信息),退出码语义与下面的人读
387
+ // 路径一致(受理被拒/批次失败 → 1)。
388
+ console.log(JSON.stringify(r, null, 2));
389
+ if (r.ok === false || (r.failed ?? 0) > 0)
390
+ process.exitCode = 1;
391
+ return;
392
+ }
393
+ if (r.ok === false) {
394
+ // 受理被拒(ARCH-31 在途批次互斥 / canary 首批失败 ok=false,failed=1):
395
+ // HTTP 仍是 2xx,但 CLI 要让 CI 看得见(对齐 task batch 部分失败语义)。
396
+ spinner.fail('Upgrade batch not started');
397
+ console.error(chalk.red(` ${r.rollout?.blockedReason ?? `first canary batch failed (${r.failed}/${r.total}) — see rolloutMeta on the app's deployments for the reason`}`));
398
+ process.exitCode = 1;
399
+ return;
400
+ }
401
+ if (strategy === 'canary') {
402
+ spinner.succeed(`Canary batch accepted: first batch ${r.succeeded}/${r.total} deployment(s)`);
403
+ console.log(chalk.gray(` batchId: ${r.rollout?.batchId ?? '-'} strategy: ${r.rollout?.strategy ?? strategy}`));
404
+ if (r.rollout?.canaryIds?.length) {
405
+ console.log(chalk.gray(` canary: ${r.rollout.canaryIds.map((x) => x.slice(0, 12)).join(', ')}`));
406
+ }
407
+ if (r.rollout?.promotedIds?.length) {
408
+ console.log(chalk.gray(` promoted so far: ${r.rollout.promotedIds.length}`));
409
+ }
410
+ console.log(chalk.yellow(` ⚠ Accepted is not finished — the batch advances asynchronously (heartbeat confirm → health probe → promote). Follow progress in the admin console or: acf app deployments ${appId}`));
411
+ }
412
+ else {
413
+ spinner.succeed(`Upgrade triggered: ${r.succeeded}/${r.total} deployment(s) accepted, ${r.failed} failed`);
414
+ if ((r.failed ?? 0) > 0) {
415
+ console.error(chalk.red(` ${r.failed} deployment(s) failed to accept the upgrade — inspect with: acf app deployments ${appId}`));
416
+ process.exitCode = 1;
417
+ }
418
+ }
419
+ }
420
+ catch (e) {
421
+ emitError('Failed to trigger upgrade-all', e, { spinner });
422
+ }
423
+ });
230
424
  // acf app deployments [appId]
231
425
  cmd.command('deployments [appId]')
232
426
  .description('List deployments (optionally filtered by application)')
@@ -303,5 +497,49 @@ export function appsCommand() {
303
497
  emitError('Failed to list versions', e, { spinner });
304
498
  }
305
499
  });
500
+ cmd.command('releases <appId>')
501
+ .description('List unified release history (version × latest deployment) for an application — the modern DEP-01 view; `app versions` is the legacy alias')
502
+ .option('-p, --page <n>', 'Page number', '1')
503
+ .option('-n, --page-size <n>', 'Page size (max 200, default 50)', '50')
504
+ // --json 补面(UX 统一):列表/信封形态 → 单行紧凑 JSON
505
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
506
+ .action(async (appId, opts) => {
507
+ const spinner = ora('Fetching releases…').start();
508
+ try {
509
+ // getReleases returns `{ data, total, page, pageSize }`
510
+ const data = await get(`/applications/${appId}/releases`, { page: opts.page, pageSize: opts.pageSize });
511
+ spinner.stop();
512
+ if (opts.json) {
513
+ console.log(JSON.stringify(data));
514
+ return;
515
+ }
516
+ const list = Array.isArray(data) ? data : (data.data ?? data.list ?? []);
517
+ if (!list.length) {
518
+ console.log(chalk.gray('No releases recorded for this application.'));
519
+ return;
520
+ }
521
+ const table = new Table({
522
+ head: ['Version', 'Deployed', 'Status', 'Count', 'Executor', 'RunMode', 'Trigger'],
523
+ colWidths: [12, 20, 12, 8, 18, 10, 12],
524
+ style: { head: ['cyan'] },
525
+ });
526
+ for (const r of list) {
527
+ table.push([
528
+ r.version ?? '-',
529
+ r.deployedAt ? new Date(r.deployedAt).toLocaleString() : '-',
530
+ statusColor(r.deploymentStatus ?? r.status),
531
+ String(r.deploymentCount),
532
+ r.executorAddress ?? '-',
533
+ r.runMode ?? '-',
534
+ r.triggerType ?? '-',
535
+ ]);
536
+ }
537
+ console.log(table.toString());
538
+ console.log(chalk.gray(`Total: ${data.total ?? list.length} page ${opts.page}`));
539
+ }
540
+ catch (e) {
541
+ emitError('Failed to list releases', e, { spinner });
542
+ }
543
+ });
306
544
  return cmd;
307
545
  }
@@ -44,9 +44,10 @@ export function auditCommand() {
44
44
  });
45
45
  spinner.stop();
46
46
  if (opts.json) {
47
- // ECO-02 同款:--json —— 后端返回的信封({ data, total },旧后端可
48
- // 能是裸数组)原样直出,不做任何字段裁剪。
49
- console.log(JSON.stringify(data, null, 2));
47
+ // ECO-02 同款:列表/信封形态 → 单行紧凑 JSON(此前误用 pretty(2),
48
+ // 与 task list / agent sessions / sop list 的列表直出口径不一致——
49
+ // README 明确列表形态是「单行紧凑 JSON」)。
50
+ console.log(JSON.stringify(data));
50
51
  return;
51
52
  }
52
53
  const rows = Array.isArray(data) ? data : (data.data ?? []);
@@ -1,2 +1,10 @@
1
1
  import { Command } from 'commander';
2
+ /**
3
+ * acf deploy 组 —— 部署行的干预/查询面。
4
+ *
5
+ * 2026-10 开发人员实测的可发现性缺口:`acf deploy --help` 只有 upgrade/stop,
6
+ * 被误读成"CLI 没有部署状态查询";实际列表在 `acf app deployments`。修复:
7
+ * ① deploy 组补 `list`(与 app deployments 同源——同一个 GET /app-deployments
8
+ * 契约,改动需两边同步);② 组描述里交叉引用。
9
+ */
2
10
  export declare function deployCommand(): Command;
@@ -1,10 +1,72 @@
1
1
  import { Command } from 'commander';
2
+ import Table from 'cli-table3';
2
3
  import chalk from 'chalk';
3
4
  import ora from 'ora';
4
- import { post } from '../client.js';
5
- import { emitError } from '../ui.js';
5
+ import { get, post, del } from '../client.js';
6
+ import { emitError, confirmDestructive } from '../ui.js';
7
+ function statusColor(s) {
8
+ if (s === 'running')
9
+ return chalk.green(s);
10
+ if (s === 'stopped')
11
+ return chalk.gray(s);
12
+ if (s === 'error' || s === 'failed')
13
+ return chalk.red(s);
14
+ if (s === 'deploying')
15
+ return chalk.cyan(s);
16
+ return chalk.yellow(s);
17
+ }
18
+ /**
19
+ * acf deploy 组 —— 部署行的干预/查询面。
20
+ *
21
+ * 2026-10 开发人员实测的可发现性缺口:`acf deploy --help` 只有 upgrade/stop,
22
+ * 被误读成"CLI 没有部署状态查询";实际列表在 `acf app deployments`。修复:
23
+ * ① deploy 组补 `list`(与 app deployments 同源——同一个 GET /app-deployments
24
+ * 契约,改动需两边同步);② 组描述里交叉引用。
25
+ */
6
26
  export function deployCommand() {
7
- const cmd = new Command('deploy').description('Manage application deployments (upgrade / stop running instances)');
27
+ const cmd = new Command('deploy').description('Manage application deployments (upgrade / stop / list / remove records). List all deployments with: acf deploy list (same data as acf app deployments)');
28
+ // acf deploy list [appId] —— 与 apps.ts 的 `app deployments` 同源同契约。
29
+ cmd.command('list [appId]')
30
+ .description('List deployments (optionally filtered by application) — same data as: acf app deployments')
31
+ .option('-p, --page <n>', 'Page number', '1')
32
+ .option('-n, --page-size <n>', 'Page size', '20')
33
+ // --json 补面(UX 统一):列表/信封形态 → 单行紧凑 JSON
34
+ .option('--json', 'Emit raw JSON (CI-consumable, no table)')
35
+ .action(async (appId, opts) => {
36
+ const spinner = ora('Fetching deployments…').start();
37
+ try {
38
+ // app-deployment.service.findAll returns `{ data, total }`
39
+ const data = await get('/app-deployments', {
40
+ ...(appId ? { applicationId: appId } : {}),
41
+ page: opts.page,
42
+ pageSize: opts.pageSize,
43
+ });
44
+ spinner.stop();
45
+ if (opts.json) {
46
+ console.log(JSON.stringify(data));
47
+ return;
48
+ }
49
+ const list = Array.isArray(data) ? data : (data.data ?? data.list ?? []);
50
+ const table = new Table({
51
+ head: ['Deployment', 'App', 'Executor', 'Status', 'RunMode'],
52
+ colWidths: [14, 14, 14, 12, 11],
53
+ style: { head: ['cyan'] },
54
+ });
55
+ for (const d of list) {
56
+ table.push([
57
+ d.id.slice(0, 12),
58
+ d.applicationId?.slice(0, 12) ?? '-',
59
+ d.executorId?.slice(0, 12) ?? '-',
60
+ statusColor(d.status),
61
+ d.runMode ?? '-',
62
+ ]);
63
+ }
64
+ console.log(table.toString());
65
+ }
66
+ catch (e) {
67
+ emitError('Failed to list deployments', e, { spinner });
68
+ }
69
+ });
8
70
  // acf deploy upgrade <deploymentId>
9
71
  cmd.command('upgrade <deploymentId>')
10
72
  .description('Trigger an overlay upgrade for a running deployment (pulls the latest application version)')
@@ -35,5 +97,28 @@ export function deployCommand() {
35
97
  emitError('Failed to stop deployment', e, { spinner });
36
98
  }
37
99
  });
100
+ // acf deploy remove <deploymentId> —— DELETE /app-deployments/:id
101
+ //
102
+ // 2026-10 开发人员遗留噪音:一条 stopped + daemon 的旧部署记录无法删除
103
+ //(CLI 只有 stop)。服务端早已提供 DELETE /app-deployments/:id(仅终态行
104
+ // FAILED/STOPPED,在途/运行/待审批 409 并说明正确出口),CLI 补齐此面。
105
+ cmd.command('remove <deploymentId>')
106
+ .description('Delete a FINISHED deployment record (failed/stopped only). In-flight, running and pending-approval rows are refused with 409 — stop a running one first, use approval reject/cancel for a pending one')
107
+ .option('-y, --yes', 'Skip confirmation prompt', false)
108
+ .action(async (deploymentId, opts) => {
109
+ // P0(CLI-AGENT-UX-AUDIT):非交互 stdin 下必须显式拒绝,不能静默假绿。
110
+ if (!(await confirmDestructive(`Delete deployment record ${deploymentId}? (terminal rows only: failed/stopped)`, { yes: opts.yes }))) {
111
+ return;
112
+ }
113
+ const spinner = ora('Deleting deployment record…').start();
114
+ try {
115
+ // DELETE /app-deployments/:id — AppDeploymentController.remove
116
+ const r = await del(`/app-deployments/${deploymentId}`);
117
+ spinner.succeed(`Deployment record ${r?.deletedId ?? deploymentId} removed`);
118
+ }
119
+ catch (e) {
120
+ emitError('Failed to remove deployment record', e, { spinner });
121
+ }
122
+ });
38
123
  return cmd;
39
124
  }
@@ -20,9 +20,11 @@
20
20
  import { Command } from 'commander';
21
21
  import axios from 'axios';
22
22
  import chalk from 'chalk';
23
- import { get, post } from '../client.js';
23
+ import { get, post, normalizeApiBase } from '../client.js';
24
24
  import { getApiUrl } from '../config.js';
25
25
  import { emitError, EXIT_CODES } from '../ui.js';
26
+ // 失败原因 → 可操作建议(与 task trigger --wait 的出口同源,见 tasks.ts)。
27
+ import { FAILURE_REASON_HINTS } from './tasks.js';
26
28
  const TERMINAL = new Set(['success', 'failed', 'timeout', 'killed', 'cancelled']);
27
29
  /**
28
30
  * 增量 SSE 解析器:feed(chunk) → 完整消息数组。跨 chunk 半行/半消息安全;
@@ -101,6 +103,22 @@ export function execCommand() {
101
103
  break;
102
104
  fromLine = printed;
103
105
  }
106
+ // 失败终态:透出结构化原因 + 可操作建议(与 task trigger --wait 同源,
107
+ // 此前 tail 只打日志不解释失败,CI 里只能靠人肉读日志)。
108
+ if (exec.status !== 'success') {
109
+ if (exec.exitCode !== null && exec.exitCode !== undefined) {
110
+ process.stderr.write(chalk.yellow(`Exit code : ${exec.exitCode}\n`));
111
+ }
112
+ if (exec.failureReason) {
113
+ process.stderr.write(chalk.yellow(`Failure reason : ${exec.failureReason}\n`));
114
+ const hint = FAILURE_REASON_HINTS[exec.failureReason];
115
+ if (hint)
116
+ process.stderr.write(chalk.yellow(`Suggestion : ${hint}\n`));
117
+ }
118
+ if (exec.errorMessage) {
119
+ process.stderr.write(chalk.yellow(`Error : ${exec.errorMessage}\n`));
120
+ }
121
+ }
104
122
  process.exitCode = exec.status === 'success' ? 0 : 1;
105
123
  return;
106
124
  }
@@ -108,8 +126,12 @@ export function execCommand() {
108
126
  // SEC-CLI-01: 先换一枚 30s TTL 的专用 SSE 票据(走常规 Authorization
109
127
  // 头的 POST),再以 ?ticket= 建流——`?access_token=` 通道已被服务端撤销,
110
128
  // 旧写法会让每次非终态 tail 直接 401。与 admin-web/src/api/sse.ts 同流程。
129
+ // API-PREFIX-01(本轮):建流 URL 必须走 normalizeApiBase——admin-api
130
+ // 有全局 /api 前缀(main.ts setGlobalPrefix),此前用裸 getApiUrl()
131
+ // 拼 URL,默认 http://localhost:3105 对标准部署恒 404(与 client.ts
132
+ // 2026-10-07 修过的普通请求同类缺陷,SSE 直连 axios 绕过了归一)。
111
133
  const { ticket } = await post('/auth/sse-ticket');
112
- const base = getApiUrl().replace(/\/+$/, '');
134
+ const base = normalizeApiBase(getApiUrl());
113
135
  const url = `${base}/tasks/${exec.taskId}/executions/${execId}/logs/stream?ticket=${encodeURIComponent(ticket)}`;
114
136
  const res = await axios.get(url, { responseType: 'stream', timeout: 0 });
115
137
  process.stderr.write(chalk.gray(`[tail] following execution ${execId} (status: ${exec.status ?? 'unknown'}) — Ctrl+C to detach\n`));
@@ -3,7 +3,7 @@ import Table from 'cli-table3';
3
3
  import chalk from 'chalk';
4
4
  import ora from 'ora';
5
5
  import { get, post } from '../client.js';
6
- import { emitError } from '../ui.js';
6
+ import { emitError, confirmDestructive } from '../ui.js';
7
7
  function statusColor(s) {
8
8
  if (s === 'online')
9
9
  return chalk.green(s);
@@ -137,7 +137,14 @@ export function executorsCommand() {
137
137
  cmd.command('rotate <nameOrId>')
138
138
  .description('Rotate an executor token (ADMIN; new token is shown ONCE in this output)')
139
139
  .option('--reason <reason>', 'Optional rotation reason (≤200 chars, recorded in the audit log)')
140
+ .option('-y, --yes', 'Skip confirmation prompt', false)
140
141
  .action(async (nameOrId, opts) => {
142
+ // P1(CLI-AGENT-UX-AUDIT):轮换是**不可逆**的——旧 token 立即失效,
143
+ // 而新 token 只在本命令输出里出现一次,没被捕获就永久丢失(只能再轮换)。
144
+ // 此前零确认。补确认,并复用统一的非交互语义(非 TTY 缺 --yes → 码 2)。
145
+ if (!(await confirmDestructive(`Rotate the token for "${nameOrId}"? The old token stops working immediately and the new one is shown only once.`, { yes: opts.yes }))) {
146
+ return;
147
+ }
141
148
  const spinner = ora('Rotating executor token…').start();
142
149
  try {
143
150
  const id = await resolveExecutorId(nameOrId);
@@ -1,4 +1,48 @@
1
1
  import { Command } from 'commander';
2
2
  import * as readline from 'readline';
3
3
  export declare function maskEcho(rl: readline.Interface, isTTY?: boolean): void;
4
+ /**
5
+ * P0(CLI-AGENT-UX-AUDIT):登录地址解析的单一事实源(导出供单测)。
6
+ *
7
+ * 优先级:显式 `--url` > `ACF_API_URL` env > 已存配置 > 内置默认值。
8
+ * 前两者与磁盘配置都由 getApiUrl() 归一(其自身就是 env || store),
9
+ * 因此这里只需在「显式 --url」与「其余」之间分流。
10
+ *
11
+ * 关键点:**不再对地址发交互 prompt**。地址有合理默认值,为它中断整条登录
12
+ * 在自动化面只会制造困惑(旧行为下 agent 会拿到空串兜底的默认地址 + 假 exit 0)。
13
+ */
14
+ export declare function resolveLoginUrl(explicit?: string): string;
15
+ /**
16
+ * P0(CLI-AGENT-UX-AUDIT):非交互下需要人工输入时给出**可操作**的用法错误,
17
+ * 而不是让 prompt 拿到 EOF 空串后静默继续。契约与 resolveTotpCode 的
18
+ * 「stdin 非交互且缺 --code」分支完全一致(UsageError → 退出码 2)。
19
+ *
20
+ * @param question 交互提示语
21
+ * @param alternative 非交互时应改用的旗标/环境变量(写进错误消息)
22
+ */
23
+ export declare function promptOrFail(question: string, alternative: string, promptFn?: (question: string) => Promise<string>): Promise<string>;
24
+ export declare function resolveTotpCode(opts: {
25
+ code?: string;
26
+ }, promptFn?: (question: string) => Promise<string>): Promise<string>;
4
27
  export declare function loginCommand(): Command;
28
+ /**
29
+ * P1(CLI-AGENT-UX-AUDIT):`acf whoami` —— 打印当前凭据的身份与角色。
30
+ *
31
+ * 为什么 agent 需要它:后端有大量 ADMIN-only 面(audit / sop / notification /
32
+ * agent / executor-packages 全模块,以及所有应用写操作)。此前 agent 无法在
33
+ * 开工前自检权限,只能靠「调用 → 403」逐个试错。profile 返回的是 AuthUser,
34
+ * 其中 `role` 是**单值**(不是 roles 数组),ADMIN 判定按此单值。
35
+ */
36
+ export declare function whoamiCommand(): Command;
37
+ /**
38
+ * P1(CLI-AGENT-UX-AUDIT):`acf logout` —— 服务端吊销 refresh token 家族的
39
+ * 同时清空本地凭据。
40
+ *
41
+ * 为什么 agent 需要它:access + refresh **双 token** 都落在磁盘 0600 文件里,
42
+ * refresh 是长效的。共享机器 / 一次性容器上跑完不清,等于把一枚长效凭证留在
43
+ * 盘上。此前面只有「再 login 一次覆盖」,没有出口。
44
+ *
45
+ * 语义:先尽力通知服务端(revoke all refresh tokens),**网络失败也照常清本地**
46
+ * ——本地凭据必须确保被抹掉,不能因为服务端不可达就把 token 留在盘上。
47
+ */
48
+ export declare function logoutCommand(): Command;