@formigio/fazemos-cli 0.10.92 → 0.10.94

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
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from 'commander';
3
3
  import chalk from 'chalk';
4
+ import { renderOverridePreview, OVERRIDE_REPLACE_COPY } from './lib/overridePreview.js';
4
5
  import { config, getEnv, getToken, getActiveEnvName, getActiveEnvSource, setEnvOverride, getActiveOrgId, setActiveOrgId, addEnvironment, hasEnvironments,
5
6
  // F15 — project context helpers
6
7
  getActiveProjectId, setActiveProjectId, clearActiveProjectId, findProjectBySlug, findProjectById, findOrgById,
@@ -4133,7 +4134,7 @@ const templates = program.command('templates').alias('tpl').description('Pipelin
4133
4134
  ' 3. tpl add-step <id> --phase ... Add steps to phases\n' +
4134
4135
  ' 4. tpl add-output / add-input Wire I/O between steps\n' +
4135
4136
  ' 5. tpl validate <id> Check for errors\n' +
4136
- ' 6. tpl activate <id> Make available for instances\n\n' +
4137
+ ' 6. tpl activate <id> Make available for instances (privileged templates need --expected-version)\n\n' +
4137
4138
  ' Use "tpl phases <id>" to list phase IDs needed by --phase options.\n' +
4138
4139
  ' Use "tpl steps <id>" to list step IDs needed by --step options.\n' +
4139
4140
  ' Use "tpl show <id>" to see full structure with I/O declarations.');
@@ -4488,14 +4489,59 @@ templates
4488
4489
  });
4489
4490
  templates
4490
4491
  .command('activate')
4491
- .description('Activate a draft template (required before creating pipeline instances). Template must have at least one phase with at least one step. Status changes from draft → active.')
4492
+ .description('Activate a draft template (required before creating pipeline instances). ' +
4493
+ 'Template must have at least one phase with at least one step. Status changes from draft → active.\n\n' +
4494
+ ' Privileged templates require --expected-version <n> (the revision from "tpl show <id>"). ' +
4495
+ 'This is a compare-and-swap guard: the version you reviewed must still match the server\'s, ' +
4496
+ 'so a concurrent edit cannot be silently activated. Non-privileged templates ignore this flag.')
4492
4497
  .argument('<id>', 'Template ID')
4493
- .action(async (id) => {
4498
+ .option('--expected-version <n>', 'Expected current revision, from "tpl show <id>" (required for privileged templates)')
4499
+ .action(async (id, opts) => {
4500
+ const body = { status: 'active' };
4501
+ let expectedVersion;
4502
+ if (opts.expectedVersion !== undefined) {
4503
+ expectedVersion = Number(opts.expectedVersion);
4504
+ if (!Number.isInteger(expectedVersion) || expectedVersion < 1) {
4505
+ console.error(chalk.red(`Invalid --expected-version: "${opts.expectedVersion}" (must be an integer >= 1)`));
4506
+ process.exit(1);
4507
+ return;
4508
+ }
4509
+ body.expected_version = expectedVersion;
4510
+ }
4494
4511
  try {
4495
- await api('PATCH', `/api/pipeline-templates/${id}/status`, { status: 'active' });
4512
+ await api('PATCH', `/api/pipeline-templates/${id}/status`, body);
4496
4513
  console.log(chalk.green('Template activated'));
4497
4514
  }
4498
4515
  catch (err) {
4516
+ // D-3 (BUG292): print ApiError code+message verbatim, no retry, no GET
4517
+ // on 403/409. RULE-CAS-PIN-IS-THE-CALLERS: this CLI never fills the
4518
+ // expected_version pin from its own read on the caller's behalf.
4519
+ if (err instanceof ApiError) {
4520
+ console.error(chalk.red(err.code ? `${err.code}: ${err.message}` : err.message));
4521
+ // D-2: only on the H3 "expected_version is required" 400
4522
+ // VALIDATION_ERROR, surface the current version as a hint (not an
4523
+ // auto-filled retry). The activate path has two OTHER 400
4524
+ // VALIDATION_ERRORs ("no phases" / phase "has no steps") that are
4525
+ // evaluated before the H3 gate and have nothing to do with
4526
+ // privilege — gating on err.code alone (Dex C-1) fired this hint on
4527
+ // those too and sent the caller on a pointless --expected-version
4528
+ // retry that fails the same way.
4529
+ if (err.code === 'VALIDATION_ERROR' &&
4530
+ expectedVersion === undefined &&
4531
+ /expected_version is required/.test(err.message)) {
4532
+ try {
4533
+ const data = await api('GET', `/api/pipeline-templates/${id}`);
4534
+ const version = data?.template?.version;
4535
+ if (version != null) {
4536
+ console.error(chalk.yellow(`Privileged template — current version is ${version}. Review with "fazemos tpl show ${id}", then re-run: fazemos tpl activate ${id} --expected-version ${version}`));
4537
+ }
4538
+ }
4539
+ catch {
4540
+ // GET failed — the verbatim error above already printed.
4541
+ }
4542
+ }
4543
+ process.exit(1);
4544
+ }
4499
4545
  console.error(chalk.red(err.message));
4500
4546
  process.exit(1);
4501
4547
  }
@@ -8301,19 +8347,27 @@ async function preCheckAgentSourceForDelete(opts) {
8301
8347
  process.exit(1);
8302
8348
  }
8303
8349
  /**
8304
- * F17 §8.3 — `agents override <name>`: create/update a Project override
8305
- * for the named Org agent. PATCH with `{override: <parsed>}`.
8350
+ * F17 §8.3 / BUG178 slice (i) — `agents override <name>`: create/update a
8351
+ * Project override for the named Org agent. PATCH with `{override: <parsed>}`.
8306
8352
  *
8307
- * --dry-run prints the shallow-merge diff and exits without calling the
8308
- * API (Kate Q2). --yes bypasses the confirmation prompt.
8353
+ * This is a whole-document replace, not a merge: any key present in the
8354
+ * current override but absent from `--config` is DROPPED and reverts to
8355
+ * the Org baseline, and `--config '{}'` deletes the override row entirely.
8356
+ * `renderOverridePreview` (src/lib/overridePreview.ts) computes the
8357
+ * ADDED/CHANGED/UNCHANGED/DROPPED status for every key so the preview
8358
+ * cannot lie about what a save will do (BUG178). --dry-run prints that
8359
+ * preview and exits without calling the API (Kate Q2). --verbose prints
8360
+ * full values instead of the >200-char truncation marker. --yes bypasses
8361
+ * the confirmation prompt.
8309
8362
  */
8310
8363
  agentsCmd
8311
8364
  .command('override')
8312
- .description('Create or update a Project-level override for an Org agent. Shallow-merge: each top-level field in --config replaces the Org baseline field entirely.')
8365
+ .description(OVERRIDE_REPLACE_COPY)
8313
8366
  .argument('<name>', 'Agent name (e.g., marco)')
8314
8367
  .requiredOption('--config <json-or-file>', 'Override config as inline JSON or a file path')
8315
8368
  .option('--project <slug>', 'Override active Project for this call')
8316
8369
  .option('--dry-run', 'Print the diff without calling the API', false)
8370
+ .option('--verbose', 'Print full values instead of truncating long ones', false)
8317
8371
  .option('--yes', 'Skip the confirmation prompt', false)
8318
8372
  .action(async (name, opts) => {
8319
8373
  try {
@@ -8339,7 +8393,6 @@ agentsCmd
8339
8393
  const existing = current.agent;
8340
8394
  const proj = findProjectById(orgId, projectId);
8341
8395
  const projSlug = proj?.slug ?? projectId;
8342
- const fieldsToUpdate = Object.keys(override);
8343
8396
  console.log(chalk.cyan(`Overriding ${name} for project: ${projSlug}`));
8344
8397
  if (existing.source === 'org') {
8345
8398
  console.log(`Source: org agent → project-override`);
@@ -8351,30 +8404,33 @@ agentsCmd
8351
8404
  console.log(chalk.yellow(`Warning: ${name} is a Project-only agent — this will be rejected by the API.`));
8352
8405
  console.log(chalk.gray('Use `fazemos agents add` (update) or PATCH via the UI.'));
8353
8406
  }
8354
- console.log(`Fields to update: ${fieldsToUpdate.join(', ')}`);
8355
8407
  console.log('');
8356
- console.log(chalk.gray('Shallow merge: each field you set replaces that field in full.'));
8357
- console.log(chalk.gray('Arrays are not merged — they replace.'));
8408
+ console.log(chalk.gray(OVERRIDE_REPLACE_COPY));
8358
8409
  console.log('');
8359
- console.log(chalk.gray('Diff (Org baseline → Project override):'));
8360
8410
  const baseline = (existing.org_baseline_config ?? {});
8361
- for (const k of fieldsToUpdate) {
8362
- const before = baseline[k];
8363
- const after = override[k];
8364
- const beforeStr = before === undefined ? chalk.gray('(unset)') : JSON.stringify(before).slice(0, 80);
8365
- const afterStr = JSON.stringify(after).slice(0, 80);
8366
- console.log(` ${k}:`);
8367
- console.log(` − ${beforeStr}`);
8368
- console.log(` + ${afterStr}`);
8411
+ const preview = renderOverridePreview(existing.project_override_config ?? null, override, baseline, { name, verbose: !!opts.verbose });
8412
+ for (const line of preview.lines) {
8413
+ const text = line.style ? chalk[line.style](line.text) : line.text;
8414
+ console.log(text);
8369
8415
  }
8370
8416
  console.log('');
8371
8417
  if (opts.dryRun) {
8372
8418
  console.log(chalk.yellow('[dry run] No changes sent to the API.'));
8373
8419
  return;
8374
8420
  }
8375
- if (existing.source === 'org' || existing.source === 'project_override') {
8421
+ if (!preview.isDelete && (existing.source === 'org' || existing.source === 'project_override')) {
8376
8422
  console.log(`This will diverge ${name}'s config in ${projSlug} from the Org baseline.`);
8377
8423
  console.log(`Future Org-level changes to these fields will not propagate.`);
8424
+ }
8425
+ if (preview.isDelete) {
8426
+ console.log(chalk.red(`This DELETES the Project override for ${name}; every field reverts to the Org baseline.`));
8427
+ }
8428
+ if (preview.droppedKeys.length > 0) {
8429
+ console.log(chalk.yellow(`This drops: ${preview.droppedKeys.join(', ')} (reverting to Org baseline).`));
8430
+ }
8431
+ if (existing.source === 'org' ||
8432
+ existing.source === 'project_override' ||
8433
+ preview.droppedKeys.length > 0) {
8378
8434
  await confirmOrAbort('Proceed? [y/N]: ', !!opts.yes);
8379
8435
  }
8380
8436
  const result = await api('PATCH', `/api/organizations/${orgId}/projects/${projectId}/agents/${encodeURIComponent(name)}`, { override }, { noProjectHeader: true });
@@ -10973,18 +11029,31 @@ transition), so this PATCHes to read first when a row is still unread, then
10973
11029
  PATCHes to actioned. A 409 on a row that is already terminal (actioned or
10974
11030
  archived) is reported and is non-fatal — it does not stop the remaining ids.
10975
11031
 
11032
+ Project scoping (BUG277-CLI containment): the listing and --mark-read are
11033
+ scoped to the caller's resolved project — --project <slug> if given, else the
11034
+ active project (.fazemos.json / fazemos projects switch). A dispatch with a
11035
+ NULL project_id is org-level: it is always listed, but --mark-read NEVER
11036
+ bulk-marks it — org-level rows are only markable by id, via --mark-actioned.
11037
+ --mark-read with no resolvable project fails closed (exits non-zero, marks
11038
+ nothing). Pass --all-projects to skip the project filter on the listing only
11039
+ (read-only widen; refused together with --mark-read).
11040
+
10976
11041
  Examples:
10977
11042
  fazemos inbox --role chief-of-staff # unread for role
10978
11043
  fazemos inbox --role engineering-director --status all
10979
- fazemos inbox --role project-manager --mark-read # drain + mark read
11044
+ fazemos inbox --role project-manager --mark-read # drain + mark read, scoped to the active project (NULL-project rows are listed but never bulk-marked)
11045
+ fazemos inbox --project other-proj --mark-read # drain a specific project
11046
+ fazemos inbox --all-projects # list across every project in the org (read-only)
10980
11047
  fazemos inbox --format json --role luca | jq .
10981
- fazemos inbox --mark-actioned <id> [<id>...] # stage row(s) to actioned`)
11048
+ fazemos inbox --mark-actioned <id> [<id>...] # stage row(s) to actioned (by id; works on org-level rows too)`)
10982
11049
  .option('--role <slug>', 'filter to a specific role-slug (defaults to all roles the caller fills)')
10983
11050
  .option('--status <status>', 'unread | read | all (default: unread)', 'unread')
10984
11051
  .option('--limit <n>', 'max dispatches to return (default: 50)', (v) => parseInt(v, 10), 50)
10985
11052
  .option('--format <format>', 'table | json (default: table)', 'table')
10986
- .option('--mark-read', 'after listing, PATCH each dispatch to status=read')
11053
+ .option('--mark-read', 'after listing, PATCH each dispatch to status=read (own-project rows only; NULL-project rows are never bulk-marked)')
10987
11054
  .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)')
11055
+ .option('--project <slug>', 'scope the listing / --mark-read to this project (default: the active project)')
11056
+ .option('--all-projects', 'skip the project filter on the listing (read-only; refused together with --mark-read)', false)
10988
11057
  .action(async (opts) => {
10989
11058
  try {
10990
11059
  // ── DISPATCH-DB-ONLY-INBOX (P2, T2.6) — `--mark-actioned <ids...>` ────
@@ -11055,23 +11124,126 @@ Examples:
11055
11124
  if (!validFormats.includes(opts.format)) {
11056
11125
  throw new Error(`Invalid --format "${opts.format}". Valid: ${validFormats.join(', ')}`);
11057
11126
  }
11127
+ // ── BUG277-CLI: project-scope guard + resolution ────────────────────
11128
+ // Dispatch reads/writes are not server-project-scoped today (fix (b),
11129
+ // API, is a separate train). This is the CLI-side containment: scope
11130
+ // the listing and --mark-read to the caller's resolved project so a
11131
+ // shared filler (e.g. a role filled in both fazemos and
11132
+ // formigio-graph) can't drain another project's rows.
11133
+ //
11134
+ // --mark-read + --all-projects is refused outright — bulk-marking
11135
+ // across every project in the org is exactly the cross-project write
11136
+ // this fix exists to close off.
11137
+ if (opts.markRead && opts.allProjects) {
11138
+ console.error(chalk.red('--mark-read cannot be combined with --all-projects.'));
11139
+ console.error(chalk.gray('Scope the drain with --project <slug>, or drop --mark-read to just list.'));
11140
+ process.exit(1);
11141
+ return;
11142
+ }
11143
+ // Resolution is for the CLIENT-SIDE filter only — `noProjectHeader:
11144
+ // true` stays on every call below, unchanged. --all-projects skips
11145
+ // resolution entirely: it's a "don't filter" switch, never a
11146
+ // `?view=all` query param (the server doesn't define one for this
11147
+ // endpoint). An unresolvable --project <slug> throws
11148
+ // ApiError(UNKNOWN_PROJECT), which the outer catch turns into the
11149
+ // standard exit 1.
11150
+ const resolvedProjectId = opts.allProjects
11151
+ ? null
11152
+ : await resolveProjectIdBySlug(opts.project);
11153
+ // Fail closed: a null resolution (no active project, no --project)
11154
+ // marks nothing. `null === null` must never be read as "no filter" —
11155
+ // that would bulk-mark every project's rows, the opposite of the fix.
11156
+ if (opts.markRead && resolvedProjectId == null) {
11157
+ console.error(chalk.red('No active project resolved — refusing to bulk-mark dispatches as read.'));
11158
+ console.error(chalk.gray('Pass --project <slug>, or set an active project: fazemos projects switch <slug>'));
11159
+ process.exit(1);
11160
+ return;
11161
+ }
11058
11162
  // Build query
11059
11163
  const params = new URLSearchParams();
11060
11164
  if (opts.role)
11061
11165
  params.set('role', opts.role);
11062
11166
  params.set('status', opts.status);
11063
11167
  params.set('limit', String(opts.limit));
11064
- const result = await api('GET', `/api/dispatches?${params.toString()}`, undefined, {
11065
- noProjectHeader: true,
11066
- });
11067
- const items = result.items ?? [];
11168
+ // ── Fetch ────────────────────────────────────────────────
11169
+ // Plain listing: one page, as before. --mark-read pages through
11170
+ // ?cursor= until exhausted (capped at PAGE_CAP) — the client-side
11171
+ // project filter runs AFTER the server's LIMIT, so other-project rows
11172
+ // can fill a page and hide the caller's own-project unread rows
11173
+ // underneath it (page starvation; a false "nothing to mark" on a
11174
+ // shared filler). This is a containment limit: PR B's server-side
11175
+ // project filter removes the need for client paging.
11176
+ const PAGE_CAP = 10;
11177
+ let items = [];
11178
+ let nextCursor = null;
11179
+ let pageCapHit = false;
11180
+ if (opts.markRead) {
11181
+ let cursor;
11182
+ let pages = 0;
11183
+ do {
11184
+ const pageQuery = new URLSearchParams(params);
11185
+ if (cursor)
11186
+ pageQuery.set('cursor', cursor);
11187
+ const page = await api('GET', `/api/dispatches?${pageQuery.toString()}`, undefined, {
11188
+ noProjectHeader: true,
11189
+ });
11190
+ items = items.concat(page.items ?? []);
11191
+ nextCursor = page.nextCursor ?? null;
11192
+ cursor = nextCursor ?? undefined;
11193
+ pages++;
11194
+ } while (cursor && pages < PAGE_CAP);
11195
+ if (cursor) {
11196
+ pageCapHit = true;
11197
+ }
11198
+ }
11199
+ else {
11200
+ const result = await api('GET', `/api/dispatches?${params.toString()}`, undefined, {
11201
+ noProjectHeader: true,
11202
+ });
11203
+ items = result.items ?? [];
11204
+ nextCursor = result.nextCursor ?? null;
11205
+ }
11206
+ // ── Client-side project filter (BUG277-CLI containment) ─────────────
11207
+ // Default: own-project + org-level (NULL project_id) rows. --all-
11208
+ // projects: unfiltered. Unresolved (no --project, no active project,
11209
+ // and NOT --all-projects): NULL rows only — never fail open to
11210
+ // everything.
11211
+ let filteredItems;
11212
+ let unresolvedListing = false;
11213
+ if (opts.allProjects) {
11214
+ filteredItems = items;
11215
+ }
11216
+ else if (resolvedProjectId == null) {
11217
+ unresolvedListing = true;
11218
+ filteredItems = items.filter(d => d.project_id == null);
11219
+ }
11220
+ else {
11221
+ filteredItems = items.filter(d => d.project_id === resolvedProjectId || d.project_id == null);
11222
+ }
11223
+ const hiddenCount = items.length - filteredItems.length;
11224
+ const notes = [];
11225
+ if (unresolvedListing) {
11226
+ notes.push('No active project resolved; showing org-level (NULL-project) dispatches only. Pass --project <slug> or --all-projects to see more.');
11227
+ }
11228
+ if (hiddenCount > 0) {
11229
+ notes.push(`${hiddenCount} other-project row(s) hidden.`);
11230
+ }
11231
+ if (opts.markRead) {
11232
+ const orgLevelUnreadCount = items.filter(d => d.project_id == null && d.status === 'unread').length;
11233
+ if (orgLevelUnreadCount > 0) {
11234
+ notes.push(`${orgLevelUnreadCount} org-level row(s) not marked; use --mark-actioned <id>.`);
11235
+ }
11236
+ }
11237
+ if (pageCapHit) {
11238
+ notes.push(`Stopped after ${PAGE_CAP} page(s) while draining; more dispatches may remain unmarked. Re-run --mark-read to continue.`);
11239
+ }
11068
11240
  // ── JSON output ──────────────────────────────────────────
11069
11241
  if (opts.format === 'json') {
11070
- console.log(JSON.stringify(result, null, 2));
11242
+ console.log(JSON.stringify({ items: filteredItems, nextCursor }, null, 2));
11071
11243
  }
11072
11244
  else {
11073
11245
  // ── Table output ─────────────────────────────────────
11074
- if (items.length === 0) {
11246
+ if (filteredItems.length === 0) {
11075
11247
  if (opts.role) {
11076
11248
  console.log(chalk.gray(`No ${opts.status} dispatches for role "${opts.role}".`));
11077
11249
  }
@@ -11111,32 +11283,48 @@ Examples:
11111
11283
  ].join(' ');
11112
11284
  console.log(header);
11113
11285
  console.log(chalk.gray('─'.repeat(130)));
11114
- for (const d of items) {
11286
+ for (const d of filteredItems) {
11115
11287
  const priColor = d.priority === 'high' ? chalk.red : d.priority === 'low' ? chalk.gray : chalk.white;
11288
+ // BUG277-CLI — flag org-level (NULL project_id) rows in the table
11289
+ // so it's visible they're never swept by --mark-read.
11290
+ const orgLevelTag = d.project_id == null ? '[org-level] ' : '';
11116
11291
  const row = [
11117
11292
  pad(d.to_role ?? '', COL_ROLE),
11118
11293
  pad(d.from_role ?? '', COL_FROM),
11119
11294
  pad(d.type ?? '', COL_TYPE),
11120
11295
  priColor(pad(d.priority ?? 'normal', COL_PRI)),
11121
11296
  chalk.gray(pad(age(d.created_at), COL_AGE)),
11122
- chalk.cyan(pad(d.summary ?? d.body?.split('\n')[0] ?? '', COL_BODY)),
11297
+ chalk.cyan(pad(orgLevelTag + (d.summary ?? d.body?.split('\n')[0] ?? ''), COL_BODY)),
11123
11298
  ].join(' ');
11124
11299
  console.log(row);
11125
11300
  }
11126
11301
  console.log(chalk.gray('─'.repeat(130)));
11127
- console.log(chalk.gray(`${items.length} dispatch(es) shown.${result.nextCursor ? ' More available (use --limit to increase).' : ''}`));
11302
+ console.log(chalk.gray(`${filteredItems.length} dispatch(es) shown.${nextCursor ? ' More available (use --limit to increase).' : ''}`));
11303
+ }
11304
+ }
11305
+ // Notes go to stderr in JSON mode (stdout must stay pure, parseable
11306
+ // JSON) and to stdout alongside the table in table mode.
11307
+ for (const note of notes) {
11308
+ if (opts.format === 'json') {
11309
+ console.error(chalk.gray(note));
11310
+ }
11311
+ else {
11312
+ console.log(chalk.gray(note));
11128
11313
  }
11129
11314
  }
11130
11315
  // ── --mark-read ──────────────────────────────────────────
11131
11316
  if (opts.markRead && items.length > 0) {
11132
- const unread = items.filter(d => d.status === 'unread');
11133
- if (unread.length === 0) {
11134
- console.log(chalk.gray('\nAll shown dispatches already read; nothing to mark.'));
11317
+ // AC1-NULL: explicit `project_id != null` BEFORE the equality check
11318
+ // — a NULL row must never compare equal to a resolved id by
11319
+ // incidental null-handling.
11320
+ const bulkSet = items.filter(d => d.status === 'unread' && d.project_id != null && d.project_id === resolvedProjectId);
11321
+ if (bulkSet.length === 0) {
11322
+ console.log(chalk.gray('\nAll shown dispatches already read, or excluded by project scope; nothing to mark.'));
11135
11323
  }
11136
11324
  else {
11137
11325
  let marked = 0;
11138
11326
  let failed = 0;
11139
- for (const d of unread) {
11327
+ for (const d of bulkSet) {
11140
11328
  try {
11141
11329
  await api('PATCH', `/api/dispatches/${d.id}`, { status: 'read' }, {
11142
11330
  noProjectHeader: true,