@formigio/fazemos-cli 0.10.85 → 0.10.86

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.
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ import { loadYaml, summarize } from './yaml/load.js';
15
15
  import { printFindings, printJson } from './yaml/format.js';
16
16
  import { validateManifest } from './manifest/checks.js';
17
17
  import { validatePath as validateRunbookPath } from './runbook/checks.js';
18
- import { findLocalRegistry, resolveRole, buildInboxFile, writeInboxFile, writeInboxFileAtPath, buildRolesSyncPayload, findUnprocessedInboxFiles, computeFileHash, gitCommitInboxFile, gitCommitAndPushInboxFile, isAgentExecution, computeRegistryInboxPath, computeChildDispatchDepth, shouldFallBackToFile, isWakeIneligibleForCadencelessRole, } from './dispatch.js';
18
+ import { findLocalRegistry, resolveRole, buildDeadLetterFile, writeInboxFileAtPath, buildRolesSyncPayload, findUnprocessedInboxFiles, computeFileHash, gitCommitInboxFile, computeRegistryDeadLetterPath, computeChildDispatchDepth, shouldFallBackToFile, isWakeIneligibleForCadencelessRole, } from './dispatch.js';
19
19
  import { execSync } from 'child_process';
20
20
  import { registerPauseCommands } from './pause.js';
21
21
  import { registerBudgetCommands } from './budget.js';
@@ -10193,11 +10193,13 @@ Examples:
10193
10193
  // --body "Should we ship F19 before F7?" --priority high --commit
10194
10194
  program
10195
10195
  .command('dispatch <to> <type>')
10196
- .description(`Send a role-to-role dispatch. Calls POST /api/dispatches (API writes DB row
10197
- + fires fan-out, returns file_path), then CLI writes the inbox file.
10196
+ .description(`Send a role-to-role dispatch. Calls POST /api/dispatches — the DB row is
10197
+ the sole delivery (DISPATCH-DB-ONLY-INBOX): no inbox file is written, no git
10198
+ operation runs, and the API's file_path is ignored entirely.
10198
10199
 
10199
- Use --file-only to skip the API and write only the local file (degraded/offline
10200
- mode, for not-yet-migrated playbooks).
10200
+ Use --file-only for a deliberate offline mode: skips the API and writes a
10201
+ local DEAD LETTER instead (no DB row, no wake, no Slack notification — the
10202
+ recipient never sees it). Only for a human with no network.
10201
10203
 
10202
10204
  Recipients are resolved via the nearest .fazemos/roles.json registry, walking
10203
10205
  up from the current directory. Cross-workspace recipients are followed via
@@ -10211,8 +10213,8 @@ Types: question | task | signal | response | flag | decision | direction | brief
10211
10213
  .option('--re <ref>', 'optional reference (worksheet id, feature token, etc.)')
10212
10214
  .option('--thread <id>', 'optional prior dispatch id this is threaded to')
10213
10215
  .option('--expires-at <iso>', 'optional deadline (ISO 8601)')
10214
- .option('--commit', 'git add + commit the inbox file after writing')
10215
- .option('--file-only', 'skip API call, write only the local inbox file (offline/legacy mode)')
10216
+ .option('--commit', 'no-op unless paired with --file-only, where it commits the dead-letter file')
10217
+ .option('--file-only', 'skip the API; write a local dead letter only (no delivery — offline mode for a human with no network)')
10216
10218
  .option('--runbook-ref <id>', 'runbook id to attach (task-only; validated by the API against the runbook contract)')
10217
10219
  .option('--params <json>', 'runbook input params as an inline JSON object (mutually exclusive with --params-file)')
10218
10220
  .option('--params-file <path>', 'read runbook input params from a JSON file (mutually exclusive with --params)')
@@ -10263,6 +10265,13 @@ Types: question | task | signal | response | flag | decision | direction | brief
10263
10265
  if (!body) {
10264
10266
  throw new Error('--body or --body-file is required');
10265
10267
  }
10268
+ // DISPATCH-DB-ONLY-INBOX (P2, T2.2): --commit is a no-op EXCEPT when
10269
+ // paired with --file-only (where it still commits the dead-letter
10270
+ // file — see the --file-only branch below). Print the exact warning
10271
+ // text the spec requires; the exit code is unaffected either way.
10272
+ if (opts.commit && !opts.fileOnly) {
10273
+ console.error('--commit is a no-op: dispatches are DB-delivered; no inbox file is written.');
10274
+ }
10266
10275
  // Find local registry
10267
10276
  const localRegistry = findLocalRegistry(process.cwd());
10268
10277
  if (!localRegistry) {
@@ -10361,7 +10370,7 @@ Types: question | task | signal | response | flag | decision | direction | brief
10361
10370
  // SKIP agent-mode commit+push (no relPath) — rul_dispatch_local_file_best_effort_cross_workspace
10362
10371
  return;
10363
10372
  }
10364
- // ── Resolved path: existing behavior unchanged ──────────────────────────
10373
+ // ── Resolved path ─────────────────────────────────────────────────
10365
10374
  const { role, registry } = resolved;
10366
10375
  const input = {
10367
10376
  to,
@@ -10375,156 +10384,111 @@ Types: question | task | signal | response | flag | decision | direction | brief
10375
10384
  runbookRef: opts.runbookRef,
10376
10385
  params: runbookParams,
10377
10386
  };
10378
- const { filename, content, summary } = buildInboxFile(input);
10379
- let fullPath;
10380
- let relPath;
10381
10387
  if (opts.fileOnly) {
10382
- // ── Legacy / offline mode: write file directly, skip API ────────
10383
- fullPath = writeInboxFile(registry._workspaceRoot, role, filename, content);
10384
- relPath = fullPath.startsWith(registry._workspaceRoot)
10385
- ? fullPath.slice(registry._workspaceRoot.length + 1)
10386
- : fullPath;
10387
- console.log(chalk.green(`✓ Wrote inbox file (--file-only):`));
10388
+ // ── DISPATCH-DB-ONLY-INBOX (P2, T2.3): dead letter, not delivery ──
10389
+ // rul_file_only_is_dead_letter: no API call, no DB row, no wake, no
10390
+ // Slack notification. Writes into the SENDER's gitignored
10391
+ // `dead-letter/` directory (resolved against the LOCAL registry,
10392
+ // since the dead letter is the sender's own offline record — not
10393
+ // the recipient's, and not necessarily in the recipient's
10394
+ // workspace when the recipient was reached via a cross-workspace
10395
+ // hop). This is an explicit, deliberate offline mode for a human
10396
+ // with no network — it must never be confused with delivery.
10397
+ const { filename, content } = buildDeadLetterFile(input);
10398
+ const senderResolved = resolveRole(opts.from, localRegistry);
10399
+ const relPath = computeRegistryDeadLetterPath(senderResolved?.role, opts.from, filename);
10400
+ const fullPath = writeInboxFileAtPath(localRegistry._workspaceRoot, relPath, content);
10401
+ console.log(chalk.yellow('✓ Wrote dead-letter file (no delivery): recipient will not be woken.'));
10388
10402
  console.log(` ${chalk.cyan(fullPath)}`);
10389
- console.log(` Workspace: ${registry.workspace} Filler: ${role.filler.identity} (${role.filler.type})`);
10390
- console.log(chalk.gray(' (API not called — file-only mode)'));
10391
- }
10392
- else {
10393
- // ── F26 API write-through (Dex S-B) ─────────────────────────────
10394
- // F35 HC2 (BUG52): propagate the dispatch-chain depth so the API's
10395
- // ceiling (TRIGGER_MAX_DISPATCH_DEPTH) actually trips. See
10396
- // computeChildDispatchDepth — env var present (agent execution) ⇒
10397
- // parent + 1; absent (human CLI) ⇒ top-of-chain depth 0.
10398
- const dispatchDepth = computeChildDispatchDepth(process.env.FAZEMOS_ORIGINATING_DISPATCH_DEPTH);
10399
- // AUTON-CAUSAL-FTR (AC15) — env-to-payload bridge (rul_runner_root_chain_id_passthrough).
10400
- // Include root_chain_id ONLY when ROOT_CHAIN_ID env is non-empty after .trim().
10401
- // DO NOT send empty string — absence means wake seam seeds a new root (documented degradation).
10402
- // Mirrors the existing FAZEMOS_ORIGINATING_DISPATCH_DEPTH bridge above.
10403
- const rootChainId = process.env.ROOT_CHAIN_ID?.trim() || undefined;
10404
- const reqBody = {
10405
- to,
10406
- from: opts.from,
10407
- type,
10408
- priority: opts.priority ?? 'normal',
10409
- body,
10410
- thread_id: opts.thread ?? null,
10411
- re: opts.re ? [opts.re] : null,
10412
- expires_at: opts.expiresAt ?? null,
10413
- source: 'cli',
10414
- runbook_ref: opts.runbookRef ?? null,
10415
- params: runbookParams ?? null,
10416
- dispatch_depth: dispatchDepth,
10417
- ...(rootChainId ? { root_chain_id: rootChainId } : {}),
10418
- };
10419
- let apiResp;
10420
- try {
10421
- apiResp = await api('POST', '/api/dispatches', reqBody);
10422
- }
10423
- catch (err) {
10424
- // BUG53: a deliberate API refusal (4xx) must HARD-FAIL — do NOT fall
10425
- // back to writing a local inbox file. Inside an agent that file gets
10426
- // committed/pushed and re-drained, re-introducing the dispatch with no
10427
- // depth tracking and bypassing the very gate that refused it (e.g. 409
10428
- // DEPTH_CEILING_EXCEEDED, the F35 loop-safety ceiling). File-fallback is
10429
- // only for genuine API-unavailable (network / 5xx).
10430
- const status = err instanceof ApiError ? err.status : undefined;
10431
- if (!shouldFallBackToFile(status)) {
10432
- const code = err instanceof ApiError && err.code ? ` ${err.code}` : '';
10433
- console.error(chalk.red(`✗ Dispatch refused (${status}${code}): ${err instanceof Error ? err.message : String(err)}`));
10434
- console.error(chalk.gray(' Not falling back to file-only — a deliberate refusal must not be bypassed.'));
10435
- process.exitCode = 1;
10436
- return;
10403
+ console.log(chalk.gray(' (API not called — file-only mode. No DB row, no wake, no Slack notification.)'));
10404
+ if (opts.commit) {
10405
+ // --file-only --commit keeps its meaning: commit the dead-letter file.
10406
+ try {
10407
+ gitCommitInboxFile(localRegistry._workspaceRoot, relPath, `dispatch(${opts.from} → ${to}): ${type} [dead-letter]`,
10408
+ /* force */ true);
10409
+ console.log(chalk.green('✓ Committed.'));
10437
10410
  }
10438
- // BUG221 lever-a (AC-2): transient network failure in resolved path.
10439
- // Write a file-only fallback (role.inbox is available) AND exit 2 (non-zero).
10440
- // The operator is told the file was written and drain-on-cadence is the recovery
10441
- // path. This replaces the old silent exit-0 — downstream tooling now sees failure.
10442
- const networkMsg = err instanceof Error ? err.message : String(err);
10443
- const apiUrl = getEnv().apiUrl;
10444
- fullPath = writeInboxFile(registry._workspaceRoot, role, filename, content);
10445
- relPath = fullPath.startsWith(registry._workspaceRoot)
10446
- ? fullPath.slice(registry._workspaceRoot.length + 1)
10447
- : fullPath;
10448
- console.error(`fazemos dispatch: API unreachable at ${apiUrl} after network error; wrote file-only fallback at ${fullPath}. Recipient will drain on next cadence tick.`);
10449
- console.error(` Error: ${networkMsg}`);
10450
- if (opts.commit) {
10451
- try {
10452
- gitCommitInboxFile(registry._workspaceRoot, relPath, `dispatch(${opts.from} → ${to}): ${type}`);
10453
- console.error(' File committed.');
10454
- }
10455
- catch (cerr) {
10456
- console.error(` warning: commit failed — ${cerr instanceof Error ? cerr.message : String(cerr)}`);
10457
- }
10411
+ catch (err) {
10412
+ const msg = err instanceof Error ? err.message : String(err);
10413
+ console.log(chalk.yellow(` warning: commit failed — ${msg}`));
10458
10414
  }
10459
- process.exitCode = 2;
10460
- return;
10461
- }
10462
- // API returned file_path — CLI writes the actual file (Dex S-B).
10463
- //
10464
- // rul_registry_inbox_field_wins_regardless_of_scope (BUG64 Fix):
10465
- // The write path is always built from the registry-declared `role.inbox`,
10466
- // regardless of what `scope` the role carries or what the API's
10467
- // `file_path` returns. This ensures org-scoped roles (e.g.
10468
- // `business-operations`, `chief-of-staff`) that declare an explicit
10469
- // `inbox` in .fazemos/roles.json write to that path, not to the
10470
- // org-layout root (`roles/<slug>/inbox/`) that the API may return for
10471
- // roles with `project_id IS NULL` in role_registrations.
10472
- //
10473
- // The API's `file_path` is preserved as `relPath` for reference/logging
10474
- // but the on-disk write uses computeRegistryInboxPath(role, filename).
10475
- if (apiResp.file_path) {
10476
- // Prefer registry-declared path; use API path only when no explicit inbox.
10477
- relPath = computeRegistryInboxPath(role, to, filename);
10478
- fullPath = writeInboxFileAtPath(registry._workspaceRoot, relPath, content);
10479
- }
10480
- else {
10481
- // API didn't return a file_path (e.g. cross-workspace agent recipient) — write locally
10482
- fullPath = writeInboxFile(registry._workspaceRoot, role, filename, content);
10483
- relPath = fullPath.startsWith(registry._workspaceRoot)
10484
- ? fullPath.slice(registry._workspaceRoot.length + 1)
10485
- : fullPath;
10486
- }
10487
- console.log(chalk.green(`✓ Dispatch created (id: ${apiResp.id}):`));
10488
- console.log(` ${chalk.cyan(fullPath)}`);
10489
- console.log(` Workspace: ${registry.workspace} Filler: ${role.filler.identity} (${role.filler.type})`);
10490
- if (apiResp.thread_id && apiResp.thread_id !== apiResp.id) {
10491
- console.log(` Thread: ${apiResp.thread_id}`);
10492
10415
  }
10416
+ return;
10493
10417
  }
10494
- // rul_dispatch_cli_pushes_inbox_file_on_agent_execution (BUG66 Fix B bridge):
10495
- // When running inside a Fargate agent task (FAZEMOS_AGENT_EXECUTION=1),
10496
- // commit + push the inbox file to origin/main so the recipient's next
10497
- // dispatch_wake clone sees it. Scoped to short-execution dispatchers only.
10498
- // Long dispatchers route through Fix A (DB-drain on wake); they must NOT
10499
- // push (BUG46 token-expiry risk on long runs is out of scope for this bridge).
10500
- //
10501
- // --commit is still honored for human-workstation operators (AC3).
10502
- // Agent-mode push is additive; it does not suppress the --commit path.
10503
- if (isAgentExecution() && !opts.fileOnly && relPath) {
10504
- try {
10505
- gitCommitAndPushInboxFile(registry._workspaceRoot, relPath, `dispatch(${opts.from} → ${to}): ${type}`);
10506
- console.log(chalk.green('✓ Committed and pushed to origin/main (agent-mode).'));
10507
- }
10508
- catch (err) {
10509
- const msg = err instanceof Error ? err.message : String(err);
10510
- // DISPATCH_PUSH_CONFLICT — loud fail. The DB dispatch row is durable;
10511
- // the recipient will drain via Fix A (wake-task DB body embed).
10512
- console.error(chalk.red(`✗ Agent push failed: ${msg}`));
10418
+ // ── DISPATCH-DB-ONLY-INBOX (P2, T2.1): DB row is the sole authority ──
10419
+ // No inbox file is written on the default path, regardless of what
10420
+ // the API returns for `file_path` — that field is ignored entirely.
10421
+ // rul_dispatch_db_row_is_sole_authority
10422
+ // F35 HC2 (BUG52): propagate the dispatch-chain depth so the API's
10423
+ // ceiling (TRIGGER_MAX_DISPATCH_DEPTH) actually trips. See
10424
+ // computeChildDispatchDepth — env var present (agent execution) ⇒
10425
+ // parent + 1; absent (human CLI) ⇒ top-of-chain depth 0.
10426
+ const dispatchDepth = computeChildDispatchDepth(process.env.FAZEMOS_ORIGINATING_DISPATCH_DEPTH);
10427
+ // AUTON-CAUSAL-FTR (AC15) — env-to-payload bridge (rul_runner_root_chain_id_passthrough).
10428
+ // Include root_chain_id ONLY when ROOT_CHAIN_ID env is non-empty after .trim().
10429
+ // DO NOT send empty string — absence means wake seam seeds a new root (documented degradation).
10430
+ // Mirrors the existing FAZEMOS_ORIGINATING_DISPATCH_DEPTH bridge above.
10431
+ const rootChainId = process.env.ROOT_CHAIN_ID?.trim() || undefined;
10432
+ const reqBody = {
10433
+ to,
10434
+ from: opts.from,
10435
+ type,
10436
+ priority: opts.priority ?? 'normal',
10437
+ body,
10438
+ thread_id: opts.thread ?? null,
10439
+ re: opts.re ? [opts.re] : null,
10440
+ expires_at: opts.expiresAt ?? null,
10441
+ source: 'cli',
10442
+ runbook_ref: opts.runbookRef ?? null,
10443
+ params: runbookParams ?? null,
10444
+ dispatch_depth: dispatchDepth,
10445
+ ...(rootChainId ? { root_chain_id: rootChainId } : {}),
10446
+ };
10447
+ let apiResp;
10448
+ try {
10449
+ apiResp = await api('POST', '/api/dispatches', reqBody);
10450
+ }
10451
+ catch (err) {
10452
+ // BUG53: a deliberate API refusal (4xx) must HARD-FAIL — do NOT fall
10453
+ // back to writing a local inbox file. Inside an agent that file gets
10454
+ // committed/pushed and re-drained, re-introducing the dispatch with no
10455
+ // depth tracking and bypassing the very gate that refused it (e.g. 409
10456
+ // DEPTH_CEILING_EXCEEDED, the F35 loop-safety ceiling). File-fallback is
10457
+ // only for genuine API-unavailable (network / 5xx).
10458
+ const status = err instanceof ApiError ? err.status : undefined;
10459
+ if (!shouldFallBackToFile(status)) {
10460
+ const code = err instanceof ApiError && err.code ? ` ${err.code}` : '';
10461
+ console.error(chalk.red(`✗ Dispatch refused (${status}${code}): ${err instanceof Error ? err.message : String(err)}`));
10462
+ console.error(chalk.gray(' Not falling back to file-only — a deliberate refusal must not be bypassed.'));
10513
10463
  process.exitCode = 1;
10514
10464
  return;
10515
10465
  }
10466
+ // DISPATCH-DB-ONLY-INBOX (P2, T2.5): API unreachable / 5xx. There is
10467
+ // no file-fallback anymore — the dispatch FAILED, full stop. Say so
10468
+ // loudly (this is the exact silent-fallback shape BUG231-C1 fixed on
10469
+ // the pin path; we do not re-introduce it here) and point at the
10470
+ // deliberate offline escape hatch (--file-only) rather than taking it
10471
+ // automatically. Exit code is unchanged (2); only the side effect goes.
10472
+ const networkMsg = err instanceof Error ? err.message : String(err);
10473
+ const apiUrl = getEnv().apiUrl;
10474
+ console.error(`fazemos dispatch: API unreachable at ${apiUrl} after network error — the dispatch FAILED. Nothing was sent, and no file was written.`);
10475
+ console.error(` Error: ${networkMsg}`);
10476
+ console.error(` Rerun offline with: fazemos dispatch ${to} ${type} --from ${opts.from} --body <same body> --file-only`);
10477
+ process.exitCode = 2;
10478
+ return;
10516
10479
  }
10517
- else if (opts.commit) {
10518
- // Human-operator --commit path (AC3: unchanged from pre-fix behavior)
10519
- try {
10520
- gitCommitInboxFile(registry._workspaceRoot, relPath, `dispatch(${opts.from} → ${to}): ${type}`);
10521
- console.log(chalk.green('✓ Committed.'));
10522
- }
10523
- catch (err) {
10524
- const msg = err instanceof Error ? err.message : String(err);
10525
- console.log(chalk.yellow(` warning: commit failed — ${msg}`));
10526
- }
10480
+ // T2.1: apiResp.file_path is ignored entirely — no file write on success.
10481
+ console.log(chalk.green(`✓ Dispatch created (id: ${apiResp.id})`));
10482
+ console.log(` Workspace: ${registry.workspace} Filler: ${role.filler.identity} (${role.filler.type})`);
10483
+ if (apiResp.thread_id && apiResp.thread_id !== apiResp.id) {
10484
+ console.log(` Thread: ${apiResp.thread_id}`);
10527
10485
  }
10486
+ // DISPATCH-DB-ONLY-INBOX (P2, T2.4): the BUG66 Fix B agent-mode
10487
+ // commit+push bridge is retired along with the file write it existed
10488
+ // to ship — there is no longer an inbox file for an agent execution to
10489
+ // push. rul_dispatch_cli_pushes_inbox_file_on_agent_execution retired.
10490
+ // The DB dispatch row (already durable at this point) is the sole
10491
+ // delivery artifact; the recipient drains it via the DB, not git.
10528
10492
  }
10529
10493
  catch (err) {
10530
10494
  console.error(chalk.red(err instanceof Error ? err.message : String(err)));
@@ -10759,18 +10723,84 @@ status=read after rendering (standard agent playbook usage).
10759
10723
  Replaces the legacy file-read drain (roles/<slug>/inbox/*.md) that silently
10760
10724
  dropped cross-workspace dispatches.
10761
10725
 
10726
+ Use --mark-actioned <id...> to stage a row all the way to actioned. The DB
10727
+ transition table only allows read→actioned (unread→actioned is not a valid
10728
+ transition), so this PATCHes to read first when a row is still unread, then
10729
+ PATCHes to actioned. A 409 on a row that is already terminal (actioned or
10730
+ archived) is reported and is non-fatal — it does not stop the remaining ids.
10731
+
10762
10732
  Examples:
10763
10733
  fazemos inbox --role chief-of-staff # unread for role
10764
10734
  fazemos inbox --role engineering-director --status all
10765
10735
  fazemos inbox --role project-manager --mark-read # drain + mark read
10766
- fazemos inbox --format json --role luca | jq .`)
10736
+ fazemos inbox --format json --role luca | jq .
10737
+ fazemos inbox --mark-actioned <id> [<id>...] # stage row(s) to actioned`)
10767
10738
  .option('--role <slug>', 'filter to a specific role-slug (defaults to all roles the caller fills)')
10768
10739
  .option('--status <status>', 'unread | read | all (default: unread)', 'unread')
10769
10740
  .option('--limit <n>', 'max dispatches to return (default: 50)', (v) => parseInt(v, 10), 50)
10770
10741
  .option('--format <format>', 'table | json (default: table)', 'table')
10771
10742
  .option('--mark-read', 'after listing, PATCH each dispatch to status=read')
10743
+ .option('--mark-actioned <ids...>', 'mark the given dispatch id(s) as actioned (staged read→actioned; a 409 on an already-terminal row is reported and non-fatal)')
10772
10744
  .action(async (opts) => {
10773
10745
  try {
10746
+ // ── DISPATCH-DB-ONLY-INBOX (P2, T2.6) — `--mark-actioned <ids...>` ────
10747
+ // NEW verb. Runs standalone: when ids are given, skip the GET listing
10748
+ // entirely and stage each id to actioned. §3 (spec r2): the API's
10749
+ // transition table only allows read→actioned, so unread→actioned goes
10750
+ // through read first. A 409 TERMINAL_STATUS (already actioned/archived)
10751
+ // is reported and does not fail the batch; any other failure does.
10752
+ if (opts.markActioned && opts.markActioned.length > 0) {
10753
+ let actioned = 0;
10754
+ let alreadyTerminal = 0;
10755
+ let failed = 0;
10756
+ for (const id of opts.markActioned) {
10757
+ try {
10758
+ await api('PATCH', `/api/dispatches/${id}`, { status: 'actioned' }, {
10759
+ noProjectHeader: true,
10760
+ });
10761
+ actioned++;
10762
+ console.log(chalk.green(` ✓ ${id} → actioned`));
10763
+ }
10764
+ catch (err) {
10765
+ const code = err instanceof ApiError ? err.code : undefined;
10766
+ if (code === 'TERMINAL_STATUS') {
10767
+ // rul_dispatch_mark_actioned_terminal_nonfatal
10768
+ alreadyTerminal++;
10769
+ console.log(chalk.gray(` ~ ${id} already terminal — not re-actioned (non-fatal)`));
10770
+ continue;
10771
+ }
10772
+ if (code === 'INVALID_TRANSITION') {
10773
+ // Row is not yet `read` (unread, or deferred) — stage through
10774
+ // read first, then retry actioned.
10775
+ try {
10776
+ await api('PATCH', `/api/dispatches/${id}`, { status: 'read' }, {
10777
+ noProjectHeader: true,
10778
+ });
10779
+ await api('PATCH', `/api/dispatches/${id}`, { status: 'actioned' }, {
10780
+ noProjectHeader: true,
10781
+ });
10782
+ actioned++;
10783
+ console.log(chalk.green(` ✓ ${id} → read → actioned`));
10784
+ }
10785
+ catch (err2) {
10786
+ failed++;
10787
+ const msg2 = err2 instanceof Error ? err2.message : String(err2);
10788
+ console.error(chalk.yellow(` ⚠ Failed to mark ${id} as actioned (after staging read): ${msg2}`));
10789
+ }
10790
+ continue;
10791
+ }
10792
+ failed++;
10793
+ const msg = err instanceof Error ? err.message : String(err);
10794
+ console.error(chalk.yellow(` ⚠ Failed to mark ${id} as actioned: ${msg}`));
10795
+ }
10796
+ }
10797
+ console.log(chalk.green(`\n✓ ${actioned} dispatch(es) actioned.`) +
10798
+ (alreadyTerminal > 0 ? chalk.gray(` ${alreadyTerminal} already terminal.`) : '') +
10799
+ (failed > 0 ? chalk.yellow(` ${failed} failed.`) : ''));
10800
+ if (failed > 0)
10801
+ process.exitCode = 1;
10802
+ return;
10803
+ }
10774
10804
  // Validate --status
10775
10805
  const validStatuses = ['unread', 'read', 'all'];
10776
10806
  if (!validStatuses.includes(opts.status)) {