@formigio/fazemos-cli 0.10.84 → 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
@@ -6,16 +6,16 @@ import { config, getEnv, getToken, getActiveEnvName, getActiveEnvSource, setEnvO
6
6
  getActiveProjectId, setActiveProjectId, clearActiveProjectId, findProjectBySlug, findProjectById, findOrgById,
7
7
  // Directory-scoped context override (.fazemos.json)
8
8
  setOrgOverride, setProjectOverride, setDirContextSource, getDirContextSource, } from './config.js';
9
- import { findDirContextFile, readDirContextFile, writeDirContextFile, removeDirContextFile, DIR_CONFIG_FILENAME, } from './dircontext.js';
9
+ import { findDirContextFile, readDirContextFile, writeDirContextFile, removeDirContextFile, DIR_CONFIG_FILENAME, applyDirContext, } from './dircontext.js';
10
10
  import { loginWithBrowser, hostedLogoutUrl, signup, confirmSignup, adminLogin } from './auth.js';
11
11
  import { fetchAuthConfig } from './authConfig.js';
12
- import { api, ApiError, refreshAuthMeCache, invalidateAuthMeCache, resolveOrgIdMaybeSlug, resolveProjectIdBySlug, patchProjectDocsRepo, patchOrgWorkspace } from './api.js';
12
+ import { api, ApiError, refreshAuthMeCache, invalidateAuthMeCache, resolveOrgIdMaybeSlug, resolveProjectIdBySlug, patchProjectDocsRepo, patchOrgWorkspace, isAgentCredential, fetchCredentialScope } from './api.js';
13
13
  import { isProjectConnectionUnavailable, renderProjectConnectionUnavailableCopy, } from './connectionErrorCopy.js';
14
14
  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';
@@ -232,6 +232,8 @@ program
232
232
  // copyInheritedSettings(), which copies _allowExcessArguments, so every
233
233
  // subcommand registered after this line inherits the strict behavior.
234
234
  .allowExcessArguments(false);
235
+ /** UUID v4 pattern — used by resolveTemplateId (G15) and elsewhere to detect a pre-resolved id vs. a name/slug. */
236
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
235
237
  // ── Directory-scoped default org/project (.fazemos.json) ─────
236
238
  //
237
239
  // Before any command action runs, discover the nearest `.fazemos.json`
@@ -239,80 +241,14 @@ program
239
241
  // them as in-memory overrides for the process. This scopes every call to the
240
242
  // pinned org/project without a manual `orgs switch` / `projects switch`.
241
243
  //
242
- // Resolution is best-effort: if a slug can't be resolved (not logged in, slug
243
- // not in your memberships, stale cache) we leave the override unset and let the
244
- // normal active-selection + API error path take over. Network resolution is
245
- // skipped for the bootstrap commands that don't need a scoped context.
246
- const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
247
- /** Top-level commands that never need (and shouldn't trigger) context resolution. */
248
- const DIR_CONTEXT_SKIP = new Set(['use', 'auth', 'env', 'init']);
244
+ // BUG231-C1: resolution is no longer best-effort. An unresolvable or
245
+ // malformed pin hard-errors (exit 2, no API call) instead of silently
246
+ // falling back to the machine-global active org/project — see
247
+ // `applyDirContext` in `src/dircontext.ts` for the resolution/bypass order.
248
+ // This wrapper owns the only piece of state involved: the once-per-process
249
+ // latch (so a second `preAction` firing in the same process, e.g. a
250
+ // subcommand dispatch, doesn't re-resolve).
249
251
  let dirContextApplied = false;
250
- async function applyDirContext(topCommand) {
251
- if (dirContextApplied)
252
- return;
253
- dirContextApplied = true;
254
- let found;
255
- try {
256
- found = findDirContextFile();
257
- }
258
- catch (err) {
259
- // Malformed .fazemos.json — surface it for normal commands, but don't
260
- // abort. The bootstrap commands (notably `use`) report it themselves, so
261
- // stay silent for them to avoid a double warning.
262
- if (!DIR_CONTEXT_SKIP.has(topCommand))
263
- console.error(chalk.yellow(err.message));
264
- return;
265
- }
266
- if (!found)
267
- return;
268
- // Record the source so whoami/config can show where the scope came from.
269
- setDirContextSource({ path: found.path, ...found.context });
270
- // Bootstrap commands (auth/env/init/use) operate without a resolved scope.
271
- if (DIR_CONTEXT_SKIP.has(topCommand))
272
- return;
273
- const { org, project } = found.context;
274
- if (org) {
275
- try {
276
- setOrgOverride(await resolveOrgIdMaybeSlug(org));
277
- }
278
- catch {
279
- // Do NOT fail silently. Leaving the override unset means the command
280
- // runs against whatever `orgs switch` last persisted machine-globally —
281
- // for a READ the API error eventually hints at it, but for a WRITE the
282
- // command simply SUCCEEDS IN THE WRONG ORG. Say so, on stderr, so the
283
- // operator can see the scope they think they pinned was not applied.
284
- console.error(chalk.yellow(`Warning: .fazemos.json pins org '${org}' but it could not be resolved ` +
285
- `(offline, wrong --env, stale cache, or a typo'd slug). ` +
286
- `Falling back to the machine-global active org — verify with 'fazemos whoami' before writing.`));
287
- }
288
- }
289
- if (project) {
290
- try {
291
- if (UUID_RE.test(project)) {
292
- setProjectOverride(project);
293
- }
294
- else {
295
- // Resolves against the active org, which now reflects the org override.
296
- const projectId = await resolveProjectIdBySlug(project);
297
- if (projectId) {
298
- setProjectOverride(projectId);
299
- }
300
- else {
301
- // Resolver MISS, not a throw — the old code fell through here in
302
- // silence, which is how a pinned scope quietly became the global one.
303
- console.error(chalk.yellow(`Warning: .fazemos.json pins project '${project}' but no such project ` +
304
- `exists in the active org. Falling back to the machine-global active project.`));
305
- }
306
- }
307
- }
308
- catch {
309
- // Same hazard as the org branch above — warn rather than silently
310
- // inheriting the machine-global project.
311
- console.error(chalk.yellow(`Warning: .fazemos.json pins project '${project}' but it could not be resolved. ` +
312
- `Falling back to the machine-global active project — verify with 'fazemos whoami' before writing.`));
313
- }
314
- }
315
- }
316
252
  program.hook('preAction', async (_thisCommand, actionCommand) => {
317
253
  // Apply the global `--env` flag first so every downstream resolution (dir
318
254
  // context slug lookups, auth, API calls) sees the right environment.
@@ -326,7 +262,26 @@ program.hook('preAction', async (_thisCommand, actionCommand) => {
326
262
  c = c.parent;
327
263
  top = c.name();
328
264
  }
329
- await applyDirContext(top ?? '');
265
+ if (dirContextApplied)
266
+ return;
267
+ dirContextApplied = true;
268
+ // Deps are wrapped in closures (not passed by reference) so that a test's
269
+ // `./api.js`/`./config.js` mock only needs to provide the specific
270
+ // resolver a given command path actually exercises — same laziness the
271
+ // pre-extraction code had, since these named imports are otherwise
272
+ // referenced all over index.ts for unrelated commands.
273
+ await applyDirContext(top ?? '', actionCommand.opts(), {
274
+ resolveOrgIdMaybeSlug: (value) => resolveOrgIdMaybeSlug(value),
275
+ resolveProjectIdBySlug: (slug) => resolveProjectIdBySlug(slug),
276
+ setOrgOverride: (orgId) => setOrgOverride(orgId),
277
+ setProjectOverride: (projectId) => setProjectOverride(projectId),
278
+ setDirContextSource: (source) => setDirContextSource(source),
279
+ exit: (code) => process.exit(code),
280
+ env: process.env,
281
+ stderr: (message) => console.error(chalk.red(message)),
282
+ isAgentCredential: () => isAgentCredential(),
283
+ fetchCredentialScope: () => fetchCredentialScope(),
284
+ });
330
285
  });
331
286
  // ── Init ────────────────────────────────────────────────────
332
287
  program
@@ -544,9 +499,39 @@ auth
544
499
  // ── Whoami ──────────────────────────────────────────────────
545
500
  program
546
501
  .command('whoami')
547
- .description('Show current user, org, and project context. Requires a user identity (JWT). Agent-key callers use `fazemos inbox --role <me>` to prove role resolution and `/api/members/me` for member identity.')
502
+ .description('Show current user, org, and project context. Human callers use their Cognito identity (JWT); agent callers (FAZEMOS_API_KEY set) use `/api/members/me` instead, since `/auth/me` 403s for them.')
548
503
  .action(async () => {
549
504
  try {
505
+ // BUG231-C1a S6: agent credentials 403 on /auth/me
506
+ // (WRONG_ENDPOINT_FOR_AGENT) — use /api/members/me instead, and show
507
+ // the dirContextSource `verified` marker so an operator can tell a
508
+ // credential-confirmed pin from one the CLI merely proceeded on.
509
+ if (isAgentCredential()) {
510
+ const me = (await api('GET', '/api/members/me', undefined, { noProjectHeader: true }));
511
+ console.log(` Member: ${chalk.cyan(me.member.display_name)} (${me.member.role}) [agent credential]`);
512
+ console.log(` Env: ${chalk.cyan(getActiveEnvName())}`);
513
+ console.log(` Org: ${me.member.org_id}`);
514
+ if (me.project) {
515
+ console.log(` Project: ${chalk.cyan(me.project.name)} (${me.project.slug})`);
516
+ }
517
+ else {
518
+ console.log(` Project: ${chalk.gray('(org-level credential — no project scope)')}`);
519
+ }
520
+ const dirSource = getDirContextSource();
521
+ if (dirSource) {
522
+ const rel = relative(process.cwd(), dirSource.path) || dirSource.path;
523
+ if (dirSource.ignored) {
524
+ console.log(chalk.gray(` Scope: pin at ${rel} IGNORED (FAZEMOS_IGNORE_DIR_CONTEXT=1)`));
525
+ }
526
+ else {
527
+ const verifiedLabel = dirSource.verified
528
+ ? chalk.gray(` [verified: ${dirSource.verified}]`)
529
+ : '';
530
+ console.log(chalk.gray(` Scope: from ${rel} (fazemos use)`) + verifiedLabel);
531
+ }
532
+ }
533
+ return;
534
+ }
550
535
  // Force-refresh the /auth/me cache on whoami so subsequent slug
551
536
  // resolutions (e.g., `projects switch vahmos`) see the fresh state
552
537
  // without a second round-trip.
@@ -594,10 +579,17 @@ program
594
579
  }
595
580
  // Note when the org/project scope is coming from a directory .fazemos.json
596
581
  // rather than the persisted active selection, so the source is obvious.
582
+ // BUG231-C1 S4: FAZEMOS_IGNORE_DIR_CONTEXT=1 sees the pin but doesn't
583
+ // apply it — say so explicitly rather than implying it was applied.
597
584
  const dirSource = getDirContextSource();
598
585
  if (dirSource) {
599
586
  const rel = relative(process.cwd(), dirSource.path) || dirSource.path;
600
- console.log(chalk.gray(` Scope: from ${rel} (fazemos use)`));
587
+ if (dirSource.ignored) {
588
+ console.log(chalk.gray(` Scope: pin at ${rel} IGNORED (FAZEMOS_IGNORE_DIR_CONTEXT=1)`));
589
+ }
590
+ else {
591
+ console.log(chalk.gray(` Scope: from ${rel} (fazemos use)`));
592
+ }
601
593
  }
602
594
  }
603
595
  catch (err) {
@@ -10201,11 +10193,13 @@ Examples:
10201
10193
  // --body "Should we ship F19 before F7?" --priority high --commit
10202
10194
  program
10203
10195
  .command('dispatch <to> <type>')
10204
- .description(`Send a role-to-role dispatch. Calls POST /api/dispatches (API writes DB row
10205
- + 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.
10206
10199
 
10207
- Use --file-only to skip the API and write only the local file (degraded/offline
10208
- 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.
10209
10203
 
10210
10204
  Recipients are resolved via the nearest .fazemos/roles.json registry, walking
10211
10205
  up from the current directory. Cross-workspace recipients are followed via
@@ -10219,8 +10213,8 @@ Types: question | task | signal | response | flag | decision | direction | brief
10219
10213
  .option('--re <ref>', 'optional reference (worksheet id, feature token, etc.)')
10220
10214
  .option('--thread <id>', 'optional prior dispatch id this is threaded to')
10221
10215
  .option('--expires-at <iso>', 'optional deadline (ISO 8601)')
10222
- .option('--commit', 'git add + commit the inbox file after writing')
10223
- .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)')
10224
10218
  .option('--runbook-ref <id>', 'runbook id to attach (task-only; validated by the API against the runbook contract)')
10225
10219
  .option('--params <json>', 'runbook input params as an inline JSON object (mutually exclusive with --params-file)')
10226
10220
  .option('--params-file <path>', 'read runbook input params from a JSON file (mutually exclusive with --params)')
@@ -10271,6 +10265,13 @@ Types: question | task | signal | response | flag | decision | direction | brief
10271
10265
  if (!body) {
10272
10266
  throw new Error('--body or --body-file is required');
10273
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
+ }
10274
10275
  // Find local registry
10275
10276
  const localRegistry = findLocalRegistry(process.cwd());
10276
10277
  if (!localRegistry) {
@@ -10369,7 +10370,7 @@ Types: question | task | signal | response | flag | decision | direction | brief
10369
10370
  // SKIP agent-mode commit+push (no relPath) — rul_dispatch_local_file_best_effort_cross_workspace
10370
10371
  return;
10371
10372
  }
10372
- // ── Resolved path: existing behavior unchanged ──────────────────────────
10373
+ // ── Resolved path ─────────────────────────────────────────────────
10373
10374
  const { role, registry } = resolved;
10374
10375
  const input = {
10375
10376
  to,
@@ -10383,156 +10384,111 @@ Types: question | task | signal | response | flag | decision | direction | brief
10383
10384
  runbookRef: opts.runbookRef,
10384
10385
  params: runbookParams,
10385
10386
  };
10386
- const { filename, content, summary } = buildInboxFile(input);
10387
- let fullPath;
10388
- let relPath;
10389
10387
  if (opts.fileOnly) {
10390
- // ── Legacy / offline mode: write file directly, skip API ────────
10391
- fullPath = writeInboxFile(registry._workspaceRoot, role, filename, content);
10392
- relPath = fullPath.startsWith(registry._workspaceRoot)
10393
- ? fullPath.slice(registry._workspaceRoot.length + 1)
10394
- : fullPath;
10395
- 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.'));
10396
10402
  console.log(` ${chalk.cyan(fullPath)}`);
10397
- console.log(` Workspace: ${registry.workspace} Filler: ${role.filler.identity} (${role.filler.type})`);
10398
- console.log(chalk.gray(' (API not called — file-only mode)'));
10399
- }
10400
- else {
10401
- // ── F26 API write-through (Dex S-B) ─────────────────────────────
10402
- // F35 HC2 (BUG52): propagate the dispatch-chain depth so the API's
10403
- // ceiling (TRIGGER_MAX_DISPATCH_DEPTH) actually trips. See
10404
- // computeChildDispatchDepth — env var present (agent execution) ⇒
10405
- // parent + 1; absent (human CLI) ⇒ top-of-chain depth 0.
10406
- const dispatchDepth = computeChildDispatchDepth(process.env.FAZEMOS_ORIGINATING_DISPATCH_DEPTH);
10407
- // AUTON-CAUSAL-FTR (AC15) — env-to-payload bridge (rul_runner_root_chain_id_passthrough).
10408
- // Include root_chain_id ONLY when ROOT_CHAIN_ID env is non-empty after .trim().
10409
- // DO NOT send empty string — absence means wake seam seeds a new root (documented degradation).
10410
- // Mirrors the existing FAZEMOS_ORIGINATING_DISPATCH_DEPTH bridge above.
10411
- const rootChainId = process.env.ROOT_CHAIN_ID?.trim() || undefined;
10412
- const reqBody = {
10413
- to,
10414
- from: opts.from,
10415
- type,
10416
- priority: opts.priority ?? 'normal',
10417
- body,
10418
- thread_id: opts.thread ?? null,
10419
- re: opts.re ? [opts.re] : null,
10420
- expires_at: opts.expiresAt ?? null,
10421
- source: 'cli',
10422
- runbook_ref: opts.runbookRef ?? null,
10423
- params: runbookParams ?? null,
10424
- dispatch_depth: dispatchDepth,
10425
- ...(rootChainId ? { root_chain_id: rootChainId } : {}),
10426
- };
10427
- let apiResp;
10428
- try {
10429
- apiResp = await api('POST', '/api/dispatches', reqBody);
10430
- }
10431
- catch (err) {
10432
- // BUG53: a deliberate API refusal (4xx) must HARD-FAIL — do NOT fall
10433
- // back to writing a local inbox file. Inside an agent that file gets
10434
- // committed/pushed and re-drained, re-introducing the dispatch with no
10435
- // depth tracking and bypassing the very gate that refused it (e.g. 409
10436
- // DEPTH_CEILING_EXCEEDED, the F35 loop-safety ceiling). File-fallback is
10437
- // only for genuine API-unavailable (network / 5xx).
10438
- const status = err instanceof ApiError ? err.status : undefined;
10439
- if (!shouldFallBackToFile(status)) {
10440
- const code = err instanceof ApiError && err.code ? ` ${err.code}` : '';
10441
- console.error(chalk.red(`✗ Dispatch refused (${status}${code}): ${err instanceof Error ? err.message : String(err)}`));
10442
- console.error(chalk.gray(' Not falling back to file-only — a deliberate refusal must not be bypassed.'));
10443
- process.exitCode = 1;
10444
- 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.'));
10445
10410
  }
10446
- // BUG221 lever-a (AC-2): transient network failure in resolved path.
10447
- // Write a file-only fallback (role.inbox is available) AND exit 2 (non-zero).
10448
- // The operator is told the file was written and drain-on-cadence is the recovery
10449
- // path. This replaces the old silent exit-0 — downstream tooling now sees failure.
10450
- const networkMsg = err instanceof Error ? err.message : String(err);
10451
- const apiUrl = getEnv().apiUrl;
10452
- fullPath = writeInboxFile(registry._workspaceRoot, role, filename, content);
10453
- relPath = fullPath.startsWith(registry._workspaceRoot)
10454
- ? fullPath.slice(registry._workspaceRoot.length + 1)
10455
- : fullPath;
10456
- console.error(`fazemos dispatch: API unreachable at ${apiUrl} after network error; wrote file-only fallback at ${fullPath}. Recipient will drain on next cadence tick.`);
10457
- console.error(` Error: ${networkMsg}`);
10458
- if (opts.commit) {
10459
- try {
10460
- gitCommitInboxFile(registry._workspaceRoot, relPath, `dispatch(${opts.from} → ${to}): ${type}`);
10461
- console.error(' File committed.');
10462
- }
10463
- catch (cerr) {
10464
- console.error(` warning: commit failed — ${cerr instanceof Error ? cerr.message : String(cerr)}`);
10465
- }
10411
+ catch (err) {
10412
+ const msg = err instanceof Error ? err.message : String(err);
10413
+ console.log(chalk.yellow(` warning: commit failed — ${msg}`));
10466
10414
  }
10467
- process.exitCode = 2;
10468
- return;
10469
- }
10470
- // API returned file_path — CLI writes the actual file (Dex S-B).
10471
- //
10472
- // rul_registry_inbox_field_wins_regardless_of_scope (BUG64 Fix):
10473
- // The write path is always built from the registry-declared `role.inbox`,
10474
- // regardless of what `scope` the role carries or what the API's
10475
- // `file_path` returns. This ensures org-scoped roles (e.g.
10476
- // `business-operations`, `chief-of-staff`) that declare an explicit
10477
- // `inbox` in .fazemos/roles.json write to that path, not to the
10478
- // org-layout root (`roles/<slug>/inbox/`) that the API may return for
10479
- // roles with `project_id IS NULL` in role_registrations.
10480
- //
10481
- // The API's `file_path` is preserved as `relPath` for reference/logging
10482
- // but the on-disk write uses computeRegistryInboxPath(role, filename).
10483
- if (apiResp.file_path) {
10484
- // Prefer registry-declared path; use API path only when no explicit inbox.
10485
- relPath = computeRegistryInboxPath(role, to, filename);
10486
- fullPath = writeInboxFileAtPath(registry._workspaceRoot, relPath, content);
10487
- }
10488
- else {
10489
- // API didn't return a file_path (e.g. cross-workspace agent recipient) — write locally
10490
- fullPath = writeInboxFile(registry._workspaceRoot, role, filename, content);
10491
- relPath = fullPath.startsWith(registry._workspaceRoot)
10492
- ? fullPath.slice(registry._workspaceRoot.length + 1)
10493
- : fullPath;
10494
- }
10495
- console.log(chalk.green(`✓ Dispatch created (id: ${apiResp.id}):`));
10496
- console.log(` ${chalk.cyan(fullPath)}`);
10497
- console.log(` Workspace: ${registry.workspace} Filler: ${role.filler.identity} (${role.filler.type})`);
10498
- if (apiResp.thread_id && apiResp.thread_id !== apiResp.id) {
10499
- console.log(` Thread: ${apiResp.thread_id}`);
10500
10415
  }
10416
+ return;
10501
10417
  }
10502
- // rul_dispatch_cli_pushes_inbox_file_on_agent_execution (BUG66 Fix B bridge):
10503
- // When running inside a Fargate agent task (FAZEMOS_AGENT_EXECUTION=1),
10504
- // commit + push the inbox file to origin/main so the recipient's next
10505
- // dispatch_wake clone sees it. Scoped to short-execution dispatchers only.
10506
- // Long dispatchers route through Fix A (DB-drain on wake); they must NOT
10507
- // push (BUG46 token-expiry risk on long runs is out of scope for this bridge).
10508
- //
10509
- // --commit is still honored for human-workstation operators (AC3).
10510
- // Agent-mode push is additive; it does not suppress the --commit path.
10511
- if (isAgentExecution() && !opts.fileOnly && relPath) {
10512
- try {
10513
- gitCommitAndPushInboxFile(registry._workspaceRoot, relPath, `dispatch(${opts.from} → ${to}): ${type}`);
10514
- console.log(chalk.green('✓ Committed and pushed to origin/main (agent-mode).'));
10515
- }
10516
- catch (err) {
10517
- const msg = err instanceof Error ? err.message : String(err);
10518
- // DISPATCH_PUSH_CONFLICT — loud fail. The DB dispatch row is durable;
10519
- // the recipient will drain via Fix A (wake-task DB body embed).
10520
- 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.'));
10521
10463
  process.exitCode = 1;
10522
10464
  return;
10523
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;
10524
10479
  }
10525
- else if (opts.commit) {
10526
- // Human-operator --commit path (AC3: unchanged from pre-fix behavior)
10527
- try {
10528
- gitCommitInboxFile(registry._workspaceRoot, relPath, `dispatch(${opts.from} → ${to}): ${type}`);
10529
- console.log(chalk.green('✓ Committed.'));
10530
- }
10531
- catch (err) {
10532
- const msg = err instanceof Error ? err.message : String(err);
10533
- console.log(chalk.yellow(` warning: commit failed — ${msg}`));
10534
- }
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}`);
10535
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.
10536
10492
  }
10537
10493
  catch (err) {
10538
10494
  console.error(chalk.red(err instanceof Error ? err.message : String(err)));
@@ -10767,18 +10723,84 @@ status=read after rendering (standard agent playbook usage).
10767
10723
  Replaces the legacy file-read drain (roles/<slug>/inbox/*.md) that silently
10768
10724
  dropped cross-workspace dispatches.
10769
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
+
10770
10732
  Examples:
10771
10733
  fazemos inbox --role chief-of-staff # unread for role
10772
10734
  fazemos inbox --role engineering-director --status all
10773
10735
  fazemos inbox --role project-manager --mark-read # drain + mark read
10774
- 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`)
10775
10738
  .option('--role <slug>', 'filter to a specific role-slug (defaults to all roles the caller fills)')
10776
10739
  .option('--status <status>', 'unread | read | all (default: unread)', 'unread')
10777
10740
  .option('--limit <n>', 'max dispatches to return (default: 50)', (v) => parseInt(v, 10), 50)
10778
10741
  .option('--format <format>', 'table | json (default: table)', 'table')
10779
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)')
10780
10744
  .action(async (opts) => {
10781
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
+ }
10782
10804
  // Validate --status
10783
10805
  const validStatuses = ['unread', 'read', 'all'];
10784
10806
  if (!validStatuses.includes(opts.status)) {