Monorepo Doctor

--- name: monorepo-doctor description: Use when a user asks for a JS/TS monorepo audit, or Bazel target visibility or testonly issues in a JS or Java workspace. Also covers Nx/Turborepo caching, affected tests, cycles an

Prompt · برومبت

Works with

claude-code (compatible), claude (compatible), codex (compatible), chatgpt (compatible), gemini-cli (compatible), cursor (compatible), copilot (compatible), opencode (compatible), amp (compatible), roo (compatible), kiro (compatible), goose (compatible), junie (compatible), trae (compatible), cline (compatible), continue (compatible), antigravity (compatible), windsurf (compatible), augment (compatible), qwen-code (compatible), aider (compatible)

Content

Monorepo Doctor

Audit a JS/TS monorepo for five classes of problems that teams routinely miss, or run the limited Bazel target checks in a standalone Bazel workspace, and produce an evidence-backed report. Bazel-only support does not analyze Java source, cycles, caching, or CI test coverage.

Prerequisites: Node ≥ 22.5. The work dir is $W = $(node -p 'require("os").tmpdir()')/monorepo-doctor (see detection.md).

Rules

  • Read-only. Never install dependencies, build, run tests, or edit project files. Allowed writes: monorepo-doctor-report.md, monorepo-doctor-report.json (default ${tmpdir}/monorepo-doctor-reports, or a user-given dir) and $W.
  • Allowed commands: the snippets in the reference files, npm pack --dry-run --json --ignore-scripts, read-only git log, and the repo's own ./node_modules/.bin/{knip,publint,nx,turbo} only if detection reports them installed (nx/turbo: graph / --dry=json / boundaries only — never real task runs, with read-only env vars from the references).
  • No runtime downloads by default. Don't fetch packages (npx, npm exec, pnpm dlx, yarn dlx, bunx). If a tool isn't installed, skip that sub-step and mark the check partial. Only if the user explicitly allows downloads in this request may you run the pinned knip@6.41.0 / publint@0.3.25 shown in the references — never other versions, other packages, or nx/turbo.
  • Never abort a check. If a tool fails, mark the check partial or skipped with a reason and continue.
  • Every finding needs evidence (config snippet, file:line, or command output). No evidence → no finding.
  • Actionable only. Do not emit a finding when the honest fix is "keep it as-is" — a deliberate, idiomatic or correct pattern (e.g. cache: false on a migration task, lazy ORM references). Mention it in the check's reason instead.
  • One root cause, one finding. If two findings share the same fix, merge them.
  • Use only the finding ids defined in the reference files.

Workflow

  1. Detect — follow [references/detection.md](references/detection.md). Stop if NO_WORKSPACE.
  2. Scan — follow [references/scan.md](references/scan.md). If Bazel is detected, also run the static inspection in [references/bazel.md](references/bazel.md) before the checks.
  3. Check — run all five unless the user asked for a subset (write {"status":"not-run","reason":"not requested","findings":[]} to $W/findings/${check}.json for the others):
  • [references/boundaries.md](references/boundaries.md) — package split & public API, including Bazel visibility
  • [references/circular-deps.md](references/circular-deps.md) — package and file cycles
  • [references/caching.md](references/caching.md) — Nx / Turborepo cache correctness
  • [references/ci-coverage.md](references/ci-coverage.md) — tests that silently don't run in CI
  • [references/prod-leakage.md](references/prod-leakage.md) — test code shipped to production The checks are independent; if you can run sub-agents, run them in parallel.
  1. Report — follow [references/report-format.md](references/report-format.md): validate each findings/${check}.json, render, then show the user where the reports were written, the summary line and the top 5 findings.
  2. CI mode (only if asked, or when invoked non-interactively with a threshold) — run the exit-code snippet from report-format.md.

Tracking

Create a todo per phase/check and mark each done as its findings file is written.

FILE:references/bazel.md

Bazel static target inspection

This supplementary scan works for Bazel-backed JS workspaces and standalone Bazel workspaces, including Java. It reads the BUILD files inventoried by [detection.md](detection.md) without invoking Bazel, loading .bzl files, or downloading anything. It writes $W/bazel.json for the boundary and production-leakage checks.

The scan deliberately recognizes only literal attributes on filegroup, java_library, java_binary, java_test loaded from @rules_java//java:defs.bzl, and js_library loaded from @aspect_rules_js//js:defs.bzl or @rules_js//js:defs.bzl. It follows literal local labels in srcs, deps, data, resources, runtime_deps, and exports. It does not evaluate macros, select(), glob(), package groups, external repositories, implicit dependencies, or nonliteral attributes; its results are always partial. It is not a general Starlark interpreter. REPO.bazel ignore_directories patterns are not evaluated: if that name occurs in the file or exclusions cannot be read, target findings are suppressed and the reason is reported. Conditional call expressions and rule names referenced as values or reassigned are not interpreted.

  • Visibility finding: an exact internal tag and an explicit, literal public visibility on the target. For a native filegroup only, an explicit package(default_visibility = ...) also counts; macro-created targets do not necessarily inherit that default. The tag is a project convention, not Bazel's own visibility policy. Public untagged targets are valid. Review the intended consumers before restricting visibility.
  • Test-only finding: a target explicitly tagged production and explicitly marked testonly = False has a literal local dependency path to a target explicitly marked testonly = True. Bazel normally rejects such a path at analysis time; the finding is a broken production build, not proof that test code actually shipped. A test target using test-only fixtures is valid.

Run after detection and the JS scan, from the audited workspace root:

W="$(node -p 'require("os").tmpdir()')/monorepo-doctor"
cat > "$W/bazel-audit.mjs" <<'EOF'
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

const work = path.join(os.tmpdir(), 'monorepo-doctor');
const ws = JSON.parse(fs.readFileSync(path.join(work, 'workspace.json'), 'utf8'));
const root = ws.root;
const findings = { boundaries: [], 'prod-leakage': [] };
const problems = [];
const targets = new Map(), duplicates = new Set();
const closing = { '(': ')', '[': ']', '{': '}' };

function lex(text) {
  const out = [];
  let i = 0, line = 1, logicalLine = 1, depth = 0;
  while (i < text.length) {
    const ch = text[i];
    if (ch === '\\' && (text[i + 1] === '\n' || (text[i + 1] === '\r' && text[i + 2] === '\n'))) {
      i += text[i + 1] === '\r' ? 3 : 2;
      line++;
      continue;
    }
    if (/\s/.test(ch)) {
      if (ch === '\n') { line++; if (!depth) logicalLine++; }
      i++;
      continue;
    }
    if (ch === '#') { while (i < text.length && text[i] !== '\n') i++; continue; }
    const start = i, startLine = line;
    if (ch === '"' || ch === "'") {
      const triple = text.slice(i, i + 3) === ch.repeat(3);
      i += triple ? 3 : 1;
      let value = '', valid = !triple, closed = false;
      while (i < text.length) {
        if (triple && text.slice(i, i + 3) === ch.repeat(3)) { i += 3; closed = true; break; }
        if (!triple && text[i] === ch) { i++; closed = true; break; }
        if (text[i] === '\\') {
          i++;
          if (i >= text.length) break;
          const escapes = { '\\': '\\', '"': '"', "'": "'", n: '\n', r: '\r', t: '\t' };
          if (!Object.hasOwn(escapes, text[i])) valid = false;
          else value += escapes[text[i]];
          if (text[i] === '\n') line++;
          i++;
        } else {
          if (text[i] === '\n') {
            line++;
            if (!triple) throw new Error(`unterminated string at line ${startLine}`);
          }
          value += text[i++];
        }
      }
      if (!closed) throw new Error(`unterminated string at line ${startLine}`);
      out.push({ type: valid ? 'string' : 'unknown', value, start, end: i, line: startLine, logicalLine });
    } else if (/[A-Za-z_]/.test(ch)) {
      i++;
      while (i < text.length && /[A-Za-z0-9_]/.test(text[i])) i++;
      out.push({ type: 'id', value: text.slice(start, i), start, end: i, line: startLine, logicalLine });
    } else {
      i++;
      out.push({ type: 'punct', value: ch, start, end: i, line: startLine, logicalLine });
      if (closing[ch]) depth++;
      else if ([')', ']', '}'].includes(ch)) depth--;
    }
  }
  return out;
}

function groupEnd(tokens, start) {
  const stack = [closing[tokens[start].value]];
  for (let i = start + 1; i < tokens.length; i++) {
    const value = tokens[i].value;
    if (tokens[i].type === 'punct' && closing[value]) stack.push(closing[value]);
    else if (tokens[i].type === 'punct' && [')', ']', '}'].includes(value)) {
      if (stack.pop() !== value) throw new Error(`unbalanced delimiter at line ${tokens[i].line}`);
      if (!stack.length) return i;
    }
  }
  throw new Error(`unclosed delimiter at line ${tokens[start].line}`);
}

function splitArgs(tokens) {
  const parts = [];
  let start = 0;
  for (let i = 0; i < tokens.length; i++) {
    if (tokens[i].type === 'punct' && closing[tokens[i].value]) i = groupEnd(tokens, i);
    else if (tokens[i].type === 'punct' && tokens[i].value === ',') { if (i > start) parts.push(tokens.slice(start, i)); start = i + 1; }
  }
  if (start < tokens.length) parts.push(tokens.slice(start));
  return parts;
}

function literal(tokens) {
  if (tokens.length === 1 && tokens[0].type === 'string') return tokens[0].value;
  if (tokens.length === 1 && tokens[0].type === 'id' && ['True', 'False'].includes(tokens[0].value)) return tokens[0].value === 'True';
  if (tokens[0]?.type === 'punct' && tokens[0].value === '[' && groupEnd(tokens, 0) === tokens.length - 1) {
    const parts = splitArgs(tokens.slice(1, -1));
    if (parts.every((p) => p.length === 1 && p[0].type === 'string')) return parts.map((p) => p[0].value);
  }
  return undefined;
}

function calls(text) {
  const tokens = lex(text), result = [], loadTokens = new Set();
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    const isSemicolon = (tok) => tok?.type === 'punct' && tok.value === ';';
    const statementStart = i === 0 || tokens[i - 1].logicalLine !== t.logicalLine || isSemicolon(tokens[i - 1]);
    if (t.type === 'id' && tokens[i + 1]?.type === 'punct' && tokens[i + 1].value === '('
        && tokens[i + 1].logicalLine === t.logicalLine && statementStart) {
      const end = groupEnd(tokens, i + 1);
      if (tokens[end + 1]?.logicalLine !== tokens[end].logicalLine || isSemicolon(tokens[end + 1])) {
        result.push({ name: t.value, line: t.line, parts: splitArgs(tokens.slice(i + 2, end)) });
        if (t.value === 'load') for (let j = i + 1; j < end; j++) loadTokens.add(j);
      }
      i = end;
    } else if (t.type === 'punct' && closing[t.value]) {
      i = groupEnd(tokens, i);
    }
  }
  const referenced = new Set(tokens.flatMap((t, i) =>
    t.type === 'id' && tokens[i + 1]?.value !== '(' && !loadTokens.has(i) ? [t.value] : []));
  return { calls: result, referenced };
}

function attributes(parts, text) {
  const attrs = {};
  for (const p of parts) {
    if (p[0]?.type !== 'id' || p[1]?.value !== '=' || p.length < 3) continue;
    if (Object.hasOwn(attrs, p[0].value)) throw new Error(`duplicate ${p[0].value} attribute at line ${p[0].line}`);
    const expr = p.slice(2);
    attrs[p[0].value] = {
      value: literal(expr),
      text: text.slice(expr[0].start, expr[expr.length - 1].end),
      line: p[0].line,
    };
  }
  return attrs;
}

function loadBindings(parsed) {
  const bindings = new Map();
  for (const call of parsed.filter((c) => c.name === 'load')) {
    const source = literal(call.parts[0] ?? []);
    if (typeof source !== 'string') continue;
    for (const part of call.parts.slice(1)) {
      const local = part.length === 1 && part[0].type === 'string' ? part[0].value
        : part[0]?.type === 'id' && part[1]?.value === '=' ? part[0].value : null;
      const symbol = part.length === 1 ? literal(part) : literal(part.slice(2));
      if (local && typeof symbol === 'string') bindings.set(local, { source, symbol });
    }
  }
  return bindings;
}

function ruleKind(name, bindings) {
  const binding = bindings.get(name);
  if (name === 'filegroup' && !binding) return name;
  if (binding?.source === '@rules_java//java:defs.bzl'
      && ['java_library', 'java_binary', 'java_test'].includes(binding.symbol)) return binding.symbol;
  if (['@aspect_rules_js//js:defs.bzl', '@rules_js//js:defs.bzl'].includes(binding?.source)
      && binding.symbol === 'js_library') return binding.symbol;
  return null;
}

function label(value, pkg) {
  if (typeof value !== 'string') return null;
  if (value.startsWith('@@//')) value = value.slice(2);
  else if (value.startsWith('@')) return null;
  let dir = pkg, name = value;
  if (value.startsWith('//')) {
    const body = value.slice(2), colon = body.indexOf(':');
    dir = colon < 0 ? body : body.slice(0, colon);
    name = colon < 0 ? path.posix.basename(dir) : body.slice(colon + 1);
  } else if (value.startsWith(':')) name = value.slice(1);
  if (!name || name.includes(':') || dir.split('/').includes('..') || name.split('/').includes('..')
      || !/^[A-Za-z0-9_./+~=-]*$/.test(dir) || !/^[A-Za-z0-9_./+~=-]+$/.test(name)) return null;
  return `//${dir}:${name}`;
}

function owner(dir) {
  return [...ws.packages]
    .filter((p) => p.dir === '.' || dir === p.dir || dir.startsWith(`${p.dir}/`))
    .sort((a, b) => b.dir.length - a.dir.length)[0]?.name;
}

for (const file of ws.bazel?.unresolvedExclusions ? [] : ws.bazel?.buildFiles ?? []) {
  try {
    const text = fs.readFileSync(path.join(root, file), 'utf8');
    const { calls: parsed, referenced } = calls(text);
    const bindings = loadBindings(parsed);
    const packageCall = !referenced.has('package') && !bindings.has('package')
      ? parsed.find((c) => c.name === 'package') : undefined;
    const defaults = packageCall ? attributes(packageCall.parts, text) : {};
    const pkg = path.posix.dirname(file) === '.' ? '' : path.posix.dirname(file);
    for (const call of parsed) {
      const kind = referenced.has(call.name) ? null : ruleKind(call.name, bindings);
      if (!kind) continue;
      const attrs = attributes(call.parts, text);
      const name = attrs.name?.value;
      const targetLabel = label(typeof name === 'string' ? `:${name}` : null, pkg);
      if (!targetLabel) continue;
      const visibility = Object.hasOwn(attrs, 'visibility') ? attrs.visibility
        : kind === 'filegroup' ? defaults.default_visibility : undefined;
      const edges = [];
      for (const key of ['srcs', 'deps', 'data', 'resources', 'runtime_deps', 'exports']) {
        if (!Array.isArray(attrs[key]?.value)) continue;
        for (const value of attrs[key].value) {
          const dest = label(value, pkg);
          if (dest) edges.push({ label: dest, attribute: key, line: attrs[key].line });
        }
      }
      const target = { label: targetLabel, file, line: call.line, pkg: owner(pkg), attrs, visibility, edges };
      if (targets.has(targetLabel)) duplicates.add(targetLabel);
      else targets.set(targetLabel, target);
    }
  } catch (error) {
    problems.push(`${file}: ${error.message}`);
  }
}
for (const duplicate of duplicates) {
  targets.delete(duplicate);
  problems.push(`duplicate target ${duplicate}`);
}

for (const target of targets.values()) {
  if (Array.isArray(target.attrs.tags?.value)
      && target.attrs.tags.value.includes('internal')
      && Array.isArray(target.visibility?.value)
      && target.visibility.value.length === 1
      && target.visibility.value[0] === '//visibility:public') {
    findings.boundaries.push({
      id: 'boundaries/bazel-public-internal-target', severity: 'medium',
      title: `Internal-tagged target ${target.label} is publicly visible`,
      location: { file: target.file, line: target.line, ...(target.pkg ? { package: target.pkg } : {}) },
      evidence: `${target.label} (${target.file}:${target.line}): tags = ${target.attrs.tags.text}; ${Object.hasOwn(target.attrs, 'visibility') ? 'visibility' : 'package default_visibility'} = ${target.visibility.text}`,
      fix: 'Confirm the intended consumers and restrict visibility if the target is meant to be internal; retain any required access.',
    });
  }

  if (!Array.isArray(target.attrs.tags?.value) || !target.attrs.tags.value.includes('production')
      || target.attrs.testonly?.value !== false) continue;
  const seen = new Set([target.label]);
  const queue = [{ target, edges: [] }];
  for (let i = 0; i < queue.length; i++) {
    const current = queue[i];
    for (const edge of current.target.edges) {
      if (seen.has(edge.label) || !targets.has(edge.label)) continue;
      seen.add(edge.label);
      const next = targets.get(edge.label);
      const chain = [...current.edges, { from: current.target, edge }];
      if (next.attrs.testonly?.value === true) {
        findings['prod-leakage'].push({
          id: 'prod-leakage/bazel-testonly-dependency', severity: 'high',
          title: `Production target ${target.label} depends on test-only target ${next.label}`,
          location: { file: target.file, line: target.line, ...(target.pkg ? { package: target.pkg } : {}) },
          evidence: `${target.label}: tags = ${target.attrs.tags.text}; testonly = ${target.attrs.testonly.text}\n${chain.map(({ from, edge: e }) => `${from.label} (${from.file}:${e.line}) ${e.attribute} -> ${e.label}`).join('\n')}\n${next.label} (${next.file}:${next.attrs.testonly.line}): testonly = ${next.attrs.testonly.text}`,
          fix: 'Remove the test-only dependency from the production target or replace it with a production-safe input; keep test fixtures test-only.',
        });
      }
      queue.push({ target: next, edges: chain });
    }
  }
}

const reason = [
  'Bazel static inspection covers only literal local targets; macros, selects, package groups and external dependencies are not resolved',
  ...(!ws.bazel?.buildFiles.length ? ['no Bazel BUILD files found'] : []),
  ...(ws.bazel?.errors ?? []),
  ...problems,
].join('; ');
const result = Object.fromEntries(Object.entries(findings).map(([check, entries]) => [check, {
  status: 'partial', reason, findings: entries,
}]));
fs.writeFileSync(path.join(work, 'bazel.json'), JSON.stringify(result, null, 2));
console.log(JSON.stringify({ boundaries: findings.boundaries.length, testonly: findings['prod-leakage'].length, status: 'partial' }));
EOF
node "$W/bazel-audit.mjs"

Each check merges its own findings from this file and keeps the scan's partial reason alongside any other incomplete subchecks. If this scan fails or bazel.json is missing or invalid, mark both Bazel-aware checks partial with the failure reason; do not treat the absence of results as a clean audit. FILE:references/boundaries.md

Check 1 — Package boundaries

Question: are packages split along real seams, and is each package's public API respected? Inputs: workspace.json, scan.json. Output: findings/boundaries.json.

Rules

| id | severity | detect | evidence | |---|---|---|---| | boundaries/oversized-package | low | scan.packages[p].sourceFiles > 500 or loc > 50000 (generated files are already excluded by scan) and at least 2 other workspace packages import it (scan.imports with target === p). Apps and leaf packages with no workspace consumers are never flagged: splitting them adds export maps and tags with no consumer that benefits. | counts + the consumers and which subpaths/symbols each uses | | boundaries/deep-import | medium | each scan.imports entry with deep && (declared \|\| fromSource === "project.json") (undeclared package.json importers are reported by ci-coverage instead) | file:line + import specifier + target's exports keys | | boundaries/unlisted-dependency | medium | knip unlisted entries | knip output line | | boundaries/unused-dependency | low | knip dependencies / devDependencies entries | knip output line | | boundaries/nx-missing-module-boundaries-rule | medium | Nx detected and no ESLint config in the root mentions @nx/enforce-module-boundaries | list of ESLint config files checked | | boundaries/nx-permissive-module-boundaries | low | the rule exists but depConstraints contains { sourceTag: '*', onlyDependOnLibsWithTags: ['*'] } | the config snippet | | boundaries/nx-untagged-project | low | Nx detected, rule absent or permissive, and a project has empty tags | project.json path | | boundaries/turbo-package-boundaries-tags | medium | verified Turbo 2.5+ (2.x) and a package-level Turbo config defines boundaries.tags, which is root-only | package config path + boundaries.tags snippet | | boundaries/turbo-tag-package-name-collision | medium | verified Turbo 2.5+ (2.x) and a root boundaries.tags rule key exactly equals a workspace package name | root rule snippet + package.json name and path | | boundaries/turbo-boundaries-violation | medium | each violation printed by turbo boundaries | output line | | boundaries/bazel-public-internal-target | medium | an explicitly internal Bazel target (tags contains internal) has effective //visibility:public | target label + tags and effective visibility declarations |

Group deep-import findings: one finding per (from, target) pair, listing up to 5 locations in evidence; location is the first occurrence. For a Bazel-only workspace, skip the JS, knip, Nx and Turbo subchecks and keep this check partial; do not present its Bazel-only result as a full package boundary audit.

Steps

  1. Load workspace.json and scan.json. Apply the size and deep-import rules directly.
  2. knip — only if hasNodeModules and tools.knip:
   W="$(node -p 'require("os").tmpdir()')/monorepo-doctor"
   ./node_modules/.bin/knip --reporter json --include dependencies,devDependencies,unlisted --no-progress --no-exit-code

If tools.knip is false, skip and mark partial with reason knip not installed locally. Only if the user explicitly allowed downloads, run npm_config_ignore_scripts=true npx --yes knip@6.41.0 with the same flags instead (exact version, never @latest). Parse stdout as JSON. Its shape varies by version; look for per-file dependencies, devDependencies and unlisted arrays of { name }. Map the file to its package via workspace.json. If knip fails or the output can't be parsed, mark the check partial with reason knip unavailable: ${first_line_of_error}. Do not report unused-dependency for @types/* packages or for tools only referenced in scripts.

  1. Nx — only if Nx is an orchestrator: read ESLint configs in the root (eslint.config.{js,mjs,cjs,ts}, .eslintrc{,.json,.js,.cjs}) and every package dir. Apply the three nx-* rules. A config that contains @nx/enforce-module-boundaries or legacy @nrwl/nx/enforce-module-boundaries anywhere counts as present. Group nx-untagged-project consistently as one finding per untagged project found from the root and package-dir project configs.
  2. Turborepo static configuration — if turbo is an orchestrator, even when not installed, follow the static checks below.
  3. Turborepo command — only if turbo is an orchestrator and installed:
   W="$(node -p 'require("os").tmpdir()')/monorepo-doctor"
   TURBO_TELEMETRY_DISABLED=1 ./node_modules/.bin/turbo boundaries

One finding per reported violation, except configuration errors already emitted by the static checks: retain the specific static finding and append command evidence instead of duplicating it as turbo-boundaries-violation. A nonzero exit caused only by reported violations is a completed inspection. If the command errors with an unknown-command message (turbo < 2.4), skip this sub-step and note it in reason. Unexpected execution/config-loading failures are partial with the first error line, not a clean result. If not installed, mark this sub-step partial with reason turbo not installed locally; retain static findings.

  1. Bazel visibility — only if Bazel is an orchestrator. Merge boundaries.findings from $W/bazel.json, generated by [bazel.md](bazel.md), and retain its partial reason alongside other skipped subchecks. The internal tag is a project convention, not a Bazel policy; do not flag untagged public targets. Do not infer visibility from macros, package groups or conditional expressions. If the file is missing or invalid, mark this check partial with the failure reason.
  2. Write findings/boundaries.json.

Turborepo static configuration

These are configuration errors, not a requirement to adopt tags. Turbo's boundaries documentation describes optional package tags and root boundaries.tags rules. The v2.5.0 schema types and boundary implementation establish the two diagnostics (PackageBoundariesHasTags, TagSharesPackageName), which also exist in the current implementation.

  1. Establish the Turbo version from installed node_modules/turbo/package.json, otherwise a resolved lockfile version. Without either, an exact stable 2.x.y dependency or a simple ^2.x.y / ~2.x.y declaration with minor >= 5 proves support: pass its lower bound to the helper. Do not treat arbitrary ranges, aliases, prereleases, or another major as verified. This conservative gate is verified for stable 2.x >= 2.5.0; it does not claim tags first appeared in 2.5. For older/unknown/unverified versions, skip these two checks with a partial reason, not a finding, and still run the command if installed.
  2. Read root turbo.json and each discovered workspace package's own turbo.json (or turbo.jsonc where supported by that version). Parse using the format's actual semantics, not regex matching or naive comment stripping. Respect file precedence for the installed version; unresolved config selection, invalid config, or unsupported inheritance makes that portion partial with the file and error. Do not silently substitute {} for unreadable files. Missing package configs are normal. Use only a package's own boundaries.tags for the package-level check, never root rules inherited via extends: ["//"]. Top-level package tags are valid.
  3. Before calling the helper, exclude workspace.json package entries with source === "project.json": these are Nx-only projects, not Turbo workspace packages. Use the helper below with parsed root config and the remaining Turbo workspace packages shaped as { name, dir, turboConfig?, turboFile? }. dir comes from workspace.json; read name from that directory's package.json manifest, not an Nx project name or directory fallback. An unreadable manifest or missing manifest name makes that package's checks partial with the file and reason. turboConfig is the package's own parsed config, and turboFile is its workspace-relative path (defaults to ${dir}/turbo.json). Do not use workspace.json's tags: those are Nx tags, not Turbo tags. Locate each emitted config key in the original file and add location.line when available.
function turboBoundaryConfigFindings({ version, config, packages, rootFile = 'turbo.json' }) {
  const findings = [];
  const stable = /^2\.(\d+)\.\d+$/.exec(version ?? '');
  if (!stable || Number(stable[1]) < 5) {
    return { findings, reason: `Turbo static boundary configuration checks require verified stable 2.x >= 2.5.0; got ${version ?? 'unknown'}` };
  }
  for (const pkg of packages) {
    if (pkg.turboConfig?.boundaries && Object.hasOwn(pkg.turboConfig.boundaries, 'tags')) {
      const file = pkg.turboFile ?? `${pkg.dir}/turbo.json`;
      findings.push({
        id: 'boundaries/turbo-package-boundaries-tags',
        severity: 'medium',
        title: `${pkg.name} defines root-only boundaries.tags in a package config`,
        location: { file, package: pkg.name },
        evidence: `${file}: boundaries.tags = ${JSON.stringify(pkg.turboConfig.boundaries.tags)}`,
        fix: 'Move tag rules to the root boundaries.tags map, preserving existing rules; keep package labels in top-level tags.',
      });
    }
    if (config.boundaries?.tags && Object.hasOwn(config.boundaries.tags, pkg.name)) {
      findings.push({
        id: 'boundaries/turbo-tag-package-name-collision',
        severity: 'medium',
        title: `Boundary tag ${pkg.name} collides with a workspace package name`,
        location: { file: rootFile, package: pkg.name },
        evidence: `${rootFile}: boundaries.tags[${JSON.stringify(pkg.name)}] = ${JSON.stringify(config.boundaries.tags[pkg.name])}; ${pkg.dir}/package.json: name = ${JSON.stringify(pkg.name)}`,
        fix: 'Rename the rule tag and its package labels/tag references to a distinct label; preserve allow/deny entries that intentionally refer to the package name.',
      });
    }
  }
  return { findings };
}

Missing boundaries, absent/empty rules, untagged packages, and tags with no rule are valid defaults: emit no missing/permissive/untagged Turbo finding. Package names in allow/deny are explicitly supported; do not confuse them with rule-map keys. Lists contain literal tags/package names, not Nx-style wildcard constraints. An omitted allow permits all; allow: [] restricts all relations, not a permissive policy. Leave dependency/dependent policy evaluation (including transitive relations and deny precedence) to turbo boundaries, rather than approximating it from direct source imports.

Fix guidance

  • deep-import: add the subpath to the target's exports, or re-export from its entry point, then import from the package root.
  • oversized-package: identify clusters by which consumers import which files (scan.imports subpaths); propose 2–3 splits along clusters used by different consumers. If every consumer uses the same parts, don't emit the finding.
  • nx-missing-module-boundaries-rule: add @nx/enforce-module-boundaries with depConstraints based on scope:*/type:* tags.

FILE:references/caching.md

Check 3 — Task caching

Question: will a cache hit ever replay a wrong result, and are tasks re-running when they should hit? Output: findings/caching.json. If no orchestrator is detected, only caching/uncached-root-script applies; set status ok with reason no task orchestrator.

These rules do not inspect Bazel caching. For a Bazel-only workspace (no JS/Nx packages), write {"status":"skipped","reason":"Bazel caching is not analyzed","findings":[]} and stop this check. In a mixed workspace, retain applicable JS/Nx/Turbo findings but mark the check partial with reason Bazel caching is not analyzed. For uncached-root-script, only Nx and Turborepo count as task orchestrators; the presence of Bazel alone does not establish how npm scripts are orchestrated.

Facts the rules rely on

  • Turborepo: a task with no outputs caches only logs — on a hit, dist/ is NOT restored, so downstream tasks see stale or missing files. A package's hash covers its own files, its package.json, turbo.json and the lockfile; changes in workspace dependencies reach a task's hash only through dependsOn entries with ^ (e.g. ^build). Env vars affect the hash only when listed in env, globalEnv (or passThroughEnv for runtime-only); framework prefixes such as NEXT_PUBLIC_, VITE_ are auto-included. Turbo 2 strict env mode can also restrict which env vars are visible to tasks, so undeclared env is both a cache-key and runtime-visibility risk.
  • Nx: when outputs is omitted, Nx caches {workspaceRoot}/dist/{projectRoot}, {projectRoot}/dist, {projectRoot}/build, {projectRoot}/public. Env vars affect the hash only through an { "env": "NAME" } entry in inputs. Without a production named input that excludes tests, editing a spec file invalidates the build cache.

Rules

| id | severity | detect | |---|---|---| | caching/missing-outputs | high | Turbo: a cacheable task named build/compile/bundle/*:build (or whose package script runs tsc, vite build, tsup, rollup, webpack, next build, esbuild) has no outputs. Package-level turbo.json overrides count. Nx: cacheable build-like target without outputs whose real out dir (outDir in the build tsconfig, outDir/--out-dir flags, build.outDir in vite config) is not one of Nx's defaults — one finding per affected project, with package. Turbo findings are per task: location.file: "turbo.json", no package. | | caching/build-inputs-include-tests | low | Turbo: build-like task has no inputs, or inputs that don't exclude test globs (!**/*.test.*, !**/*.spec.*, !/__tests__/). Nx: no production named input, or build inputs don't reference it, or production doesn't negate test globs. Low severity because $TURBO_DEFAULT$ already covers all git-tracked files; the finding is about avoiding rebuilds when tests change, not correctness. Follow dependsOn chains: tests hashed by a dependency task (e.g. a transit task, or ^build of a package whose build inputs include tests) also invalidate the build. Measure impact (step 3) and put it in evidence. | | caching/undeclared-env | medium | for each scan.env entry that can affect a cacheable task output. Flag build tasks only when the build inlines env (Next/Vite framework bundlers, webpack/Rspack/Rsbuild define, esbuild/tsup define, Rollup/plugin-replace, or similar bundlers), not runtime-only reads in a plain tsc service. Always flag cacheable test tasks when tests execute code that reads the env var (scan.env.isTest, or a test file in the package imports the module with the env read), because a cached pass can be replayed under a different value. Turbo: name not matched by the task's env or globalEnv (* wildcards; ! negation) and not framework-prefixed. passThroughEnv / globalPassThroughEnv do not count: they make the var available without adding it to the hash, so a cached result can still be replayed under a different value. Nx: no { "env": NAME } in the target's inputs (resolve named inputs). Ignore CI, PATH, HOME, TZ, PWD. Ignore NODE_ENV only when the scan confirms it cannot affect the output (e.g. the task's script or bundler sets it to a fixed value); otherwise treat it like any other name. One finding per task config (Turbo task, or Nx target/targetDefault) that is missing declarations: list every missing name with its packages and up to 5 locations across all names, and set location.package only when a single package is affected. | | caching/turbo-cache-disabled | low | Turbo task with cache: false that is deterministic by name: build, compile, bundle, lint, typecheck, check-types, format:check, or a unit test (test, test:unit, *:build, *:lint). Treat cache: false as deliberate — and do not flag — when the task is persistent: true; its name contains dev, start, serve, watch, deploy, release, publish, clean, db, migrat, seed, generate, extract, sync, upload, e2e, integration, or ends in :ci; or its env/passThroughEnv lists external-state vars (*DATABASE*, *DB_*, *REDIS*, *_URL, *TOKEN*, *SECRET*). Mention deliberately uncached tasks in reason, not as findings. | | caching/nx-cache-disabled | low | An existing Nx target whose effective configuration explicitly sets cache: false and whose name is deterministic by the same allowlist as caching/turbo-cache-disabled. Resolve configuration as below; never treat an omitted cache as explicit false. Apply the same deliberate-task name exclusions, and skip continuous: true, watch-mode commands/options, long-running servers, and targets with external-state env inputs (resolve named inputs; match the external-state patterns above). Also skip when the command, executor, or configuration shows side effects or external-state dependence despite a deterministic name (e.g. test running integration tests). Mention deliberately uncached targets in reason, not as findings. | | caching/unstable-hash | high | turbo installed: run TURBO_TELEMETRY_DISABLED=1 ./node_modules/.bin/turbo run build --dry=json twice; any task whose hash differs between runs. Report the task and the inputs/environmentVariables that differ. | | caching/volatile-input | high | non-negated task inputs or globalDependencies include build artifacts or machine-local files: dist, build, .turbo, .nx, *.tsbuildinfo, **/*.log, node_modules. Ignore negated globs (!…). Do not flag .env* files: including env files usually makes caches more correct. | | caching/uncached-root-script | low | a root package.json script that runs tasks across packages bypassing the orchestrator: -r/--recursive, --workspaces/-ws, yarn workspaces foreach, lerna run. In repos without an orchestrator, say "consider adding Nx or Turborepo" in fix. |

Steps

  1. Read turbo.json (Turbo v2 tasks and Turbo v1 pipeline, plus //#task root tasks and ${pkg}/turbo.json overrides with "extends": ["//"]) and/or nx.json + every project.json / package.json#nx. For Nx, also read targetDefaults (including defaults keyed by executor), namedInputs, and legacy tasksRunnerOptions.*.options.cacheableOperations, and remember that Nx plugins (plugins in nx.json) can infer targets — if a target exists only via plugin inference, report rules that depend on its config as partial and say so.
  2. Apply the rules above. Quote the exact JSON in evidence (task name + its config object). Config-level findings (Turbo tasks, Nx targetDefaults/namedInputs) omit location.package; only set package when the problem is specific to one package (e.g. its own turbo.json/project.json, or an env read in its source).
  3. For build-inputs-include-tests, measure how often it matters with read-only git: git log --since="6 months ago" --name-only --format=%x00%H and count commits whose changed files are all test files (TEST pattern from scan.md). Report N of M commits (P%) changed only tests. Skip if the repo has no git history.
  4. unstable-hash runs only when turbo is installed; otherwise mark the check partial with reason turbo not installed; dry-run hash comparison skipped. Never run real tasks — only --dry=json.
  5. Write findings/caching.json.

Resolving Nx disabled-cache findings

  • Enumerate actual targets from project configuration, package.json scripts / nx.targets, and available inferred-target data. A targetDefaults entry does not itself create a target. Merge package configuration with project.json (project configuration takes precedence for the same target).
  • Select the applicable nx.json#targetDefaults for each target: a matching executor key takes precedence over a target-name key; do not merge both defaults. Account for matching target-name patterns and filtered defaults supported by the workspace's Nx version (see Nx target defaults). Before applying a selected default, check Nx's target compatibility: skip it when both it and the target specify different executors. For nx:run-commands / nx:run-script, also respect the workspace version's command/script compatibility checks. An incompatible default does not supply an effective cache: false. Apply compatible defaults below explicit project/p

Source and license

Source
Prompts Chat
Original
f/awesome-chatgpt-prompts/prompts.csv#monorepo-doctor
License
MIT

Monorepo Doctor

--- name: monorepo-doctor description: Use when a user asks for a JS/TS monorepo audit, or Bazel target visibility or testonly issues in a JS or Java workspace. Also covers Nx/Turborepo caching, affected tests, cycles an

Prompt · برومبت

Works with

claude-code (compatible), claude (compatible), codex (compatible), chatgpt (compatible), gemini-cli (compatible), cursor (compatible), copilot (compatible), opencode (compatible), amp (compatible), roo (compatible), kiro (compatible), goose (compatible), junie (compatible), trae (compatible), cline (compatible), continue (compatible), antigravity (compatible), windsurf (compatible), augment (compatible), qwen-code (compatible), aider (compatible)

Content

Monorepo Doctor

Audit a JS/TS monorepo for five classes of problems that teams routinely miss, or run the limited Bazel target checks in a standalone Bazel workspace, and produce an evidence-backed report. Bazel-only support does not analyze Java source, cycles, caching, or CI test coverage.

Prerequisites: Node ≥ 22.5. The work dir is $W = $(node -p 'require("os").tmpdir()')/monorepo-doctor (see detection.md).

Rules

  • Read-only. Never install dependencies, build, run tests, or edit project files. Allowed writes: monorepo-doctor-report.md, monorepo-doctor-report.json (default ${tmpdir}/monorepo-doctor-reports, or a user-given dir) and $W.
  • Allowed commands: the snippets in the reference files, npm pack --dry-run --json --ignore-scripts, read-only git log, and the repo's own ./node_modules/.bin/{knip,publint,nx,turbo} only if detection reports them installed (nx/turbo: graph / --dry=json / boundaries only — never real task runs, with read-only env vars from the references).
  • No runtime downloads by default. Don't fetch packages (npx, npm exec, pnpm dlx, yarn dlx, bunx). If a tool isn't installed, skip that sub-step and mark the check partial. Only if the user explicitly allows downloads in this request may you run the pinned knip@6.41.0 / publint@0.3.25 shown in the references — never other versions, other packages, or nx/turbo.
  • Never abort a check. If a tool fails, mark the check partial or skipped with a reason and continue.
  • Every finding needs evidence (config snippet, file:line, or command output). No evidence → no finding.
  • Actionable only. Do not emit a finding when the honest fix is "keep it as-is" — a deliberate, idiomatic or correct pattern (e.g. cache: false on a migration task, lazy ORM references). Mention it in the check's reason instead.
  • One root cause, one finding. If two findings share the same fix, merge them.
  • Use only the finding ids defined in the reference files.

Workflow

  1. Detect — follow [references/detection.md](references/detection.md). Stop if NO_WORKSPACE.
  2. Scan — follow [references/scan.md](references/scan.md). If Bazel is detected, also run the static inspection in [references/bazel.md](references/bazel.md) before the checks.
  3. Check — run all five unless the user asked for a subset (write {"status":"not-run","reason":"not requested","findings":[]} to $W/findings/${check}.json for the others):
  • [references/boundaries.md](references/boundaries.md) — package split & public API, including Bazel visibility
  • [references/circular-deps.md](references/circular-deps.md) — package and file cycles
  • [references/caching.md](references/caching.md) — Nx / Turborepo cache correctness
  • [references/ci-coverage.md](references/ci-coverage.md) — tests that silently don't run in CI
  • [references/prod-leakage.md](references/prod-leakage.md) — test code shipped to production The checks are independent; if you can run sub-agents, run them in parallel.
  1. Report — follow [references/report-format.md](references/report-format.md): validate each findings/${check}.json, render, then show the user where the reports were written, the summary line and the top 5 findings.
  2. CI mode (only if asked, or when invoked non-interactively with a threshold) — run the exit-code snippet from report-format.md.

Tracking

Create a todo per phase/check and mark each done as its findings file is written.

FILE:references/bazel.md

Bazel static target inspection

This supplementary scan works for Bazel-backed JS workspaces and standalone Bazel workspaces, including Java. It reads the BUILD files inventoried by [detection.md](detection.md) without invoking Bazel, loading .bzl files, or downloading anything. It writes $W/bazel.json for the boundary and production-leakage checks.

The scan deliberately recognizes only literal attributes on filegroup, java_library, java_binary, java_test loaded from @rules_java//java:defs.bzl, and js_library loaded from @aspect_rules_js//js:defs.bzl or @rules_js//js:defs.bzl. It follows literal local labels in srcs, deps, data, resources, runtime_deps, and exports. It does not evaluate macros, select(), glob(), package groups, external repositories, implicit dependencies, or nonliteral attributes; its results are always partial. It is not a general Starlark interpreter. REPO.bazel ignore_directories patterns are not evaluated: if that name occurs in the file or exclusions cannot be read, target findings are suppressed and the reason is reported. Conditional call expressions and rule names referenced as values or reassigned are not interpreted.

  • Visibility finding: an exact internal tag and an explicit, literal public visibility on the target. For a native filegroup only, an explicit package(default_visibility = ...) also counts; macro-created targets do not necessarily inherit that default. The tag is a project convention, not Bazel's own visibility policy. Public untagged targets are valid. Review the intended consumers before restricting visibility.
  • Test-only finding: a target explicitly tagged production and explicitly marked testonly = False has a literal local dependency path to a target explicitly marked testonly = True. Bazel normally rejects such a path at analysis time; the finding is a broken production build, not proof that test code actually shipped. A test target using test-only fixtures is valid.

Run after detection and the JS scan, from the audited workspace root:

W="$(node -p 'require("os").tmpdir()')/monorepo-doctor"
cat > "$W/bazel-audit.mjs" <<'EOF'
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

const work = path.join(os.tmpdir(), 'monorepo-doctor');
const ws = JSON.parse(fs.readFileSync(path.join(work, 'workspace.json'), 'utf8'));
const root = ws.root;
const findings = { boundaries: [], 'prod-leakage': [] };
const problems = [];
const targets = new Map(), duplicates = new Set();
const closing = { '(': ')', '[': ']', '{': '}' };

function lex(text) {
  const out = [];
  let i = 0, line = 1, logicalLine = 1, depth = 0;
  while (i < text.length) {
    const ch = text[i];
    if (ch === '\\' && (text[i + 1] === '\n' || (text[i + 1] === '\r' && text[i + 2] === '\n'))) {
      i += text[i + 1] === '\r' ? 3 : 2;
      line++;
      continue;
    }
    if (/\s/.test(ch)) {
      if (ch === '\n') { line++; if (!depth) logicalLine++; }
      i++;
      continue;
    }
    if (ch === '#') { while (i < text.length && text[i] !== '\n') i++; continue; }
    const start = i, startLine = line;
    if (ch === '"' || ch === "'") {
      const triple = text.slice(i, i + 3) === ch.repeat(3);
      i += triple ? 3 : 1;
      let value = '', valid = !triple, closed = false;
      while (i < text.length) {
        if (triple && text.slice(i, i + 3) === ch.repeat(3)) { i += 3; closed = true; break; }
        if (!triple && text[i] === ch) { i++; closed = true; break; }
        if (text[i] === '\\') {
          i++;
          if (i >= text.length) break;
          const escapes = { '\\': '\\', '"': '"', "'": "'", n: '\n', r: '\r', t: '\t' };
          if (!Object.hasOwn(escapes, text[i])) valid = false;
          else value += escapes[text[i]];
          if (text[i] === '\n') line++;
          i++;
        } else {
          if (text[i] === '\n') {
            line++;
            if (!triple) throw new Error(`unterminated string at line ${startLine}`);
          }
          value += text[i++];
        }
      }
      if (!closed) throw new Error(`unterminated string at line ${startLine}`);
      out.push({ type: valid ? 'string' : 'unknown', value, start, end: i, line: startLine, logicalLine });
    } else if (/[A-Za-z_]/.test(ch)) {
      i++;
      while (i < text.length && /[A-Za-z0-9_]/.test(text[i])) i++;
      out.push({ type: 'id', value: text.slice(start, i), start, end: i, line: startLine, logicalLine });
    } else {
      i++;
      out.push({ type: 'punct', value: ch, start, end: i, line: startLine, logicalLine });
      if (closing[ch]) depth++;
      else if ([')', ']', '}'].includes(ch)) depth--;
    }
  }
  return out;
}

function groupEnd(tokens, start) {
  const stack = [closing[tokens[start].value]];
  for (let i = start + 1; i < tokens.length; i++) {
    const value = tokens[i].value;
    if (tokens[i].type === 'punct' && closing[value]) stack.push(closing[value]);
    else if (tokens[i].type === 'punct' && [')', ']', '}'].includes(value)) {
      if (stack.pop() !== value) throw new Error(`unbalanced delimiter at line ${tokens[i].line}`);
      if (!stack.length) return i;
    }
  }
  throw new Error(`unclosed delimiter at line ${tokens[start].line}`);
}

function splitArgs(tokens) {
  const parts = [];
  let start = 0;
  for (let i = 0; i < tokens.length; i++) {
    if (tokens[i].type === 'punct' && closing[tokens[i].value]) i = groupEnd(tokens, i);
    else if (tokens[i].type === 'punct' && tokens[i].value === ',') { if (i > start) parts.push(tokens.slice(start, i)); start = i + 1; }
  }
  if (start < tokens.length) parts.push(tokens.slice(start));
  return parts;
}

function literal(tokens) {
  if (tokens.length === 1 && tokens[0].type === 'string') return tokens[0].value;
  if (tokens.length === 1 && tokens[0].type === 'id' && ['True', 'False'].includes(tokens[0].value)) return tokens[0].value === 'True';
  if (tokens[0]?.type === 'punct' && tokens[0].value === '[' && groupEnd(tokens, 0) === tokens.length - 1) {
    const parts = splitArgs(tokens.slice(1, -1));
    if (parts.every((p) => p.length === 1 && p[0].type === 'string')) return parts.map((p) => p[0].value);
  }
  return undefined;
}

function calls(text) {
  const tokens = lex(text), result = [], loadTokens = new Set();
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    const isSemicolon = (tok) => tok?.type === 'punct' && tok.value === ';';
    const statementStart = i === 0 || tokens[i - 1].logicalLine !== t.logicalLine || isSemicolon(tokens[i - 1]);
    if (t.type === 'id' && tokens[i + 1]?.type === 'punct' && tokens[i + 1].value === '('
        && tokens[i + 1].logicalLine === t.logicalLine && statementStart) {
      const end = groupEnd(tokens, i + 1);
      if (tokens[end + 1]?.logicalLine !== tokens[end].logicalLine || isSemicolon(tokens[end + 1])) {
        result.push({ name: t.value, line: t.line, parts: splitArgs(tokens.slice(i + 2, end)) });
        if (t.value === 'load') for (let j = i + 1; j < end; j++) loadTokens.add(j);
      }
      i = end;
    } else if (t.type === 'punct' && closing[t.value]) {
      i = groupEnd(tokens, i);
    }
  }
  const referenced = new Set(tokens.flatMap((t, i) =>
    t.type === 'id' && tokens[i + 1]?.value !== '(' && !loadTokens.has(i) ? [t.value] : []));
  return { calls: result, referenced };
}

function attributes(parts, text) {
  const attrs = {};
  for (const p of parts) {
    if (p[0]?.type !== 'id' || p[1]?.value !== '=' || p.length < 3) continue;
    if (Object.hasOwn(attrs, p[0].value)) throw new Error(`duplicate ${p[0].value} attribute at line ${p[0].line}`);
    const expr = p.slice(2);
    attrs[p[0].value] = {
      value: literal(expr),
      text: text.slice(expr[0].start, expr[expr.length - 1].end),
      line: p[0].line,
    };
  }
  return attrs;
}

function loadBindings(parsed) {
  const bindings = new Map();
  for (const call of parsed.filter((c) => c.name === 'load')) {
    const source = literal(call.parts[0] ?? []);
    if (typeof source !== 'string') continue;
    for (const part of call.parts.slice(1)) {
      const local = part.length === 1 && part[0].type === 'string' ? part[0].value
        : part[0]?.type === 'id' && part[1]?.value === '=' ? part[0].value : null;
      const symbol = part.length === 1 ? literal(part) : literal(part.slice(2));
      if (local && typeof symbol === 'string') bindings.set(local, { source, symbol });
    }
  }
  return bindings;
}

function ruleKind(name, bindings) {
  const binding = bindings.get(name);
  if (name === 'filegroup' && !binding) return name;
  if (binding?.source === '@rules_java//java:defs.bzl'
      && ['java_library', 'java_binary', 'java_test'].includes(binding.symbol)) return binding.symbol;
  if (['@aspect_rules_js//js:defs.bzl', '@rules_js//js:defs.bzl'].includes(binding?.source)
      && binding.symbol === 'js_library') return binding.symbol;
  return null;
}

function label(value, pkg) {
  if (typeof value !== 'string') return null;
  if (value.startsWith('@@//')) value = value.slice(2);
  else if (value.startsWith('@')) return null;
  let dir = pkg, name = value;
  if (value.startsWith('//')) {
    const body = value.slice(2), colon = body.indexOf(':');
    dir = colon < 0 ? body : body.slice(0, colon);
    name = colon < 0 ? path.posix.basename(dir) : body.slice(colon + 1);
  } else if (value.startsWith(':')) name = value.slice(1);
  if (!name || name.includes(':') || dir.split('/').includes('..') || name.split('/').includes('..')
      || !/^[A-Za-z0-9_./+~=-]*$/.test(dir) || !/^[A-Za-z0-9_./+~=-]+$/.test(name)) return null;
  return `//${dir}:${name}`;
}

function owner(dir) {
  return [...ws.packages]
    .filter((p) => p.dir === '.' || dir === p.dir || dir.startsWith(`${p.dir}/`))
    .sort((a, b) => b.dir.length - a.dir.length)[0]?.name;
}

for (const file of ws.bazel?.unresolvedExclusions ? [] : ws.bazel?.buildFiles ?? []) {
  try {
    const text = fs.readFileSync(path.join(root, file), 'utf8');
    const { calls: parsed, referenced } = calls(text);
    const bindings = loadBindings(parsed);
    const packageCall = !referenced.has('package') && !bindings.has('package')
      ? parsed.find((c) => c.name === 'package') : undefined;
    const defaults = packageCall ? attributes(packageCall.parts, text) : {};
    const pkg = path.posix.dirname(file) === '.' ? '' : path.posix.dirname(file);
    for (const call of parsed) {
      const kind = referenced.has(call.name) ? null : ruleKind(call.name, bindings);
      if (!kind) continue;
      const attrs = attributes(call.parts, text);
      const name = attrs.name?.value;
      const targetLabel = label(typeof name === 'string' ? `:${name}` : null, pkg);
      if (!targetLabel) continue;
      const visibility = Object.hasOwn(attrs, 'visibility') ? attrs.visibility
        : kind === 'filegroup' ? defaults.default_visibility : undefined;
      const edges = [];
      for (const key of ['srcs', 'deps', 'data', 'resources', 'runtime_deps', 'exports']) {
        if (!Array.isArray(attrs[key]?.value)) continue;
        for (const value of attrs[key].value) {
          const dest = label(value, pkg);
          if (dest) edges.push({ label: dest, attribute: key, line: attrs[key].line });
        }
      }
      const target = { label: targetLabel, file, line: call.line, pkg: owner(pkg), attrs, visibility, edges };
      if (targets.has(targetLabel)) duplicates.add(targetLabel);
      else targets.set(targetLabel, target);
    }
  } catch (error) {
    problems.push(`${file}: ${error.message}`);
  }
}
for (const duplicate of duplicates) {
  targets.delete(duplicate);
  problems.push(`duplicate target ${duplicate}`);
}

for (const target of targets.values()) {
  if (Array.isArray(target.attrs.tags?.value)
      && target.attrs.tags.value.includes('internal')
      && Array.isArray(target.visibility?.value)
      && target.visibility.value.length === 1
      && target.visibility.value[0] === '//visibility:public') {
    findings.boundaries.push({
      id: 'boundaries/bazel-public-internal-target', severity: 'medium',
      title: `Internal-tagged target ${target.label} is publicly visible`,
      location: { file: target.file, line: target.line, ...(target.pkg ? { package: target.pkg } : {}) },
      evidence: `${target.label} (${target.file}:${target.line}): tags = ${target.attrs.tags.text}; ${Object.hasOwn(target.attrs, 'visibility') ? 'visibility' : 'package default_visibility'} = ${target.visibility.text}`,
      fix: 'Confirm the intended consumers and restrict visibility if the target is meant to be internal; retain any required access.',
    });
  }

  if (!Array.isArray(target.attrs.tags?.value) || !target.attrs.tags.value.includes('production')
      || target.attrs.testonly?.value !== false) continue;
  const seen = new Set([target.label]);
  const queue = [{ target, edges: [] }];
  for (let i = 0; i < queue.length; i++) {
    const current = queue[i];
    for (const edge of current.target.edges) {
      if (seen.has(edge.label) || !targets.has(edge.label)) continue;
      seen.add(edge.label);
      const next = targets.get(edge.label);
      const chain = [...current.edges, { from: current.target, edge }];
      if (next.attrs.testonly?.value === true) {
        findings['prod-leakage'].push({
          id: 'prod-leakage/bazel-testonly-dependency', severity: 'high',
          title: `Production target ${target.label} depends on test-only target ${next.label}`,
          location: { file: target.file, line: target.line, ...(target.pkg ? { package: target.pkg } : {}) },
          evidence: `${target.label}: tags = ${target.attrs.tags.text}; testonly = ${target.attrs.testonly.text}\n${chain.map(({ from, edge: e }) => `${from.label} (${from.file}:${e.line}) ${e.attribute} -> ${e.label}`).join('\n')}\n${next.label} (${next.file}:${next.attrs.testonly.line}): testonly = ${next.attrs.testonly.text}`,
          fix: 'Remove the test-only dependency from the production target or replace it with a production-safe input; keep test fixtures test-only.',
        });
      }
      queue.push({ target: next, edges: chain });
    }
  }
}

const reason = [
  'Bazel static inspection covers only literal local targets; macros, selects, package groups and external dependencies are not resolved',
  ...(!ws.bazel?.buildFiles.length ? ['no Bazel BUILD files found'] : []),
  ...(ws.bazel?.errors ?? []),
  ...problems,
].join('; ');
const result = Object.fromEntries(Object.entries(findings).map(([check, entries]) => [check, {
  status: 'partial', reason, findings: entries,
}]));
fs.writeFileSync(path.join(work, 'bazel.json'), JSON.stringify(result, null, 2));
console.log(JSON.stringify({ boundaries: findings.boundaries.length, testonly: findings['prod-leakage'].length, status: 'partial' }));
EOF
node "$W/bazel-audit.mjs"

Each check merges its own findings from this file and keeps the scan's partial reason alongside any other incomplete subchecks. If this scan fails or bazel.json is missing or invalid, mark both Bazel-aware checks partial with the failure reason; do not treat the absence of results as a clean audit. FILE:references/boundaries.md

Check 1 — Package boundaries

Question: are packages split along real seams, and is each package's public API respected? Inputs: workspace.json, scan.json. Output: findings/boundaries.json.

Rules

| id | severity | detect | evidence | |---|---|---|---| | boundaries/oversized-package | low | scan.packages[p].sourceFiles > 500 or loc > 50000 (generated files are already excluded by scan) and at least 2 other workspace packages import it (scan.imports with target === p). Apps and leaf packages with no workspace consumers are never flagged: splitting them adds export maps and tags with no consumer that benefits. | counts + the consumers and which subpaths/symbols each uses | | boundaries/deep-import | medium | each scan.imports entry with deep && (declared \|\| fromSource === "project.json") (undeclared package.json importers are reported by ci-coverage instead) | file:line + import specifier + target's exports keys | | boundaries/unlisted-dependency | medium | knip unlisted entries | knip output line | | boundaries/unused-dependency | low | knip dependencies / devDependencies entries | knip output line | | boundaries/nx-missing-module-boundaries-rule | medium | Nx detected and no ESLint config in the root mentions @nx/enforce-module-boundaries | list of ESLint config files checked | | boundaries/nx-permissive-module-boundaries | low | the rule exists but depConstraints contains { sourceTag: '*', onlyDependOnLibsWithTags: ['*'] } | the config snippet | | boundaries/nx-untagged-project | low | Nx detected, rule absent or permissive, and a project has empty tags | project.json path | | boundaries/turbo-package-boundaries-tags | medium | verified Turbo 2.5+ (2.x) and a package-level Turbo config defines boundaries.tags, which is root-only | package config path + boundaries.tags snippet | | boundaries/turbo-tag-package-name-collision | medium | verified Turbo 2.5+ (2.x) and a root boundaries.tags rule key exactly equals a workspace package name | root rule snippet + package.json name and path | | boundaries/turbo-boundaries-violation | medium | each violation printed by turbo boundaries | output line | | boundaries/bazel-public-internal-target | medium | an explicitly internal Bazel target (tags contains internal) has effective //visibility:public | target label + tags and effective visibility declarations |

Group deep-import findings: one finding per (from, target) pair, listing up to 5 locations in evidence; location is the first occurrence. For a Bazel-only workspace, skip the JS, knip, Nx and Turbo subchecks and keep this check partial; do not present its Bazel-only result as a full package boundary audit.

Steps

  1. Load workspace.json and scan.json. Apply the size and deep-import rules directly.
  2. knip — only if hasNodeModules and tools.knip:
   W="$(node -p 'require("os").tmpdir()')/monorepo-doctor"
   ./node_modules/.bin/knip --reporter json --include dependencies,devDependencies,unlisted --no-progress --no-exit-code

If tools.knip is false, skip and mark partial with reason knip not installed locally. Only if the user explicitly allowed downloads, run npm_config_ignore_scripts=true npx --yes knip@6.41.0 with the same flags instead (exact version, never @latest). Parse stdout as JSON. Its shape varies by version; look for per-file dependencies, devDependencies and unlisted arrays of { name }. Map the file to its package via workspace.json. If knip fails or the output can't be parsed, mark the check partial with reason knip unavailable: ${first_line_of_error}. Do not report unused-dependency for @types/* packages or for tools only referenced in scripts.

  1. Nx — only if Nx is an orchestrator: read ESLint configs in the root (eslint.config.{js,mjs,cjs,ts}, .eslintrc{,.json,.js,.cjs}) and every package dir. Apply the three nx-* rules. A config that contains @nx/enforce-module-boundaries or legacy @nrwl/nx/enforce-module-boundaries anywhere counts as present. Group nx-untagged-project consistently as one finding per untagged project found from the root and package-dir project configs.
  2. Turborepo static configuration — if turbo is an orchestrator, even when not installed, follow the static checks below.
  3. Turborepo command — only if turbo is an orchestrator and installed:
   W="$(node -p 'require("os").tmpdir()')/monorepo-doctor"
   TURBO_TELEMETRY_DISABLED=1 ./node_modules/.bin/turbo boundaries

One finding per reported violation, except configuration errors already emitted by the static checks: retain the specific static finding and append command evidence instead of duplicating it as turbo-boundaries-violation. A nonzero exit caused only by reported violations is a completed inspection. If the command errors with an unknown-command message (turbo < 2.4), skip this sub-step and note it in reason. Unexpected execution/config-loading failures are partial with the first error line, not a clean result. If not installed, mark this sub-step partial with reason turbo not installed locally; retain static findings.

  1. Bazel visibility — only if Bazel is an orchestrator. Merge boundaries.findings from $W/bazel.json, generated by [bazel.md](bazel.md), and retain its partial reason alongside other skipped subchecks. The internal tag is a project convention, not a Bazel policy; do not flag untagged public targets. Do not infer visibility from macros, package groups or conditional expressions. If the file is missing or invalid, mark this check partial with the failure reason.
  2. Write findings/boundaries.json.

Turborepo static configuration

These are configuration errors, not a requirement to adopt tags. Turbo's boundaries documentation describes optional package tags and root boundaries.tags rules. The v2.5.0 schema types and boundary implementation establish the two diagnostics (PackageBoundariesHasTags, TagSharesPackageName), which also exist in the current implementation.

  1. Establish the Turbo version from installed node_modules/turbo/package.json, otherwise a resolved lockfile version. Without either, an exact stable 2.x.y dependency or a simple ^2.x.y / ~2.x.y declaration with minor >= 5 proves support: pass its lower bound to the helper. Do not treat arbitrary ranges, aliases, prereleases, or another major as verified. This conservative gate is verified for stable 2.x >= 2.5.0; it does not claim tags first appeared in 2.5. For older/unknown/unverified versions, skip these two checks with a partial reason, not a finding, and still run the command if installed.
  2. Read root turbo.json and each discovered workspace package's own turbo.json (or turbo.jsonc where supported by that version). Parse using the format's actual semantics, not regex matching or naive comment stripping. Respect file precedence for the installed version; unresolved config selection, invalid config, or unsupported inheritance makes that portion partial with the file and error. Do not silently substitute {} for unreadable files. Missing package configs are normal. Use only a package's own boundaries.tags for the package-level check, never root rules inherited via extends: ["//"]. Top-level package tags are valid.
  3. Before calling the helper, exclude workspace.json package entries with source === "project.json": these are Nx-only projects, not Turbo workspace packages. Use the helper below with parsed root config and the remaining Turbo workspace packages shaped as { name, dir, turboConfig?, turboFile? }. dir comes from workspace.json; read name from that directory's package.json manifest, not an Nx project name or directory fallback. An unreadable manifest or missing manifest name makes that package's checks partial with the file and reason. turboConfig is the package's own parsed config, and turboFile is its workspace-relative path (defaults to ${dir}/turbo.json). Do not use workspace.json's tags: those are Nx tags, not Turbo tags. Locate each emitted config key in the original file and add location.line when available.
function turboBoundaryConfigFindings({ version, config, packages, rootFile = 'turbo.json' }) {
  const findings = [];
  const stable = /^2\.(\d+)\.\d+$/.exec(version ?? '');
  if (!stable || Number(stable[1]) < 5) {
    return { findings, reason: `Turbo static boundary configuration checks require verified stable 2.x >= 2.5.0; got ${version ?? 'unknown'}` };
  }
  for (const pkg of packages) {
    if (pkg.turboConfig?.boundaries && Object.hasOwn(pkg.turboConfig.boundaries, 'tags')) {
      const file = pkg.turboFile ?? `${pkg.dir}/turbo.json`;
      findings.push({
        id: 'boundaries/turbo-package-boundaries-tags',
        severity: 'medium',
        title: `${pkg.name} defines root-only boundaries.tags in a package config`,
        location: { file, package: pkg.name },
        evidence: `${file}: boundaries.tags = ${JSON.stringify(pkg.turboConfig.boundaries.tags)}`,
        fix: 'Move tag rules to the root boundaries.tags map, preserving existing rules; keep package labels in top-level tags.',
      });
    }
    if (config.boundaries?.tags && Object.hasOwn(config.boundaries.tags, pkg.name)) {
      findings.push({
        id: 'boundaries/turbo-tag-package-name-collision',
        severity: 'medium',
        title: `Boundary tag ${pkg.name} collides with a workspace package name`,
        location: { file: rootFile, package: pkg.name },
        evidence: `${rootFile}: boundaries.tags[${JSON.stringify(pkg.name)}] = ${JSON.stringify(config.boundaries.tags[pkg.name])}; ${pkg.dir}/package.json: name = ${JSON.stringify(pkg.name)}`,
        fix: 'Rename the rule tag and its package labels/tag references to a distinct label; preserve allow/deny entries that intentionally refer to the package name.',
      });
    }
  }
  return { findings };
}

Missing boundaries, absent/empty rules, untagged packages, and tags with no rule are valid defaults: emit no missing/permissive/untagged Turbo finding. Package names in allow/deny are explicitly supported; do not confuse them with rule-map keys. Lists contain literal tags/package names, not Nx-style wildcard constraints. An omitted allow permits all; allow: [] restricts all relations, not a permissive policy. Leave dependency/dependent policy evaluation (including transitive relations and deny precedence) to turbo boundaries, rather than approximating it from direct source imports.

Fix guidance

  • deep-import: add the subpath to the target's exports, or re-export from its entry point, then import from the package root.
  • oversized-package: identify clusters by which consumers import which files (scan.imports subpaths); propose 2–3 splits along clusters used by different consumers. If every consumer uses the same parts, don't emit the finding.
  • nx-missing-module-boundaries-rule: add @nx/enforce-module-boundaries with depConstraints based on scope:*/type:* tags.

FILE:references/caching.md

Check 3 — Task caching

Question: will a cache hit ever replay a wrong result, and are tasks re-running when they should hit? Output: findings/caching.json. If no orchestrator is detected, only caching/uncached-root-script applies; set status ok with reason no task orchestrator.

These rules do not inspect Bazel caching. For a Bazel-only workspace (no JS/Nx packages), write {"status":"skipped","reason":"Bazel caching is not analyzed","findings":[]} and stop this check. In a mixed workspace, retain applicable JS/Nx/Turbo findings but mark the check partial with reason Bazel caching is not analyzed. For uncached-root-script, only Nx and Turborepo count as task orchestrators; the presence of Bazel alone does not establish how npm scripts are orchestrated.

Facts the rules rely on

  • Turborepo: a task with no outputs caches only logs — on a hit, dist/ is NOT restored, so downstream tasks see stale or missing files. A package's hash covers its own files, its package.json, turbo.json and the lockfile; changes in workspace dependencies reach a task's hash only through dependsOn entries with ^ (e.g. ^build). Env vars affect the hash only when listed in env, globalEnv (or passThroughEnv for runtime-only); framework prefixes such as NEXT_PUBLIC_, VITE_ are auto-included. Turbo 2 strict env mode can also restrict which env vars are visible to tasks, so undeclared env is both a cache-key and runtime-visibility risk.
  • Nx: when outputs is omitted, Nx caches {workspaceRoot}/dist/{projectRoot}, {projectRoot}/dist, {projectRoot}/build, {projectRoot}/public. Env vars affect the hash only through an { "env": "NAME" } entry in inputs. Without a production named input that excludes tests, editing a spec file invalidates the build cache.

Rules

| id | severity | detect | |---|---|---| | caching/missing-outputs | high | Turbo: a cacheable task named build/compile/bundle/*:build (or whose package script runs tsc, vite build, tsup, rollup, webpack, next build, esbuild) has no outputs. Package-level turbo.json overrides count. Nx: cacheable build-like target without outputs whose real out dir (outDir in the build tsconfig, outDir/--out-dir flags, build.outDir in vite config) is not one of Nx's defaults — one finding per affected project, with package. Turbo findings are per task: location.file: "turbo.json", no package. | | caching/build-inputs-include-tests | low | Turbo: build-like task has no inputs, or inputs that don't exclude test globs (!**/*.test.*, !**/*.spec.*, !/__tests__/). Nx: no production named input, or build inputs don't reference it, or production doesn't negate test globs. Low severity because $TURBO_DEFAULT$ already covers all git-tracked files; the finding is about avoiding rebuilds when tests change, not correctness. Follow dependsOn chains: tests hashed by a dependency task (e.g. a transit task, or ^build of a package whose build inputs include tests) also invalidate the build. Measure impact (step 3) and put it in evidence. | | caching/undeclared-env | medium | for each scan.env entry that can affect a cacheable task output. Flag build tasks only when the build inlines env (Next/Vite framework bundlers, webpack/Rspack/Rsbuild define, esbuild/tsup define, Rollup/plugin-replace, or similar bundlers), not runtime-only reads in a plain tsc service. Always flag cacheable test tasks when tests execute code that reads the env var (scan.env.isTest, or a test file in the package imports the module with the env read), because a cached pass can be replayed under a different value. Turbo: name not matched by the task's env or globalEnv (* wildcards; ! negation) and not framework-prefixed. passThroughEnv / globalPassThroughEnv do not count: they make the var available without adding it to the hash, so a cached result can still be replayed under a different value. Nx: no { "env": NAME } in the target's inputs (resolve named inputs). Ignore CI, PATH, HOME, TZ, PWD. Ignore NODE_ENV only when the scan confirms it cannot affect the output (e.g. the task's script or bundler sets it to a fixed value); otherwise treat it like any other name. One finding per task config (Turbo task, or Nx target/targetDefault) that is missing declarations: list every missing name with its packages and up to 5 locations across all names, and set location.package only when a single package is affected. | | caching/turbo-cache-disabled | low | Turbo task with cache: false that is deterministic by name: build, compile, bundle, lint, typecheck, check-types, format:check, or a unit test (test, test:unit, *:build, *:lint). Treat cache: false as deliberate — and do not flag — when the task is persistent: true; its name contains dev, start, serve, watch, deploy, release, publish, clean, db, migrat, seed, generate, extract, sync, upload, e2e, integration, or ends in :ci; or its env/passThroughEnv lists external-state vars (*DATABASE*, *DB_*, *REDIS*, *_URL, *TOKEN*, *SECRET*). Mention deliberately uncached tasks in reason, not as findings. | | caching/nx-cache-disabled | low | An existing Nx target whose effective configuration explicitly sets cache: false and whose name is deterministic by the same allowlist as caching/turbo-cache-disabled. Resolve configuration as below; never treat an omitted cache as explicit false. Apply the same deliberate-task name exclusions, and skip continuous: true, watch-mode commands/options, long-running servers, and targets with external-state env inputs (resolve named inputs; match the external-state patterns above). Also skip when the command, executor, or configuration shows side effects or external-state dependence despite a deterministic name (e.g. test running integration tests). Mention deliberately uncached targets in reason, not as findings. | | caching/unstable-hash | high | turbo installed: run TURBO_TELEMETRY_DISABLED=1 ./node_modules/.bin/turbo run build --dry=json twice; any task whose hash differs between runs. Report the task and the inputs/environmentVariables that differ. | | caching/volatile-input | high | non-negated task inputs or globalDependencies include build artifacts or machine-local files: dist, build, .turbo, .nx, *.tsbuildinfo, **/*.log, node_modules. Ignore negated globs (!…). Do not flag .env* files: including env files usually makes caches more correct. | | caching/uncached-root-script | low | a root package.json script that runs tasks across packages bypassing the orchestrator: -r/--recursive, --workspaces/-ws, yarn workspaces foreach, lerna run. In repos without an orchestrator, say "consider adding Nx or Turborepo" in fix. |

Steps

  1. Read turbo.json (Turbo v2 tasks and Turbo v1 pipeline, plus //#task root tasks and ${pkg}/turbo.json overrides with "extends": ["//"]) and/or nx.json + every project.json / package.json#nx. For Nx, also read targetDefaults (including defaults keyed by executor), namedInputs, and legacy tasksRunnerOptions.*.options.cacheableOperations, and remember that Nx plugins (plugins in nx.json) can infer targets — if a target exists only via plugin inference, report rules that depend on its config as partial and say so.
  2. Apply the rules above. Quote the exact JSON in evidence (task name + its config object). Config-level findings (Turbo tasks, Nx targetDefaults/namedInputs) omit location.package; only set package when the problem is specific to one package (e.g. its own turbo.json/project.json, or an env read in its source).
  3. For build-inputs-include-tests, measure how often it matters with read-only git: git log --since="6 months ago" --name-only --format=%x00%H and count commits whose changed files are all test files (TEST pattern from scan.md). Report N of M commits (P%) changed only tests. Skip if the repo has no git history.
  4. unstable-hash runs only when turbo is installed; otherwise mark the check partial with reason turbo not installed; dry-run hash comparison skipped. Never run real tasks — only --dry=json.
  5. Write findings/caching.json.

Resolving Nx disabled-cache findings

  • Enumerate actual targets from project configuration, package.json scripts / nx.targets, and available inferred-target data. A targetDefaults entry does not itself create a target. Merge package configuration with project.json (project configuration takes precedence for the same target).
  • Select the applicable nx.json#targetDefaults for each target: a matching executor key takes precedence over a target-name key; do not merge both defaults. Account for matching target-name patterns and filtered defaults supported by the workspace's Nx version (see Nx target defaults). Before applying a selected default, check Nx's target compatibility: skip it when both it and the target specify different executors. For nx:run-commands / nx:run-script, also respect the workspace version's command/script compatibility checks. An incompatible default does not supply an effective cache: false. Apply compatible defaults below explicit project/p

Source and license

Source
Prompts Chat
Original
f/awesome-chatgpt-prompts/prompts.csv#monorepo-doctor
License
MIT

Monorepo Doctor

--- name: monorepo-doctor description: Use when a user asks for a JS/TS monorepo audit, or Bazel target visibility or testonly issues in a JS or Java workspace. Also covers Nx/Turborepo caching, affected tests, cycles an

Prompt · برومبت

Works with

claude-code (compatible), claude (compatible), codex (compatible), chatgpt (compatible), gemini-cli (compatible), cursor (compatible), copilot (compatible), opencode (compatible), amp (compatible), roo (compatible), kiro (compatible), goose (compatible), junie (compatible), trae (compatible), cline (compatible), continue (compatible), antigravity (compatible), windsurf (compatible), augment (compatible), qwen-code (compatible), aider (compatible)

Content

Monorepo Doctor

Audit a JS/TS monorepo for five classes of problems that teams routinely miss, or run the limited Bazel target checks in a standalone Bazel workspace, and produce an evidence-backed report. Bazel-only support does not analyze Java source, cycles, caching, or CI test coverage.

Prerequisites: Node ≥ 22.5. The work dir is $W = $(node -p 'require("os").tmpdir()')/monorepo-doctor (see detection.md).

Rules

  • Read-only. Never install dependencies, build, run tests, or edit project files. Allowed writes: monorepo-doctor-report.md, monorepo-doctor-report.json (default ${tmpdir}/monorepo-doctor-reports, or a user-given dir) and $W.
  • Allowed commands: the snippets in the reference files, npm pack --dry-run --json --ignore-scripts, read-only git log, and the repo's own ./node_modules/.bin/{knip,publint,nx,turbo} only if detection reports them installed (nx/turbo: graph / --dry=json / boundaries only — never real task runs, with read-only env vars from the references).
  • No runtime downloads by default. Don't fetch packages (npx, npm exec, pnpm dlx, yarn dlx, bunx). If a tool isn't installed, skip that sub-step and mark the check partial. Only if the user explicitly allows downloads in this request may you run the pinned knip@6.41.0 / publint@0.3.25 shown in the references — never other versions, other packages, or nx/turbo.
  • Never abort a check. If a tool fails, mark the check partial or skipped with a reason and continue.
  • Every finding needs evidence (config snippet, file:line, or command output). No evidence → no finding.
  • Actionable only. Do not emit a finding when the honest fix is "keep it as-is" — a deliberate, idiomatic or correct pattern (e.g. cache: false on a migration task, lazy ORM references). Mention it in the check's reason instead.
  • One root cause, one finding. If two findings share the same fix, merge them.
  • Use only the finding ids defined in the reference files.

Workflow

  1. Detect — follow [references/detection.md](references/detection.md). Stop if NO_WORKSPACE.
  2. Scan — follow [references/scan.md](references/scan.md). If Bazel is detected, also run the static inspection in [references/bazel.md](references/bazel.md) before the checks.
  3. Check — run all five unless the user asked for a subset (write {"status":"not-run","reason":"not requested","findings":[]} to $W/findings/${check}.json for the others):
  • [references/boundaries.md](references/boundaries.md) — package split & public API, including Bazel visibility
  • [references/circular-deps.md](references/circular-deps.md) — package and file cycles
  • [references/caching.md](references/caching.md) — Nx / Turborepo cache correctness
  • [references/ci-coverage.md](references/ci-coverage.md) — tests that silently don't run in CI
  • [references/prod-leakage.md](references/prod-leakage.md) — test code shipped to production The checks are independent; if you can run sub-agents, run them in parallel.
  1. Report — follow [references/report-format.md](references/report-format.md): validate each findings/${check}.json, render, then show the user where the reports were written, the summary line and the top 5 findings.
  2. CI mode (only if asked, or when invoked non-interactively with a threshold) — run the exit-code snippet from report-format.md.

Tracking

Create a todo per phase/check and mark each done as its findings file is written.

FILE:references/bazel.md

Bazel static target inspection

This supplementary scan works for Bazel-backed JS workspaces and standalone Bazel workspaces, including Java. It reads the BUILD files inventoried by [detection.md](detection.md) without invoking Bazel, loading .bzl files, or downloading anything. It writes $W/bazel.json for the boundary and production-leakage checks.

The scan deliberately recognizes only literal attributes on filegroup, java_library, java_binary, java_test loaded from @rules_java//java:defs.bzl, and js_library loaded from @aspect_rules_js//js:defs.bzl or @rules_js//js:defs.bzl. It follows literal local labels in srcs, deps, data, resources, runtime_deps, and exports. It does not evaluate macros, select(), glob(), package groups, external repositories, implicit dependencies, or nonliteral attributes; its results are always partial. It is not a general Starlark interpreter. REPO.bazel ignore_directories patterns are not evaluated: if that name occurs in the file or exclusions cannot be read, target findings are suppressed and the reason is reported. Conditional call expressions and rule names referenced as values or reassigned are not interpreted.

  • Visibility finding: an exact internal tag and an explicit, literal public visibility on the target. For a native filegroup only, an explicit package(default_visibility = ...) also counts; macro-created targets do not necessarily inherit that default. The tag is a project convention, not Bazel's own visibility policy. Public untagged targets are valid. Review the intended consumers before restricting visibility.
  • Test-only finding: a target explicitly tagged production and explicitly marked testonly = False has a literal local dependency path to a target explicitly marked testonly = True. Bazel normally rejects such a path at analysis time; the finding is a broken production build, not proof that test code actually shipped. A test target using test-only fixtures is valid.

Run after detection and the JS scan, from the audited workspace root:

W="$(node -p 'require("os").tmpdir()')/monorepo-doctor"
cat > "$W/bazel-audit.mjs" <<'EOF'
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

const work = path.join(os.tmpdir(), 'monorepo-doctor');
const ws = JSON.parse(fs.readFileSync(path.join(work, 'workspace.json'), 'utf8'));
const root = ws.root;
const findings = { boundaries: [], 'prod-leakage': [] };
const problems = [];
const targets = new Map(), duplicates = new Set();
const closing = { '(': ')', '[': ']', '{': '}' };

function lex(text) {
  const out = [];
  let i = 0, line = 1, logicalLine = 1, depth = 0;
  while (i < text.length) {
    const ch = text[i];
    if (ch === '\\' && (text[i + 1] === '\n' || (text[i + 1] === '\r' && text[i + 2] === '\n'))) {
      i += text[i + 1] === '\r' ? 3 : 2;
      line++;
      continue;
    }
    if (/\s/.test(ch)) {
      if (ch === '\n') { line++; if (!depth) logicalLine++; }
      i++;
      continue;
    }
    if (ch === '#') { while (i < text.length && text[i] !== '\n') i++; continue; }
    const start = i, startLine = line;
    if (ch === '"' || ch === "'") {
      const triple = text.slice(i, i + 3) === ch.repeat(3);
      i += triple ? 3 : 1;
      let value = '', valid = !triple, closed = false;
      while (i < text.length) {
        if (triple && text.slice(i, i + 3) === ch.repeat(3)) { i += 3; closed = true; break; }
        if (!triple && text[i] === ch) { i++; closed = true; break; }
        if (text[i] === '\\') {
          i++;
          if (i >= text.length) break;
          const escapes = { '\\': '\\', '"': '"', "'": "'", n: '\n', r: '\r', t: '\t' };
          if (!Object.hasOwn(escapes, text[i])) valid = false;
          else value += escapes[text[i]];
          if (text[i] === '\n') line++;
          i++;
        } else {
          if (text[i] === '\n') {
            line++;
            if (!triple) throw new Error(`unterminated string at line ${startLine}`);
          }
          value += text[i++];
        }
      }
      if (!closed) throw new Error(`unterminated string at line ${startLine}`);
      out.push({ type: valid ? 'string' : 'unknown', value, start, end: i, line: startLine, logicalLine });
    } else if (/[A-Za-z_]/.test(ch)) {
      i++;
      while (i < text.length && /[A-Za-z0-9_]/.test(text[i])) i++;
      out.push({ type: 'id', value: text.slice(start, i), start, end: i, line: startLine, logicalLine });
    } else {
      i++;
      out.push({ type: 'punct', value: ch, start, end: i, line: startLine, logicalLine });
      if (closing[ch]) depth++;
      else if ([')', ']', '}'].includes(ch)) depth--;
    }
  }
  return out;
}

function groupEnd(tokens, start) {
  const stack = [closing[tokens[start].value]];
  for (let i = start + 1; i < tokens.length; i++) {
    const value = tokens[i].value;
    if (tokens[i].type === 'punct' && closing[value]) stack.push(closing[value]);
    else if (tokens[i].type === 'punct' && [')', ']', '}'].includes(value)) {
      if (stack.pop() !== value) throw new Error(`unbalanced delimiter at line ${tokens[i].line}`);
      if (!stack.length) return i;
    }
  }
  throw new Error(`unclosed delimiter at line ${tokens[start].line}`);
}

function splitArgs(tokens) {
  const parts = [];
  let start = 0;
  for (let i = 0; i < tokens.length; i++) {
    if (tokens[i].type === 'punct' && closing[tokens[i].value]) i = groupEnd(tokens, i);
    else if (tokens[i].type === 'punct' && tokens[i].value === ',') { if (i > start) parts.push(tokens.slice(start, i)); start = i + 1; }
  }
  if (start < tokens.length) parts.push(tokens.slice(start));
  return parts;
}

function literal(tokens) {
  if (tokens.length === 1 && tokens[0].type === 'string') return tokens[0].value;
  if (tokens.length === 1 && tokens[0].type === 'id' && ['True', 'False'].includes(tokens[0].value)) return tokens[0].value === 'True';
  if (tokens[0]?.type === 'punct' && tokens[0].value === '[' && groupEnd(tokens, 0) === tokens.length - 1) {
    const parts = splitArgs(tokens.slice(1, -1));
    if (parts.every((p) => p.length === 1 && p[0].type === 'string')) return parts.map((p) => p[0].value);
  }
  return undefined;
}

function calls(text) {
  const tokens = lex(text), result = [], loadTokens = new Set();
  for (let i = 0; i < tokens.length; i++) {
    const t = tokens[i];
    const isSemicolon = (tok) => tok?.type === 'punct' && tok.value === ';';
    const statementStart = i === 0 || tokens[i - 1].logicalLine !== t.logicalLine || isSemicolon(tokens[i - 1]);
    if (t.type === 'id' && tokens[i + 1]?.type === 'punct' && tokens[i + 1].value === '('
        && tokens[i + 1].logicalLine === t.logicalLine && statementStart) {
      const end = groupEnd(tokens, i + 1);
      if (tokens[end + 1]?.logicalLine !== tokens[end].logicalLine || isSemicolon(tokens[end + 1])) {
        result.push({ name: t.value, line: t.line, parts: splitArgs(tokens.slice(i + 2, end)) });
        if (t.value === 'load') for (let j = i + 1; j < end; j++) loadTokens.add(j);
      }
      i = end;
    } else if (t.type === 'punct' && closing[t.value]) {
      i = groupEnd(tokens, i);
    }
  }
  const referenced = new Set(tokens.flatMap((t, i) =>
    t.type === 'id' && tokens[i + 1]?.value !== '(' && !loadTokens.has(i) ? [t.value] : []));
  return { calls: result, referenced };
}

function attributes(parts, text) {
  const attrs = {};
  for (const p of parts) {
    if (p[0]?.type !== 'id' || p[1]?.value !== '=' || p.length < 3) continue;
    if (Object.hasOwn(attrs, p[0].value)) throw new Error(`duplicate ${p[0].value} attribute at line ${p[0].line}`);
    const expr = p.slice(2);
    attrs[p[0].value] = {
      value: literal(expr),
      text: text.slice(expr[0].start, expr[expr.length - 1].end),
      line: p[0].line,
    };
  }
  return attrs;
}

function loadBindings(parsed) {
  const bindings = new Map();
  for (const call of parsed.filter((c) => c.name === 'load')) {
    const source = literal(call.parts[0] ?? []);
    if (typeof source !== 'string') continue;
    for (const part of call.parts.slice(1)) {
      const local = part.length === 1 && part[0].type === 'string' ? part[0].value
        : part[0]?.type === 'id' && part[1]?.value === '=' ? part[0].value : null;
      const symbol = part.length === 1 ? literal(part) : literal(part.slice(2));
      if (local && typeof symbol === 'string') bindings.set(local, { source, symbol });
    }
  }
  return bindings;
}

function ruleKind(name, bindings) {
  const binding = bindings.get(name);
  if (name === 'filegroup' && !binding) return name;
  if (binding?.source === '@rules_java//java:defs.bzl'
      && ['java_library', 'java_binary', 'java_test'].includes(binding.symbol)) return binding.symbol;
  if (['@aspect_rules_js//js:defs.bzl', '@rules_js//js:defs.bzl'].includes(binding?.source)
      && binding.symbol === 'js_library') return binding.symbol;
  return null;
}

function label(value, pkg) {
  if (typeof value !== 'string') return null;
  if (value.startsWith('@@//')) value = value.slice(2);
  else if (value.startsWith('@')) return null;
  let dir = pkg, name = value;
  if (value.startsWith('//')) {
    const body = value.slice(2), colon = body.indexOf(':');
    dir = colon < 0 ? body : body.slice(0, colon);
    name = colon < 0 ? path.posix.basename(dir) : body.slice(colon + 1);
  } else if (value.startsWith(':')) name = value.slice(1);
  if (!name || name.includes(':') || dir.split('/').includes('..') || name.split('/').includes('..')
      || !/^[A-Za-z0-9_./+~=-]*$/.test(dir) || !/^[A-Za-z0-9_./+~=-]+$/.test(name)) return null;
  return `//${dir}:${name}`;
}

function owner(dir) {
  return [...ws.packages]
    .filter((p) => p.dir === '.' || dir === p.dir || dir.startsWith(`${p.dir}/`))
    .sort((a, b) => b.dir.length - a.dir.length)[0]?.name;
}

for (const file of ws.bazel?.unresolvedExclusions ? [] : ws.bazel?.buildFiles ?? []) {
  try {
    const text = fs.readFileSync(path.join(root, file), 'utf8');
    const { calls: parsed, referenced } = calls(text);
    const bindings = loadBindings(parsed);
    const packageCall = !referenced.has('package') && !bindings.has('package')
      ? parsed.find((c) => c.name === 'package') : undefined;
    const defaults = packageCall ? attributes(packageCall.parts, text) : {};
    const pkg = path.posix.dirname(file) === '.' ? '' : path.posix.dirname(file);
    for (const call of parsed) {
      const kind = referenced.has(call.name) ? null : ruleKind(call.name, bindings);
      if (!kind) continue;
      const attrs = attributes(call.parts, text);
      const name = attrs.name?.value;
      const targetLabel = label(typeof name === 'string' ? `:${name}` : null, pkg);
      if (!targetLabel) continue;
      const visibility = Object.hasOwn(attrs, 'visibility') ? attrs.visibility
        : kind === 'filegroup' ? defaults.default_visibility : undefined;
      const edges = [];
      for (const key of ['srcs', 'deps', 'data', 'resources', 'runtime_deps', 'exports']) {
        if (!Array.isArray(attrs[key]?.value)) continue;
        for (const value of attrs[key].value) {
          const dest = label(value, pkg);
          if (dest) edges.push({ label: dest, attribute: key, line: attrs[key].line });
        }
      }
      const target = { label: targetLabel, file, line: call.line, pkg: owner(pkg), attrs, visibility, edges };
      if (targets.has(targetLabel)) duplicates.add(targetLabel);
      else targets.set(targetLabel, target);
    }
  } catch (error) {
    problems.push(`${file}: ${error.message}`);
  }
}
for (const duplicate of duplicates) {
  targets.delete(duplicate);
  problems.push(`duplicate target ${duplicate}`);
}

for (const target of targets.values()) {
  if (Array.isArray(target.attrs.tags?.value)
      && target.attrs.tags.value.includes('internal')
      && Array.isArray(target.visibility?.value)
      && target.visibility.value.length === 1
      && target.visibility.value[0] === '//visibility:public') {
    findings.boundaries.push({
      id: 'boundaries/bazel-public-internal-target', severity: 'medium',
      title: `Internal-tagged target ${target.label} is publicly visible`,
      location: { file: target.file, line: target.line, ...(target.pkg ? { package: target.pkg } : {}) },
      evidence: `${target.label} (${target.file}:${target.line}): tags = ${target.attrs.tags.text}; ${Object.hasOwn(target.attrs, 'visibility') ? 'visibility' : 'package default_visibility'} = ${target.visibility.text}`,
      fix: 'Confirm the intended consumers and restrict visibility if the target is meant to be internal; retain any required access.',
    });
  }

  if (!Array.isArray(target.attrs.tags?.value) || !target.attrs.tags.value.includes('production')
      || target.attrs.testonly?.value !== false) continue;
  const seen = new Set([target.label]);
  const queue = [{ target, edges: [] }];
  for (let i = 0; i < queue.length; i++) {
    const current = queue[i];
    for (const edge of current.target.edges) {
      if (seen.has(edge.label) || !targets.has(edge.label)) continue;
      seen.add(edge.label);
      const next = targets.get(edge.label);
      const chain = [...current.edges, { from: current.target, edge }];
      if (next.attrs.testonly?.value === true) {
        findings['prod-leakage'].push({
          id: 'prod-leakage/bazel-testonly-dependency', severity: 'high',
          title: `Production target ${target.label} depends on test-only target ${next.label}`,
          location: { file: target.file, line: target.line, ...(target.pkg ? { package: target.pkg } : {}) },
          evidence: `${target.label}: tags = ${target.attrs.tags.text}; testonly = ${target.attrs.testonly.text}\n${chain.map(({ from, edge: e }) => `${from.label} (${from.file}:${e.line}) ${e.attribute} -> ${e.label}`).join('\n')}\n${next.label} (${next.file}:${next.attrs.testonly.line}): testonly = ${next.attrs.testonly.text}`,
          fix: 'Remove the test-only dependency from the production target or replace it with a production-safe input; keep test fixtures test-only.',
        });
      }
      queue.push({ target: next, edges: chain });
    }
  }
}

const reason = [
  'Bazel static inspection covers only literal local targets; macros, selects, package groups and external dependencies are not resolved',
  ...(!ws.bazel?.buildFiles.length ? ['no Bazel BUILD files found'] : []),
  ...(ws.bazel?.errors ?? []),
  ...problems,
].join('; ');
const result = Object.fromEntries(Object.entries(findings).map(([check, entries]) => [check, {
  status: 'partial', reason, findings: entries,
}]));
fs.writeFileSync(path.join(work, 'bazel.json'), JSON.stringify(result, null, 2));
console.log(JSON.stringify({ boundaries: findings.boundaries.length, testonly: findings['prod-leakage'].length, status: 'partial' }));
EOF
node "$W/bazel-audit.mjs"

Each check merges its own findings from this file and keeps the scan's partial reason alongside any other incomplete subchecks. If this scan fails or bazel.json is missing or invalid, mark both Bazel-aware checks partial with the failure reason; do not treat the absence of results as a clean audit. FILE:references/boundaries.md

Check 1 — Package boundaries

Question: are packages split along real seams, and is each package's public API respected? Inputs: workspace.json, scan.json. Output: findings/boundaries.json.

Rules

| id | severity | detect | evidence | |---|---|---|---| | boundaries/oversized-package | low | scan.packages[p].sourceFiles > 500 or loc > 50000 (generated files are already excluded by scan) and at least 2 other workspace packages import it (scan.imports with target === p). Apps and leaf packages with no workspace consumers are never flagged: splitting them adds export maps and tags with no consumer that benefits. | counts + the consumers and which subpaths/symbols each uses | | boundaries/deep-import | medium | each scan.imports entry with deep && (declared \|\| fromSource === "project.json") (undeclared package.json importers are reported by ci-coverage instead) | file:line + import specifier + target's exports keys | | boundaries/unlisted-dependency | medium | knip unlisted entries | knip output line | | boundaries/unused-dependency | low | knip dependencies / devDependencies entries | knip output line | | boundaries/nx-missing-module-boundaries-rule | medium | Nx detected and no ESLint config in the root mentions @nx/enforce-module-boundaries | list of ESLint config files checked | | boundaries/nx-permissive-module-boundaries | low | the rule exists but depConstraints contains { sourceTag: '*', onlyDependOnLibsWithTags: ['*'] } | the config snippet | | boundaries/nx-untagged-project | low | Nx detected, rule absent or permissive, and a project has empty tags | project.json path | | boundaries/turbo-package-boundaries-tags | medium | verified Turbo 2.5+ (2.x) and a package-level Turbo config defines boundaries.tags, which is root-only | package config path + boundaries.tags snippet | | boundaries/turbo-tag-package-name-collision | medium | verified Turbo 2.5+ (2.x) and a root boundaries.tags rule key exactly equals a workspace package name | root rule snippet + package.json name and path | | boundaries/turbo-boundaries-violation | medium | each violation printed by turbo boundaries | output line | | boundaries/bazel-public-internal-target | medium | an explicitly internal Bazel target (tags contains internal) has effective //visibility:public | target label + tags and effective visibility declarations |

Group deep-import findings: one finding per (from, target) pair, listing up to 5 locations in evidence; location is the first occurrence. For a Bazel-only workspace, skip the JS, knip, Nx and Turbo subchecks and keep this check partial; do not present its Bazel-only result as a full package boundary audit.

Steps

  1. Load workspace.json and scan.json. Apply the size and deep-import rules directly.
  2. knip — only if hasNodeModules and tools.knip:
   W="$(node -p 'require("os").tmpdir()')/monorepo-doctor"
   ./node_modules/.bin/knip --reporter json --include dependencies,devDependencies,unlisted --no-progress --no-exit-code

If tools.knip is false, skip and mark partial with reason knip not installed locally. Only if the user explicitly allowed downloads, run npm_config_ignore_scripts=true npx --yes knip@6.41.0 with the same flags instead (exact version, never @latest). Parse stdout as JSON. Its shape varies by version; look for per-file dependencies, devDependencies and unlisted arrays of { name }. Map the file to its package via workspace.json. If knip fails or the output can't be parsed, mark the check partial with reason knip unavailable: ${first_line_of_error}. Do not report unused-dependency for @types/* packages or for tools only referenced in scripts.

  1. Nx — only if Nx is an orchestrator: read ESLint configs in the root (eslint.config.{js,mjs,cjs,ts}, .eslintrc{,.json,.js,.cjs}) and every package dir. Apply the three nx-* rules. A config that contains @nx/enforce-module-boundaries or legacy @nrwl/nx/enforce-module-boundaries anywhere counts as present. Group nx-untagged-project consistently as one finding per untagged project found from the root and package-dir project configs.
  2. Turborepo static configuration — if turbo is an orchestrator, even when not installed, follow the static checks below.
  3. Turborepo command — only if turbo is an orchestrator and installed:
   W="$(node -p 'require("os").tmpdir()')/monorepo-doctor"
   TURBO_TELEMETRY_DISABLED=1 ./node_modules/.bin/turbo boundaries

One finding per reported violation, except configuration errors already emitted by the static checks: retain the specific static finding and append command evidence instead of duplicating it as turbo-boundaries-violation. A nonzero exit caused only by reported violations is a completed inspection. If the command errors with an unknown-command message (turbo < 2.4), skip this sub-step and note it in reason. Unexpected execution/config-loading failures are partial with the first error line, not a clean result. If not installed, mark this sub-step partial with reason turbo not installed locally; retain static findings.

  1. Bazel visibility — only if Bazel is an orchestrator. Merge boundaries.findings from $W/bazel.json, generated by [bazel.md](bazel.md), and retain its partial reason alongside other skipped subchecks. The internal tag is a project convention, not a Bazel policy; do not flag untagged public targets. Do not infer visibility from macros, package groups or conditional expressions. If the file is missing or invalid, mark this check partial with the failure reason.
  2. Write findings/boundaries.json.

Turborepo static configuration

These are configuration errors, not a requirement to adopt tags. Turbo's boundaries documentation describes optional package tags and root boundaries.tags rules. The v2.5.0 schema types and boundary implementation establish the two diagnostics (PackageBoundariesHasTags, TagSharesPackageName), which also exist in the current implementation.

  1. Establish the Turbo version from installed node_modules/turbo/package.json, otherwise a resolved lockfile version. Without either, an exact stable 2.x.y dependency or a simple ^2.x.y / ~2.x.y declaration with minor >= 5 proves support: pass its lower bound to the helper. Do not treat arbitrary ranges, aliases, prereleases, or another major as verified. This conservative gate is verified for stable 2.x >= 2.5.0; it does not claim tags first appeared in 2.5. For older/unknown/unverified versions, skip these two checks with a partial reason, not a finding, and still run the command if installed.
  2. Read root turbo.json and each discovered workspace package's own turbo.json (or turbo.jsonc where supported by that version). Parse using the format's actual semantics, not regex matching or naive comment stripping. Respect file precedence for the installed version; unresolved config selection, invalid config, or unsupported inheritance makes that portion partial with the file and error. Do not silently substitute {} for unreadable files. Missing package configs are normal. Use only a package's own boundaries.tags for the package-level check, never root rules inherited via extends: ["//"]. Top-level package tags are valid.
  3. Before calling the helper, exclude workspace.json package entries with source === "project.json": these are Nx-only projects, not Turbo workspace packages. Use the helper below with parsed root config and the remaining Turbo workspace packages shaped as { name, dir, turboConfig?, turboFile? }. dir comes from workspace.json; read name from that directory's package.json manifest, not an Nx project name or directory fallback. An unreadable manifest or missing manifest name makes that package's checks partial with the file and reason. turboConfig is the package's own parsed config, and turboFile is its workspace-relative path (defaults to ${dir}/turbo.json). Do not use workspace.json's tags: those are Nx tags, not Turbo tags. Locate each emitted config key in the original file and add location.line when available.
function turboBoundaryConfigFindings({ version, config, packages, rootFile = 'turbo.json' }) {
  const findings = [];
  const stable = /^2\.(\d+)\.\d+$/.exec(version ?? '');
  if (!stable || Number(stable[1]) < 5) {
    return { findings, reason: `Turbo static boundary configuration checks require verified stable 2.x >= 2.5.0; got ${version ?? 'unknown'}` };
  }
  for (const pkg of packages) {
    if (pkg.turboConfig?.boundaries && Object.hasOwn(pkg.turboConfig.boundaries, 'tags')) {
      const file = pkg.turboFile ?? `${pkg.dir}/turbo.json`;
      findings.push({
        id: 'boundaries/turbo-package-boundaries-tags',
        severity: 'medium',
        title: `${pkg.name} defines root-only boundaries.tags in a package config`,
        location: { file, package: pkg.name },
        evidence: `${file}: boundaries.tags = ${JSON.stringify(pkg.turboConfig.boundaries.tags)}`,
        fix: 'Move tag rules to the root boundaries.tags map, preserving existing rules; keep package labels in top-level tags.',
      });
    }
    if (config.boundaries?.tags && Object.hasOwn(config.boundaries.tags, pkg.name)) {
      findings.push({
        id: 'boundaries/turbo-tag-package-name-collision',
        severity: 'medium',
        title: `Boundary tag ${pkg.name} collides with a workspace package name`,
        location: { file: rootFile, package: pkg.name },
        evidence: `${rootFile}: boundaries.tags[${JSON.stringify(pkg.name)}] = ${JSON.stringify(config.boundaries.tags[pkg.name])}; ${pkg.dir}/package.json: name = ${JSON.stringify(pkg.name)}`,
        fix: 'Rename the rule tag and its package labels/tag references to a distinct label; preserve allow/deny entries that intentionally refer to the package name.',
      });
    }
  }
  return { findings };
}

Missing boundaries, absent/empty rules, untagged packages, and tags with no rule are valid defaults: emit no missing/permissive/untagged Turbo finding. Package names in allow/deny are explicitly supported; do not confuse them with rule-map keys. Lists contain literal tags/package names, not Nx-style wildcard constraints. An omitted allow permits all; allow: [] restricts all relations, not a permissive policy. Leave dependency/dependent policy evaluation (including transitive relations and deny precedence) to turbo boundaries, rather than approximating it from direct source imports.

Fix guidance

  • deep-import: add the subpath to the target's exports, or re-export from its entry point, then import from the package root.
  • oversized-package: identify clusters by which consumers import which files (scan.imports subpaths); propose 2–3 splits along clusters used by different consumers. If every consumer uses the same parts, don't emit the finding.
  • nx-missing-module-boundaries-rule: add @nx/enforce-module-boundaries with depConstraints based on scope:*/type:* tags.

FILE:references/caching.md

Check 3 — Task caching

Question: will a cache hit ever replay a wrong result, and are tasks re-running when they should hit? Output: findings/caching.json. If no orchestrator is detected, only caching/uncached-root-script applies; set status ok with reason no task orchestrator.

These rules do not inspect Bazel caching. For a Bazel-only workspace (no JS/Nx packages), write {"status":"skipped","reason":"Bazel caching is not analyzed","findings":[]} and stop this check. In a mixed workspace, retain applicable JS/Nx/Turbo findings but mark the check partial with reason Bazel caching is not analyzed. For uncached-root-script, only Nx and Turborepo count as task orchestrators; the presence of Bazel alone does not establish how npm scripts are orchestrated.

Facts the rules rely on

  • Turborepo: a task with no outputs caches only logs — on a hit, dist/ is NOT restored, so downstream tasks see stale or missing files. A package's hash covers its own files, its package.json, turbo.json and the lockfile; changes in workspace dependencies reach a task's hash only through dependsOn entries with ^ (e.g. ^build). Env vars affect the hash only when listed in env, globalEnv (or passThroughEnv for runtime-only); framework prefixes such as NEXT_PUBLIC_, VITE_ are auto-included. Turbo 2 strict env mode can also restrict which env vars are visible to tasks, so undeclared env is both a cache-key and runtime-visibility risk.
  • Nx: when outputs is omitted, Nx caches {workspaceRoot}/dist/{projectRoot}, {projectRoot}/dist, {projectRoot}/build, {projectRoot}/public. Env vars affect the hash only through an { "env": "NAME" } entry in inputs. Without a production named input that excludes tests, editing a spec file invalidates the build cache.

Rules

| id | severity | detect | |---|---|---| | caching/missing-outputs | high | Turbo: a cacheable task named build/compile/bundle/*:build (or whose package script runs tsc, vite build, tsup, rollup, webpack, next build, esbuild) has no outputs. Package-level turbo.json overrides count. Nx: cacheable build-like target without outputs whose real out dir (outDir in the build tsconfig, outDir/--out-dir flags, build.outDir in vite config) is not one of Nx's defaults — one finding per affected project, with package. Turbo findings are per task: location.file: "turbo.json", no package. | | caching/build-inputs-include-tests | low | Turbo: build-like task has no inputs, or inputs that don't exclude test globs (!**/*.test.*, !**/*.spec.*, !/__tests__/). Nx: no production named input, or build inputs don't reference it, or production doesn't negate test globs. Low severity because $TURBO_DEFAULT$ already covers all git-tracked files; the finding is about avoiding rebuilds when tests change, not correctness. Follow dependsOn chains: tests hashed by a dependency task (e.g. a transit task, or ^build of a package whose build inputs include tests) also invalidate the build. Measure impact (step 3) and put it in evidence. | | caching/undeclared-env | medium | for each scan.env entry that can affect a cacheable task output. Flag build tasks only when the build inlines env (Next/Vite framework bundlers, webpack/Rspack/Rsbuild define, esbuild/tsup define, Rollup/plugin-replace, or similar bundlers), not runtime-only reads in a plain tsc service. Always flag cacheable test tasks when tests execute code that reads the env var (scan.env.isTest, or a test file in the package imports the module with the env read), because a cached pass can be replayed under a different value. Turbo: name not matched by the task's env or globalEnv (* wildcards; ! negation) and not framework-prefixed. passThroughEnv / globalPassThroughEnv do not count: they make the var available without adding it to the hash, so a cached result can still be replayed under a different value. Nx: no { "env": NAME } in the target's inputs (resolve named inputs). Ignore CI, PATH, HOME, TZ, PWD. Ignore NODE_ENV only when the scan confirms it cannot affect the output (e.g. the task's script or bundler sets it to a fixed value); otherwise treat it like any other name. One finding per task config (Turbo task, or Nx target/targetDefault) that is missing declarations: list every missing name with its packages and up to 5 locations across all names, and set location.package only when a single package is affected. | | caching/turbo-cache-disabled | low | Turbo task with cache: false that is deterministic by name: build, compile, bundle, lint, typecheck, check-types, format:check, or a unit test (test, test:unit, *:build, *:lint). Treat cache: false as deliberate — and do not flag — when the task is persistent: true; its name contains dev, start, serve, watch, deploy, release, publish, clean, db, migrat, seed, generate, extract, sync, upload, e2e, integration, or ends in :ci; or its env/passThroughEnv lists external-state vars (*DATABASE*, *DB_*, *REDIS*, *_URL, *TOKEN*, *SECRET*). Mention deliberately uncached tasks in reason, not as findings. | | caching/nx-cache-disabled | low | An existing Nx target whose effective configuration explicitly sets cache: false and whose name is deterministic by the same allowlist as caching/turbo-cache-disabled. Resolve configuration as below; never treat an omitted cache as explicit false. Apply the same deliberate-task name exclusions, and skip continuous: true, watch-mode commands/options, long-running servers, and targets with external-state env inputs (resolve named inputs; match the external-state patterns above). Also skip when the command, executor, or configuration shows side effects or external-state dependence despite a deterministic name (e.g. test running integration tests). Mention deliberately uncached targets in reason, not as findings. | | caching/unstable-hash | high | turbo installed: run TURBO_TELEMETRY_DISABLED=1 ./node_modules/.bin/turbo run build --dry=json twice; any task whose hash differs between runs. Report the task and the inputs/environmentVariables that differ. | | caching/volatile-input | high | non-negated task inputs or globalDependencies include build artifacts or machine-local files: dist, build, .turbo, .nx, *.tsbuildinfo, **/*.log, node_modules. Ignore negated globs (!…). Do not flag .env* files: including env files usually makes caches more correct. | | caching/uncached-root-script | low | a root package.json script that runs tasks across packages bypassing the orchestrator: -r/--recursive, --workspaces/-ws, yarn workspaces foreach, lerna run. In repos without an orchestrator, say "consider adding Nx or Turborepo" in fix. |

Steps

  1. Read turbo.json (Turbo v2 tasks and Turbo v1 pipeline, plus //#task root tasks and ${pkg}/turbo.json overrides with "extends": ["//"]) and/or nx.json + every project.json / package.json#nx. For Nx, also read targetDefaults (including defaults keyed by executor), namedInputs, and legacy tasksRunnerOptions.*.options.cacheableOperations, and remember that Nx plugins (plugins in nx.json) can infer targets — if a target exists only via plugin inference, report rules that depend on its config as partial and say so.
  2. Apply the rules above. Quote the exact JSON in evidence (task name + its config object). Config-level findings (Turbo tasks, Nx targetDefaults/namedInputs) omit location.package; only set package when the problem is specific to one package (e.g. its own turbo.json/project.json, or an env read in its source).
  3. For build-inputs-include-tests, measure how often it matters with read-only git: git log --since="6 months ago" --name-only --format=%x00%H and count commits whose changed files are all test files (TEST pattern from scan.md). Report N of M commits (P%) changed only tests. Skip if the repo has no git history.
  4. unstable-hash runs only when turbo is installed; otherwise mark the check partial with reason turbo not installed; dry-run hash comparison skipped. Never run real tasks — only --dry=json.
  5. Write findings/caching.json.

Resolving Nx disabled-cache findings

  • Enumerate actual targets from project configuration, package.json scripts / nx.targets, and available inferred-target data. A targetDefaults entry does not itself create a target. Merge package configuration with project.json (project configuration takes precedence for the same target).
  • Select the applicable nx.json#targetDefaults for each target: a matching executor key takes precedence over a target-name key; do not merge both defaults. Account for matching target-name patterns and filtered defaults supported by the workspace's Nx version (see Nx target defaults). Before applying a selected default, check Nx's target compatibility: skip it when both it and the target specify different executors. For nx:run-commands / nx:run-script, also respect the workspace version's command/script compatibility checks. An incompatible default does not supply an effective cache: false. Apply compatible defaults below explicit project/p

Source and license

Source
Prompts Chat
Original
f/awesome-chatgpt-prompts/prompts.csv#monorepo-doctor
License
MIT