@formigio/fazemos-cli 0.10.88 → 0.10.90

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,20 @@ 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
+ // BUG242-R2: also the ONLY call site that opts into
1633
+ // `allowAgentListFallback` — the org-projects-list route is already
1634
+ // agent-reachable (same as `projects list`), so this is the one
1635
+ // "look up this slug" read command that should actually work for an
1636
+ // agent seat. Every other `--project <slug>` site leaves it unset.
1637
+ const project = await resolveProjectBySlug(slug, { orgId, includeArchived: true, allowAgentListFallback: true });
1636
1638
  if (!project) {
1637
1639
  console.error(chalk.red(`Unknown project: ${slug}`));
1638
1640
  console.log(chalk.gray('Run: fazemos projects list'));
1639
1641
  process.exit(1);
1642
+ return;
1640
1643
  }
1641
1644
  const data = await api('GET', `/api/organizations/${orgId}/projects/${project.id}`, undefined, { noProjectHeader: true });
1642
1645
  const p = data.project;
@@ -1723,16 +1726,13 @@ projects
1723
1726
  .action(async (slug) => {
1724
1727
  try {
1725
1728
  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
- }
1729
+ // BUG242: shared cache → refresh → org-projects-list fallback.
1730
+ const project = await resolveProjectBySlug(slug, { orgId });
1732
1731
  if (!project) {
1733
1732
  console.error(chalk.red(`Unknown project: ${slug}`));
1734
1733
  console.log(chalk.gray('Run: fazemos projects list'));
1735
1734
  process.exit(1);
1735
+ return;
1736
1736
  }
1737
1737
  setActiveProjectId(orgId, project.id);
1738
1738
  const org = findOrgById(orgId);
@@ -1751,14 +1751,12 @@ projects
1751
1751
  .action(async (slug) => {
1752
1752
  try {
1753
1753
  const orgId = requireActiveOrgOrExit();
1754
- let project = findProjectBySlug(orgId, slug);
1755
- if (!project) {
1756
- await refreshAuthMeCache();
1757
- project = findProjectBySlug(orgId, slug);
1758
- }
1754
+ // BUG242: shared cache → refresh → org-projects-list fallback.
1755
+ const project = await resolveProjectBySlug(slug, { orgId });
1759
1756
  if (!project) {
1760
1757
  console.error(chalk.red(`Unknown project: ${slug}`));
1761
1758
  process.exit(1);
1759
+ return;
1762
1760
  }
1763
1761
  const data = await api('POST', `/api/organizations/${orgId}/projects/${project.id}/archive`, {}, { noProjectHeader: true });
1764
1762
  console.log(chalk.green(`Archived: ${data.project.name} (${data.project.slug})`));
@@ -1797,25 +1795,16 @@ projects
1797
1795
  try {
1798
1796
  const orgId = requireActiveOrgOrExit();
1799
1797
  // 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
- }
1798
+ // can't always resolve via cache. BUG242: routed through the shared
1799
+ // resolver with includeArchived — `unarchive`'s whole purpose is
1800
+ // finding an archived project by slug, so it needs the same org-list
1801
+ // fallback `projects show` uses, not the active-only default every
1802
+ // other `--project <slug>` site gets.
1803
+ const project = await resolveProjectBySlug(slug, { orgId, includeArchived: true });
1816
1804
  if (!project) {
1817
1805
  console.error(chalk.red(`Unknown project: ${slug}`));
1818
1806
  process.exit(1);
1807
+ return;
1819
1808
  }
1820
1809
  const data = await api('POST', `/api/organizations/${orgId}/projects/${project.id}/unarchive`, {}, { noProjectHeader: true });
1821
1810
  console.log(chalk.green(`Unarchived: ${data.project.name} (${data.project.slug})`));
@@ -1839,14 +1828,12 @@ projects
1839
1828
  process.exit(1);
1840
1829
  }
1841
1830
  const orgId = requireActiveOrgOrExit();
1842
- let project = findProjectBySlug(orgId, slug);
1843
- if (!project) {
1844
- await refreshAuthMeCache();
1845
- project = findProjectBySlug(orgId, slug);
1846
- }
1831
+ // BUG242: shared cache → refresh → org-projects-list fallback.
1832
+ const project = await resolveProjectBySlug(slug, { orgId });
1847
1833
  if (!project) {
1848
1834
  console.error(chalk.red(`Unknown project: ${slug}`));
1849
1835
  process.exit(1);
1836
+ return;
1850
1837
  }
1851
1838
  const body = {};
1852
1839
  if (opts.name)
@@ -1872,15 +1859,13 @@ projects
1872
1859
  .action(async (slug, connection) => {
1873
1860
  try {
1874
1861
  const orgId = requireActiveOrgOrExit();
1875
- let project = findProjectBySlug(orgId, slug);
1876
- if (!project) {
1877
- await refreshAuthMeCache();
1878
- project = findProjectBySlug(orgId, slug);
1879
- }
1862
+ // BUG242: shared cache → refresh → org-projects-list fallback.
1863
+ const project = await resolveProjectBySlug(slug, { orgId });
1880
1864
  if (!project) {
1881
1865
  console.error(chalk.red(`Unknown project: ${slug}`));
1882
1866
  console.log(chalk.gray('Run: fazemos projects list'));
1883
1867
  process.exit(1);
1868
+ return;
1884
1869
  }
1885
1870
  const githubConnectionId = connection === 'none' ? null : connection;
1886
1871
  const data = await api('PATCH', `/api/organizations/${orgId}/projects/${project.id}`, { githubConnectionId }, { noProjectHeader: true });
@@ -2066,11 +2051,8 @@ projects
2066
2051
  }
2067
2052
  // ── Resolve slug → project ID ──────────────────────────────
2068
2053
  const orgId = requireActiveOrgOrExit();
2069
- let project = findProjectBySlug(orgId, slug);
2070
- if (!project) {
2071
- await refreshAuthMeCache();
2072
- project = findProjectBySlug(orgId, slug);
2073
- }
2054
+ // BUG242: shared cache → refresh → org-projects-list fallback.
2055
+ const project = await resolveProjectBySlug(slug, { orgId });
2074
2056
  if (!project) {
2075
2057
  const msg = `Unknown project: ${slug}`;
2076
2058
  if (opts.json) {
@@ -4075,6 +4057,26 @@ function allSteps(definition) {
4075
4057
  function findStepById(definition, stepId) {
4076
4058
  return allSteps(definition).find((s) => s.id === stepId);
4077
4059
  }
4060
+ /**
4061
+ * BUG261: `step.sections` is typed as `string` on the API contract, but some
4062
+ * stored template definitions (older imports, hand-edited JSON) persist it as
4063
+ * an array or object instead. Rendering code used to `as string` cast the raw
4064
+ * value and call `.split('\n')` on it directly, which threw
4065
+ * "full.split is not a function" at runtime for any non-string value. Render
4066
+ * sites should call this helper instead of touching `step.sections` directly:
4067
+ * a string passes through unchanged; anything else is pretty-printed as JSON
4068
+ * so it can still be truncated/split like text.
4069
+ */
4070
+ export function normalizeSectionsForDisplay(sections) {
4071
+ if (typeof sections === 'string')
4072
+ return sections;
4073
+ try {
4074
+ return JSON.stringify(sections, null, 2);
4075
+ }
4076
+ catch {
4077
+ return String(sections);
4078
+ }
4079
+ }
4078
4080
  /**
4079
4081
  * Pipeline-sourced step inputs went through a schema migration: the old
4080
4082
  * shape stored the pipeline input name under `pipeline_input`; the new shape
@@ -4262,7 +4264,7 @@ templates
4262
4264
  }
4263
4265
  // sections (agent instructions) — truncated at 200 chars unless --show-sections
4264
4266
  if (step.sections) {
4265
- const full = step.sections;
4267
+ const full = normalizeSectionsForDisplay(step.sections);
4266
4268
  if (opts.showSections || full.length <= 200) {
4267
4269
  console.log(` Sections:\n${full.split('\n').map((l) => ` ${l}`).join('\n')}`);
4268
4270
  }
@@ -5449,6 +5451,92 @@ templates
5449
5451
  process.exit(1);
5450
5452
  }
5451
5453
  });
5454
+ // ── `tpl drift` — BUG244 L1: file ↔ live step-body mirror detector ──
5455
+ //
5456
+ // Enforces rul_step_file_mirrors_live (2026-09-28 sizing brief §(c)):
5457
+ // - Un-flipped, file present: normalized(file body) == normalized(live `sections`).
5458
+ // - Flipped (runbooks/flip-state.json): live `sections` is empty after normalization.
5459
+ // - No file: live `sections` renders. No mirror obligation.
5460
+ // Normalization (Q2 amendment, both sides): strip ONE leading frontmatter
5461
+ // block only if it starts at byte 0, using the same splitter as
5462
+ // parseFrontmatter, THEN CRLF→LF, trim trailing per-line whitespace, trim
5463
+ // leading/trailing blank lines. See src/tpl/normalize.ts and src/tpl/drift.ts.
5464
+ templates
5465
+ .command('drift')
5466
+ .description('BUG244 — detect drift between a template step\'s file body (steps/<Template>/<Step>.md in the ' +
5467
+ 'local workspace clone) and its live `sections`. Un-flipped steps must match after normalization ' +
5468
+ '(frontmatter-strip + CRLF/whitespace/blank-line trim); flipped steps must have empty live sections ' +
5469
+ 'after the same normalization; a step-doc file with no live step is an orphan. A divergence is a ' +
5470
+ 'defect to detect, never resolved by precedence — file still wins at render time regardless. ' +
5471
+ 'Rule slugs: step.body_drift (error, unified diff), step.flipped_live_nonempty (error), ' +
5472
+ 'step.file_orphan (warning), step.live_embedded_frontmatter (info — the 18 CLI Publishing / Pin Bump ' +
5473
+ 'steps carry this today; inert at render time, a hygiene signal only). Exit is non-zero on any error.')
5474
+ .argument('[template]', 'Template ID or name (use "tpl list" to find them). Omit when using --all.')
5475
+ .option('--all', 'Check every active template in the active project instead of a single one', false)
5476
+ .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')
5477
+ .option('--project <slug>', 'Override active project when resolving a template name, or for --all')
5478
+ .option('--json', 'Emit structured JSON output — one object per template, always includes info findings')
5479
+ .option('--verbose', 'Show info-severity findings in human output too (always included in --json)', false)
5480
+ .action(async (template, opts) => {
5481
+ try {
5482
+ if (!opts.all && !template) {
5483
+ console.error(chalk.red('Provide a template ID/name, or pass --all to check every active template.'));
5484
+ process.exit(1);
5485
+ }
5486
+ if (opts.all && template) {
5487
+ console.error(chalk.red('Pass either a template argument or --all, not both.'));
5488
+ process.exit(1);
5489
+ }
5490
+ const stepsRoot = opts.stepsDir ? resolve(opts.stepsDir) : resolveStepsRoot(process.cwd());
5491
+ if (!stepsRoot) {
5492
+ console.error(chalk.red('Could not locate projects/fazemos/steps by walking up from the current directory. ' +
5493
+ 'Run from inside a fazemos-workspace clone, or pass --steps-dir explicitly.'));
5494
+ process.exit(1);
5495
+ }
5496
+ let targets;
5497
+ if (opts.all) {
5498
+ const data = await api('GET', '/api/pipeline-templates?status=active', undefined, projectOpts(opts));
5499
+ targets = [];
5500
+ for (const t of data.templates ?? []) {
5501
+ const full = await api('GET', `/api/pipeline-templates/${t.id}`);
5502
+ targets.push({ name: full.template.name, definition: full.template.definition });
5503
+ }
5504
+ }
5505
+ else {
5506
+ const resolvedId = await resolveTemplateId(template, opts);
5507
+ const data = await api('GET', `/api/pipeline-templates/${resolvedId}`);
5508
+ targets = [{ name: data.template.name, definition: data.template.definition }];
5509
+ }
5510
+ const flip = loadFlipState(stepsRoot);
5511
+ let totalErrors = 0;
5512
+ const results = targets.map((t) => ({
5513
+ source: t.name,
5514
+ findings: checkTemplateDrift(t.name, t.definition, join(stepsRoot, t.name), flip.ledger, flip.error),
5515
+ }));
5516
+ if (opts.json) {
5517
+ const payload = results.map(({ source, findings }) => {
5518
+ const summary = summarize(findings);
5519
+ totalErrors += summary.errors;
5520
+ return { source, ok: summary.errors === 0, summary, findings };
5521
+ });
5522
+ console.log(JSON.stringify(payload, null, 2));
5523
+ }
5524
+ else {
5525
+ for (const { source, findings } of results) {
5526
+ const summary = summarize(findings);
5527
+ totalErrors += summary.errors;
5528
+ const visible = opts.verbose ? findings : findings.filter((f) => f.severity !== 'info');
5529
+ printFindings(source, visible, summary);
5530
+ console.log('');
5531
+ }
5532
+ }
5533
+ if (totalErrors > 0)
5534
+ process.exit(1);
5535
+ }
5536
+ catch (err) {
5537
+ handleScopedError(err);
5538
+ }
5539
+ });
5452
5540
  // ── Pipelines ──────────────────────────────────────────────
5453
5541
  const pipelines = program.command('pipelines').alias('pl').description('Pipeline instance commands');
5454
5542
  // Keep this in sync with the `pl list --status` help text below. A typo like
@@ -7199,10 +7287,119 @@ executions
7199
7287
  process.exit(1);
7200
7288
  }
7201
7289
  });
7290
+ async function fetchUnreadDispatches() {
7291
+ if (isAgentCredential())
7292
+ return { kind: 'not_applicable' };
7293
+ let countResult;
7294
+ try {
7295
+ countResult = (await api('GET', '/api/dispatches/unread-count', undefined, {
7296
+ noProjectHeader: true,
7297
+ }));
7298
+ }
7299
+ catch (err) {
7300
+ if (err instanceof ApiError && err.code === 'INBOX_IS_HUMAN_SURFACE') {
7301
+ // Not applicable rather than unavailable — see header comment.
7302
+ return { kind: 'not_applicable' };
7303
+ }
7304
+ const code = err instanceof ApiError ? err.status : 'unknown';
7305
+ return { kind: 'error', code };
7306
+ }
7307
+ if (countResult.total === 0) {
7308
+ return { kind: 'ok', summary: { total: 0, byRole: [] } };
7309
+ }
7310
+ const agg = new Map();
7311
+ let cursor = null;
7312
+ let page = 0;
7313
+ let truncated = false;
7314
+ for (;;) {
7315
+ page++;
7316
+ const params = new URLSearchParams();
7317
+ params.set('status', 'unread');
7318
+ params.set('limit', '100');
7319
+ if (cursor)
7320
+ params.set('cursor', cursor);
7321
+ let result;
7322
+ try {
7323
+ result = (await api('GET', `/api/dispatches?${params.toString()}`, undefined, {
7324
+ noProjectHeader: true,
7325
+ }));
7326
+ }
7327
+ catch (err) {
7328
+ const code = err instanceof ApiError ? err.status : 'unknown';
7329
+ return { kind: 'error', code };
7330
+ }
7331
+ for (const item of result.items ?? []) {
7332
+ const entry = agg.get(item.to_role) ?? { high: 0, oldest: null };
7333
+ if (item.priority === 'high')
7334
+ entry.high++;
7335
+ if (!entry.oldest || item.created_at < entry.oldest)
7336
+ entry.oldest = item.created_at;
7337
+ agg.set(item.to_role, entry);
7338
+ }
7339
+ cursor = result.nextCursor;
7340
+ if (!cursor)
7341
+ break;
7342
+ if (page >= 10) {
7343
+ truncated = true;
7344
+ break;
7345
+ }
7346
+ }
7347
+ const byRole = Object.entries(countResult.byRole).map(([role, unread]) => {
7348
+ const entry = agg.get(role);
7349
+ return {
7350
+ role,
7351
+ unread,
7352
+ high: entry?.high ?? 0,
7353
+ oldestCreatedAt: entry?.oldest ?? null,
7354
+ truncated,
7355
+ };
7356
+ });
7357
+ return { kind: 'ok', summary: { total: countResult.total, byRole } };
7358
+ }
7359
+ /** Renders the pointer block to stdout for the table (non-JSON) path. */
7360
+ function renderUnreadDispatchesPointer(fetched) {
7361
+ if (fetched.kind === 'not_applicable')
7362
+ return;
7363
+ if (fetched.kind === 'error') {
7364
+ console.log(chalk.gray(`unread dispatches: unavailable (${fetched.code})`));
7365
+ return;
7366
+ }
7367
+ if (fetched.summary.total === 0)
7368
+ return;
7369
+ const now = Date.now();
7370
+ for (const r of fetched.summary.byRole) {
7371
+ if (r.unread < 1)
7372
+ continue;
7373
+ const pieces = [];
7374
+ if (r.high > 0)
7375
+ pieces.push(`${r.high} high`);
7376
+ if (r.oldestCreatedAt) {
7377
+ const days = Math.max(0, Math.floor((now - new Date(r.oldestCreatedAt).getTime()) / 86400000));
7378
+ pieces.push(`oldest ${r.truncated ? '≥' : ''}${days}d`);
7379
+ }
7380
+ const suffix = pieces.length ? ` (${pieces.join(', ')})` : '';
7381
+ console.log(`${r.unread} unread dispatches${suffix} — fazemos inbox --role ${r.role}`);
7382
+ }
7383
+ console.log('');
7384
+ }
7385
+ /** Additive `--json` shape: `unread_dispatches: { total, by_role: [...] }`. */
7386
+ function unreadDispatchesToJson(fetched) {
7387
+ if (fetched.kind !== 'ok')
7388
+ return null;
7389
+ return {
7390
+ total: fetched.summary.total,
7391
+ by_role: fetched.summary.byRole.map((r) => ({
7392
+ role: r.role,
7393
+ unread: r.unread,
7394
+ high: r.high,
7395
+ oldest_created_at: r.oldestCreatedAt,
7396
+ })),
7397
+ };
7398
+ }
7202
7399
  // ── My Work ─────────────────────────────────────────────────
7203
7400
  program
7204
7401
  .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>`.')
7402
+ .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
7403
  .option('--project <slug>', 'Override active project for this call')
7207
7404
  .option('--all-projects', 'Show pending work across every project in the active org', false)
7208
7405
  .option('-a, --all-orgs', 'Show pending work across every org you are a member of (calls /api/my-work/unified)', false)
@@ -7215,11 +7412,13 @@ program
7215
7412
  // an active member of. See rul_cross_org_auth_no_org_middleware.
7216
7413
  if (opts.allOrgs) {
7217
7414
  try {
7415
+ const unread = await fetchUnreadDispatches();
7218
7416
  const data = await api('GET', '/api/my-work/unified', undefined, { noProjectHeader: true });
7219
7417
  if (opts.json) {
7220
- console.log(JSON.stringify(data, null, 2));
7418
+ console.log(JSON.stringify({ ...data, unread_dispatches: unreadDispatchesToJson(unread) }, null, 2));
7221
7419
  return;
7222
7420
  }
7421
+ renderUnreadDispatchesPointer(unread);
7223
7422
  // Sage edge case #24: single-Org user with --all-orgs gets a soft
7224
7423
  // notice + their normal output (no flag-stripping, no error).
7225
7424
  if (data.meta.orgCount === 1) {
@@ -7244,15 +7443,17 @@ program
7244
7443
  process.exit(1);
7245
7444
  }
7246
7445
  }
7247
- // ── Default project-scoped path (unchanged) ─────────────────
7446
+ // ── Default project-scoped path ─────────────────────────────
7248
7447
  try {
7448
+ const unread = await fetchUnreadDispatches();
7249
7449
  const data = await api('GET', '/api/my-work', undefined, projectOpts(opts));
7250
7450
  const c = data.commitments;
7251
7451
  const total = c.overdue.length + c.due_today.length + c.due_this_week.length + c.upcoming.length;
7252
7452
  if (opts.json) {
7253
- console.log(JSON.stringify(data, null, 2));
7453
+ console.log(JSON.stringify({ ...data, unread_dispatches: unreadDispatchesToJson(unread) }, null, 2));
7254
7454
  return;
7255
7455
  }
7456
+ renderUnreadDispatchesPointer(unread);
7256
7457
  console.log(chalk.cyan(`Commitments: ${total}`));
7257
7458
  if (c.overdue.length)
7258
7459
  console.log(chalk.red(` Overdue: ${c.overdue.length}`));
@@ -7441,14 +7642,10 @@ agentsCmd
7441
7642
  let credentialProjectId;
7442
7643
  if (provisionCredential) {
7443
7644
  if (opts.project) {
7444
- // Resolve slug → id via cache; refresh once on miss.
7645
+ // BUG242: shared cache → refresh → org-projects-list fallback.
7445
7646
  const orgId = getActiveOrgId();
7446
7647
  if (orgId) {
7447
- let proj = findProjectBySlug(orgId, opts.project);
7448
- if (!proj) {
7449
- await refreshAuthMeCache();
7450
- proj = findProjectBySlug(orgId, opts.project);
7451
- }
7648
+ const proj = await resolveProjectBySlug(opts.project, { orgId });
7452
7649
  if (proj) {
7453
7650
  credentialProjectId = proj.id;
7454
7651
  }
@@ -7835,15 +8032,13 @@ async function resolveProjectIdForAgentsList(slugOverride) {
7835
8032
  const orgId = getActiveOrgId();
7836
8033
  if (!orgId)
7837
8034
  return null;
7838
- let project = findProjectBySlug(orgId, slugOverride);
7839
- if (!project) {
7840
- await refreshAuthMeCache();
7841
- project = findProjectBySlug(orgId, slugOverride);
7842
- }
8035
+ // BUG242: shared cache → refresh → org-projects-list fallback.
8036
+ const project = await resolveProjectBySlug(slugOverride, { orgId });
7843
8037
  if (!project) {
7844
8038
  console.error(chalk.red(`Unknown project: ${slugOverride}`));
7845
8039
  console.error(chalk.gray('Run: fazemos projects list'));
7846
8040
  process.exit(1);
8041
+ return null;
7847
8042
  }
7848
8043
  return project.id;
7849
8044
  }
@@ -9453,15 +9648,13 @@ async function requireProjectForDocs(slugOverride) {
9453
9648
  let projectId = null;
9454
9649
  let projectSlug = null;
9455
9650
  if (slugOverride) {
9456
- let project = findProjectBySlug(orgId, slugOverride);
9457
- if (!project) {
9458
- await refreshAuthMeCache();
9459
- project = findProjectBySlug(orgId, slugOverride);
9460
- }
9651
+ // BUG242: shared cache → refresh → org-projects-list fallback.
9652
+ const project = await resolveProjectBySlug(slugOverride, { orgId });
9461
9653
  if (!project) {
9462
9654
  console.error(chalk.red(`Unknown project: ${slugOverride}`));
9463
9655
  console.error(chalk.gray('Run: fazemos projects list'));
9464
9656
  process.exit(1);
9657
+ return { orgId, projectId: '', projectSlug: '' };
9465
9658
  }
9466
9659
  projectId = project.id;
9467
9660
  projectSlug = project.slug;