mandrel 2.95.0 → 2.97.0

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/.agents/audit-checklists/policies.md +23 -0
  2. package/.agents/audit-checklists/red-team.md +20 -0
  3. package/.agents/docs/agentrc-reference.json +2 -5
  4. package/.agents/docs/configuration.md +8 -6
  5. package/.agents/docs/workflows.md +4 -1
  6. package/.agents/schemas/agentrc.schema.json +46 -29
  7. package/.agents/schemas/audit-rules.json +48 -0
  8. package/.agents/schemas/audit-rules.schema.json +2 -2
  9. package/.agents/scripts/lib/audit-suite/selector.js +119 -27
  10. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +2 -0
  11. package/.agents/scripts/lib/baselines/duplication-scanner.js +44 -3
  12. package/.agents/scripts/lib/baselines/refresh-service.js +54 -14
  13. package/.agents/scripts/lib/config/explain.js +1 -7
  14. package/.agents/scripts/lib/config/gates/duplication.schema.js +12 -5
  15. package/.agents/scripts/lib/config-settings-schema-quality.js +0 -27
  16. package/.agents/scripts/lib/config-settings-schema.js +30 -0
  17. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  18. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +2 -14
  19. package/.agents/scripts/lib/orchestration/review-providers/generated-diff.js +61 -0
  20. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +19 -4
  21. package/.agents/scripts/lib/source-extensions.js +3 -2
  22. package/.agents/scripts/lint-issue-body.js +65 -10
  23. package/.agents/workflows/audit-documentation.md +5 -0
  24. package/.agents/workflows/audit-policies.md +221 -0
  25. package/.agents/workflows/audit-red-team.md +191 -0
  26. package/.agents/workflows/audit-security.md +4 -1
  27. package/.agents/workflows/mandrel-leverage.md +199 -0
  28. package/.agents/workflows/mandrel-plan.md +3 -1
  29. package/docs/CHANGELOG.md +23 -0
  30. package/lib/migrations/index.js +2 -0
  31. package/lib/migrations/steps/2.91.0-retire-duplication-formats.js +65 -9
  32. package/lib/migrations/steps/2.97.0-retire-quality-navigability.js +80 -0
  33. package/package.json +1 -1
@@ -0,0 +1,23 @@
1
+ <!-- GENERATED FILE — do not edit by hand.
2
+ Source of truth: .agents/workflows/audit-policies.md
3
+ Regenerate: node .agents/scripts/generate-lens-checklists.js
4
+ Drift is gated by: npm run docs:check
5
+ -->
6
+
7
+ # Policy Consistency Audit — authoring checklist
8
+
9
+ > Audit a project's published customer-facing policies (Terms, Privacy, Cookie, refund and cancellation, consent and waiver text) against what the code actually does, in both directions — promises the system does not keep and practices no policy discloses. Never edits policy text…
10
+
11
+ Self-check your change against this lens's concerns before you ship:
12
+
13
+ - [ ] Unresolved cross-references
14
+ - [ ] Absent referenced documents
15
+ - [ ] Contact drift
16
+ - [ ] Money literals
17
+ - [ ] Contradiction
18
+ - [ ] Unbacked Promise
19
+ - [ ] Undisclosed Practice
20
+ - [ ] Stale Reference
21
+ - [ ] Internal Inconsistency
22
+ - [ ] Unverifiable
23
+ - [ ] Scheduled invocation
@@ -0,0 +1,20 @@
1
+ <!-- GENERATED FILE — do not edit by hand.
2
+ Source of truth: .agents/workflows/audit-red-team.md
3
+ Regenerate: node .agents/scripts/generate-lens-checklists.js
4
+ Drift is gated by: npm run docs:check
5
+ -->
6
+
7
+ # Red-Team Audit — authoring checklist
8
+
9
+ > Audit the project as a goal-directed adversary — attack paths that chain two or more crossings, abuse of intended features, agent exposure to hostile repository or inbound content, hostile operations and operator hazards — graded under a reproduced-or-reasoned evidence bar. A d…
10
+
11
+ Self-check your change against this lens's concerns before you ship:
12
+
13
+ - [ ] Promises.
14
+ - [ ] Adversaries.
15
+ - [ ] Agent-facing surfaces.
16
+ - [ ] Attack Path
17
+ - [ ] Abuse & Misuse
18
+ - [ ] Agent Exposure
19
+ - [ ] Hostile Operations
20
+ - [ ] Operator Hazard
@@ -209,17 +209,14 @@
209
209
  }
210
210
  },
211
211
  "targetDirs": ["src"],
212
+ "additionalFormats": [],
212
213
  "ignoreGlobs": []
213
214
  }
214
215
  },
215
216
  "autoRefresh": {
216
217
  "enabled": true
217
218
  },
218
- "requireBaselines": false,
219
- "navigability": {
220
- "routeGlobs": [],
221
- "navRegistry": []
222
- }
219
+ "requireBaselines": false
223
220
  },
224
221
  "mergeWatch": {
225
222
  "maxBudgetSeconds": 3600
@@ -90,6 +90,11 @@ Project identity, filesystem roots, planner docs context, and the commands the c
90
90
  | `commands.lint` | No | `string` \| `null` | `"npm run lint"` | Lint command run as a close-validation gate and by the handoff preflight. An explicit `null` disables both (skip reason `lint-disabled`). Point it at the scoped command your hooks already run to stop paying for a third whole-repo lint at close — the gate still lints the diff, and CI still owns whole-repo drift. |
91
91
  | `commands.formatCheck` | No | `string` \| `null` | `"npx biome format ."` | Non-mutating format verification run as a close-validation gate. An explicit `null` disables the gate (skip reason `format-disabled`). |
92
92
  | `commands.formatWrite` | No | `string` | `"npx biome format --write ."` | Mutating format command the close-time format-autofix step spawns. |
93
+ | `policies` | No | `object` | — | Published customer-facing policy corpus read by `/audit-policies`. Optional: absent means the lens and its applicability probe fall back to conventional policy file names (files under `policies/` or `legal/`, or basenames such as `privacy-policy` or `terms-of-service`). |
94
+ | `policies.corpusGlobs` | No | `array<string>` | — | Globs naming where the published policy text lives (markdown, HTML, Astro or similar). Non-empty makes the project applicable for `/audit-policies` without a filesystem scan. |
95
+ | `policies.impactMap` | No | `string` | — | Repo-relative path to a JSON object mapping code globs to arrays of policy paths; focuses a change-set-scoped `/audit-policies` run on the policies a change can invalidate. |
96
+ | `policies.backingDocs` | No | `array<string>` | — | Runbook or SOP globs. A policy claim a documented manual procedure honors is reported as backed, not as a finding. |
97
+ | `policies.acceptedFindings` | No | `string` | — | Repo-relative path to a JSON array of `{ policy, quote, reason, reviewBy }` entries (`reviewBy` is `YYYY-MM-DD`). A matching unexpired entry suppresses the finding; an expired one is reported. |
93
98
 
94
99
  ### `github` (optional)
95
100
 
@@ -221,7 +226,7 @@ Everything `/mandrel-deliver` and `single-story-close` consume: worktree isolati
221
226
  | `quality.gates.bundle-size.floors` | No | `object<map>` | `{"*":{}}` | Component-keyed absolute floors: `{ "<component>": { "<metric>": number } }` — the threshold half of the component mapping whose membership half is `components`. `"*"` is the project-wide catch-all component; the metric keyset is open so per-rollup keys flow through without each gate enumerating them. Floors are absolute — unlike `tolerance`, they are enforced regardless of the baseline. |
222
227
  | `quality.gates.bundle-size.components` | No | `object<map>` | — | Component-keyed membership map — the membership half of the component mapping whose threshold half is `floors`: component name to the glob list whose rows roll up under it (matched against the row key: the file path, or the bundle name for bundle-size). `check-baselines` reports one rollup per component that matches a row and holds it to `floors.<component>`, falling back to `floors["*"]`. Defaults to `{ "*": ["**"] }` at the resolver layer. |
223
228
  | `quality.gates.bundle-size.bundles[]` | No | `array<object>` | `[]` | The artifacts to weigh. Empty means the gate has nothing to do. Each item has: name, path, limit. |
224
- | `quality.gates.duplication` | No | `object` | — | Code-duplication (DRY) gate (Story #3664). Shares the gate base and adds the scan-scope extras: the `targetDirs` the duplication scanner walks and `ignoreGlobs` to exclude files from the scan. The jscpd formats it reads are derived from the scorable-extension list every other gate scores (JavaScript, JSX, TypeScript, TSX), so they are not configurable (Story #5738). |
229
+ | `quality.gates.duplication` | No | `object` | — | Code-duplication (DRY) gate (Story #3664). Shares the gate base and adds the scan-scope extras: the `targetDirs` the duplication scanner walks and `ignoreGlobs` to exclude files from the scan. The jscpd formats it reads always include the scorable-extension list every other gate scores (JavaScript, JSX, TypeScript, TSX, Story #5738); `additionalFormats` can only extend that list (Story #5849). |
225
230
  | `quality.gates.duplication.enabled` | No | `boolean` | `false` | When false, the checker exits 0 with a skip line and the gate is reported as `skipped`, never omitted. |
226
231
  | `quality.gates.duplication.baselinePath` | No | `string` | `"baselines/duplication.json"` | Repo-root-relative path to the gate's committed baseline artifact. |
227
232
  | `quality.gates.duplication.tolerance` | No | `object` | `{"kind":"absolute","value":1}` | How much a rollup may drift from the committed baseline before the gate reports a regression. |
@@ -229,15 +234,12 @@ Everything `/mandrel-deliver` and `single-story-close` consume: worktree isolati
229
234
  | `quality.gates.duplication.tolerance.value` | Yes | `number` | — | The tolerance magnitude. 0 means no drift is allowed. |
230
235
  | `quality.gates.duplication.floors` | No | `object<map>` | `{"*":{"percentage":25}}` | Component-keyed absolute floors: `{ "<component>": { "<metric>": number } }` — the threshold half of the component mapping whose membership half is `components`. `"*"` is the project-wide catch-all component; the metric keyset is open so per-rollup keys flow through without each gate enumerating them. Floors are absolute — unlike `tolerance`, they are enforced regardless of the baseline. |
231
236
  | `quality.gates.duplication.components` | No | `object<map>` | — | Component-keyed membership map — the membership half of the component mapping whose threshold half is `floors`: component name to the glob list whose rows roll up under it (matched against the row key: the file path, or the bundle name for bundle-size). `check-baselines` reports one rollup per component that matches a row and holds it to `floors.<component>`, falling back to `floors["*"]`. Defaults to `{ "*": ["**"] }` at the resolver layer. |
232
- | `quality.gates.duplication.targetDirs` | No | `string[]` or `{ append?, prepend? }` | `["src"]` | Directories whose scorable sources (`.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.mts`, `.cts`) the duplication (DRY) gate scans for copy-paste clones. Mandrel ships a `src/`-centric default; projects whose executable code lives elsewhere (e.g. this repo's `.agents/scripts/`) override here. The framework default is intentionally not auto-discovered, so an override is the explicit, auditable signal (Story #3664). |
237
+ | `quality.gates.duplication.targetDirs` | No | `string[]` or `{ append?, prepend? }` | `["src"]` | Directories whose scorable sources (`.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.mts`, `.cts`), plus the files of any `additionalFormats`, the duplication (DRY) gate scans for copy-paste clones. Mandrel ships a `src/`-centric default; projects whose executable code lives elsewhere (e.g. this repo's `.agents/scripts/`) override here. The framework default is intentionally not auto-discovered, so an override is the explicit, auditable signal (Story #3664). |
238
+ | `quality.gates.duplication.additionalFormats` | No | `array<string>` | `[]` | Extra jscpd format names (e.g. `python`, `go`) the duplication gate scans on top of the scorable formats it always reads. Extend-only: the scorable formats cannot be removed, and naming one here is a no-op. An unknown format name fails the scan rather than measuring nothing. The CRAP, MI, coverage and native-review gates still score only the scorable list (Story #5849). |
233
239
  | `quality.gates.duplication.ignoreGlobs` | No | `array<string>` | `[]` | Minimatch glob patterns matched against the canonicalised repo-relative path of each discovered file. Files matching any pattern are excluded from duplication discovery before scanning. Orthogonal to `components` (grouping). Absent or empty preserves the existing behaviour (Story #3664). This is the lever for scanning fewer files. |
234
240
  | `quality.autoRefresh` | No | `object` | — | Baseline-attribution auto-refresh: when a gate can prove a regression is a legitimate consequence of the diff, it rewrites the baseline instead of blocking. The single-row CRAP jump cap (5) and the rescore scope (`diff`) are fixed. |
235
241
  | `quality.autoRefresh.enabled` | No | `boolean` | `true` | Master switch for the auto-refresh path. When false, every baseline refresh is a deliberate operator action. |
236
242
  | `quality.requireBaselines` | No | `boolean` | `false` | Story #4495. Fail-closed baseline-enforcement policy for the unified check-baselines close-validation gate. When false (default), a consumer that enables baseline gates (crap/maintainability/…) but has not committed the corresponding baseline artifacts under baselines/ gets a clean skip-with-reason instead of a deterministic first-try close failure. Set true to keep the gate registered so an absent baseline artifact fails close-validation with a preflight hint naming the fix (the fail-closed posture). |
237
- | `quality.navigability` | No | `object` | — | Navigability lens + journey-suite config (Epic #4131, F2/F3/F1/F4). Read by audit-suite/selector.js (route globs) and /mandrel-deliver's per-Story ceremony (journey suite). Opt-in: absent or empty routeGlobs degrades to a silent no-op. |
238
- | `quality.navigability.routeGlobs` | No | `array<string>` | `[]` | Glob patterns (pages/**, app/**/route.ts) marking paths that add a user-facing route — the route-tree SSOT the navigability lens enumerates and the route-added routing predicate matches against. |
239
- | `quality.navigability.navRegistry` | No | `array<string>` | `[]` | Tokens identifying the nav-registry SSOT the navigability lens checks every route resolves a nav door against. |
240
- | `quality.navigability.journeySuite` | No | `string` | — | Path or command for the per-persona journey suite /mandrel-deliver's per-Story ceremony runs. |
241
243
  | `mergeWatch` | No | `object` | — | Knobs consumed by the close-and-land merge wait (Story #4543). `mode` (Story #4698) selects the close-time merge posture. `maxWaitSeconds` bounds ONE invocation of the merge wait and its expiry returns a resumable `pending` terminal with no label mutation; `maxBudgetSeconds` bounds the CUMULATIVE wait across resumes (anchored at the later of the PR's createdAt and its latest auto-merge arm, so a `--wait` resume does not restart the clock while a re-close that re-arms gets a fresh budget) and exhausting it is the genuine give-up that classifies and blocks. The poll cadence is internal (at most 30s while checks run, at most 10s once they are green and the PR is unmerged); it and the cap of 3 behind-the-base updates are not configurable. |
242
244
  | `mergeWatch.mode` | No | `"sync"` \| `"async"` | — | Close-time merge-wait posture (Story #4698). `sync` (default) keeps the in-close foreground merge wait unchanged. `async` caps the per-invocation wait to a short ~60s probe window — long enough to catch an instant merge and, via the head-anchored required-check predicate, an instantly-red required check — then returns the resumable `pending` terminal (exit 3) with a `nextCommand`. Opt in when slow CI makes the foreground wait routinely expire: the worker launches `nextCommand` in the background instead of burning the host tool slot polling. `maxBudgetSeconds` (the cumulative give-up) is unchanged. |
243
245
  | `mergeWatch.maxWaitSeconds` | No | `integer` | — | Per-invocation merge-wait bound (seconds). Default 300 (5 minutes) — chosen to fit inside a single host tool invocation (~10 min ceiling) alongside the close gates that precede the wait. Expiry yields `pending` (exit 3), never a block. Headless callers with no host ceiling raise this to land in one block. |
@@ -51,7 +51,7 @@ by `node .agents/scripts/generate-workflows-doc.js`; `npm run docs:check`
51
51
  fails when it drifts from the on-disk workflow set. To change a command’s
52
52
  description, edit the workflow file’s front-matter and regenerate.
53
53
 
54
- ## Commands (33)
54
+ ## Commands (36)
55
55
 
56
56
  | Command | Description |
57
57
  | --- | --- |
@@ -69,8 +69,10 @@ description, edit the workflow file’s front-matter and regenerate.
69
69
  | `/audit-mobile` | Audit mobile and tablet UX — layout and viewport correctness, touch ergonomics, responsive assets, and whether anything actually verifies them at a small viewport (static-first, with an optional runtime viewport pass) |
70
70
  | `/audit-navigability` | Audit the whole route tree against the consumer's nav-registry SSOT — every route has a persona nav door and no nav href is dead. A deliberately-global lens exempt from the cross-epic-leak guard and routed onto route-adding change sets. |
71
71
  | `/audit-performance` | Audit performance by measuring first — profile hot paths, I/O, memory, and payload against the repo's own numbers — and audit interleaving/partial-failure correctness (TOCTOU, unawaited promises, non-atomic writes) as a first-class dimension. |
72
+ | `/audit-policies` | Audit a project's published customer-facing policies (Terms, Privacy, Cookie, refund and cancellation, consent and waiver text) against what the code actually does, in both directions — promises the system does not keep and practices no policy discloses. Never edits policy text; every finding names a decision. |
72
73
  | `/audit-privacy` | Audit logs, telemetry, and persistence paths for PII leakage and retention violations; surface secrets exposure and consent gaps. |
73
74
  | `/audit-quality` | Audit test coverage gaps, flaky tests, missing assertions, and test-pyramid balance; recommend a remediation batch. |
75
+ | `/audit-red-team` | Audit the project as a goal-directed adversary — attack paths that chain two or more crossings, abuse of intended features, agent exposure to hostile repository or inbound content, hostile operations and operator hazards — graded under a reproduced-or-reasoned evidence bar. A deliberately-global lens that runs on any project. |
74
76
  | `/audit-security` | Audit dependency CVEs, input-validation gaps, secrets handling, auth boundaries, and the trust-boundary attack classes the baseline is silent on (business logic, SSRF/traversal, deserialization, crypto misuse, feature abuse, LLM tool-binding); emit a structured High/Medium/Low findings report. |
75
77
  | `/audit-seo` | Audit SEO fundamentals and Generative Engine Optimization signals (meta, structured data, crawlability); only relevant for web targets. |
76
78
  | `/audit-sre` | "Audit production-readiness for a release candidate: SLOs, observability, runbooks, error budgets, and rollback paths." |
@@ -81,6 +83,7 @@ description, edit the workflow file’s front-matter and regenerate.
81
83
  | `/clean-worktrees` | Reclaim disk from dead worktrees: list every worktree of this project as a removal candidate (closed Story, merged branch, orphaned directory, detached HEAD) or as kept with a reason, then remove candidates only on `--execute`. |
82
84
  | `/git-deliver` | Single ad-hoc delivery command for working-tree changes. Detects the git setup and escalates to the right terminal step — commit only, commit + push, or commit + push + open a PR with native auto-merge — picking the default from observable state and letting flags pin any level explicitly. Replaces the retired git-commit-all, git-push, and git-pr-all trio. |
83
85
  | `/mandrel-deliver` | Unified delivery entry point. Takes Story ids or a plain-language prompt, derives which path the work belongs on, and lands it via the single deliver-story engine — story-<id> → PR → main. |
86
+ | `/mandrel-leverage` | Evidence-cited leverage review — draft five to twelve bets on how the project could be ~10x more useful, reliable or valuable, refute most of them with two maker-blind skeptics each, write the survivors, downgrades and refutations to temp/leverage/<run-id>/bets.md, and hand each survivor to /mandrel-plan behind a HITL gate. |
84
87
  | `/mandrel-plan` | Unified planning entry point. Interrogate → author → persist. Emits one Story by default; splits into N>1 only under the default-single split policy. |
85
88
  | `/mandrel-update` | npm-era upgrade wraparound for a Mandrel consumer. Runs `npx mandrel update` (resolve newest published version → install → re-materialize `.agents/` → migrate → doctor → surface changelog) as the single mechanical step, then walks the operator through the judgment wraparound the CLI deliberately leaves unowned: reconcile `.agentrc.json`, install the stabilized quality-gate surface, refresh the harness permission allowlist, reconcile the consumer's `AGENTS.md` / runbooks against the surfaced changelog, and stage + commit the dependency bump the CLI's closing report describes. |
86
89
  | `/memory-consolidate` | Attended consolidation pass over this project's agent memory pool — merge duplicates, verify claims against the current tree, prune with operator confirmation, rewrite the index, and stamp the pool with the date and entry count the /mandrel-plan advisory measures its next nudge against. |
@@ -125,6 +125,41 @@
125
125
  }
126
126
  },
127
127
  "additionalProperties": false
128
+ },
129
+ "policies": {
130
+ "type": "object",
131
+ "description": "Published customer-facing policy corpus read by `/audit-policies`. Optional: absent means the lens and its applicability probe fall back to conventional policy file names (files under `policies/` or `legal/`, or basenames such as `privacy-policy` or `terms-of-service`).",
132
+ "properties": {
133
+ "corpusGlobs": {
134
+ "type": "array",
135
+ "items": {
136
+ "type": "string"
137
+ },
138
+ "description": "Globs naming where the published policy text lives (markdown, HTML, Astro or similar). Non-empty makes the project applicable for `/audit-policies` without a filesystem scan."
139
+ },
140
+ "impactMap": {
141
+ "type": "string",
142
+ "not": {
143
+ "pattern": "([;&|`]|\\$\\()"
144
+ },
145
+ "description": "Repo-relative path to a JSON object mapping code globs to arrays of policy paths; focuses a change-set-scoped `/audit-policies` run on the policies a change can invalidate."
146
+ },
147
+ "backingDocs": {
148
+ "type": "array",
149
+ "items": {
150
+ "type": "string"
151
+ },
152
+ "description": "Runbook or SOP globs. A policy claim a documented manual procedure honors is reported as backed, not as a finding."
153
+ },
154
+ "acceptedFindings": {
155
+ "type": "string",
156
+ "not": {
157
+ "pattern": "([;&|`]|\\$\\()"
158
+ },
159
+ "description": "Repo-relative path to a JSON array of `{ policy, quote, reason, reviewBy }` entries (`reviewBy` is `YYYY-MM-DD`). A matching unexpired entry suppresses the finding; an expired one is reported."
160
+ }
161
+ },
162
+ "additionalProperties": false
128
163
  }
129
164
  },
130
165
  "additionalProperties": false
@@ -1108,7 +1143,7 @@
1108
1143
  },
1109
1144
  "duplication": {
1110
1145
  "type": "object",
1111
- "description": "Code-duplication (DRY) gate (Story #3664). Shares the gate base and adds the scan-scope extras: the `targetDirs` the duplication scanner walks and `ignoreGlobs` to exclude files from the scan. The jscpd formats it reads are derived from the scorable-extension list every other gate scores (JavaScript, JSX, TypeScript, TSX), so they are not configurable (Story #5738).",
1146
+ "description": "Code-duplication (DRY) gate (Story #3664). Shares the gate base and adds the scan-scope extras: the `targetDirs` the duplication scanner walks and `ignoreGlobs` to exclude files from the scan. The jscpd formats it reads always include the scorable-extension list every other gate scores (JavaScript, JSX, TypeScript, TSX, Story #5738); `additionalFormats` can only extend that list (Story #5849).",
1112
1147
  "properties": {
1113
1148
  "enabled": {
1114
1149
  "type": "boolean",
@@ -1199,9 +1234,18 @@
1199
1234
  "additionalProperties": false
1200
1235
  }
1201
1236
  ],
1202
- "description": "Directories whose scorable sources (`.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.mts`, `.cts`) the duplication (DRY) gate scans for copy-paste clones. Mandrel ships a `src/`-centric default; projects whose executable code lives elsewhere (e.g. this repo's `.agents/scripts/`) override here. The framework default is intentionally not auto-discovered, so an override is the explicit, auditable signal (Story #3664).",
1237
+ "description": "Directories whose scorable sources (`.js`, `.mjs`, `.cjs`, `.jsx`, `.ts`, `.tsx`, `.mts`, `.cts`), plus the files of any `additionalFormats`, the duplication (DRY) gate scans for copy-paste clones. Mandrel ships a `src/`-centric default; projects whose executable code lives elsewhere (e.g. this repo's `.agents/scripts/`) override here. The framework default is intentionally not auto-discovered, so an override is the explicit, auditable signal (Story #3664).",
1203
1238
  "default": ["src"]
1204
1239
  },
1240
+ "additionalFormats": {
1241
+ "type": "array",
1242
+ "items": {
1243
+ "type": "string",
1244
+ "minLength": 1
1245
+ },
1246
+ "description": "Extra jscpd format names (e.g. `python`, `go`) the duplication gate scans on top of the scorable formats it always reads. Extend-only: the scorable formats cannot be removed, and naming one here is a no-op. An unknown format name fails the scan rather than measuring nothing. The CRAP, MI, coverage and native-review gates still score only the scorable list (Story #5849).",
1247
+ "default": []
1248
+ },
1205
1249
  "ignoreGlobs": {
1206
1250
  "type": "array",
1207
1251
  "items": {
@@ -1233,33 +1277,6 @@
1233
1277
  "type": "boolean",
1234
1278
  "description": "Story #4495. Fail-closed baseline-enforcement policy for the unified check-baselines close-validation gate. When false (default), a consumer that enables baseline gates (crap/maintainability/…) but has not committed the corresponding baseline artifacts under baselines/ gets a clean skip-with-reason instead of a deterministic first-try close failure. Set true to keep the gate registered so an absent baseline artifact fails close-validation with a preflight hint naming the fix (the fail-closed posture).",
1235
1279
  "default": false
1236
- },
1237
- "navigability": {
1238
- "type": "object",
1239
- "description": "Navigability lens + journey-suite config (Epic #4131, F2/F3/F1/F4). Read by audit-suite/selector.js (route globs) and /mandrel-deliver's per-Story ceremony (journey suite). Opt-in: absent or empty routeGlobs degrades to a silent no-op.",
1240
- "properties": {
1241
- "routeGlobs": {
1242
- "type": "array",
1243
- "items": {
1244
- "type": "string"
1245
- },
1246
- "description": "Glob patterns (pages/**, app/**/route.ts) marking paths that add a user-facing route — the route-tree SSOT the navigability lens enumerates and the route-added routing predicate matches against.",
1247
- "default": []
1248
- },
1249
- "navRegistry": {
1250
- "type": "array",
1251
- "items": {
1252
- "type": "string"
1253
- },
1254
- "description": "Tokens identifying the nav-registry SSOT the navigability lens checks every route resolves a nav door against.",
1255
- "default": []
1256
- },
1257
- "journeySuite": {
1258
- "type": "string",
1259
- "description": "Path or command for the per-persona journey suite /mandrel-deliver's per-Story ceremony runs."
1260
- }
1261
- },
1262
- "additionalProperties": false
1263
1280
  }
1264
1281
  },
1265
1282
  "additionalProperties": false
@@ -110,6 +110,38 @@
110
110
  "scope": "local",
111
111
  "substitutionKeys": []
112
112
  },
113
+ "audit-policies": {
114
+ "triggers": {
115
+ "gates": ["gate1", "gate3"],
116
+ "keywords": [
117
+ "policy",
118
+ "policies",
119
+ "terms of service",
120
+ "privacy policy",
121
+ "cookie notice",
122
+ "refund policy",
123
+ "cancellation policy",
124
+ "waiver",
125
+ "consent form",
126
+ "legal text"
127
+ ],
128
+ "filePatterns": [
129
+ "**/policies/**",
130
+ "**/legal/**",
131
+ "**/*privacy-policy*",
132
+ "**/*cookie-policy*",
133
+ "**/*cookie-notice*",
134
+ "**/*refund-policy*",
135
+ "**/*cancellation-policy*",
136
+ "**/*terms-of-service*",
137
+ "**/*terms-of-use*",
138
+ "**/*terms-and-conditions*"
139
+ ]
140
+ },
141
+ "target": "policies",
142
+ "scope": "cumulative",
143
+ "substitutionKeys": []
144
+ },
113
145
  "audit-accessibility": {
114
146
  "triggers": {
115
147
  "gates": ["gate2", "gate3"],
@@ -434,6 +466,22 @@
434
466
  },
435
467
  "scope": "global",
436
468
  "substitutionKeys": []
469
+ },
470
+ "audit-red-team": {
471
+ "triggers": {
472
+ "gates": ["gate3"],
473
+ "keywords": [
474
+ "red team",
475
+ "red-team",
476
+ "adversarial",
477
+ "threat model",
478
+ "attack path",
479
+ "abuse case",
480
+ "blast radius"
481
+ ]
482
+ },
483
+ "scope": "global",
484
+ "substitutionKeys": []
437
485
  }
438
486
  },
439
487
  "sensitivePaths": {
@@ -61,8 +61,8 @@
61
61
  },
62
62
  "target": {
63
63
  "type": "string",
64
- "enum": ["web", "data-model", "any"],
65
- "description": "Target-applicability gate: the kind of project this lens can say anything about. `web` — the lens reads a rendered web surface (pages, routes, HTML/CSS, design tokens) and is skipped entirely on a project that has none, however well its keyword or file-pattern triggers match. `data-model` — the lens reads a persistence layer (ORM models, schema migrations, seed data) and is skipped entirely on a project that has none. `any` — always applicable. ABSENT MEANS `any`: omitting the key never changes a lens's behaviour. Applicability is decided by a probe in lib/audit-suite/selector.js from observables in the consumer's own checkout — hasWebSurface() for `web` (configured navigability routeGlobs, a declared web-framework dependency, or a tracked .html/.css/.jsx/.tsx source file), hasPersistenceLayer() for `data-model` (a declared ORM dependency, a database migrations directory, or a tracked .prisma/.sql schema file) — and NOT from an .agentrc key, so a consumer with a real surface keeps these lenses with no configuration. Each probe fails OPEN: an indeterminate answer treats the project as capable, because a wasted lens run is recoverable and silently dropped coverage is not.",
64
+ "enum": ["web", "data-model", "policies", "any"],
65
+ "description": "Target-applicability gate: the kind of project this lens can say anything about. `web` — the lens reads a rendered web surface (pages, routes, HTML/CSS, design tokens) and is skipped entirely on a project that has none, however well its keyword or file-pattern triggers match. `data-model` — the lens reads a persistence layer (ORM models, schema migrations, seed data) and is skipped entirely on a project that has none. `policies` — the lens reads a published customer-facing policy corpus (Terms, Privacy, Cookie, refund/cancellation, consent and waiver text) and is skipped entirely on a project that has none. `any` — always applicable. ABSENT MEANS `any`: omitting the key never changes a lens's behaviour. Applicability is decided by a probe in lib/audit-suite/selector.js from observables in the consumer's own checkout — hasWebSurface() for `web` (configured navigability routeGlobs, a declared web-framework dependency, or a tracked .html/.css/.jsx/.tsx source file), hasPersistenceLayer() for `data-model` (a declared ORM dependency, a database migrations directory, or a tracked .prisma/.sql schema file), hasPolicyCorpus() for `policies` (configured project.policies.corpusGlobs, or a policy text file under a policies/ or legal/ directory or whose basename carries an explicit policy compound such as privacy-policy or terms-of-service) — and, outside project.policies.corpusGlobs, NOT from an .agentrc key, so a consumer with a real surface keeps these lenses with no configuration. Each probe fails OPEN: an indeterminate answer treats the project as capable, because a wasted lens run is recoverable and silently dropped coverage is not.",
66
66
  "default": "any"
67
67
  },
68
68
  "substitutionKeys": {
@@ -7,6 +7,7 @@ import picomatch from 'picomatch';
7
7
  import { getPaths, PROJECT_ROOT, resolveConfig } from '../config-resolver.js';
8
8
  import { softFailOrThrow } from '../degraded-mode.js';
9
9
  import { gitSpawn } from '../git-utils.js';
10
+ import { resolveNavConfig } from '../orchestration/plan-navigation.js';
10
11
  import { withTimeout } from '../util/with-timeout.js';
11
12
  import { readAuditRulesSync } from './audit-rules-reader.js';
12
13
 
@@ -71,15 +72,6 @@ export function selectSensitivePathClasses({
71
72
  return matched;
72
73
  }
73
74
 
74
- /**
75
- * @param {object|null|undefined} config Resolved `.agentrc.json` wrapper.
76
- * @returns {string[]} Route globs, or `[]` when unconfigured.
77
- */
78
- function resolveNavigabilityRouteGlobs(config) {
79
- const globs = config?.delivery?.quality?.navigability?.routeGlobs;
80
- return Array.isArray(globs) ? globs.filter((g) => typeof g === 'string') : [];
81
- }
82
-
83
75
  /** Matched segment-wise against dependency names (`@angular/core` → `angular`). */
84
76
  const WEB_FRAMEWORK_PACKAGES = Object.freeze([
85
77
  'react',
@@ -227,7 +219,7 @@ function scanForWebAssets(root) {
227
219
  * @returns {boolean}
228
220
  */
229
221
  export function hasWebSurface({ config, projectRoot = PROJECT_ROOT } = {}) {
230
- if (resolveNavigabilityRouteGlobs(config).length > 0) return true;
222
+ if (resolveNavConfig(config).routeGlobs.length > 0) return true;
231
223
 
232
224
  if (_webSurfaceFsCache.has(projectRoot)) {
233
225
  return _webSurfaceFsCache.get(projectRoot);
@@ -293,13 +285,18 @@ function declaresOrmDependency(root) {
293
285
  }
294
286
 
295
287
  /**
296
- * Unlike the web scan, an exhausted budget is `false` (these artifacts live
297
- * near the root); only an unreadable root is `null`.
288
+ * Bounded near-root walk shared by the persistence and policy probes. Unlike
289
+ * the web scan, an exhausted budget is `false` (these artifacts live near the
290
+ * root); only an unreadable root is `null`.
298
291
  *
299
292
  * @param {string} root
293
+ * @param {{
294
+ * isMarkerDir?: (dir: string, name: string) => boolean,
295
+ * isMarkerFile: (dir: string, name: string) => boolean,
296
+ * }} matchers `dir` is the entry's parent directory.
300
297
  * @returns {boolean|null}
301
298
  */
302
- function scanForPersistenceArtifacts(root) {
299
+ function scanNearRoot(root, { isMarkerDir = () => false, isMarkerFile }) {
303
300
  let budget = WEB_SCAN_MAX_ENTRIES;
304
301
  const queue = [{ dir: root, depth: 0 }];
305
302
 
@@ -315,27 +312,34 @@ function scanForPersistenceArtifacts(root) {
315
312
 
316
313
  for (const entry of entries) {
317
314
  if (budget-- <= 0) return false; // bounded near-root scan exhausted
318
- if (entry.isDirectory()) {
319
- if (WEB_SCAN_SKIP_DIRS.includes(entry.name)) continue;
320
- if (
321
- MIGRATION_DIR_NAMES.includes(entry.name) &&
322
- DB_MIGRATION_PARENTS.includes(path.basename(dir))
323
- ) {
324
- return true;
325
- }
326
- if (depth + 1 <= WEB_SCAN_MAX_DEPTH) {
327
- queue.push({ dir: path.join(dir, entry.name), depth: depth + 1 });
328
- }
315
+ if (!entry.isDirectory()) {
316
+ if (isMarkerFile(dir, entry.name)) return true;
329
317
  continue;
330
318
  }
331
- if (PERSISTENCE_SCHEMA_EXTENSIONS.includes(path.extname(entry.name))) {
332
- return true;
319
+ if (WEB_SCAN_SKIP_DIRS.includes(entry.name)) continue;
320
+ if (isMarkerDir(dir, entry.name)) return true;
321
+ if (depth + 1 <= WEB_SCAN_MAX_DEPTH) {
322
+ queue.push({ dir: path.join(dir, entry.name), depth: depth + 1 });
333
323
  }
334
324
  }
335
325
  }
336
326
  return false;
337
327
  }
338
328
 
329
+ /**
330
+ * @param {string} root
331
+ * @returns {boolean|null}
332
+ */
333
+ function scanForPersistenceArtifacts(root) {
334
+ return scanNearRoot(root, {
335
+ isMarkerDir: (dir, name) =>
336
+ MIGRATION_DIR_NAMES.includes(name) &&
337
+ DB_MIGRATION_PARENTS.includes(path.basename(dir)),
338
+ isMarkerFile: (_dir, name) =>
339
+ PERSISTENCE_SCHEMA_EXTENSIONS.includes(path.extname(name)),
340
+ });
341
+ }
342
+
339
343
  /**
340
344
  * Applicability predicate for `target: "data-model"` lenses: an ORM
341
345
  * dependency or a schema artifact. Fails OPEN like {@link hasWebSurface}.
@@ -359,6 +363,88 @@ export function hasPersistenceLayer({ projectRoot = PROJECT_ROOT } = {}) {
359
363
  return result;
360
364
  }
361
365
 
366
+ /**
367
+ * @param {object|null|undefined} config Resolved `.agentrc.json` wrapper.
368
+ * @returns {string[]} Policy corpus globs, or `[]` when unconfigured.
369
+ */
370
+ function resolvePolicyCorpusGlobs(config) {
371
+ const globs = config?.project?.policies?.corpusGlobs;
372
+ return Array.isArray(globs) ? globs.filter((g) => typeof g === 'string') : [];
373
+ }
374
+
375
+ const POLICY_TEXT_EXTENSIONS = Object.freeze([
376
+ '.md',
377
+ '.mdx',
378
+ '.html',
379
+ '.htm',
380
+ '.astro',
381
+ '.txt',
382
+ ]);
383
+
384
+ const POLICY_DIR_NAMES = Object.freeze(['policies', 'legal']);
385
+
386
+ /**
387
+ * A bare `privacy.md` is not enough: only an explicit compound names a
388
+ * published policy rather than, say, a lens checklist about privacy.
389
+ */
390
+ const POLICY_BASENAME_PATTERN =
391
+ /(privacy[-_]policy|cookie[-_](policy|notice)|refund[-_]policy|cancellation[-_]policy|terms[-_]of[-_](service|use)|terms[-_]and[-_]conditions)/i;
392
+
393
+ /** @type {Map<string, boolean>} */
394
+ const _policyCorpusFsCache = new Map();
395
+
396
+ /** Test-only. */
397
+ export function _resetPolicyCorpusCache() {
398
+ _policyCorpusFsCache.clear();
399
+ }
400
+
401
+ /**
402
+ * @param {string} dir Directory holding `name`.
403
+ * @param {string} name File basename.
404
+ * @returns {boolean}
405
+ */
406
+ function isPolicyTextFile(dir, name) {
407
+ if (!POLICY_TEXT_EXTENSIONS.includes(path.extname(name).toLowerCase())) {
408
+ return false;
409
+ }
410
+ const underPolicyDir = dir
411
+ .split(path.sep)
412
+ .some((segment) => POLICY_DIR_NAMES.includes(segment.toLowerCase()));
413
+ return underPolicyDir || POLICY_BASENAME_PATTERN.test(name);
414
+ }
415
+
416
+ /**
417
+ * @param {string} root
418
+ * @returns {boolean|null}
419
+ */
420
+ function scanForPolicyFiles(root) {
421
+ return scanNearRoot(root, {
422
+ isMarkerFile: (dir, name) =>
423
+ isPolicyTextFile(path.relative(root, dir), name),
424
+ });
425
+ }
426
+
427
+ /**
428
+ * Applicability predicate for `target: "policies"` lenses: configured corpus
429
+ * globs, or a conventional policy file. Fails OPEN like {@link hasWebSurface}.
430
+ *
431
+ * @param {{ config?: object|null, projectRoot?: string }} [params]
432
+ * @returns {boolean}
433
+ */
434
+ export function hasPolicyCorpus({ config, projectRoot = PROJECT_ROOT } = {}) {
435
+ if (resolvePolicyCorpusGlobs(config).length > 0) return true;
436
+
437
+ if (_policyCorpusFsCache.has(projectRoot)) {
438
+ return _policyCorpusFsCache.get(projectRoot);
439
+ }
440
+
441
+ // `null` is indeterminate, not false — fail open.
442
+ const result = scanForPolicyFiles(projectRoot) !== false;
443
+
444
+ _policyCorpusFsCache.set(projectRoot, result);
445
+ return result;
446
+ }
447
+
362
448
  /** Single file × single glob, with the project's matcher semantics (`dot: true`). */
363
449
  export function matchesFilePattern(pattern, file) {
364
450
  return picomatch(pattern, { dot: true })(file);
@@ -443,6 +529,8 @@ export function changeSetLacksSiblingTest(changedFiles) {
443
529
  * @param {number} [params.gitTimeoutMsOverride]
444
530
  * @param {{ argv?: string[], env?: NodeJS.ProcessEnv }} [params.gateModeOpts]
445
531
  * @param {typeof hasWebSurface} [params.hasWebSurfaceFn]
532
+ * @param {typeof hasPersistenceLayer} [params.hasPersistenceLayerFn]
533
+ * @param {typeof hasPolicyCorpus} [params.hasPolicyCorpusFn]
446
534
  */
447
535
  export async function selectAudits({
448
536
  ticketId,
@@ -456,6 +544,7 @@ export async function selectAudits({
456
544
  gateModeOpts,
457
545
  hasWebSurfaceFn = hasWebSurface,
458
546
  hasPersistenceLayerFn = hasPersistenceLayer,
547
+ hasPolicyCorpusFn = hasPolicyCorpus,
459
548
  }) {
460
549
  const config = resolveConfig();
461
550
  const timeoutMs = gitTimeoutMsOverride ?? DEFAULT_GIT_TIMEOUT_MS;
@@ -504,6 +593,7 @@ export async function selectAudits({
504
593
  config,
505
594
  hasWebSurfaceFn,
506
595
  hasPersistenceLayerFn,
596
+ hasPolicyCorpusFn,
507
597
  }),
508
598
  });
509
599
 
@@ -650,17 +740,19 @@ function matchesAnyKeyword(keywords, content) {
650
740
  * Lazily memoized per target, so a roster without a `web` lens never pays the
651
741
  * filesystem scan.
652
742
  *
653
- * @param {{ config: object, hasWebSurfaceFn: Function, hasPersistenceLayerFn: Function }} params
743
+ * @param {{ config: object, hasWebSurfaceFn: Function, hasPersistenceLayerFn: Function, hasPolicyCorpusFn: Function }} params
654
744
  * @returns {(target: string) => boolean}
655
745
  */
656
746
  function makeTargetApplicabilityProbe({
657
747
  config,
658
748
  hasWebSurfaceFn,
659
749
  hasPersistenceLayerFn,
750
+ hasPolicyCorpusFn,
660
751
  }) {
661
752
  const probes = {
662
753
  web: hasWebSurfaceFn,
663
754
  'data-model': hasPersistenceLayerFn,
755
+ policies: hasPolicyCorpusFn,
664
756
  };
665
757
  const memo = new Map();
666
758
  return (target) => {
@@ -24,8 +24,10 @@ export const AUDIT_LENSES = Object.freeze([
24
24
  'mobile',
25
25
  'navigability',
26
26
  'performance',
27
+ 'policies',
27
28
  'privacy',
28
29
  'quality',
30
+ 'red-team',
29
31
  'security',
30
32
  'seo',
31
33
  'sre',