@hublo/sentinel 1.7.0-alpha.20 → 1.7.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/README.md +1 -2
  2. package/dist/bin/sentinel.js +37 -9
  3. package/dist/{chunk-LX7EG6PJ.js → chunk-BBNABWZ6.js} +2 -2
  4. package/dist/chunk-BBNABWZ6.js.map +1 -0
  5. package/dist/{chunk-PMRL4MH6.js → chunk-J2RMARWP.js} +2 -2
  6. package/dist/{chunk-B3Y7F7BA.js → chunk-RI7R3S3T.js} +6566 -7500
  7. package/dist/{chunk-AVT5FSPO.js → chunk-UVXXEAHU.js} +4 -6
  8. package/dist/{chunk-JT7ZMH44.js → chunk-XTBHIKFG.js} +5 -5
  9. package/dist/chunk-XTBHIKFG.js.map +1 -0
  10. package/dist/chunk-XYOIXC6A.js +126 -0
  11. package/dist/chunk-XYOIXC6A.js.map +1 -0
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.js +5 -5
  14. package/dist/roles/code-churn/config.d.ts +92 -0
  15. package/dist/roles/code-churn/config.js +10 -0
  16. package/dist/roles/static-analysis/config.js +1 -1
  17. package/dist/roles/test/setup/jest-parity.js +2 -2
  18. package/dist/roles/test/setup/workspace-entry.js +2 -2
  19. package/dist/{validate-B5567Z7X.js → validate-YCTNTNFT.js} +2 -2
  20. package/docs/code-churn-adoption.md +237 -0
  21. package/docs/static-analysis-study.md +49 -10
  22. package/docs/typescript-traces.md +140 -142
  23. package/docs/using-sentinel.md +1 -2
  24. package/package.json +4 -5
  25. package/dist/chunk-JT7ZMH44.js.map +0 -1
  26. package/dist/chunk-LX7EG6PJ.js.map +0 -1
  27. package/dist/chunk-NGLEGAEN.js +0 -190
  28. package/dist/chunk-NGLEGAEN.js.map +0 -1
  29. package/dist/roles/sql/config.d.ts +0 -68
  30. package/dist/roles/sql/config.js +0 -8
  31. package/docs/sql-adoption.md +0 -552
  32. /package/dist/{chunk-PMRL4MH6.js.map → chunk-J2RMARWP.js.map} +0 -0
  33. /package/dist/roles/{sql → code-churn}/config.js.map +0 -0
@@ -6,7 +6,7 @@ import {
6
6
  readNxProjectName,
7
7
  readOwnPackage,
8
8
  readProjectPackageJson
9
- } from "./chunk-JT7ZMH44.js";
9
+ } from "./chunk-XTBHIKFG.js";
10
10
  import {
11
11
  matchesTsconfigPattern
12
12
  } from "./chunk-O7REVMOC.js";
@@ -9984,6 +9984,8 @@ export {
9984
9984
  rewriteToolchainImports,
9985
9985
  resolveOxfmt,
9986
9986
  oxfmtRejects,
9987
+ writtenFileFormatter,
9988
+ RESOLVABLE_EXTENSIONS,
9987
9989
  canonicalRuleName,
9988
9990
  describeRuleKey,
9989
9991
  LINT_BASELINE_FILE,
@@ -10024,12 +10026,8 @@ export {
10024
10026
  oxlintPath,
10025
10027
  oxlintSearchPath,
10026
10028
  walk,
10027
- MEMBER_TYPES,
10028
- writtenFileFormatter,
10029
- RESOLVABLE_EXTENSIONS,
10030
- findModuleRoot,
10031
- resolveContext,
10032
10029
  readTestAdoption,
10030
+ resolveContext,
10033
10031
  moduleEnvironment,
10034
10032
  suiteOf,
10035
10033
  captureReference,
@@ -186,10 +186,10 @@ var REPORT_DIRS = {
186
186
  header: "# @hublo/sentinel: static analysis reports, written inside each module",
187
187
  label: "the static analysis role"
188
188
  },
189
- sql: {
190
- dir: "sql-report",
191
- header: "# @hublo/sentinel: sql reports, written inside each module",
192
- label: "the sql role"
189
+ "code-churn": {
190
+ dir: "code-churn-report",
191
+ header: "# @hublo/sentinel: code churn reports, written inside each module",
192
+ label: "the code churn role"
193
193
  }
194
194
  };
195
195
  var ignores = (text, dir) => text.split("\n").some((line) => line.trim().replace(/^\//, "").replace(/\/$/, "") === dir);
@@ -332,4 +332,4 @@ export {
332
332
  ensureWorkspacePrep,
333
333
  inspectWorkspacePrep
334
334
  };
335
- //# sourceMappingURL=chunk-JT7ZMH44.js.map
335
+ //# sourceMappingURL=chunk-XTBHIKFG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shared/package-json.ts","../src/core/settings.ts","../src/core/workspace-prep.ts"],"sourcesContent":["/**\n * package.json helpers, shared by the CLI and the engine.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\n/**\n * sentinel's OWN version, for `--version`. We must NOT use\n * `process.env.npm_package_version`, that is the version of whatever script\n * invoked us (an app's package.json, or nothing). Instead walk up from this\n * module to the nearest package.json, which is always sentinel's own, whether\n * running from source or the bundled dist.\n */\n/**\n * sentinel's OWN name + version, read by walking up from this module to the nearest\n * package.json. Used both for `--version` and to pin the exact dependency `--init`\n * writes into an adopted module, so a module always references the version that adopted it.\n */\nexport function readOwnPackage(): { name: string; version: string; bin?: string } {\n let dir = dirname(fileURLToPath(import.meta.url))\n for (;;) {\n const pkgPath = join(dir, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as {\n name?: string\n version?: string\n bin?: string | Record<string, string>\n }\n if (typeof pkg.version === 'string') {\n // The bin PATH, not the command name: a package that adopts itself has to invoke\n // its own build output, because the `.bin` shim does not exist yet (see below).\n const bin = typeof pkg.bin === 'string' ? pkg.bin : Object.values(pkg.bin ?? {})[0]\n return { name: pkg.name ?? '@hublo/sentinel', version: pkg.version, bin }\n }\n } catch {\n // Malformed package.json; keep walking up.\n }\n }\n const parent = dirname(dir)\n if (parent === dir) return { name: '@hublo/sentinel', version: '0.0.0' } // filesystem root\n dir = parent\n }\n}\n\nexport function readOwnVersion(): string {\n return readOwnPackage().version\n}\n\n/**\n * The directory sentinel's own `package.json` sits in, for the files it SHIPS beside its code.\n *\n * ⛔ Walked up to, never computed from a count of `..`. The emitted layout is not ours to predict:\n * `tsup` bundles the source into chunks whose depth has nothing to do with the source tree's, and\n * it moves code between them from one build to the next. A relative path from `import.meta.url` is\n * therefore right in `src/` and wrong in `dist/`, which is exactly the failure\n * `roles/test/shared-test-config.ts` records at length after it cost a module 83 passing tests.\n *\n * Measured here: `plugins/sonar-cognitive.js` resolved through a four-segment relative path existed\n * when run from source and did not after the build, and the only symptom was the whole size pass\n * reporting \"oxlint could not be run\".\n */\nexport function ownPackageDir(): string {\n let dir = dirname(fileURLToPath(import.meta.url))\n for (;;) {\n if (existsSync(join(dir, 'package.json'))) return dir\n const parent = dirname(dir)\n if (parent === dir) return dir\n dir = parent\n }\n}\n\n/**\n * Read a module's package.json for framework detection; tolerant of a missing or\n * malformed file (returns `{}`, so detection falls through to the `node` default).\n */\nexport function readProjectPackageJson(dir: string): {\n /** The package name, which is also what nx calls the project when there is no `project.json`. */\n name?: string\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n /**\n * How the module's `.js`/`.ts` files are loaded. It decides whether a Vite config can import\n * an ESM-only package at all, which is why the build role reads it before rewriting one.\n */\n type?: string\n /**\n * What nx alone needs per target, which every role writes here and none could read back.\n *\n * Typed loosely on purpose: this reader is shared by every role and each one knows the shape of\n * its own target. Declared at all because a role that WRITES a block and then has to cast to\n * read it is one refactor away from reading a key it never wrote.\n */\n nx?: { targets?: Record<string, Record<string, unknown>> }\n /**\n * The npm scripts, which several roles read to know what a module can DO rather than what it is.\n *\n * ⚠️ Added when the bundle pass had to tell two silences apart: a module that declares a build\n * and produced no manifest is a defect to act on, a module that declares none has nothing to\n * measure. Without this the two shared one sentence, and it told a front team their application\n * ships no bundle.\n */\n scripts?: Record<string, string>\n} {\n const path = join(dir, 'package.json')\n if (!existsSync(path)) return {}\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as Record<string, never>\n } catch {\n process.stderr.write(`sentinel: could not parse ${path}; ignoring for detection.\\n`)\n return {}\n }\n}\n\n/**\n * The nx project name for a module, read from its `project.json`, or undefined if\n * there is none/unreadable. Used when `--init` has to scaffold a `package.json`\n * for a module that only has a `project.json` (common for nx apps/services): the\n * scaffolded file borrows this name so it is a valid, uniquely-named workspace\n * package. Reusable by any tool that scaffolds, not just TypeScript.\n */\nexport function readNxProjectName(dir: string): string | undefined {\n const path = join(dir, 'project.json')\n if (!existsSync(path)) return undefined\n try {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as { name?: unknown }\n return typeof parsed.name === 'string' ? parsed.name : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * What nx calls this module, resolved the way nx itself resolves it.\n *\n * The precedence is `project.json`, then `package.json`, then the directory, and only the\n * first and last of those were being consulted. A module with no `project.json` therefore\n * answered with its DIRECTORY while nx answered with its package name, and the two disagree\n * in the real repo: `apps/front/hr-management` is `front-hr-management` to nx, as is\n * `apps/front/storybook-app`.\n *\n * That gap is not cosmetic, because this name is what `--module` is matched against. The\n * `serve` script `--init` writes carries `--module <name>`, so a module in that shape was\n * adopted with a script naming a project the workspace does not contain, and `pnpm run serve`\n * failed the day it was adopted with nothing having reported it.\n *\n * One function so the two ends cannot drift again: whoever WRITES the name and whoever\n * RESOLVES it now read the same source.\n */\nexport function moduleName(dir: string): string {\n const declared = readProjectPackageJson(dir).name\n return readNxProjectName(dir) ?? (declared === undefined ? basename(dir) : declared)\n}\n","/**\n * Tunable settings: the knobs you would actually change. The fixed vocabulary and\n * its types live in `domain.ts`.\n *\n * Note: the preset is DETECTED from a module's dependencies (see\n * `detect-framework.ts`), deterministically, `node` when no framework dep is present.\n * `--preset` overrides the detection (recommended for `--init`, since hoisted deps\n * can make detection return `node`). The detection table lives in `detect-framework.ts`.\n */\n\n/** A file that marks a workspace root; sentinel refuses to operate there. */\nexport const WORKSPACE_ROOT_MARKER = 'nx.json'\n\n/**\n * How many structured diagnostics a report embeds per module, when the caller does not say.\n *\n * A cap, not a limit on what is counted: the totals stay exact and `diagnosticsTruncated`\n * says when rows were dropped, so a bounded envelope never reads as a clean module. Shared\n * by every role, because a consumer reading `--json` across roles should not have to learn\n * a different cap for each one. `--max-diagnostics 0` means no cap.\n */\nexport const DEFAULT_MAX_DIAGNOSTICS = 100\n","/**\n * Workspace-level preparation that `--init` applies once, at the workspace root, so an\n * adopted module actually installs and resolves cleanly. `--init` writes a module's own\n * files; this is the small, deliberate exception where it also touches the root, because\n * \"set this module up\" is not honest if the workspace it lives in cannot then install or\n * resolve it.\n *\n * Kept intentionally narrow (YAGNI): it applies the specific fixes a workspace's OWN\n * config shows it needs, and is a no-op everywhere else. It is NOT a speculative dedupe\n * engine, when a second, different case appears we generalize from real cases instead of\n * predicting them. The two fixes today:\n *\n * - i18next singleton override. If the root declares a second TypeScript via the\n * `@typescript/native` alias (a repo mid-migration running two TypeScripts), adopting a\n * module re-resolves pnpm and i18next, which carries an optional type-only `typescript`\n * peer, forks into two peer-keyed variants. That forks react-i18next into two React\n * contexts and breaks translation-singleton tests. Pinning i18next's `typescript` peer\n * to the declared TS collapses it to one. Read from the root's own declaration, so it\n * tracks the version and disappears (no-op) once the migration removes the second TS.\n * Written to `pnpm-workspace.yaml`, the only place current pnpm reads overrides from.\n *\n * - release-age allow-list. If the root uses pnpm's `minimumReleaseAgeExclude` gate, a\n * freshly published sentinel is younger than the gate and will not install; allow-list\n * it. Only touched when the gate is actually configured.\n *\n * - root formatter exclusion. A module that has adopted the FORMAT role is formatted by\n * oxfmt, from its own config. The root Prettier does not know that and still owns every\n * file in the repo, so `nx format:write` or `prettier --write .` from the root reformats\n * the module back to the ROOT's style, and the next `pnpm run format` in the module\n * reverses it. Two formatters fighting over the same files, with whichever ran last\n * winning, is the exact state adoption removes INSIDE a module, and it has to be removed\n * at the root too. So the module is excluded in the root `.prettierignore` as it adopts,\n * and the root's own config is otherwise untouched: it still serves every module that has\n * not migrated.\n *\n * All three edits are idempotent and defensive: absent the trigger (no second TypeScript, no\n * release-age gate, no root Prettier) each is skipped, so the step is safe on any workspace.\n */\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { dirname, join, relative } from 'node:path'\n\nimport { readOwnPackage } from '../shared/package-json.js'\n\nimport { WORKSPACE_ROOT_MARKER } from './settings.js'\n\nconst OVERRIDE_KEY = 'i18next>typescript'\nconst NATIVE_TS_ALIAS = '@typescript/native' // `npm:typescript@^7.x`: a workspace's second, real TS\nconst WORKSPACE_YAML = 'pnpm-workspace.yaml'\nconst RELEASE_AGE_KEY = 'minimumReleaseAgeExclude'\nconst LIST_ITEM = /^(\\s*)-\\s+(.*?)\\s*$/\nconst MAP_ENTRY = /^(\\s+)(.*?):\\s+(.*?)\\s*$/\n/** A line yaml ignores inside a block: blank, or a comment at any indentation. */\nconst BLANK_OR_COMMENT = /^\\s*(#.*)?$/\n/** A value's trailing ` # comment`, kept apart so an update rewrites the value and nothing else. */\nconst INLINE_COMMENT = /^(.*?)(\\s+#.*)?$/\n\ninterface RootPackageJson {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n pnpm?: { overrides?: Record<string, string> }\n}\n\n/** Walk up from a module directory to the workspace root (the dir holding the marker). */\nexport function findWorkspaceRoot(startDir: string): string | undefined {\n let dir = startDir\n for (;;) {\n if (existsSync(join(dir, WORKSPACE_ROOT_MARKER))) return dir\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n}\n\n/**\n * The TypeScript version to pin i18next's peer to, read from the root's own\n * `@typescript/native` alias (`npm:typescript@^7.0.2` -> `7.0.2`). Returns undefined when\n * the alias is absent (no second TypeScript, so no fork to fix).\n */\nfunction declaredNativeTs(pkg: RootPackageJson): string | undefined {\n const spec = pkg.dependencies?.[NATIVE_TS_ALIAS] ?? pkg.devDependencies?.[NATIVE_TS_ALIAS]\n if (!spec) return undefined\n const version = spec.slice(spec.lastIndexOf('@') + 1).replace(/^[\\^~>=<\\s]+/, '')\n return version || undefined\n}\n\n/**\n * Ensure the i18next singleton override matches the declared second TypeScript. No-op when\n * the workspace runs a single TypeScript (no `@typescript/native`). Returns a message when\n * it changed (or would change, under dryRun), else undefined.\n *\n * The override is written to `pnpm-workspace.yaml`, never to `package.json#pnpm`: pnpm 11\n * stopped reading the `pnpm` field and does so SILENTLY, with no warning and no deprecation\n * (pnpm/pnpm#11536), so an override left in `package.json` is simply not applied. The yaml is\n * read by pnpm 10 and 11 alike (https://pnpm.io/settings), which is why there is one target\n * here rather than a version-dependent fallback.\n */\nfunction ensureI18nextSingleton(root: string, dryRun: boolean): string | undefined {\n const pkgPath = join(root, 'package.json')\n if (!existsSync(pkgPath)) return undefined\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as RootPackageJson\n const want = declaredNativeTs(pkg)\n if (!want) return undefined // single TypeScript: nothing forks\n\n const yamlPath = join(root, WORKSPACE_YAML)\n if (!existsSync(yamlPath)) return undefined // no workspace file: nowhere pnpm would read it\n const lines = readFileSync(yamlPath, 'utf8').split('\\n')\n const entry = findOverrideEntry(lines)\n if (entry.inline) {\n // Said, not skipped silently: the fork this override prevents is still there.\n return `did not pin ${OVERRIDE_KEY} to ${want}: \\`overrides:\\` in ${WORKSPACE_YAML} is written inline, add \\`${OVERRIDE_KEY}: ${want}\\` to it by hand (i18next singleton)`\n }\n if (entry.valueIdx !== undefined && entry.value === want) return undefined // already pinned\n if (dryRun) return `would pin ${OVERRIDE_KEY} to ${want} in ${WORKSPACE_YAML} (i18next singleton)`\n\n applyOverride(lines, entry, want)\n writeFileSync(yamlPath, lines.join('\\n'))\n return `pinned ${OVERRIDE_KEY} to ${want} in ${WORKSPACE_YAML} (i18next singleton)`\n}\n\n/** Where the override sits in the yaml, if at all, plus where a new one would be inserted. */\ninterface OverrideEntry {\n /** Index of the `OVERRIDE_KEY` line, when the key is already declared. */\n valueIdx?: number\n /** Its current value, unquoted, without an inline comment. */\n value?: string\n /** The key exactly as the file spells it (quoted or not), so an update keeps that spelling. */\n rawKey?: string\n /** The value's inline comment, with its leading whitespace, so an update keeps it. */\n comment?: string\n /** Index of the `overrides:` key line, when the block exists. */\n blockIdx?: number\n /** Index of the block's last entry, so an insertion keeps the block contiguous. */\n lastEntryIdx?: number\n /** Indentation the block's entries use. */\n indent: string\n /** `overrides:` is written inline (`overrides: {}`): a line edit cannot add to it safely. */\n inline?: boolean\n}\n\nconst unquote = (text: string): string => text.replace(/^['\"]|['\"]$/g, '')\nconst indentOf = (line: string): number => line.length - line.trimStart().length\n\n/**\n * The indexes of the lines that belong to the top-level block opened at `keyIdx`, blank lines and\n * comments left out.\n *\n * ⚠️ A comment or a blank line never ends a block, at any indentation: yaml ignores both, and the\n * monorepo's `overrides:` OPENS with a two-line comment. An earlier scan stopped at the first line\n * that was not an entry, so on that file it never saw `i18next>typescript`, 85 entries down, and\n * wrote it a second time: a duplicate mapping key, which yaml rejects and `pnpm run format` failed\n * on. The block ends at the first other line indented no deeper than the key. A list may sit at\n * the key's own indentation (`key:` then `- item`), so `sameIndentItems` keeps those lines in.\n */\nfunction blockLines(lines: string[], keyIdx: number, sameIndentItems = false): number[] {\n const keyIndent = indentOf(lines[keyIdx] ?? '')\n const inside: number[] = []\n for (let i = keyIdx + 1; i < lines.length; i++) {\n const line = lines[i] ?? ''\n if (BLANK_OR_COMMENT.test(line)) continue\n const indent = indentOf(line)\n const ownItem = sameIndentItems && indent === keyIndent && /^\\s*-(\\s|$)/.test(line)\n if (indent <= keyIndent && !ownItem) break // the next key: the block ended\n inside.push(i)\n }\n return inside\n}\n\n/**\n * Locate the `overrides:` block and the i18next key inside it. A targeted text read rather\n * than a yaml parse, for the same reason `ensureReleaseAgeAllowList` does it: this file is\n * hand-maintained and round-tripping it through a parser would drop its comments and ordering.\n */\nfunction findOverrideEntry(lines: string[]): OverrideEntry {\n const blockIdx = lines.findIndex((line) => /^overrides:\\s*(#.*)?$/.test(line))\n if (blockIdx === -1) {\n // Declared, but inline (`overrides: {}`). Opening a second block would be a duplicate key.\n const inline = lines.some((line) => /^overrides:\\s*[^\\s#]/.test(line))\n return inline ? { indent: ' ', inline } : { indent: ' ' }\n }\n\n const inside = blockLines(lines, blockIdx)\n // The entries are the lines at the block's own indentation; anything deeper continues one.\n const entryIndent = inside.length > 0 ? indentOf(lines[inside[0] ?? blockIdx] ?? '') : 2\n let lastEntryIdx = blockIdx\n let entry: Omit<OverrideEntry, 'blockIdx' | 'lastEntryIdx' | 'indent'> = {}\n for (const i of inside) {\n lastEntryIdx = i // past a continuation line too, so an insertion never splits an entry\n const match = lines[i]?.match(MAP_ENTRY)\n if (!match || indentOf(lines[i] ?? '') !== entryIndent) continue\n const rawKey = match[2] ?? ''\n if (entry.valueIdx !== undefined || unquote(rawKey) !== OVERRIDE_KEY) continue\n const [, value = '', comment] = (match[3] ?? '').match(INLINE_COMMENT) ?? []\n entry = { valueIdx: i, value: unquote(value), rawKey, comment }\n }\n return { ...entry, blockIdx, lastEntryIdx, indent: ' '.repeat(entryIndent) }\n}\n\n/** Update the key in place, append it to an existing block, or open a block at the end. */\nfunction applyOverride(lines: string[], entry: OverrideEntry, want: string): void {\n if (entry.valueIdx !== undefined) {\n // Only the value changes: the key keeps its spelling, the value its inline comment.\n lines[entry.valueIdx] =\n `${entry.indent}${entry.rawKey ?? `'${OVERRIDE_KEY}'`}: ${want}${entry.comment ?? ''}`\n return\n }\n const line = `${entry.indent}'${OVERRIDE_KEY}': ${want}`\n if (entry.lastEntryIdx !== undefined) {\n lines.splice(entry.lastEntryIdx + 1, 0, line)\n return\n }\n // No `overrides:` block at all: open one, keeping a single trailing newline.\n while (lines.length > 0 && lines[lines.length - 1] === '') lines.pop()\n lines.push('overrides:', line, '')\n}\n\n/**\n * Ensure sentinel is allow-listed under `minimumReleaseAgeExclude` so a fresh publish\n * installs. No-op when the workspace has no such gate. Targeted text edit so comments and\n * formatting are preserved. Returns a message when it changed (or would), else undefined.\n */\nfunction ensureReleaseAgeAllowList(root: string, dryRun: boolean): string | undefined {\n const yamlPath = join(root, WORKSPACE_YAML)\n if (!existsSync(yamlPath)) return undefined\n const own = readOwnPackage().name\n const lines = readFileSync(yamlPath, 'utf8').split('\\n')\n const keyIdx = lines.findIndex((line) => line.replace(/\\s+$/, '') === `${RELEASE_AGE_KEY}:`)\n if (keyIdx === -1) return undefined // no release-age gate in use\n\n // The whole list, comments included: the same early stop as the overrides scan listed\n // sentinel a second time below a comment (see `blockLines`).\n let lastItemIdx = keyIdx\n let indent = ' '\n for (const i of blockLines(lines, keyIdx, true)) {\n lastItemIdx = i\n const match = lines[i]?.match(LIST_ITEM)\n if (!match) continue\n indent = match[1] ?? indent\n const [, item = ''] = (match[2] ?? '').match(INLINE_COMMENT) ?? []\n if (unquote(item) === own) return undefined // already listed\n }\n if (dryRun) return `would allow-list ${own} under ${RELEASE_AGE_KEY}`\n\n lines.splice(lastItemIdx + 1, 0, `${indent}- '${own}'`)\n writeFileSync(yamlPath, lines.join('\\n'))\n return `allow-listed ${own} under ${RELEASE_AGE_KEY} in ${WORKSPACE_YAML}`\n}\n\n/** The root ignore file Prettier reads, and the section sentinel owns inside it. */\nconst GIT_IGNORE = '.gitignore'\n/**\n * The roles that write report files inside a module, the directory each writes, and the header\n * its root ignore line carries. One entry per role, so a new role that writes reports adds a row\n * here and nothing else: the write, the read and the inspection below all walk this table.\n *\n * ⚠️ The static analysis header is kept byte for byte: workspaces adopted before this table hold\n * that exact line, and a reworded header would read as a missing one.\n */\nconst REPORT_DIRS: Readonly<Record<string, { dir: string; header: string; label: string }>> = {\n 'static-analysis': {\n dir: 'static-analysis-report',\n header: '# @hublo/sentinel: static analysis reports, written inside each module',\n label: 'the static analysis role',\n },\n 'code-churn': {\n dir: 'code-churn-report',\n header: '# @hublo/sentinel: code churn reports, written inside each module',\n label: 'the code churn role',\n },\n}\n\n/** Is `dir` ignored by a line of `text`, in whichever spelling a human may have used? */\nconst ignores = (text: string, dir: string): boolean =>\n text.split('\\n').some((line) => line.trim().replace(/^\\//, '').replace(/\\/$/, '') === dir)\nconst PRETTIER_IGNORE = '.prettierignore'\nconst EXCLUSION_HEADER = '# @hublo/sentinel: modules formatted by oxfmt, not by the root Prettier'\n\n/** Root Prettier configs. Their presence is what makes an exclusion meaningful. */\nconst ROOT_PRETTIER_CONFIGS = [\n '.prettierrc',\n '.prettierrc.json',\n '.prettierrc.json5',\n '.prettierrc.yml',\n '.prettierrc.yaml',\n '.prettierrc.js',\n '.prettierrc.cjs',\n '.prettierrc.mjs',\n 'prettier.config.js',\n 'prettier.config.cjs',\n 'prettier.config.mjs',\n]\n\n/**\n * Exclude a module that now formats itself from the ROOT Prettier.\n *\n * Written as a directory pattern anchored at the root (`/apps/front/x/`), which is what\n * gitignore syntax means by \"this exact directory\", so a module cannot accidentally exclude a\n * same-named directory somewhere else.\n *\n * Skipped entirely when the root has no Prettier at all: there is then nothing to conflict\n * with, and creating an ignore file for a tool the workspace does not use would be noise.\n */\nfunction ensureFormatterExclusion(\n root: string,\n moduleDir: string,\n dryRun: boolean,\n): string | undefined {\n const rel = relative(root, moduleDir).replaceAll('\\\\', '/')\n if (rel === '' || rel.startsWith('..')) return undefined // the root itself, or outside it\n\n const ignorePath = join(root, PRETTIER_IGNORE)\n const hasPrettier =\n existsSync(ignorePath) || ROOT_PRETTIER_CONFIGS.some((name) => existsSync(join(root, name)))\n if (!hasPrettier) return undefined\n\n const pattern = `/${rel}/`\n const existing = existsSync(ignorePath) ? readFileSync(ignorePath, 'utf8') : ''\n const lines = existing.split('\\n')\n // Already excluded, in whichever spelling a human may have used.\n if (lines.some((line) => line.trim().replace(/\\/$/, '') === pattern.replace(/\\/$/, ''))) {\n return undefined\n }\n if (dryRun) return `would exclude ${rel} from the root Prettier (${PRETTIER_IGNORE})`\n\n const headerIdx = lines.findIndex((line) => line.trim() === EXCLUSION_HEADER)\n if (headerIdx === -1) {\n const prefix = existing.trim() === '' ? '' : `${existing.replace(/\\n*$/, '')}\\n\\n`\n writeFileSync(ignorePath, `${prefix}${EXCLUSION_HEADER}\\n${pattern}\\n`)\n } else {\n // Keep the managed section together and sorted, so the list stays readable as it grows\n // to 150 entries and a diff shows one added line rather than a reshuffle.\n let end = headerIdx + 1\n while (end < lines.length && lines[end]?.trim().startsWith('/')) end += 1\n const managed = [...lines.slice(headerIdx + 1, end), pattern].sort()\n writeFileSync(\n ignorePath,\n [...lines.slice(0, headerIdx + 1), ...managed, ...lines.slice(end)].join('\\n'),\n )\n }\n return `excluded ${rel} from the root Prettier (${PRETTIER_IGNORE}): it formats itself now`\n}\n\n/**\n * Apply every workspace-level fix the given root needs. Returns the human-readable\n * messages for what changed (empty when nothing did). Under dryRun nothing is written and\n * the messages describe what would change.\n *\n * `formattedModule` is the module that just adopted the FORMAT role, when one did. Absent\n * for an `--init` that adopted neither lint nor format (`--init --typescript`, say), because\n * a module that has not adopted the formatter must keep being formatted by the root. There is\n * no lint-only `--init` any more: naming lint adopts format with it (see `run-init`), so the\n * module that gets oxlint also gets oxfmt and this exclusion.\n */\n/**\n * Ignore the static analysis report directory, once, at the ROOT.\n *\n * ## Why the root and not each module\n *\n * The role writes its json and html into `<module>/static-analysis-report/`, so the obvious place\n * for the rule is the module. It was there first, and it was wrong twice over: it CREATES a\n * `.gitignore` in a module that had none, which is a structural change to someone else's module for\n * one line, and it repeats that line once per adopting module. The root already ignores output this\n * way, with `/dist` and `/coverage`.\n *\n * ⚠️ The pattern is deliberately NOT anchored. `/dist` matches only the root's `dist`; the report\n * directory lives inside a module, so `static-analysis-report/` has to match at any depth. Getting\n * that backwards would leave every adopting module with an untracked directory, which is the exact\n * defect this guards against.\n *\n * ## Why this root write is not the dangerous kind\n *\n * The comment on `inspectWorkspacePrep` is right that root writes are what nobody sees afterwards,\n * and the i18next override earned that warning: it re-resolved a module from a pull request that\n * touched none of its files. An ignore line changes no resolution, no build and no install. If it\n * ever goes stale the cost is one unused line, which is why it is reported rather than feared.\n */\nfunction ensureReportIgnored(root: string, role: string, dryRun: boolean): string | undefined {\n const entry = REPORT_DIRS[role]\n if (entry === undefined) return undefined\n const pattern = `${entry.dir}/`\n const path = join(root, GIT_IGNORE)\n const existing = existsSync(path) ? readFileSync(path, 'utf8') : ''\n if (ignores(existing, entry.dir)) return undefined\n if (dryRun) return `would ignore ${pattern} in the root ${GIT_IGNORE}`\n\n const prefix = existing.trim() === '' ? '' : `${existing.replace(/\\n*$/, '')}\\n\\n`\n writeFileSync(path, `${prefix}${entry.header}\\n${pattern}\\n`)\n return `ignored ${pattern} in the root ${GIT_IGNORE}`\n}\n\nexport function ensureWorkspacePrep(opts: {\n root: string\n dryRun?: boolean\n formattedModule?: string\n /** The roles that adopted on this run: a role writing reports earns its ignore line. */\n adoptedRoles?: readonly string[]\n}): string[] {\n const dryRun = Boolean(opts.dryRun)\n return [\n ensureI18nextSingleton(opts.root, dryRun),\n ensureReleaseAgeAllowList(opts.root, dryRun),\n opts.formattedModule === undefined\n ? undefined\n : ensureFormatterExclusion(opts.root, opts.formattedModule, dryRun),\n ...Object.keys(REPORT_DIRS)\n .filter((role) => opts.adoptedRoles?.includes(role) === true)\n .map((role) => ensureReportIgnored(opts.root, role, dryRun)),\n ].filter((message): message is string => message !== undefined)\n}\n\n/**\n * One standing change sentinel has made to the workspace ROOT, and whether it is still earned.\n *\n * This exists because the three root writes are the only thing sentinel does that nobody can\n * see afterwards. `--init` announces each one on the run that makes it, and then it is a line\n * in someone else's file forever. Two consequences already bit us.\n *\n * The `i18next>typescript` override re-resolved `apps/front/console` from a PR that touched no\n * file under it, so CODEOWNERS pulled nobody and its owners learned about it afterwards.\n *\n * And every one of them is TEMPORARY with its removal condition written in prose. That failed\n * three times in one week: `SENTINEL_TAG=alpha` in the migration-page workflow kept building\n * with a pre-release long after 1.1.0 went stable and reported `Format 0/439` for 15 adopted\n * modules; ADR 0042 and its RFC both sat mid-flight past their deadline; and this release-age\n * exclusion is still waiting on \"once sentinel's release cadence settles\". Nothing failed when\n * any of them expired, because a comment cannot fail.\n *\n * So each entry carries the condition that JUSTIFIES it, evaluated now rather than described.\n * A trigger that has gone away makes the entry dead config, and dead config is something a\n * command can say out loud instead of something a reader has to notice.\n *\n * Read-only, and offline: it inspects the same files `--init` writes and nothing else. What it\n * deliberately does NOT claim is anything needing the npm registry — whether a published\n * version is old enough to clear the release-age gate is not knowable from the repo, so it is\n * stated as the standing exemption it is rather than guessed at.\n */\nexport interface WorkspacePrepEntry {\n /** `rule` to match the shape the shared renderer already prints as a labelled block. */\n rule: string\n /** What it does, whether its trigger still holds, and what would retire it. */\n reason: string\n}\n\n/** The root-level changes sentinel maintains here, each with its justification checked now. */\nexport function inspectWorkspacePrep(root: string): WorkspacePrepEntry[] {\n const entries: WorkspacePrepEntry[] = []\n // Tolerant, unlike the write path above, and the difference is deliberate. `--init` should\n // fail loudly on a root it cannot parse, because it is about to edit it. `--inspect` is a\n // read verb that sweeps 441 modules, and one malformed root file must not take the whole\n // sweep down: the modules still have honest answers to give. Caught by its own test.\n let pkg: RootPackageJson = {}\n const pkgPath = join(root, 'package.json')\n if (existsSync(pkgPath)) {\n try {\n pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as RootPackageJson\n } catch {\n pkg = {}\n }\n }\n\n const yamlPath = join(root, WORKSPACE_YAML)\n const yaml = existsSync(yamlPath) ? readFileSync(yamlPath, 'utf8') : undefined\n\n const pinned = yaml === undefined ? undefined : findOverrideEntry(yaml.split('\\n')).value\n if (pinned !== undefined) {\n const stillForks = declaredNativeTs(pkg)\n entries.push({\n rule: `${WORKSPACE_YAML} → overrides.${OVERRIDE_KEY}`,\n reason:\n stillForks === undefined\n ? `pinned to ${pinned}, but the root no longer declares ${NATIVE_TS_ALIAS}, so nothing ` +\n `forks any more. This override is now dead config and can be removed.`\n : `pinned to ${pinned}, matching the second TypeScript the root declares ` +\n `(${NATIVE_TS_ALIAS}). It re-resolves i18next for EVERY module that depends on it, ` +\n `not only adopted ones. It retires with the second TypeScript.`,\n })\n }\n\n // A copy left in `package.json#pnpm` by an older sentinel, or by hand. Reported because it\n // is INERT rather than redundant: pnpm 11 dropped the `pnpm` field with no warning\n // (pnpm/pnpm#11536), so it reads as protection that is not applied.\n const legacy = pkg.pnpm?.overrides?.[OVERRIDE_KEY]\n if (legacy !== undefined) {\n entries.push({\n rule: `package.json → pnpm.overrides.${OVERRIDE_KEY}`,\n reason:\n `pinned to ${legacy}, but pnpm 11 no longer reads the \\`pnpm\\` field of package.json ` +\n `and says nothing about it, so this override is not applied. Move it to ` +\n `${WORKSPACE_YAML} under \\`overrides:\\`, which pnpm 10 and 11 both read.`,\n })\n }\n\n const ignorePath = join(root, GIT_IGNORE)\n if (existsSync(ignorePath)) {\n const ignoreText = readFileSync(ignorePath, 'utf8')\n for (const [role, entry] of Object.entries(REPORT_DIRS)) {\n if (!ignores(ignoreText, entry.dir)) continue\n const pattern = `${entry.dir}/`\n entries.push({\n rule: `${GIT_IGNORE} → ${pattern}`,\n reason:\n `${entry.label} writes its report files into ` +\n `\\`<module>/${pattern}\\`, and one unanchored line at the root covers every module ` +\n `instead of creating a \\`${GIT_IGNORE}\\` in each one. Unlike the override above it changes ` +\n `no resolution and no build, so a stale one costs a single unused line. It retires when no ` +\n `module declares a \\`${role}\\` script any more, which the adoption report counts ` +\n `and this read deliberately does not: it would have to sweep every module.`,\n })\n }\n }\n\n const own = readOwnPackage().name\n if (yaml !== undefined) {\n const listed = new RegExp(`^\\\\s*-\\\\s*['\"]?${own.replace('/', '\\\\/')}['\"]?\\\\s*$`, 'm').test(yaml)\n if (listed) {\n const gated = new RegExp(`^\\\\s*minimumReleaseAge\\\\s*:`, 'm').test(yaml)\n entries.push({\n rule: `${WORKSPACE_YAML} → ${RELEASE_AGE_KEY}: ${own}`,\n reason: gated\n ? `${own} is exempt from this workspace's release-age gate, so a freshly published ` +\n `version installs instead of being held. That is a standing exemption from a ` +\n `supply-chain control: the exposure is one bump wide, since the version is pinned ` +\n `and the lockfile carries its integrity, so a re-publish of the same version does ` +\n `not pass. Retire it once a bump can simply wait out the window.`\n : `${own} is allow-listed, but this workspace no longer sets minimumReleaseAge, so ` +\n `there is no gate to be exempt from. This entry is now dead config and can be removed.`,\n })\n }\n }\n\n return entries\n}\n"],"mappings":";AAGA,SAAS,YAAY,oBAAoB;AACzC,SAAS,UAAU,SAAS,YAAY;AACxC,SAAS,qBAAqB;AAcvB,SAAS,iBAAkE;AAChF,MAAI,MAAM,QAAQ,cAAc,YAAY,GAAG,CAAC;AACh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AG,EAAG;AACrC,YAAM,UAAU,GAAG,MAAM,GAAG;AAC5B,cAAQ,KAAK;AAAA,QACX,MAAM,GAAG,UAAU,WAAM,OAAO;AAAA,QAChC,QACE,GAAG,MAAM,KAAK,4CACA,OAAO,uFACM,UAAU,sKAEd,IAAI;AAAA,MAE/B,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,MAAM,eAAe,EAAE;AAC7B,MAAI,SAAS,QAAW;AACtB,UAAM,SAAS,IAAI,OAAO,kBAAkB,IAAI,QAAQ,KAAK,KAAK,CAAC,cAAc,GAAG,EAAE,KAAK,IAAI;AAC/F,QAAI,QAAQ;AACV,YAAM,QAAQ,IAAI,OAAO,+BAA+B,GAAG,EAAE,KAAK,IAAI;AACtE,cAAQ,KAAK;AAAA,QACX,MAAM,GAAG,cAAc,WAAM,eAAe,KAAK,GAAG;AAAA,QACpD,QAAQ,QACJ,GAAG,GAAG,4XAKN,GAAG,GAAG;AAAA,MAEZ,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SAAO;AACT;","names":["existsSync","readFileSync","dirname","join","existsSync","join","dirname","readFileSync"]}
@@ -0,0 +1,126 @@
1
+ import {
2
+ isPlainObject
3
+ } from "./chunk-PXTU5MPW.js";
4
+
5
+ // src/roles/code-churn/presets/shared.json
6
+ var shared_default = {
7
+ window: {
8
+ reworkDays: 21,
9
+ periodDays: 90
10
+ },
11
+ maxFilesPerCommit: 100,
12
+ levels: {
13
+ minimumAdded: 500,
14
+ low: 3,
15
+ above: 11,
16
+ watch: 16
17
+ },
18
+ include: ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,svelte,vue}"],
19
+ includeTests: false,
20
+ tests: [
21
+ "**/{test,tests,__tests__,e2e,fixtures,mocks,__mocks__,test-utils}/**",
22
+ "**/*.{spec,test,integration-spec,e2e-spec,steps,test-util,mock}.{ts,tsx,mts,cts,js,jsx}"
23
+ ],
24
+ ignore: [
25
+ "**/node_modules/**",
26
+ "**/dist/**",
27
+ "**/build/**",
28
+ "**/coverage/**",
29
+ "**/*.d.{ts,mts,cts}",
30
+ "**/*.generated.*",
31
+ "**/*.gen.*",
32
+ "**/generated/**"
33
+ ],
34
+ listed: 10
35
+ };
36
+
37
+ // src/roles/code-churn/preset-data.ts
38
+ var TARGET = "code-churn";
39
+ var CODE_CHURN_CONFIG_FILE = "code-churn.config.mjs";
40
+ var REPORT_DIR = "code-churn-report";
41
+ var SCRIPTS = {
42
+ console: "code-churn",
43
+ json: "code-churn:json",
44
+ html: "code-churn:html"
45
+ };
46
+ var defaults = shared_default;
47
+
48
+ // src/roles/code-churn/configs/define.ts
49
+ function mergeInto(base, patch) {
50
+ if (!isPlainObject(patch)) return base;
51
+ if (!isPlainObject(base)) return patch;
52
+ const out = { ...base };
53
+ for (const [key, value] of Object.entries(patch)) {
54
+ out[key] = isPlainObject(value) ? mergeInto(out[key], value) : value;
55
+ }
56
+ return out;
57
+ }
58
+ function leafPaths(patch, prefix = "") {
59
+ if (!isPlainObject(patch)) return prefix ? [prefix] : [];
60
+ return Object.entries(patch).flatMap(
61
+ ([key, value]) => leafPaths(value, prefix ? `${prefix}.${key}` : key)
62
+ );
63
+ }
64
+ function defineCodeChurn(input = {}) {
65
+ return {
66
+ ...mergeInto(defaults, input.overrides),
67
+ root: input.root ?? null,
68
+ moved: leafPaths(input.overrides).sort()
69
+ };
70
+ }
71
+ function invalidSettings(config) {
72
+ const problems = [];
73
+ const positive = (path, value) => {
74
+ if (!Number.isInteger(value) || value < 1) {
75
+ problems.push(`${path} must be a whole number of 1 or more, got ${JSON.stringify(value)}`);
76
+ }
77
+ };
78
+ const strings = (path, value, allowEmpty) => {
79
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
80
+ problems.push(`${path} must be a list of globs, got ${JSON.stringify(value)}`);
81
+ } else if (!allowEmpty && value.length === 0) {
82
+ problems.push(`${path} must name at least one glob, or nothing is measured`);
83
+ }
84
+ };
85
+ positive("window.reworkDays", config.window?.reworkDays);
86
+ positive("window.periodDays", config.window?.periodDays);
87
+ positive("maxFilesPerCommit", config.maxFilesPerCommit);
88
+ positive("levels.minimumAdded", config.levels?.minimumAdded);
89
+ const percentage = (path, value) => {
90
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 100) {
91
+ problems.push(
92
+ `${path} must be a percentage above 0 and at most 100, got ${JSON.stringify(value)}`
93
+ );
94
+ }
95
+ };
96
+ percentage("levels.low", config.levels?.low);
97
+ percentage("levels.above", config.levels?.above);
98
+ percentage("levels.watch", config.levels?.watch);
99
+ const { low, above, watch } = config.levels ?? {};
100
+ if (typeof low === "number" && typeof above === "number" && typeof watch === "number" && !(low < above && above < watch)) {
101
+ problems.push(`levels must rise: low < above < watch, got ${low}, ${above}, ${watch}`);
102
+ }
103
+ if (!Number.isInteger(config.listed) || config.listed < 0) {
104
+ problems.push(
105
+ `listed must be a whole number of 0 or more, got ${JSON.stringify(config.listed)}`
106
+ );
107
+ }
108
+ if (typeof config.includeTests !== "boolean") {
109
+ problems.push(`includeTests must be true or false, got ${JSON.stringify(config.includeTests)}`);
110
+ }
111
+ strings("include", config.include, false);
112
+ strings("tests", config.tests, true);
113
+ strings("ignore", config.ignore, true);
114
+ return problems;
115
+ }
116
+
117
+ export {
118
+ TARGET,
119
+ CODE_CHURN_CONFIG_FILE,
120
+ REPORT_DIR,
121
+ SCRIPTS,
122
+ defaults,
123
+ defineCodeChurn,
124
+ invalidSettings
125
+ };
126
+ //# sourceMappingURL=chunk-XYOIXC6A.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/roles/code-churn/presets/shared.json","../src/roles/code-churn/preset-data.ts","../src/roles/code-churn/configs/define.ts"],"sourcesContent":["{\n \"window\": {\n \"reworkDays\": 21,\n \"periodDays\": 90\n },\n \"maxFilesPerCommit\": 100,\n \"levels\": {\n \"minimumAdded\": 500,\n \"low\": 3,\n \"above\": 11,\n \"watch\": 16\n },\n \"include\": [\"**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,svelte,vue}\"],\n \"includeTests\": false,\n \"tests\": [\n \"**/{test,tests,__tests__,e2e,fixtures,mocks,__mocks__,test-utils}/**\",\n \"**/*.{spec,test,integration-spec,e2e-spec,steps,test-util,mock}.{ts,tsx,mts,cts,js,jsx}\"\n ],\n \"ignore\": [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/coverage/**\",\n \"**/*.d.{ts,mts,cts}\",\n \"**/*.generated.*\",\n \"**/*.gen.*\",\n \"**/generated/**\"\n ],\n \"listed\": 10\n}\n","/**\n * The code churn role's values: what it reads, where it writes, and what a module may move.\n *\n * ## What this role measures\n *\n * Code churn in the sense Sourcegraph and DevStats give it: of the lines a module ADDED in a period,\n * the share that was rewritten or deleted within a few weeks of being written. A line rewritten\n * days after it landed is work done twice, which is what the figure is about, and a module whose\n * share is high is one where the code is written before what it must do is settled.\n *\n * It reads the git history and nothing else: no build, no test run, no network. The static\n * analysis role answers what the code IS today; this one answers how it got there. The two are\n * separate roles because one reads the tree and the other reads the history, and a module adopts\n * either without the other (HUB-46818, hublo/sentinel#98).\n *\n * ## Which modules: the ones that hold code\n *\n * Every preset, like the static analysis role: rework is the same question whatever the stack. A\n * module with no file the role reads is skipped by `--init`, and said so.\n */\nimport sharedData from './presets/shared.json'\n\n/** The target this role serves, and the flag that runs it: `sentinel --run --code-churn`. */\nexport const TARGET = 'code-churn'\n\n/** The file a module writes at its root to move a setting. Optional at every moment. */\nexport const CODE_CHURN_CONFIG_FILE = 'code-churn.config.mjs'\n\n/**\n * Where the files of `--output json|html|markdown` land, inside the module.\n *\n * Its own directory rather than `static-analysis-report/`: two roles writing into one folder would\n * each clear the other's stale files.\n */\nexport const REPORT_DIR = 'code-churn-report'\n\n/**\n * One script per shape a DEVELOPER runs. `markdown` gets none: it is the pull request comment a CI\n * workflow produces, the decision static analysis took for the same reason.\n */\nexport const SCRIPTS = {\n console: 'code-churn',\n json: 'code-churn:json',\n html: 'code-churn:html',\n} as const\n\nexport interface CodeChurnDefaults {\n /** The two durations the figure is made of, in days. */\n window: {\n /**\n * How long after a line is written a change to it counts as rework. 21 days, the window\n * Sourcegraph uses (\"code rewritten or deleted within three weeks of being written\"); DevStats\n * gives 14 to 21. A change after it is maintenance, not rework, and is not counted.\n */\n reworkDays: number\n /**\n * How far back the lines that are measured were written, in days, ending `reworkDays` before\n * the newest commit read. The period stops there so every line it holds has had its full\n * window: a line written yesterday cannot have been rewritten yet, and counting it would lower\n * the figure for a reason that has nothing to do with the code.\n */\n periodDays: number\n }\n /**\n * A commit that touches more files than this IN THE MODULE is a sweep, a formatter run or a\n * rename sweep, and its lines are not counted. Counted in the module and not in the repository,\n * which was measured: see `churn.ts`, \"What is not counted\".\n */\n maxFilesPerCommit: number\n /**\n * Where a module's figure stands, in percent, and below how many added lines it has none.\n *\n * Calibrated on hublo/monorepo `main` f12da701121 (2026-07-28 to 2026-10-26): of the 113 sentinel\n * modules, 33 added no line and 44 fewer than 500 (26 in the median), where one rewrite moves the\n * figure by points; over the 36 others, the 25th, 75th and 90th percentiles are 3.1, 11.4 and\n * 15.9%, rounded DOWN to 3, 11 and 16. They say where a module stands among those modules, never\n * whether its code is good, and are recalibrated by a sweep at each stable release.\n */\n levels: {\n /** Below this many lines added in the period, the module is `quiet`: no percentage stated. */\n minimumAdded: number\n /** Under this, `low`. */\n low: number\n /** Over this, `above`. Between `low` and it, `usual`. */\n above: number\n /** Over this, `watch`. */\n watch: number\n }\n /** The files whose lines are measured, as globs relative to the module. */\n include: string[]\n /**\n * Measure the tests too. OFF by default: the figure is about the product code, and a test\n * rewritten with the code it checks is the expected case, not rework. A module that decides\n * otherwise sets it to true, and the report says so.\n */\n includeTests: boolean\n /** What counts as a test, by path. The list the sql role measured, extended to JavaScript. */\n tests: string[]\n /**\n * Files never measured, whatever `include` says: generated and built output. `*.gen.*` is\n * TanStack Router's `routeTree.gen.ts`, regenerated on every route change (career, console and\n * host-admin on hublo/monorepo): measured, it was one of host-admin's most changed files.\n */\n ignore: string[]\n /** How many files the report lists, highest churn first. */\n listed: number\n}\n\n/**\n * The role's values, read from `presets/shared.json`: preset data is JSON, never TypeScript, in every\n * role (AGENTS.md, and `tests/role-layout.test.ts` holds it). The reasons for each value are the\n * comments on `CodeChurnDefaults` above, since JSON carries none.\n */\nexport const defaults: CodeChurnDefaults = sharedData as CodeChurnDefaults\n","/**\n * `defineCodeChurn`: what a module imports to declare its own code churn settings.\n *\n * ```js\n * // code-churn.config.mjs\n * import { defineCodeChurn } from '@hublo/sentinel/code-churn'\n *\n * export default defineCodeChurn({\n * root: import.meta.dirname,\n * overrides: { window: { periodDays: 180 } },\n * })\n * ```\n *\n * The shape of `defineStaticAnalysis` and `defineSql`, for the two reasons stated there. A function\n * receives the module's INTENT, the keys it actually passed, and merges them here, so setting one\n * key never drops its siblings: a spread in the module's file would replace the whole `window` block\n * to set `periodDays`, and lose `reworkDays` with nobody seeing it. And the defaults are never\n * copied into a module, so a changed default reaches every module at the next release instead of\n * leaving stale copies behind.\n *\n * `overrides` REPLACES what it names, lists included, and every path it sets lands in `moved`, so\n * the report prints `(module)` beside it: two modules measured with different windows no longer\n * compare, and the reader has to be told.\n */\nimport { isPlainObject } from '../../../shared/deep-merge.js'\nimport { defaults, type CodeChurnDefaults } from '../preset-data.js'\n\ntype DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] }\n\n/** What a module's config file passes. Everything is optional, including the file itself. */\nexport interface CodeChurnInput {\n /** The module's own directory, normally `import.meta.dirname`. */\n root?: string\n /** The seam. Replaces whatever it names, and every path it sets lands in `moved`. */\n overrides?: DeepPartial<CodeChurnDefaults>\n}\n\nexport interface ResolvedCodeChurnConfig extends CodeChurnDefaults {\n /** The module's directory, or null when its config file did not say. */\n root: string | null\n /** Dotted paths the module set through `overrides`, sorted so two runs print the same report. */\n moved: string[]\n}\n\n/**\n * Merge `patch` into `base`, recursively, patch winning.\n *\n * Arrays are REPLACED, never concatenated: a merge that concatenates cannot express \"replace this\n * list\", which is exactly what a team reaching for `overrides` asks for.\n */\nfunction mergeInto<T>(base: T, patch: unknown): T {\n if (!isPlainObject(patch)) return base\n if (!isPlainObject(base)) return patch as T\n const out: Record<string, unknown> = { ...base }\n for (const [key, value] of Object.entries(patch)) {\n out[key] = isPlainObject(value) ? mergeInto(out[key], value) : value\n }\n return out as T\n}\n\n/** Every leaf path in `patch`, dotted, so a reader can be told what the module decided. */\nfunction leafPaths(patch: unknown, prefix = ''): string[] {\n if (!isPlainObject(patch)) return prefix ? [prefix] : []\n return Object.entries(patch).flatMap(([key, value]) =>\n leafPaths(value, prefix ? `${prefix}.${key}` : key),\n )\n}\n\n/** Resolve a module's declaration against this role's defaults. */\nexport function defineCodeChurn(input: CodeChurnInput = {}): ResolvedCodeChurnConfig {\n return {\n ...mergeInto(defaults, input.overrides),\n root: input.root ?? null,\n moved: leafPaths(input.overrides).sort(),\n }\n}\n\n/**\n * The settings of a resolved config that cannot be measured with, one sentence each naming the\n * setting and the value. Empty when the config is usable.\n *\n * ⛔ Checked rather than trusted: a negative window runs the period into the future, a `listed` of\n * -1 drops the last file through `slice(0, -1)`, a cap of 0 makes every commit a sweep, an empty\n * `include` measures nothing, levels that do not rise put every module in two bands at once, and\n * none of them says so. Each one is a figure that looks right.\n */\nexport function invalidSettings(config: CodeChurnDefaults): string[] {\n const problems: string[] = []\n const positive = (path: string, value: unknown): void => {\n if (!Number.isInteger(value) || (value as number) < 1) {\n problems.push(`${path} must be a whole number of 1 or more, got ${JSON.stringify(value)}`)\n }\n }\n const strings = (path: string, value: unknown, allowEmpty: boolean): void => {\n if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {\n problems.push(`${path} must be a list of globs, got ${JSON.stringify(value)}`)\n } else if (!allowEmpty && value.length === 0) {\n problems.push(`${path} must name at least one glob, or nothing is measured`)\n }\n }\n positive('window.reworkDays', config.window?.reworkDays)\n positive('window.periodDays', config.window?.periodDays)\n positive('maxFilesPerCommit', config.maxFilesPerCommit)\n positive('levels.minimumAdded', config.levels?.minimumAdded)\n const percentage = (path: string, value: unknown): void => {\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value > 100) {\n problems.push(\n `${path} must be a percentage above 0 and at most 100, got ${JSON.stringify(value)}`,\n )\n }\n }\n percentage('levels.low', config.levels?.low)\n percentage('levels.above', config.levels?.above)\n percentage('levels.watch', config.levels?.watch)\n const { low, above, watch } = config.levels ?? {}\n if (\n typeof low === 'number' &&\n typeof above === 'number' &&\n typeof watch === 'number' &&\n !(low < above && above < watch)\n ) {\n problems.push(`levels must rise: low < above < watch, got ${low}, ${above}, ${watch}`)\n }\n if (!Number.isInteger(config.listed) || config.listed < 0) {\n problems.push(\n `listed must be a whole number of 0 or more, got ${JSON.stringify(config.listed)}`,\n )\n }\n if (typeof config.includeTests !== 'boolean') {\n problems.push(`includeTests must be true or false, got ${JSON.stringify(config.includeTests)}`)\n }\n strings('include', config.include, false)\n strings('tests', config.tests, true)\n strings('ignore', config.ignore, true)\n return problems\n}\n"],"mappings":";;;;;AAAA;AAAA,EACE,QAAU;AAAA,IACR,YAAc;AAAA,IACd,YAAc;AAAA,EAChB;AAAA,EACA,mBAAqB;AAAA,EACrB,QAAU;AAAA,IACR,cAAgB;AAAA,IAChB,KAAO;AAAA,IACP,OAAS;AAAA,IACT,OAAS;AAAA,EACX;AAAA,EACA,SAAW,CAAC,iDAAiD;AAAA,EAC7D,cAAgB;AAAA,EAChB,OAAS;AAAA,IACP;AAAA,IACA;AAAA,EACF;AAAA,EACA,QAAU;AAAA,IACR;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,QAAU;AACZ;;;ACNO,IAAM,SAAS;AAGf,IAAM,yBAAyB;AAQ/B,IAAM,aAAa;AAMnB,IAAM,UAAU;AAAA,EACrB,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AACR;AAqEO,IAAM,WAA8B;;;AC/D3C,S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ts CHANGED
@@ -32,7 +32,7 @@ declare function registerAdapters(): void;
32
32
  declare const VERBS: readonly ["run", "inspect", "init", "migrate", "validate", "report", "status"];
33
33
  type Verb = (typeof VERBS)[number];
34
34
  /** Targets: the kind of check. The CLI `--<target>` flags map 1:1 to these. */
35
- declare const TARGETS: readonly ["lint", "format", "typescript", "build", "dev", "test", "static-analysis", "sql", "env", "runtime-analysis", "arch"];
35
+ declare const TARGETS: readonly ["lint", "format", "typescript", "build", "dev", "test", "static-analysis", "code-churn", "env", "runtime-analysis", "arch"];
36
36
  type Target = (typeof TARGETS)[number];
37
37
  /** Presets: the stack preset a project resolves to (strict by default). */
38
38
  declare const PRESET_NAMES: readonly ["react", "nest", "svelte", "node", "tools"];
package/dist/index.js CHANGED
@@ -6,13 +6,13 @@ import {
6
6
  registerAdapters,
7
7
  resolve,
8
8
  setDefaultRunner
9
- } from "./chunk-B3Y7F7BA.js";
9
+ } from "./chunk-RI7R3S3T.js";
10
10
  import {
11
11
  BaseAdapter
12
- } from "./chunk-AVT5FSPO.js";
13
- import "./chunk-JT7ZMH44.js";
14
- import "./chunk-LX7EG6PJ.js";
15
- import "./chunk-NGLEGAEN.js";
12
+ } from "./chunk-UVXXEAHU.js";
13
+ import "./chunk-XTBHIKFG.js";
14
+ import "./chunk-BBNABWZ6.js";
15
+ import "./chunk-XYOIXC6A.js";
16
16
  import "./chunk-PXTU5MPW.js";
17
17
  import "./chunk-4EIY7TTR.js";
18
18
  import "./chunk-O7REVMOC.js";
@@ -0,0 +1,92 @@
1
+ interface CodeChurnDefaults {
2
+ /** The two durations the figure is made of, in days. */
3
+ window: {
4
+ /**
5
+ * How long after a line is written a change to it counts as rework. 21 days, the window
6
+ * Sourcegraph uses ("code rewritten or deleted within three weeks of being written"); DevStats
7
+ * gives 14 to 21. A change after it is maintenance, not rework, and is not counted.
8
+ */
9
+ reworkDays: number;
10
+ /**
11
+ * How far back the lines that are measured were written, in days, ending `reworkDays` before
12
+ * the newest commit read. The period stops there so every line it holds has had its full
13
+ * window: a line written yesterday cannot have been rewritten yet, and counting it would lower
14
+ * the figure for a reason that has nothing to do with the code.
15
+ */
16
+ periodDays: number;
17
+ };
18
+ /**
19
+ * A commit that touches more files than this IN THE MODULE is a sweep, a formatter run or a
20
+ * rename sweep, and its lines are not counted. Counted in the module and not in the repository,
21
+ * which was measured: see `churn.ts`, "What is not counted".
22
+ */
23
+ maxFilesPerCommit: number;
24
+ /**
25
+ * Where a module's figure stands, in percent, and below how many added lines it has none.
26
+ *
27
+ * Calibrated on hublo/monorepo `main` f12da701121 (2026-07-28 to 2026-10-26): of the 113 sentinel
28
+ * modules, 33 added no line and 44 fewer than 500 (26 in the median), where one rewrite moves the
29
+ * figure by points; over the 36 others, the 25th, 75th and 90th percentiles are 3.1, 11.4 and
30
+ * 15.9%, rounded DOWN to 3, 11 and 16. They say where a module stands among those modules, never
31
+ * whether its code is good, and are recalibrated by a sweep at each stable release.
32
+ */
33
+ levels: {
34
+ /** Below this many lines added in the period, the module is `quiet`: no percentage stated. */
35
+ minimumAdded: number;
36
+ /** Under this, `low`. */
37
+ low: number;
38
+ /** Over this, `above`. Between `low` and it, `usual`. */
39
+ above: number;
40
+ /** Over this, `watch`. */
41
+ watch: number;
42
+ };
43
+ /** The files whose lines are measured, as globs relative to the module. */
44
+ include: string[];
45
+ /**
46
+ * Measure the tests too. OFF by default: the figure is about the product code, and a test
47
+ * rewritten with the code it checks is the expected case, not rework. A module that decides
48
+ * otherwise sets it to true, and the report says so.
49
+ */
50
+ includeTests: boolean;
51
+ /** What counts as a test, by path. The list the sql role measured, extended to JavaScript. */
52
+ tests: string[];
53
+ /**
54
+ * Files never measured, whatever `include` says: generated and built output. `*.gen.*` is
55
+ * TanStack Router's `routeTree.gen.ts`, regenerated on every route change (career, console and
56
+ * host-admin on hublo/monorepo): measured, it was one of host-admin's most changed files.
57
+ */
58
+ ignore: string[];
59
+ /** How many files the report lists, highest churn first. */
60
+ listed: number;
61
+ }
62
+
63
+ type DeepPartial<T> = {
64
+ [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
65
+ };
66
+ /** What a module's config file passes. Everything is optional, including the file itself. */
67
+ interface CodeChurnInput {
68
+ /** The module's own directory, normally `import.meta.dirname`. */
69
+ root?: string;
70
+ /** The seam. Replaces whatever it names, and every path it sets lands in `moved`. */
71
+ overrides?: DeepPartial<CodeChurnDefaults>;
72
+ }
73
+ interface ResolvedCodeChurnConfig extends CodeChurnDefaults {
74
+ /** The module's directory, or null when its config file did not say. */
75
+ root: string | null;
76
+ /** Dotted paths the module set through `overrides`, sorted so two runs print the same report. */
77
+ moved: string[];
78
+ }
79
+ /** Resolve a module's declaration against this role's defaults. */
80
+ declare function defineCodeChurn(input?: CodeChurnInput): ResolvedCodeChurnConfig;
81
+ /**
82
+ * The settings of a resolved config that cannot be measured with, one sentence each naming the
83
+ * setting and the value. Empty when the config is usable.
84
+ *
85
+ * ⛔ Checked rather than trusted: a negative window runs the period into the future, a `listed` of
86
+ * -1 drops the last file through `slice(0, -1)`, a cap of 0 makes every commit a sweep, an empty
87
+ * `include` measures nothing, levels that do not rise put every module in two bands at once, and
88
+ * none of them says so. Each one is a figure that looks right.
89
+ */
90
+ declare function invalidSettings(config: CodeChurnDefaults): string[];
91
+
92
+ export { type CodeChurnInput, type ResolvedCodeChurnConfig, defineCodeChurn, invalidSettings };
@@ -0,0 +1,10 @@
1
+ import {
2
+ defineCodeChurn,
3
+ invalidSettings
4
+ } from "../../chunk-XYOIXC6A.js";
5
+ import "../../chunk-PXTU5MPW.js";
6
+ export {
7
+ defineCodeChurn,
8
+ invalidSettings
9
+ };
10
+ //# sourceMappingURL=config.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  defineStaticAnalysis
3
- } from "../../chunk-LX7EG6PJ.js";
3
+ } from "../../chunk-BBNABWZ6.js";
4
4
  import "../../chunk-PXTU5MPW.js";
5
5
  export {
6
6
  defineStaticAnalysis
@@ -7,9 +7,9 @@ import {
7
7
  } from "../../../chunk-NUOQXAYR.js";
8
8
  import {
9
9
  installWorkspaceSetup
10
- } from "../../../chunk-PMRL4MH6.js";
10
+ } from "../../../chunk-J2RMARWP.js";
11
11
  import "../../../chunk-ELZHIN6E.js";
12
- import "../../../chunk-JT7ZMH44.js";
12
+ import "../../../chunk-XTBHIKFG.js";
13
13
 
14
14
  // src/roles/test/setup/jest-parity.ts
15
15
  import { expect, vi } from "vitest";
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  pinWorkspaceTimezone
3
- } from "../../../chunk-PMRL4MH6.js";
3
+ } from "../../../chunk-J2RMARWP.js";
4
4
  import "../../../chunk-ELZHIN6E.js";
5
- import "../../../chunk-JT7ZMH44.js";
5
+ import "../../../chunk-XTBHIKFG.js";
6
6
 
7
7
  // src/roles/test/setup/workspace-entry.ts
8
8
  await pinWorkspaceTimezone();
@@ -7,8 +7,8 @@ import {
7
7
  readTestAdoption,
8
8
  resolveVitest,
9
9
  suiteOf
10
- } from "./chunk-AVT5FSPO.js";
11
- import "./chunk-JT7ZMH44.js";
10
+ } from "./chunk-UVXXEAHU.js";
11
+ import "./chunk-XTBHIKFG.js";
12
12
  import "./chunk-O7REVMOC.js";
13
13
  import "./chunk-QXFCZON7.js";
14
14