@formigio/fazemos-cli 0.11.1 → 0.12.0

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
@@ -9,6 +9,7 @@ getActiveProjectId, setActiveProjectId, clearActiveProjectId, findProjectBySlug,
9
9
  setOrgOverride, setProjectOverride, setDirContextSource, getDirContextSource, } from './config.js';
10
10
  import { findDirContextFile, readDirContextFile, writeDirContextFile, removeDirContextFile, DIR_CONFIG_FILENAME, applyDirContext, } from './dircontext.js';
11
11
  import { EXIT, exitForError } from './exitCodes.js';
12
+ import { validateDispatchForm, validateFormEnvelope, formatFormErrors, selectAnswerOutput, RETRACT_REASON_MAX, } from './lib/dispatchForm.js';
12
13
  import { loginWithBrowser, hostedLogoutUrl, signup, confirmSignup, adminLogin } from './auth.js';
13
14
  import { fetchAuthConfig } from './authConfig.js';
14
15
  import { api, ApiError, refreshAuthMeCache, invalidateAuthMeCache, resolveOrgIdMaybeSlug, resolveProjectIdBySlug, resolveProjectBySlug, patchProjectDocsRepo, patchOrgWorkspace, isAgentCredential, fetchCredentialScope } from './api.js';
@@ -10555,7 +10556,7 @@ Examples:
10555
10556
  // Example:
10556
10557
  // fazemos dispatch founder question --from business-strategist \
10557
10558
  // --body "Should we ship F19 before F7?" --priority high --commit
10558
- program
10559
+ const dispatchCommand = program
10559
10560
  .command('dispatch <to> <type>')
10560
10561
  .description(`Send a role-to-role dispatch. Calls POST /api/dispatches — the DB row is
10561
10562
  the sole delivery (DISPATCH-DB-ONLY-INBOX): no inbox file is written, no git
@@ -10569,8 +10570,25 @@ Recipients are resolved via the nearest .fazemos/roles.json registry, walking
10569
10570
  up from the current directory. Cross-workspace recipients are followed via
10570
10571
  the local registry's cross_workspace_roles block.
10571
10572
 
10572
- Types: question | task | signal | response | flag | decision | direction | brief`)
10573
- .requiredOption('--from <role>', 'sender role-slug (required)')
10573
+ Types: question | task | signal | response | flag | decision | direction | brief
10574
+
10575
+ Structured question (F84): --form-file <path> attaches a validated v1 form
10576
+ (1-4 questions, 2-4 options each). It is only allowed with type "question",
10577
+ requires a future --expires-at, and cannot be combined with --body,
10578
+ --body-file or --file-only, because the server composes the body from
10579
+ form.ask. The file is checked offline against the same limits and named
10580
+ 400 codes as the API before anything is sent. A failed check exits 2.
10581
+
10582
+ Subcommands (a recipient role literally named "answer" or "retract" cannot
10583
+ be dispatched to from this CLI):
10584
+ dispatch answer <id> read a form question's answer (or its state)
10585
+ dispatch retract <id> retract your own open form question`)
10586
+ // F84 C2/C3: `--from` is enforced in the action, not via requiredOption.
10587
+ // Commander v12 checks mandatory options on every ANCESTOR of the command
10588
+ // being run, so a requiredOption here would make `dispatch answer <id>`
10589
+ // and `dispatch retract <id>` demand a --from they don't use. The
10590
+ // action below reproduces Commander's own message and exit code.
10591
+ .option('--from <role>', 'sender role-slug (required)')
10574
10592
  .option('--body <text>', 'markdown body of the dispatch (or use --body-file)')
10575
10593
  .option('--body-file <path>', 'read body from a file')
10576
10594
  .option('--priority <level>', 'low | normal | high', 'normal')
@@ -10582,7 +10600,14 @@ Types: question | task | signal | response | flag | decision | direction | brief
10582
10600
  .option('--runbook-ref <id>', 'runbook id to attach (task-only; validated by the API against the runbook contract)')
10583
10601
  .option('--params <json>', 'runbook input params as an inline JSON object (mutually exclusive with --params-file)')
10584
10602
  .option('--params-file <path>', 'read runbook input params from a JSON file (mutually exclusive with --params)')
10603
+ .option('--form-file <path>', 'F84 structured question: a v1 form JSON file (type=question only; requires --expires-at; no --body)')
10585
10604
  .action(async (to, type, opts) => {
10605
+ if (!opts.from) {
10606
+ dispatchCommand.error("error: required option '--from <role>' not specified", {
10607
+ code: 'commander.missingMandatoryOptionValue',
10608
+ });
10609
+ return;
10610
+ }
10586
10611
  try {
10587
10612
  // Validate type
10588
10613
  // AUTON-ROLLUP-INBOX-API Leg B: 'brief' added (mirrors API allowedTypes + migration 068).
@@ -10621,12 +10646,50 @@ Types: question | task | signal | response | flag | decision | direction | brief
10621
10646
  throw new Error(`--params-file "${opts.paramsFile}": ${e instanceof Error ? e.message : String(e)}`);
10622
10647
  }
10623
10648
  }
10624
- // Resolve body
10649
+ // F84 C1: --form-file. Validate offline against the vendored schema
10650
+ // (src/lib/dispatchForm.ts) BEFORE any API call. The server composes
10651
+ // the body from form.ask, so a client body is refused rather than
10652
+ // silently dropped (400 FORM_BODY_SERVER_COMPOSED on the server side).
10653
+ let form;
10654
+ if (opts.formFile) {
10655
+ const usage = [];
10656
+ if (opts.body || opts.bodyFile) {
10657
+ usage.push(' --form-file cannot be combined with --body/--body-file: the server composes the body from form.ask');
10658
+ }
10659
+ if (opts.fileOnly) {
10660
+ usage.push(' --form-file cannot be combined with --file-only: a dead letter cannot carry a form');
10661
+ }
10662
+ const envelopeErrors = validateFormEnvelope(type, opts.expiresAt);
10663
+ let parsedForm;
10664
+ let readError = null;
10665
+ try {
10666
+ parsedForm = JSON.parse(readFileSync(opts.formFile, 'utf-8'));
10667
+ }
10668
+ catch (e) {
10669
+ readError = ` --form-file "${opts.formFile}": ${e instanceof Error ? e.message : String(e)}`;
10670
+ }
10671
+ const formErrors = readError ? [] : validateDispatchForm(parsedForm);
10672
+ if (usage.length || envelopeErrors.length || readError || formErrors.length) {
10673
+ console.error(chalk.red('✗ Form not sent: it fails client-side validation (nothing was sent).'));
10674
+ for (const line of usage)
10675
+ console.error(line);
10676
+ if (envelopeErrors.length)
10677
+ console.error(formatFormErrors(envelopeErrors));
10678
+ if (readError)
10679
+ console.error(readError);
10680
+ if (formErrors.length)
10681
+ console.error(formatFormErrors(formErrors));
10682
+ process.exitCode = EXIT.USAGE;
10683
+ return;
10684
+ }
10685
+ form = parsedForm;
10686
+ }
10687
+ // Resolve body (not used with a form: the server composes it)
10625
10688
  let body = opts.body;
10626
10689
  if (!body && opts.bodyFile) {
10627
10690
  body = readFileSync(opts.bodyFile, 'utf-8').trim();
10628
10691
  }
10629
- if (!body) {
10692
+ if (!body && !form) {
10630
10693
  throw new Error('--body or --body-file is required');
10631
10694
  }
10632
10695
  // DISPATCH-DB-ONLY-INBOX (P2, T2.2): --commit is a no-op EXCEPT when
@@ -10687,7 +10750,7 @@ Types: question | task | signal | response | flag | decision | direction | brief
10687
10750
  from: opts.from,
10688
10751
  type,
10689
10752
  priority: opts.priority ?? 'normal',
10690
- body,
10753
+ ...(form ? { form } : { body }),
10691
10754
  thread_id: opts.thread ?? null,
10692
10755
  re: opts.re ? [opts.re] : null,
10693
10756
  expires_at: opts.expiresAt ?? null,
@@ -10761,7 +10824,7 @@ Types: question | task | signal | response | flag | decision | direction | brief
10761
10824
  from: opts.from,
10762
10825
  type: type,
10763
10826
  priority: (opts.priority ?? 'normal'),
10764
- body,
10827
+ body: body ?? '',
10765
10828
  re: opts.re,
10766
10829
  thread: opts.thread,
10767
10830
  expiresAt: opts.expiresAt,
@@ -10818,7 +10881,7 @@ Types: question | task | signal | response | flag | decision | direction | brief
10818
10881
  from: opts.from,
10819
10882
  type,
10820
10883
  priority: opts.priority ?? 'normal',
10821
- body,
10884
+ ...(form ? { form } : { body }),
10822
10885
  thread_id: opts.thread ?? null,
10823
10886
  re: opts.re ? [opts.re] : null,
10824
10887
  expires_at: opts.expiresAt ?? null,
@@ -10920,6 +10983,141 @@ Types: question | task | signal | response | flag | decision | direction | brief
10920
10983
  exitForError(err);
10921
10984
  }
10922
10985
  });
10986
+ // ── F84 C2: `fazemos dispatch answer <id>` (R4) ────────────────────
10987
+ //
10988
+ // GET /api/dispatches/:id/answer. Prints the latest answer, or
10989
+ // {"form_state":"expired"|"retracted"|"open"} (`pending` → `open`).
10990
+ // Exit 0 in EVERY form state: an unanswered form is a state, not an
10991
+ // error. Exit 4 on 404 (not found), OR on 403 where the response body's
10992
+ // `code` is `FORBIDDEN` (dispatchesService's "not visible to you" refusal,
10993
+ // api src/services/dispatchesService.ts) — both mean "there is nothing
10994
+ // here this caller may read." Every OTHER 403 (e.g. routes/dispatches.ts's
10995
+ // INBOX_IS_HUMAN_SURFACE) takes the generic EXIT.API exit, same as any
10996
+ // other error. NOTE: 4 is also EXIT.PARTIAL elsewhere. The C2 contract
10997
+ // names 4 for this not-found-or-hidden case explicitly, so it is a
10998
+ // distinct, documented meaning on this command only.
10999
+ //
11000
+ // ED-12-03q §2 correction (flat envelope): the API's errorHandler.ts
11001
+ // serialises errors as FLAT `{ error: <message string>, code: <CODE> }` —
11002
+ // never `{ error: { code } }`. The check below is `err.body?.code`, NOT
11003
+ // `err.body?.error?.code` (the latter is always undefined on a string
11004
+ // `error` field and would silently disable the exit-4 path for every 403).
11005
+ export const DISPATCH_ANSWER_NOT_FOUND_EXIT = 4;
11006
+ function renderAnswerHuman(answer) {
11007
+ const who = answer?.answered_by_name ?? answer?.answered_by_member_id ?? 'unknown';
11008
+ console.log(chalk.green(`answered by ${who} at ${answer?.answered_at ?? '?'}`));
11009
+ if (answer?.response_dispatch_id)
11010
+ console.log(` response: ${answer.response_dispatch_id}`);
11011
+ if (answer?.supersedes)
11012
+ console.log(` supersedes: ${answer.supersedes}`);
11013
+ for (const a of Array.isArray(answer?.answers) ? answer.answers : []) {
11014
+ const vals = Array.isArray(a.values) && a.values.length ? a.values.join(', ') : '(none)';
11015
+ console.log(` ${a.question_id}: ${vals}`);
11016
+ if (a.other_text)
11017
+ console.log(` other: ${a.other_text}`);
11018
+ if (a.note)
11019
+ console.log(` note: ${a.note}`);
11020
+ }
11021
+ }
11022
+ dispatchCommand
11023
+ .command('answer <id>')
11024
+ .description(`Read a form question's answer (F84, GET /api/dispatches/:id/answer).
11025
+
11026
+ Prints the latest answer when the form is answered, otherwise its state:
11027
+ {"form_state":"open"|"expired"|"retracted"}. --json prints exactly that JSON
11028
+ on one line (the latest answer object, or the {"form_state"} object).
11029
+
11030
+ Exit codes: 0 in every form state (open/answered/expired/retracted);
11031
+ 4 when the dispatch is not found, or not visible to this caller (403
11032
+ FORBIDDEN); 1 on any other error (including every other 403). On a 404 or
11033
+ 403, the API's JSON response body is echoed verbatim to stderr.`)
11034
+ .option('--json', 'print machine-readable JSON (the latest answer, or {"form_state":...})', false)
11035
+ .action(async (id, opts) => {
11036
+ let r4;
11037
+ try {
11038
+ r4 = await api('GET', `/api/dispatches/${encodeURIComponent(id)}/answer`);
11039
+ }
11040
+ catch (err) {
11041
+ if (err instanceof ApiError && (err.status === 404 || err.status === 403)) {
11042
+ // Echo the body verbatim to stderr in both cases — the body is the
11043
+ // parsed JSON object (`err.body`), not re-derived text, same
11044
+ // convention as `dispatch retract` below.
11045
+ console.error(typeof err.body === 'string' ? err.body : JSON.stringify(err.body));
11046
+ const notFoundOrHidden = err.status === 404 || err.body?.code === 'FORBIDDEN';
11047
+ process.exitCode = notFoundOrHidden ? DISPATCH_ANSWER_NOT_FOUND_EXIT : EXIT.API;
11048
+ return;
11049
+ }
11050
+ console.error(chalk.red(err instanceof Error ? err.message : String(err)));
11051
+ exitForError(err);
11052
+ return;
11053
+ }
11054
+ const out = selectAnswerOutput(r4 ?? {});
11055
+ if (opts.json) {
11056
+ console.log(JSON.stringify(out.kind === 'answer' ? out.answer : { form_state: out.form_state }));
11057
+ return;
11058
+ }
11059
+ if (out.kind === 'answer') {
11060
+ renderAnswerHuman(out.answer);
11061
+ }
11062
+ else {
11063
+ console.log(`form_state: ${out.form_state ?? '(none: this dispatch carries no form)'}`);
11064
+ }
11065
+ });
11066
+ // ── F84 C3: `fazemos dispatch retract <id>` (R3) ───────────────────
11067
+ //
11068
+ // POST /api/dispatches/:id/retract { reason, superseded_by? }. Only the
11069
+ // sender may retract (403 FORM_RETRACT_NOT_SENDER); an already-closed form
11070
+ // is 409 FORM_NOT_OPEN; an unknown id or a cross-org superseded_by is 404.
11071
+ // Those bodies are surfaced VERBATIM on stderr, never remapped. Retract
11072
+ // writes no response row and wakes nobody.
11073
+ dispatchCommand
11074
+ .command('retract <id>')
11075
+ .description(`Retract your own open form question (F84, POST /api/dispatches/:id/retract).
11076
+
11077
+ --reason is required (1-${RETRACT_REASON_MAX} chars). --superseded-by points at the dispatch
11078
+ that replaces this one (must be in the same org). Retract writes no response
11079
+ and wakes nobody.
11080
+
11081
+ A refusal (403 FORM_RETRACT_NOT_SENDER, 404, 409 FORM_NOT_OPEN) prints the API's
11082
+ JSON body verbatim on stderr and exits 1. A bad --reason exits 2. If the
11083
+ connection drops mid-write, the command exits 5 (outcome unknown): read back
11084
+ with \`fazemos dispatch answer <id>\` before re-running.`)
11085
+ .requiredOption('--reason <text>', `why the question is retracted (1-${RETRACT_REASON_MAX} chars)`)
11086
+ .option('--superseded-by <id>', 'id of the dispatch that replaces this one')
11087
+ .action(async (id, opts) => {
11088
+ if (opts.reason.trim().length === 0 || opts.reason.length > RETRACT_REASON_MAX) {
11089
+ console.error(chalk.red(`--reason must be 1-${RETRACT_REASON_MAX} characters (got ${opts.reason.length}); nothing was sent.`));
11090
+ process.exitCode = EXIT.USAGE;
11091
+ return;
11092
+ }
11093
+ const body = { reason: opts.reason };
11094
+ if (opts.supersededBy)
11095
+ body.superseded_by = opts.supersededBy;
11096
+ try {
11097
+ const resp = (await api('POST', `/api/dispatches/${encodeURIComponent(id)}/retract`, body));
11098
+ console.log(chalk.green(`✓ Retracted ${resp?.id ?? id}`));
11099
+ if (resp?.form_state)
11100
+ console.log(` form_state: ${resp.form_state}`);
11101
+ if (opts.supersededBy)
11102
+ console.log(` superseded by: ${opts.supersededBy}`);
11103
+ }
11104
+ catch (err) {
11105
+ if (err instanceof ApiError && err.exitCode != null) {
11106
+ console.error(chalk.yellow(`⚠ Retract outcome unknown (${err.code}): ${err.message}`));
11107
+ console.error(chalk.gray(` It may have landed. Read back with: fazemos dispatch answer ${id}`));
11108
+ process.exitCode = err.exitCode;
11109
+ return;
11110
+ }
11111
+ if (err instanceof ApiError && err.body !== undefined && [403, 404, 409].includes(err.status)) {
11112
+ console.error(chalk.red(`✗ Retract refused (${err.status}):`));
11113
+ console.error(typeof err.body === 'string' ? err.body : JSON.stringify(err.body));
11114
+ process.exitCode = EXIT.API;
11115
+ return;
11116
+ }
11117
+ console.error(chalk.red(err instanceof Error ? err.message : String(err)));
11118
+ exitForError(err);
11119
+ }
11120
+ });
10923
11121
  // ── `fazemos roles sync` — upsert roles.json into role_registrations ──
10924
11122
  //
10925
11123
  // F26 (Dex M2): reads cognito_sub from roles.json filler entries and