@formigio/fazemos-cli 0.10.88 → 0.10.89

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,12 +9,13 @@ setOrgOverride, setProjectOverride, setDirContextSource, getDirContextSource, }
9
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, isAgentCredential, fetchCredentialScope } from './api.js';
12
+ import { api, ApiError, refreshAuthMeCache, invalidateAuthMeCache, resolveOrgIdMaybeSlug, resolveProjectIdBySlug, resolveProjectBySlug, 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
- import { validatePath as validateRunbookPath } from './runbook/checks.js';
17
+ import { validatePath as validateRunbookPath, loadFlipState } from './runbook/checks.js';
18
+ import { checkTemplateDrift, resolveStepsRoot } from './tpl/drift.js';
18
19
  import { findLocalRegistry, resolveRole, buildDeadLetterFile, writeInboxFileAtPath, buildRolesSyncPayload, findUnprocessedInboxFiles, computeFileHash, gitCommitInboxFile, computeRegistryDeadLetterPath, computeChildDispatchDepth, shouldFallBackToFile, isWakeIneligibleForCadencelessRole, } from './dispatch.js';
19
20
  import { execSync } from 'child_process';
20
21
  import { registerPauseCommands } from './pause.js';
@@ -39,7 +40,7 @@ import { runProvision } from './commands/provision.js';
39
40
  import { parseExecutionsJson, resolveWaitOptions, waitForPipelines, buildAwsCommand, validateExecutionEntry, } from './wait-for-pipeline.js';
40
41
  import { readFileSync, readdirSync, writeFileSync, mkdirSync, existsSync, statSync } from 'fs';
41
42
  import { fileURLToPath } from 'url';
42
- import { dirname, resolve, basename, relative } from 'path';
43
+ import { dirname, resolve, basename, relative, join } from 'path';
43
44
  const __dirname = dirname(fileURLToPath(import.meta.url));
44
45
  const pkg = JSON.parse(readFileSync(resolve(__dirname, '..', 'package.json'), 'utf-8'));
45
46
  function parseNumber(val) {
@@ -653,15 +654,13 @@ program
653
654
  // Validate the project slug within that org.
654
655
  let projectName = projectSlug;
655
656
  if (projectSlug && resolvedOrgId) {
656
- let project = findProjectBySlug(resolvedOrgId, projectSlug);
657
- if (!project) {
658
- await refreshAuthMeCache();
659
- project = findProjectBySlug(resolvedOrgId, projectSlug);
660
- }
657
+ // BUG242: shared cache → refresh → org-projects-list fallback.
658
+ const project = await resolveProjectBySlug(projectSlug, { orgId: resolvedOrgId });
661
659
  if (!project) {
662
660
  console.error(chalk.red(`Unknown project "${projectSlug}" in org ${orgName}.`));
663
661
  console.log(chalk.gray('Run: fazemos projects list'));
664
662
  process.exit(1);
663
+ return;
665
664
  }
666
665
  projectName = project.name;
667
666
  }
@@ -1627,16 +1626,15 @@ projects
1627
1626
  .action(async (slug) => {
1628
1627
  try {
1629
1628
  const orgId = requireActiveOrgOrExit();
1630
- // Resolve slug -> id via cached /auth/me; refresh once on miss.
1631
- let project = findProjectBySlug(orgId, slug);
1632
- if (!project) {
1633
- await refreshAuthMeCache();
1634
- project = findProjectBySlug(orgId, slug);
1635
- }
1629
+ // BUG242: shared cache → refresh → org-projects-list fallback. `projects
1630
+ // show` is the ONLY call site that opts into `includeArchived` — every
1631
+ // other `--project <slug>` path stays active-only (rul_project_archived_scope_gate).
1632
+ const project = await resolveProjectBySlug(slug, { orgId, includeArchived: true });
1636
1633
  if (!project) {
1637
1634
  console.error(chalk.red(`Unknown project: ${slug}`));
1638
1635
  console.log(chalk.gray('Run: fazemos projects list'));
1639
1636
  process.exit(1);
1637
+ return;
1640
1638
  }
1641
1639
  const data = await api('GET', `/api/organizations/${orgId}/projects/${project.id}`, undefined, { noProjectHeader: true });
1642
1640
  const p = data.project;
@@ -1723,16 +1721,13 @@ projects
1723
1721
  .action(async (slug) => {
1724
1722
  try {
1725
1723
  const orgId = requireActiveOrgOrExit();
1726
- let project = findProjectBySlug(orgId, slug);
1727
- if (!project) {
1728
- // Slug-miss cache refresh per §8.3.
1729
- await refreshAuthMeCache();
1730
- project = findProjectBySlug(orgId, slug);
1731
- }
1724
+ // BUG242: shared cache → refresh → org-projects-list fallback.
1725
+ const project = await resolveProjectBySlug(slug, { orgId });
1732
1726
  if (!project) {
1733
1727
  console.error(chalk.red(`Unknown project: ${slug}`));
1734
1728
  console.log(chalk.gray('Run: fazemos projects list'));
1735
1729
  process.exit(1);
1730
+ return;
1736
1731
  }
1737
1732
  setActiveProjectId(orgId, project.id);
1738
1733
  const org = findOrgById(orgId);
@@ -1751,14 +1746,12 @@ projects
1751
1746
  .action(async (slug) => {
1752
1747
  try {
1753
1748
  const orgId = requireActiveOrgOrExit();
1754
- let project = findProjectBySlug(orgId, slug);
1755
- if (!project) {
1756
- await refreshAuthMeCache();
1757
- project = findProjectBySlug(orgId, slug);
1758
- }
1749
+ // BUG242: shared cache → refresh → org-projects-list fallback.
1750
+ const project = await resolveProjectBySlug(slug, { orgId });
1759
1751
  if (!project) {
1760
1752
  console.error(chalk.red(`Unknown project: ${slug}`));
1761
1753
  process.exit(1);
1754
+ return;
1762
1755
  }
1763
1756
  const data = await api('POST', `/api/organizations/${orgId}/projects/${project.id}/archive`, {}, { noProjectHeader: true });
1764
1757
  console.log(chalk.green(`Archived: ${data.project.name} (${data.project.slug})`));
@@ -1797,25 +1790,16 @@ projects
1797
1790
  try {
1798
1791
  const orgId = requireActiveOrgOrExit();
1799
1792
  // Archived projects aren't in the default /auth/me response, so we
1800
- // can't always resolve via cache. Fall back to the full-status list
1801
- // endpoint to find the id.
1802
- let project = findProjectBySlug(orgId, slug);
1803
- if (!project) {
1804
- const listData = await api('GET', `/api/organizations/${orgId}/projects?status=all`, undefined, { noProjectHeader: true });
1805
- const match = (listData.projects ?? []).find((p) => p.slug === slug);
1806
- if (match) {
1807
- project = {
1808
- id: match.id,
1809
- slug: match.slug,
1810
- name: match.name,
1811
- colorIndex: match.colorIndex ?? 0,
1812
- status: match.status,
1813
- };
1814
- }
1815
- }
1793
+ // can't always resolve via cache. BUG242: routed through the shared
1794
+ // resolver with includeArchived — `unarchive`'s whole purpose is
1795
+ // finding an archived project by slug, so it needs the same org-list
1796
+ // fallback `projects show` uses, not the active-only default every
1797
+ // other `--project <slug>` site gets.
1798
+ const project = await resolveProjectBySlug(slug, { orgId, includeArchived: true });
1816
1799
  if (!project) {
1817
1800
  console.error(chalk.red(`Unknown project: ${slug}`));
1818
1801
  process.exit(1);
1802
+ return;
1819
1803
  }
1820
1804
  const data = await api('POST', `/api/organizations/${orgId}/projects/${project.id}/unarchive`, {}, { noProjectHeader: true });
1821
1805
  console.log(chalk.green(`Unarchived: ${data.project.name} (${data.project.slug})`));
@@ -1839,14 +1823,12 @@ projects
1839
1823
  process.exit(1);
1840
1824
  }
1841
1825
  const orgId = requireActiveOrgOrExit();
1842
- let project = findProjectBySlug(orgId, slug);
1843
- if (!project) {
1844
- await refreshAuthMeCache();
1845
- project = findProjectBySlug(orgId, slug);
1846
- }
1826
+ // BUG242: shared cache → refresh → org-projects-list fallback.
1827
+ const project = await resolveProjectBySlug(slug, { orgId });
1847
1828
  if (!project) {
1848
1829
  console.error(chalk.red(`Unknown project: ${slug}`));
1849
1830
  process.exit(1);
1831
+ return;
1850
1832
  }
1851
1833
  const body = {};
1852
1834
  if (opts.name)
@@ -1872,15 +1854,13 @@ projects
1872
1854
  .action(async (slug, connection) => {
1873
1855
  try {
1874
1856
  const orgId = requireActiveOrgOrExit();
1875
- let project = findProjectBySlug(orgId, slug);
1876
- if (!project) {
1877
- await refreshAuthMeCache();
1878
- project = findProjectBySlug(orgId, slug);
1879
- }
1857
+ // BUG242: shared cache → refresh → org-projects-list fallback.
1858
+ const project = await resolveProjectBySlug(slug, { orgId });
1880
1859
  if (!project) {
1881
1860
  console.error(chalk.red(`Unknown project: ${slug}`));
1882
1861
  console.log(chalk.gray('Run: fazemos projects list'));
1883
1862
  process.exit(1);
1863
+ return;
1884
1864
  }
1885
1865
  const githubConnectionId = connection === 'none' ? null : connection;
1886
1866
  const data = await api('PATCH', `/api/organizations/${orgId}/projects/${project.id}`, { githubConnectionId }, { noProjectHeader: true });
@@ -2066,11 +2046,8 @@ projects
2066
2046
  }
2067
2047
  // ── Resolve slug → project ID ──────────────────────────────
2068
2048
  const orgId = requireActiveOrgOrExit();
2069
- let project = findProjectBySlug(orgId, slug);
2070
- if (!project) {
2071
- await refreshAuthMeCache();
2072
- project = findProjectBySlug(orgId, slug);
2073
- }
2049
+ // BUG242: shared cache → refresh → org-projects-list fallback.
2050
+ const project = await resolveProjectBySlug(slug, { orgId });
2074
2051
  if (!project) {
2075
2052
  const msg = `Unknown project: ${slug}`;
2076
2053
  if (opts.json) {
@@ -4075,6 +4052,26 @@ function allSteps(definition) {
4075
4052
  function findStepById(definition, stepId) {
4076
4053
  return allSteps(definition).find((s) => s.id === stepId);
4077
4054
  }
4055
+ /**
4056
+ * BUG261: `step.sections` is typed as `string` on the API contract, but some
4057
+ * stored template definitions (older imports, hand-edited JSON) persist it as
4058
+ * an array or object instead. Rendering code used to `as string` cast the raw
4059
+ * value and call `.split('\n')` on it directly, which threw
4060
+ * "full.split is not a function" at runtime for any non-string value. Render
4061
+ * sites should call this helper instead of touching `step.sections` directly:
4062
+ * a string passes through unchanged; anything else is pretty-printed as JSON
4063
+ * so it can still be truncated/split like text.
4064
+ */
4065
+ export function normalizeSectionsForDisplay(sections) {
4066
+ if (typeof sections === 'string')
4067
+ return sections;
4068
+ try {
4069
+ return JSON.stringify(sections, null, 2);
4070
+ }
4071
+ catch {
4072
+ return String(sections);
4073
+ }
4074
+ }
4078
4075
  /**
4079
4076
  * Pipeline-sourced step inputs went through a schema migration: the old
4080
4077
  * shape stored the pipeline input name under `pipeline_input`; the new shape
@@ -4262,7 +4259,7 @@ templates
4262
4259
  }
4263
4260
  // sections (agent instructions) — truncated at 200 chars unless --show-sections
4264
4261
  if (step.sections) {
4265
- const full = step.sections;
4262
+ const full = normalizeSectionsForDisplay(step.sections);
4266
4263
  if (opts.showSections || full.length <= 200) {
4267
4264
  console.log(` Sections:\n${full.split('\n').map((l) => ` ${l}`).join('\n')}`);
4268
4265
  }
@@ -5449,6 +5446,92 @@ templates
5449
5446
  process.exit(1);
5450
5447
  }
5451
5448
  });
5449
+ // ── `tpl drift` — BUG244 L1: file ↔ live step-body mirror detector ──
5450
+ //
5451
+ // Enforces rul_step_file_mirrors_live (2026-09-28 sizing brief §(c)):
5452
+ // - Un-flipped, file present: normalized(file body) == normalized(live `sections`).
5453
+ // - Flipped (runbooks/flip-state.json): live `sections` is empty after normalization.
5454
+ // - No file: live `sections` renders. No mirror obligation.
5455
+ // Normalization (Q2 amendment, both sides): strip ONE leading frontmatter
5456
+ // block only if it starts at byte 0, using the same splitter as
5457
+ // parseFrontmatter, THEN CRLF→LF, trim trailing per-line whitespace, trim
5458
+ // leading/trailing blank lines. See src/tpl/normalize.ts and src/tpl/drift.ts.
5459
+ templates
5460
+ .command('drift')
5461
+ .description('BUG244 — detect drift between a template step\'s file body (steps/<Template>/<Step>.md in the ' +
5462
+ 'local workspace clone) and its live `sections`. Un-flipped steps must match after normalization ' +
5463
+ '(frontmatter-strip + CRLF/whitespace/blank-line trim); flipped steps must have empty live sections ' +
5464
+ 'after the same normalization; a step-doc file with no live step is an orphan. A divergence is a ' +
5465
+ 'defect to detect, never resolved by precedence — file still wins at render time regardless. ' +
5466
+ 'Rule slugs: step.body_drift (error, unified diff), step.flipped_live_nonempty (error), ' +
5467
+ 'step.file_orphan (warning), step.live_embedded_frontmatter (info — the 18 CLI Publishing / Pin Bump ' +
5468
+ 'steps carry this today; inert at render time, a hygiene signal only). Exit is non-zero on any error.')
5469
+ .argument('[template]', 'Template ID or name (use "tpl list" to find them). Omit when using --all.')
5470
+ .option('--all', 'Check every active template in the active project instead of a single one', false)
5471
+ .option('--steps-dir <dir>', 'Directory holding steps/<Template>/<Step>.md — defaults to the workspace clone\'s projects/fazemos/steps, found by walking up from the current directory')
5472
+ .option('--project <slug>', 'Override active project when resolving a template name, or for --all')
5473
+ .option('--json', 'Emit structured JSON output — one object per template, always includes info findings')
5474
+ .option('--verbose', 'Show info-severity findings in human output too (always included in --json)', false)
5475
+ .action(async (template, opts) => {
5476
+ try {
5477
+ if (!opts.all && !template) {
5478
+ console.error(chalk.red('Provide a template ID/name, or pass --all to check every active template.'));
5479
+ process.exit(1);
5480
+ }
5481
+ if (opts.all && template) {
5482
+ console.error(chalk.red('Pass either a template argument or --all, not both.'));
5483
+ process.exit(1);
5484
+ }
5485
+ const stepsRoot = opts.stepsDir ? resolve(opts.stepsDir) : resolveStepsRoot(process.cwd());
5486
+ if (!stepsRoot) {
5487
+ console.error(chalk.red('Could not locate projects/fazemos/steps by walking up from the current directory. ' +
5488
+ 'Run from inside a fazemos-workspace clone, or pass --steps-dir explicitly.'));
5489
+ process.exit(1);
5490
+ }
5491
+ let targets;
5492
+ if (opts.all) {
5493
+ const data = await api('GET', '/api/pipeline-templates?status=active', undefined, projectOpts(opts));
5494
+ targets = [];
5495
+ for (const t of data.templates ?? []) {
5496
+ const full = await api('GET', `/api/pipeline-templates/${t.id}`);
5497
+ targets.push({ name: full.template.name, definition: full.template.definition });
5498
+ }
5499
+ }
5500
+ else {
5501
+ const resolvedId = await resolveTemplateId(template, opts);
5502
+ const data = await api('GET', `/api/pipeline-templates/${resolvedId}`);
5503
+ targets = [{ name: data.template.name, definition: data.template.definition }];
5504
+ }
5505
+ const flip = loadFlipState(stepsRoot);
5506
+ let totalErrors = 0;
5507
+ const results = targets.map((t) => ({
5508
+ source: t.name,
5509
+ findings: checkTemplateDrift(t.name, t.definition, join(stepsRoot, t.name), flip.ledger, flip.error),
5510
+ }));
5511
+ if (opts.json) {
5512
+ const payload = results.map(({ source, findings }) => {
5513
+ const summary = summarize(findings);
5514
+ totalErrors += summary.errors;
5515
+ return { source, ok: summary.errors === 0, summary, findings };
5516
+ });
5517
+ console.log(JSON.stringify(payload, null, 2));
5518
+ }
5519
+ else {
5520
+ for (const { source, findings } of results) {
5521
+ const summary = summarize(findings);
5522
+ totalErrors += summary.errors;
5523
+ const visible = opts.verbose ? findings : findings.filter((f) => f.severity !== 'info');
5524
+ printFindings(source, visible, summary);
5525
+ console.log('');
5526
+ }
5527
+ }
5528
+ if (totalErrors > 0)
5529
+ process.exit(1);
5530
+ }
5531
+ catch (err) {
5532
+ handleScopedError(err);
5533
+ }
5534
+ });
5452
5535
  // ── Pipelines ──────────────────────────────────────────────
5453
5536
  const pipelines = program.command('pipelines').alias('pl').description('Pipeline instance commands');
5454
5537
  // Keep this in sync with the `pl list --status` help text below. A typo like
@@ -7199,10 +7282,119 @@ executions
7199
7282
  process.exit(1);
7200
7283
  }
7201
7284
  });
7285
+ async function fetchUnreadDispatches() {
7286
+ if (isAgentCredential())
7287
+ return { kind: 'not_applicable' };
7288
+ let countResult;
7289
+ try {
7290
+ countResult = (await api('GET', '/api/dispatches/unread-count', undefined, {
7291
+ noProjectHeader: true,
7292
+ }));
7293
+ }
7294
+ catch (err) {
7295
+ if (err instanceof ApiError && err.code === 'INBOX_IS_HUMAN_SURFACE') {
7296
+ // Not applicable rather than unavailable — see header comment.
7297
+ return { kind: 'not_applicable' };
7298
+ }
7299
+ const code = err instanceof ApiError ? err.status : 'unknown';
7300
+ return { kind: 'error', code };
7301
+ }
7302
+ if (countResult.total === 0) {
7303
+ return { kind: 'ok', summary: { total: 0, byRole: [] } };
7304
+ }
7305
+ const agg = new Map();
7306
+ let cursor = null;
7307
+ let page = 0;
7308
+ let truncated = false;
7309
+ for (;;) {
7310
+ page++;
7311
+ const params = new URLSearchParams();
7312
+ params.set('status', 'unread');
7313
+ params.set('limit', '100');
7314
+ if (cursor)
7315
+ params.set('cursor', cursor);
7316
+ let result;
7317
+ try {
7318
+ result = (await api('GET', `/api/dispatches?${params.toString()}`, undefined, {
7319
+ noProjectHeader: true,
7320
+ }));
7321
+ }
7322
+ catch (err) {
7323
+ const code = err instanceof ApiError ? err.status : 'unknown';
7324
+ return { kind: 'error', code };
7325
+ }
7326
+ for (const item of result.items ?? []) {
7327
+ const entry = agg.get(item.to_role) ?? { high: 0, oldest: null };
7328
+ if (item.priority === 'high')
7329
+ entry.high++;
7330
+ if (!entry.oldest || item.created_at < entry.oldest)
7331
+ entry.oldest = item.created_at;
7332
+ agg.set(item.to_role, entry);
7333
+ }
7334
+ cursor = result.nextCursor;
7335
+ if (!cursor)
7336
+ break;
7337
+ if (page >= 10) {
7338
+ truncated = true;
7339
+ break;
7340
+ }
7341
+ }
7342
+ const byRole = Object.entries(countResult.byRole).map(([role, unread]) => {
7343
+ const entry = agg.get(role);
7344
+ return {
7345
+ role,
7346
+ unread,
7347
+ high: entry?.high ?? 0,
7348
+ oldestCreatedAt: entry?.oldest ?? null,
7349
+ truncated,
7350
+ };
7351
+ });
7352
+ return { kind: 'ok', summary: { total: countResult.total, byRole } };
7353
+ }
7354
+ /** Renders the pointer block to stdout for the table (non-JSON) path. */
7355
+ function renderUnreadDispatchesPointer(fetched) {
7356
+ if (fetched.kind === 'not_applicable')
7357
+ return;
7358
+ if (fetched.kind === 'error') {
7359
+ console.log(chalk.gray(`unread dispatches: unavailable (${fetched.code})`));
7360
+ return;
7361
+ }
7362
+ if (fetched.summary.total === 0)
7363
+ return;
7364
+ const now = Date.now();
7365
+ for (const r of fetched.summary.byRole) {
7366
+ if (r.unread < 1)
7367
+ continue;
7368
+ const pieces = [];
7369
+ if (r.high > 0)
7370
+ pieces.push(`${r.high} high`);
7371
+ if (r.oldestCreatedAt) {
7372
+ const days = Math.max(0, Math.floor((now - new Date(r.oldestCreatedAt).getTime()) / 86400000));
7373
+ pieces.push(`oldest ${r.truncated ? '≥' : ''}${days}d`);
7374
+ }
7375
+ const suffix = pieces.length ? ` (${pieces.join(', ')})` : '';
7376
+ console.log(`${r.unread} unread dispatches${suffix} — fazemos inbox --role ${r.role}`);
7377
+ }
7378
+ console.log('');
7379
+ }
7380
+ /** Additive `--json` shape: `unread_dispatches: { total, by_role: [...] }`. */
7381
+ function unreadDispatchesToJson(fetched) {
7382
+ if (fetched.kind !== 'ok')
7383
+ return null;
7384
+ return {
7385
+ total: fetched.summary.total,
7386
+ by_role: fetched.summary.byRole.map((r) => ({
7387
+ role: r.role,
7388
+ unread: r.unread,
7389
+ high: r.high,
7390
+ oldest_created_at: r.oldestCreatedAt,
7391
+ })),
7392
+ };
7393
+ }
7202
7394
  // ── My Work ─────────────────────────────────────────────────
7203
7395
  program
7204
7396
  .command('my-work')
7205
- .description('Show pending work in the active project (or all projects with --all-projects, or across every org with --all-orgs). Requires a user identity (JWT). Not available to agent-key callers — agents read their own inbox and executions via `fazemos inbox --role <me>` and `fazemos ex list --role <me>`.')
7397
+ .description('Show pending work in the active project (or all projects with --all-projects, or across every org with --all-orgs). Requires a user identity (JWT). Not available to agent-key callers — agents read their own inbox and executions via `fazemos inbox --role <me>` and `fazemos ex list --role <me>`.\n\nUnread-dispatch counts (human callers only) span every org the caller belongs to, even on the default project-scoped view — dispatches are role- and org-scoped, not project-scoped.')
7206
7398
  .option('--project <slug>', 'Override active project for this call')
7207
7399
  .option('--all-projects', 'Show pending work across every project in the active org', false)
7208
7400
  .option('-a, --all-orgs', 'Show pending work across every org you are a member of (calls /api/my-work/unified)', false)
@@ -7215,11 +7407,13 @@ program
7215
7407
  // an active member of. See rul_cross_org_auth_no_org_middleware.
7216
7408
  if (opts.allOrgs) {
7217
7409
  try {
7410
+ const unread = await fetchUnreadDispatches();
7218
7411
  const data = await api('GET', '/api/my-work/unified', undefined, { noProjectHeader: true });
7219
7412
  if (opts.json) {
7220
- console.log(JSON.stringify(data, null, 2));
7413
+ console.log(JSON.stringify({ ...data, unread_dispatches: unreadDispatchesToJson(unread) }, null, 2));
7221
7414
  return;
7222
7415
  }
7416
+ renderUnreadDispatchesPointer(unread);
7223
7417
  // Sage edge case #24: single-Org user with --all-orgs gets a soft
7224
7418
  // notice + their normal output (no flag-stripping, no error).
7225
7419
  if (data.meta.orgCount === 1) {
@@ -7244,15 +7438,17 @@ program
7244
7438
  process.exit(1);
7245
7439
  }
7246
7440
  }
7247
- // ── Default project-scoped path (unchanged) ─────────────────
7441
+ // ── Default project-scoped path ─────────────────────────────
7248
7442
  try {
7443
+ const unread = await fetchUnreadDispatches();
7249
7444
  const data = await api('GET', '/api/my-work', undefined, projectOpts(opts));
7250
7445
  const c = data.commitments;
7251
7446
  const total = c.overdue.length + c.due_today.length + c.due_this_week.length + c.upcoming.length;
7252
7447
  if (opts.json) {
7253
- console.log(JSON.stringify(data, null, 2));
7448
+ console.log(JSON.stringify({ ...data, unread_dispatches: unreadDispatchesToJson(unread) }, null, 2));
7254
7449
  return;
7255
7450
  }
7451
+ renderUnreadDispatchesPointer(unread);
7256
7452
  console.log(chalk.cyan(`Commitments: ${total}`));
7257
7453
  if (c.overdue.length)
7258
7454
  console.log(chalk.red(` Overdue: ${c.overdue.length}`));
@@ -7441,14 +7637,10 @@ agentsCmd
7441
7637
  let credentialProjectId;
7442
7638
  if (provisionCredential) {
7443
7639
  if (opts.project) {
7444
- // Resolve slug → id via cache; refresh once on miss.
7640
+ // BUG242: shared cache → refresh → org-projects-list fallback.
7445
7641
  const orgId = getActiveOrgId();
7446
7642
  if (orgId) {
7447
- let proj = findProjectBySlug(orgId, opts.project);
7448
- if (!proj) {
7449
- await refreshAuthMeCache();
7450
- proj = findProjectBySlug(orgId, opts.project);
7451
- }
7643
+ const proj = await resolveProjectBySlug(opts.project, { orgId });
7452
7644
  if (proj) {
7453
7645
  credentialProjectId = proj.id;
7454
7646
  }
@@ -7835,15 +8027,13 @@ async function resolveProjectIdForAgentsList(slugOverride) {
7835
8027
  const orgId = getActiveOrgId();
7836
8028
  if (!orgId)
7837
8029
  return null;
7838
- let project = findProjectBySlug(orgId, slugOverride);
7839
- if (!project) {
7840
- await refreshAuthMeCache();
7841
- project = findProjectBySlug(orgId, slugOverride);
7842
- }
8030
+ // BUG242: shared cache → refresh → org-projects-list fallback.
8031
+ const project = await resolveProjectBySlug(slugOverride, { orgId });
7843
8032
  if (!project) {
7844
8033
  console.error(chalk.red(`Unknown project: ${slugOverride}`));
7845
8034
  console.error(chalk.gray('Run: fazemos projects list'));
7846
8035
  process.exit(1);
8036
+ return null;
7847
8037
  }
7848
8038
  return project.id;
7849
8039
  }
@@ -9453,15 +9643,13 @@ async function requireProjectForDocs(slugOverride) {
9453
9643
  let projectId = null;
9454
9644
  let projectSlug = null;
9455
9645
  if (slugOverride) {
9456
- let project = findProjectBySlug(orgId, slugOverride);
9457
- if (!project) {
9458
- await refreshAuthMeCache();
9459
- project = findProjectBySlug(orgId, slugOverride);
9460
- }
9646
+ // BUG242: shared cache → refresh → org-projects-list fallback.
9647
+ const project = await resolveProjectBySlug(slugOverride, { orgId });
9461
9648
  if (!project) {
9462
9649
  console.error(chalk.red(`Unknown project: ${slugOverride}`));
9463
9650
  console.error(chalk.gray('Run: fazemos projects list'));
9464
9651
  process.exit(1);
9652
+ return { orgId, projectId: '', projectSlug: '' };
9465
9653
  }
9466
9654
  projectId = project.id;
9467
9655
  projectSlug = project.slug;