mandrel 2.79.0 → 2.81.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 (55) hide show
  1. package/.agents/agents/auditor.md +8 -3
  2. package/.agents/audit-checklists/data-model.md +9 -1
  3. package/.agents/audit-checklists/security.md +15 -1
  4. package/.agents/docs/agentrc-reference.json +4 -0
  5. package/.agents/docs/configuration.md +4 -3
  6. package/.agents/docs/execution-reference.md +25 -5
  7. package/.agents/docs/workflows.md +2 -2
  8. package/.agents/schemas/agentrc.schema.json +31 -3
  9. package/.agents/schemas/audit-rules.json +15 -2
  10. package/.agents/scripts/deliver-run.js +43 -8
  11. package/.agents/scripts/lib/audit-to-stories/seed-from-findings.js +37 -2
  12. package/.agents/scripts/lib/baselines/duplication-scanner.js +7 -1
  13. package/.agents/scripts/lib/baselines/refresh-service.js +6 -0
  14. package/.agents/scripts/lib/cli-args.js +16 -2
  15. package/.agents/scripts/lib/config/explain.js +1 -1
  16. package/.agents/scripts/lib/config/gates/duplication.schema.js +10 -2
  17. package/.agents/scripts/lib/config-settings-schema.js +18 -1
  18. package/.agents/scripts/lib/findings/audit-finding-record.js +95 -0
  19. package/.agents/scripts/lib/findings/route-finding.js +4 -3
  20. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  21. package/.agents/scripts/lib/observability/close-telemetry.js +17 -2
  22. package/.agents/scripts/lib/orchestration/complexity-gate.js +58 -11
  23. package/.agents/scripts/lib/orchestration/plan-persist/audit-attribution.js +182 -0
  24. package/.agents/scripts/lib/orchestration/plan-persist/audit-provenance.js +11 -10
  25. package/.agents/scripts/lib/orchestration/plan-persist/collision-message.js +52 -0
  26. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +56 -9
  27. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +177 -0
  28. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +202 -57
  29. package/.agents/scripts/lib/orchestration/plan-persist/supersede-ops.js +57 -15
  30. package/.agents/scripts/lib/orchestration/plan-persist/wave-collision-gate.js +8 -4
  31. package/.agents/scripts/lib/orchestration/plan-persist/wave-serialisation.js +3 -2
  32. package/.agents/scripts/lib/orchestration/resolve-stories.js +12 -3
  33. package/.agents/scripts/lib/orchestration/resume-effort.js +121 -0
  34. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +13 -2
  35. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +10 -2
  36. package/.agents/scripts/lib/orchestration/ticketing/reads.js +3 -0
  37. package/.agents/scripts/lib/qa/resolve-qa-contract.js +28 -9
  38. package/.agents/scripts/lib/templates/decomposer-prompts.js +2 -2
  39. package/.agents/scripts/lib/wave-runner/footprint.js +114 -17
  40. package/.agents/scripts/lib/wave-runner/ready-set.js +16 -5
  41. package/.agents/scripts/plan-persist.js +20 -6
  42. package/.agents/scripts/providers/github/tickets.js +2 -1
  43. package/.agents/scripts/resolve-stories.js +8 -2
  44. package/.agents/scripts/single-story-close.js +11 -3
  45. package/.agents/workflows/audit-data-model.md +94 -10
  46. package/.agents/workflows/audit-security.md +136 -49
  47. package/.agents/workflows/audit-to-stories.md +22 -7
  48. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  49. package/.agents/workflows/helpers/deliver-reference.md +7 -2
  50. package/.agents/workflows/helpers/deliver-story.md +5 -3
  51. package/.agents/workflows/helpers/plan-reference.md +53 -5
  52. package/.agents/workflows/mandrel-deliver.md +9 -4
  53. package/.agents/workflows/mandrel-plan.md +7 -1
  54. package/docs/CHANGELOG.md +25 -0
  55. package/package.json +2 -1
@@ -68,9 +68,14 @@ file is its standalone-agent form.
68
68
  (e.g. `perf-baseline.json`).
69
69
  - Running **non-mutating** measurements/scanners the lens calls for (profilers,
70
70
  timers, `npm audit`, read-only status commands) is permitted; running
71
- anything that installs, mutates git/labels, edits source, or connects to a
72
- production database is forbidden. A lens that names a stricter carve-out
73
- tightens this for that lens.
71
+ anything that installs, mutates git/labels, or edits source is forbidden.
72
+ A lens that names a stricter carve-out tightens this for that lens.
73
+ - **Databases.** Never connect to a production database, under any
74
+ configuration. Connect to any other database only when the lens body
75
+ provides for it **and** that environment opts in via `allowAudit`, through
76
+ the environment variable named by `urlEnv`, read-only, with
77
+ `default_transaction_read_only=on` on any session you open. Never run a
78
+ migration or any statement that writes.
74
79
 
75
80
  ## Scope
76
81
 
@@ -6,7 +6,7 @@
6
6
 
7
7
  # Data Model & Persistence Audit — authoring checklist
8
8
 
9
- > Audit the persistence layer as a first-class artifact — model↔migration↔seed drift, constraint completeness, migration hygiene, type fidelity, and access-pattern fit; gated by a persistence-layer applicability probe so DB-less repos skip cleanly.
9
+ > Audit the persistence layer as a first-class artifact — model↔migration↔seed drift, constraint completeness, migration hygiene, type fidelity, access-pattern fit, and dead schema — with an opt-in read-only live-schema pass; gated by a persistence-layer applicability probe so DB-…
10
10
 
11
11
  Self-check your change against this lens's concerns before you ship:
12
12
 
@@ -20,3 +20,11 @@ Self-check your change against this lens's concerns before you ship:
20
20
  - [ ] Migration hygiene
21
21
  - [ ] Type fidelity
22
22
  - [ ] Access-pattern fit
23
+ - [ ] Dead schema
24
+ - [ ] Unused schema
25
+ - [ ] Schema gap
26
+ - [ ] Provisional until corroborated
27
+ - [ ] Common identifiers are runtime-only
28
+ - [ ] Introspection diff
29
+ - [ ] Migration ledger
30
+ - [ ] Catalog statistics (Postgres)
@@ -6,7 +6,7 @@
6
6
 
7
7
  # Security & Vulnerability Audit — authoring checklist
8
8
 
9
- > Audit dependency CVEs, input-validation gaps, secrets handling, and auth boundaries; emit a structured High/Medium/Low findings report.
9
+ > 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 f…
10
10
 
11
11
  Self-check your change against this lens's concerns before you ship:
12
12
 
@@ -19,3 +19,17 @@ Self-check your change against this lens's concerns before you ship:
19
19
  - [ ] Cryptographic Failures
20
20
  - [ ] Security Misconfiguration
21
21
  - [ ] Vulnerable Components
22
+ - [ ] Business logic & state machines
23
+ - [ ] Access-control depth
24
+ - [ ] Resource & file handling
25
+ - [ ] Cryptography & secrets misuse
26
+ - [ ] Feature abuse & data leakage
27
+ - [ ] LLM & tool-binding boundaries
28
+ - [ ] An unfillable Boundary is not a finding.
29
+ - [ ] Defense-in-depth gaps are hardening notes.
30
+ - [ ] Severity never exceeds the demonstrated result.
31
+ - [ ] Critical
32
+ - [ ] High
33
+ - [ ] Medium
34
+ - [ ] Low
35
+ - [ ] Info
@@ -205,6 +205,7 @@
205
205
  }
206
206
  },
207
207
  "targetDirs": ["src"],
208
+ "formats": ["javascript", "jsx", "typescript", "tsx"],
208
209
  "ignoreGlobs": []
209
210
  }
210
211
  },
@@ -263,6 +264,9 @@
263
264
  "baseUrl": "http://localhost:3000",
264
265
  "signInSeam": {
265
266
  "urlTemplate": "/dev/sign-in-as/{persona}"
267
+ },
268
+ "database": {
269
+ "urlEnv": "DATABASE_URL"
266
270
  }
267
271
  },
268
272
  "staging": {
@@ -215,7 +215,7 @@ Everything `/mandrel-deliver` and `single-story-close` consume: worktree isolati
215
215
  | `quality.gates.bundle-size.floors` | No | `object<map>` | `{"*":{}}` | Workspace-keyed absolute floors: `{ "<workspace>": { "<metric>": number } }`. `"*"` is the project-wide catch-all; 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. |
216
216
  | `quality.gates.bundle-size.components` | No | `object<map>` | — | Per-gate component map — component name to the glob list whose files roll up under it. Defaults to `{ "*": ["**"] }` at the resolver layer. |
217
217
  | `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. |
218
- | `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. |
218
+ | `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, the jscpd `formats` it reads there, and `ignoreGlobs` to exclude files from the scan. |
219
219
  | `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. |
220
220
  | `quality.gates.duplication.baselinePath` | No | `string` | `"baselines/duplication.json"` | Repo-root-relative path to the gate's committed baseline artifact. |
221
221
  | `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. |
@@ -223,7 +223,8 @@ Everything `/mandrel-deliver` and `single-story-close` consume: worktree isolati
223
223
  | `quality.gates.duplication.tolerance.value` | Yes | `number` | — | The tolerance magnitude. 0 means no drift is allowed. |
224
224
  | `quality.gates.duplication.floors` | No | `object<map>` | `{"*":{"percentage":25}}` | Workspace-keyed absolute floors: `{ "<workspace>": { "<metric>": number } }`. `"*"` is the project-wide catch-all; 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. |
225
225
  | `quality.gates.duplication.components` | No | `object<map>` | — | Per-gate component map — component name to the glob list whose files roll up under it. Defaults to `{ "*": ["**"] }` at the resolver layer. |
226
- | `quality.gates.duplication.targetDirs` | No | `string[]` or `{ append?, prepend? }` | `["src"]` | Directories whose JS sources 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). |
226
+ | `quality.gates.duplication.targetDirs` | No | `string[]` or `{ append?, prepend? }` | `["src"]` | Directories whose sources — the languages `formats` selects — 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). |
227
+ | `quality.gates.duplication.formats` | No | `array<string>` | `["javascript","jsx","typescript","tsx"]` | jscpd format names the duplication (DRY) gate scans under `targetDirs`. The default covers JavaScript, JSX, TypeScript and TSX; jscpd's `javascript` format alone reads only `.js`/`.es`/`.es6`/`.mjs`/`.cjs`. Names are jscpd's own vocabulary and are not restricted here. Widening the set adds rows, so re-seat the baseline with `npm run duplication:reanchor` after changing it. |
227
228
  | `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). |
228
229
  | `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. |
229
230
  | `quality.autoRefresh.enabled` | No | `boolean` | `true` | Master switch for the auto-refresh path. When false, every baseline refresh is a deliberate operator action. |
@@ -264,7 +265,7 @@ Agent-driven QA harness contract (Epic #3214; environment-keyed by Epic #4326).
264
265
  | --- | --- | --- | --- | --- |
265
266
  | `featureRoot` | No | `string` | `"tests/features"` | Directory holding the Gherkin feature files the QA sweep drives. |
266
267
  | `fixturesManifest` | No | `string` | `"tests/fixtures/personas.json"` | Path to the persona/fixture manifest the harness seeds from. |
267
- | `environments` | No | `object<map>` | `{"local":{"baseUrl":"http://localhost:3000","signInSeam":{"urlTemplate":"/dev/sign-in-as/{persona}"}},"staging":{"baseUrl":"https://staging.example.test","allowWrites":false}}` | Deployment targets the QA harness can run against (Epic #4326). A map keyed by environment name (e.g. `local`, `staging`), each carrying its own `baseUrl`, an optional per-environment sign-in seam, and an optional `allowWrites` gate. `signInSeam` is the union `{ urlTemplate }` (a dev impersonation route) or `{ skill }` (a skill id such as `stack/qa/acme-sso`, resolved against `.agents/skills/` then the consumer-writable `.agents/local/skills/` zone, and rejected loudly by resolveQaEnvironment when it resolves under neither); omit it entirely for a target with no sign-in seam. resolveQaEnvironment selects one environment per invocation by name or by raw-URL origin match against `baseUrl`; `allowWrites` defaults to true only for the `local` environment. Replaces the retired top-level single `signInSeam`. |
268
+ | `environments` | No | `object<map>` | `{"local":{"baseUrl":"http://localhost:3000","signInSeam":{"urlTemplate":"/dev/sign-in-as/{persona}"},"database":{"urlEnv":"DATABASE_URL"}},"staging":{"baseUrl":"https://staging.example.test","allowWrites":false}}` | Deployment targets the QA harness can run against (Epic #4326). A map keyed by environment name (e.g. `local`, `staging`), each carrying its own `baseUrl`, an optional per-environment sign-in seam, and an optional `allowWrites` gate. `signInSeam` is the union `{ urlTemplate }` (a dev impersonation route) or `{ skill }` (a skill id such as `stack/qa/acme-sso`, resolved against `.agents/skills/` then the consumer-writable `.agents/local/skills/` zone, and rejected loudly by resolveQaEnvironment when it resolves under neither); omit it entirely for a target with no sign-in seam. resolveQaEnvironment selects one environment per invocation by name or by raw-URL origin match against `baseUrl`; `allowWrites` defaults to true only for the `local` environment. An optional `database` object `{ urlEnv, allowAudit? }` names the environment variable holding that target's database connection string (the name only, never the URL) for the `/audit-data-model` live-schema pass; `allowAudit` gates that read-only pass and, like `allowWrites`, defaults to true only for `local`. Point `urlEnv` at a role granted catalog read only. A production database is never audited live, whatever this block says. Replaces the retired top-level single `signInSeam`. |
268
269
  | `personas` | No | one of: `array`, `object` | `{"admin":{"credentialRef":"QA_ADMIN_CREDENTIAL"},"member":{"credentialRef":"QA_MEMBER_CREDENTIAL"}}` | Personas the QA-harness sign-in seam accepts. Two accepted shapes: (1) a plain array of persona names — the honest shape for a `urlTemplate` dev-impersonation seam, where the persona name is the sole input the workflow consumes; (2) the object-map form keyed by persona name, where each entry carries per-persona auth material (`credentialRef` or `signInSkill`) consulted only under a skill-based or credential-based seam. |
269
270
  | `gherkinLint` | No | `object` | `{"scopes":{"web":{"featureRoots":["apps/web/tests/features"],"stepRoots":["apps/web/tests/steps"]}},"exemptionTags":["@skip"],"stepWaivers":[]}` | Static Gherkin corpus gate (Story #5013). Optional; the gate runs only when this block is present, so an upgrade never reddens the lint of a consumer that never asked the framework to police its `.feature` files. Inside the opt-in it fails closed: an unresolvable `@cucumber/gherkin` parser, or a scope resolving zero step definitions, exits 1 rather than reporting a clean run. |
270
271
  | `gherkinLint.scopes` | Yes | `object<map>` | — | Binding scopes, keyed by name. Each scope resolves its own features against its own step definitions only — pooling every step root into one matcher list is what makes a cross-app false bind possible, where a step defined solely in app B silently vouches for app A. The scope name appears verbatim in every unbound finding. |
@@ -138,13 +138,33 @@ everything that follows.
138
138
  are well-scoped by construction, so delivery rarely needs more. `high` for
139
139
  `/mandrel-plan`: a Spec defect costs a redraft or a blocked Story
140
140
  downstream, which is dearer than the planning turn.
141
+ - **Recommended session model.** Set the session model explicitly — a
142
+ frontier model — for `/mandrel-plan` and `/mandrel-deliver` rather than
143
+ trusting the client default (recent Claude Code builds have been reported to
144
+ default to a small model). `story-worker`, `acceptance-critic` and
145
+ `plan-critic` declare `model: inherit`, so they run on whatever the session
146
+ runs on; `auditor` pins `sonnet`. Move one role off the session model with
147
+ `delivery.routing.agentModels`.
141
148
  - **Role agents.** `story-worker` declares no effort and inherits the
142
- session's (Story #5426). The evaluator roles (`acceptance-critic`,
143
- `plan-critic`, `auditor`) pin `medium`.
149
+ session's (Story #5426) — except on a resume, below. The evaluator roles
150
+ (`acceptance-critic`, `plan-critic`, `auditor`) pin `medium`.
144
151
  - **Where pins live.** Effort and model pins belong only on role agents under
145
152
  `.agents/agents/`, never in workflow or command frontmatter: a command that
146
153
  pinned its own effort would change effort mid-session and break the prompt
147
154
  cache.
148
- - **Escalation is an operator step.** The Agent tool takes no per-call
149
- effort, so no workflow can escalate on its own. Before resuming a blocked
150
- Story, raise session effort one step; raise effort before switching models.
155
+ - **Resume escalation is per call.** The Agent tool takes a per-call `effort`,
156
+ so a resumed blocked Story escalates on its own `story-worker` spawn and the
157
+ session (and its prompt cache) stays where it is. The ladder counts the
158
+ Story's prior blocks in its local signals stream — un-recovered
159
+ `story-blocked` records: 1 prior block → `high`, 2 or more → `xhigh`, none
160
+ → no per-call effort (the worker inherits the session). The ladder is
161
+ absolute, not relative to session effort — a script cannot read the
162
+ session's — so an operator already delivering at `high` or above gets the
163
+ ladder value. A one-Story resume therefore dispatches a worker instead of
164
+ running inline. A Story blocked on another machine has no local record and
165
+ resumes at session effort.
166
+ - **Inline fallback keeps the operator step.** With
167
+ `delivery.routing.roleScopedAgents: false`, or on a harness that cannot
168
+ nest spawns, a one-Story run executes inline and no spawn carries the
169
+ effort: before resuming a blocked Story there, raise session effort one
170
+ step; raise effort before switching models.
@@ -41,7 +41,7 @@ description, edit the workflow file’s front-matter and regenerate.
41
41
  | `/audit-architecture` | Audit architectural boundaries, module coupling, layering violations, and shipped-but-uncalled seams; emit a structured findings report keyed to the canonical severity scale. |
42
42
  | `/audit-baselines` | Audit the committed baseline surface — dead instruments, stale baselines, cross-gate hotspot clusters, trend drift, and floor-tightening headroom — and emit findings whose remediation burns the measured debt down and tightens the ratchet behind it. |
43
43
  | `/audit-clean-code` | Audit code smells, dead code, complexity hotspots, and maintainability-index outliers; emit a structured findings report. |
44
- | `/audit-data-model` | Audit the persistence layer as a first-class artifact — model↔migration↔seed drift, constraint completeness, migration hygiene, type fidelity, and access-pattern fit; gated by a persistence-layer applicability probe so DB-less repos skip cleanly. |
44
+ | `/audit-data-model` | Audit the persistence layer as a first-class artifact — model↔migration↔seed drift, constraint completeness, migration hygiene, type fidelity, access-pattern fit, and dead schema — with an opt-in read-only live-schema pass; gated by a persistence-layer applicability probe so DB-less repos skip cleanly. |
45
45
  | `/audit-dependencies` | Audit `package.json` for unused, outdated, and major-version-stale dependencies; surface Node-engine drift and propose upgrade batches. |
46
46
  | `/audit-devops` | Audit CI/CD workflows, container images, infrastructure-as-code, and deployment pipelines; surface failure modes and hardening gaps. |
47
47
  | `/audit-documentation` | Audit the repository's main documentation for staleness, semantic drift, and completeness; emit a structured High/Medium/Low findings report. |
@@ -51,7 +51,7 @@ description, edit the workflow file’s front-matter and regenerate.
51
51
  | `/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. |
52
52
  | `/audit-privacy` | Audit logs, telemetry, and persistence paths for PII leakage and retention violations; surface secrets exposure and consent gaps. |
53
53
  | `/audit-quality` | Audit test coverage gaps, flaky tests, missing assertions, and test-pyramid balance; recommend a remediation batch. |
54
- | `/audit-security` | Audit dependency CVEs, input-validation gaps, secrets handling, and auth boundaries; emit a structured High/Medium/Low findings report. |
54
+ | `/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. |
55
55
  | `/audit-seo` | Audit SEO fundamentals and Generative Engine Optimization signals (meta, structured data, crawlability); only relevant for web targets. |
56
56
  | `/audit-sre` | "Audit production-readiness for a release candidate: SLOs, observability, runbooks, error budgets, and rollback paths." |
57
57
  | `/audit-to-stories` | Convert findings produced by the audit-\* workflows into actionable GitHub Stories. Reads temp/audits/audit-\*-results.md, groups findings cross-audit, deduplicates against existing Issues by fingerprint, and either chains into /mandrel-plan --seed-file or opens standalone Stories. |
@@ -1040,7 +1040,7 @@
1040
1040
  },
1041
1041
  "duplication": {
1042
1042
  "type": "object",
1043
- "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.",
1043
+ "description": "Code-duplication (DRY) gate (Story #3664). Shares the gate base and adds the scan-scope extras: the `targetDirs` the duplication scanner walks, the jscpd `formats` it reads there, and `ignoreGlobs` to exclude files from the scan.",
1044
1044
  "properties": {
1045
1045
  "enabled": {
1046
1046
  "type": "boolean",
@@ -1131,9 +1131,19 @@
1131
1131
  "additionalProperties": false
1132
1132
  }
1133
1133
  ],
1134
- "description": "Directories whose JS sources 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).",
1134
+ "description": "Directories whose sources — the languages `formats` selects — 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).",
1135
1135
  "default": ["src"]
1136
1136
  },
1137
+ "formats": {
1138
+ "type": "array",
1139
+ "items": {
1140
+ "type": "string",
1141
+ "minLength": 1
1142
+ },
1143
+ "minItems": 1,
1144
+ "description": "jscpd format names the duplication (DRY) gate scans under `targetDirs`. The default covers JavaScript, JSX, TypeScript and TSX; jscpd's `javascript` format alone reads only `.js`/`.es`/`.es6`/`.mjs`/`.cjs`. Names are jscpd's own vocabulary and are not restricted here. Widening the set adds rows, so re-seat the baseline with `npm run duplication:reanchor` after changing it.",
1145
+ "default": ["javascript", "jsx", "typescript", "tsx"]
1146
+ },
1137
1147
  "ignoreGlobs": {
1138
1148
  "type": "array",
1139
1149
  "items": {
@@ -1439,12 +1449,15 @@
1439
1449
  },
1440
1450
  "environments": {
1441
1451
  "type": "object",
1442
- "description": "Deployment targets the QA harness can run against (Epic #4326). A map keyed by environment name (e.g. `local`, `staging`), each carrying its own `baseUrl`, an optional per-environment sign-in seam, and an optional `allowWrites` gate. `signInSeam` is the union `{ urlTemplate }` (a dev impersonation route) or `{ skill }` (a skill id such as `stack/qa/acme-sso`, resolved against `.agents/skills/` then the consumer-writable `.agents/local/skills/` zone, and rejected loudly by resolveQaEnvironment when it resolves under neither); omit it entirely for a target with no sign-in seam. resolveQaEnvironment selects one environment per invocation by name or by raw-URL origin match against `baseUrl`; `allowWrites` defaults to true only for the `local` environment. Replaces the retired top-level single `signInSeam`.",
1452
+ "description": "Deployment targets the QA harness can run against (Epic #4326). A map keyed by environment name (e.g. `local`, `staging`), each carrying its own `baseUrl`, an optional per-environment sign-in seam, and an optional `allowWrites` gate. `signInSeam` is the union `{ urlTemplate }` (a dev impersonation route) or `{ skill }` (a skill id such as `stack/qa/acme-sso`, resolved against `.agents/skills/` then the consumer-writable `.agents/local/skills/` zone, and rejected loudly by resolveQaEnvironment when it resolves under neither); omit it entirely for a target with no sign-in seam. resolveQaEnvironment selects one environment per invocation by name or by raw-URL origin match against `baseUrl`; `allowWrites` defaults to true only for the `local` environment. An optional `database` object `{ urlEnv, allowAudit? }` names the environment variable holding that target's database connection string (the name only, never the URL) for the `/audit-data-model` live-schema pass; `allowAudit` gates that read-only pass and, like `allowWrites`, defaults to true only for `local`. Point `urlEnv` at a role granted catalog read only. A production database is never audited live, whatever this block says. Replaces the retired top-level single `signInSeam`.",
1443
1453
  "default": {
1444
1454
  "local": {
1445
1455
  "baseUrl": "http://localhost:3000",
1446
1456
  "signInSeam": {
1447
1457
  "urlTemplate": "/dev/sign-in-as/{persona}"
1458
+ },
1459
+ "database": {
1460
+ "urlEnv": "DATABASE_URL"
1448
1461
  }
1449
1462
  },
1450
1463
  "staging": {
@@ -1499,6 +1512,21 @@
1499
1512
  },
1500
1513
  "allowWrites": {
1501
1514
  "type": "boolean"
1515
+ },
1516
+ "database": {
1517
+ "type": "object",
1518
+ "description": "Database target for the `/audit-data-model` read-only live-schema pass. `urlEnv` is the name of the environment variable carrying the connection string — never the URL itself. `allowAudit` opts the environment in to that pass; it defaults to true only for `local`.",
1519
+ "properties": {
1520
+ "urlEnv": {
1521
+ "type": "string",
1522
+ "pattern": "^[A-Z_][A-Z0-9_]*$"
1523
+ },
1524
+ "allowAudit": {
1525
+ "type": "boolean"
1526
+ }
1527
+ },
1528
+ "required": ["urlEnv"],
1529
+ "additionalProperties": false
1502
1530
  }
1503
1531
  },
1504
1532
  "required": ["baseUrl"],
@@ -25,7 +25,11 @@
25
25
  "foreign key",
26
26
  "constraint",
27
27
  "cascade",
28
- "backfill"
28
+ "backfill",
29
+ "unused table",
30
+ "dead column",
31
+ "drop column",
32
+ "introspect"
29
33
  ],
30
34
  "filePatterns": [
31
35
  "**/migrations/**",
@@ -50,7 +54,16 @@
50
54
  "vulnerability",
51
55
  "cve",
52
56
  "password",
53
- "encrypt"
57
+ "encrypt",
58
+ "ssrf",
59
+ "deserializ",
60
+ "traversal",
61
+ "webhook",
62
+ "export",
63
+ "prompt injection",
64
+ "llm",
65
+ "mcp",
66
+ "tool call"
54
67
  ],
55
68
  "filePatterns": [
56
69
  "**/*.lock",
@@ -18,6 +18,7 @@ import { resolveStoryWorkerModel } from './lib/config/agent-models.js';
18
18
  import { getPaths, resolveConfig } from './lib/config-resolver.js';
19
19
  import { Logger } from './lib/Logger.js';
20
20
  import { ensureDocsDigest } from './lib/orchestration/docs-digest.js';
21
+ import { resolveResumeEffort } from './lib/orchestration/resume-effort.js';
21
22
  import { expandIdList } from './lib/util/parse-id-list.js';
22
23
  import { runProbedStoriesWaveTick } from './stories-wave-tick.js';
23
24
 
@@ -51,6 +52,8 @@ const USAGE = {
51
52
  'The run ledger (<tempRoot>/run-<id>/ledger.json) records every id handed out\nas ready, so a repeat beat withholds it with no --dispatched bookkeeping from\nthe caller. It is additive: the tick still filters it against live state, so a\nledgered id that has since gone agent::done is dropped for you.',
52
53
  'A ledgered id that live state still reports as agent::ready is named in\nstalledDispatch[], with stalledDispatchReason carrying the recovery. It is a\nreport, never a release: a slow init and a dead spawn read alike here, so the\noperator edits the ledger and re-beats with --run-id.',
53
54
  '--merge-watch-mode async is added to every close command when the run holds\nmore than one Story, and omitted for a run of one. Close sees a single Story\nand cannot make that call for itself.',
55
+ 'Every close command carries --worker-model, and --worker-effort when the\nStory resumes after a prior block: every Story a beat hands out is\nworker-dispatched, including a one-Story resume.',
56
+ 'Each ready[] entry carries effort: "high" after one local un-recovered\nstory-blocked signal, "xhigh" after two or more, null otherwise. Pass a\nnon-null effort as the Agent call\'s effort; omit the parameter for null.',
54
57
  'Exit codes:\n 0 beat emitted\n 1 input error\n 2 dependency cycle (cycleError)\n 3 wedged\n 4 blocked — the HITL pause; stop the loop, do not poll',
55
58
  ],
56
59
  };
@@ -122,9 +125,10 @@ function writeLedger(
122
125
  /**
123
126
  * `--merge-watch-mode async` is a run-topology call close cannot make: with
124
127
  * siblings, sync closes serialize every merge wait; alone, sync lands fastest.
125
- * `--worker-model` rides only a multi-Story close — a one-Story run is inline.
128
+ * The worker flags ride every close a beat renders — every Story a beat hands
129
+ * out is worker-dispatched, a one-Story resume included.
126
130
  * @param {{ storyId: number, mainRepo: string, storyCount: number,
127
- * workerModel?: string|null }} args
131
+ * workerModel?: string|null, workerEffort?: string|null }} args
128
132
  * @returns {string}
129
133
  */
130
134
  export function renderCloseCommand({
@@ -132,6 +136,7 @@ export function renderCloseCommand({
132
136
  mainRepo,
133
137
  storyCount,
134
138
  workerModel,
139
+ workerEffort,
135
140
  }) {
136
141
  const parts = [
137
142
  'node',
@@ -139,17 +144,20 @@ export function renderCloseCommand({
139
144
  `--story ${storyId}`,
140
145
  `--cwd ${mainRepo}`,
141
146
  ];
142
- if (storyCount > 1) parts.push(...multiStoryCloseFlags(workerModel));
147
+ if (storyCount > 1) parts.push('--merge-watch-mode async');
148
+ parts.push(...workerCloseFlags(workerModel, workerEffort));
143
149
  return parts.join(' ');
144
150
  }
145
151
 
146
152
  /**
147
153
  * @param {string|null|undefined} workerModel
154
+ * @param {string|null|undefined} workerEffort
148
155
  * @returns {string[]}
149
156
  */
150
- function multiStoryCloseFlags(workerModel) {
151
- const flags = ['--merge-watch-mode async'];
157
+ function workerCloseFlags(workerModel, workerEffort) {
158
+ const flags = [];
152
159
  if (workerModel) flags.push(`--worker-model ${workerModel}`);
160
+ if (workerEffort) flags.push(`--worker-effort ${workerEffort}`);
153
161
  return flags;
154
162
  }
155
163
 
@@ -268,11 +276,20 @@ export function renderDispatchPrompt({
268
276
  * @param {string} args.mainRepo
269
277
  * @param {string|null} args.docsDigestPath
270
278
  * @param {object} [args.config]
279
+ * @param {string|null} [args.effort] The resume effort; null inherits.
271
280
  * @param {object} [deps]
272
- * @returns {{ id: number, promptPath: string }}
281
+ * @returns {{ id: number, promptPath: string, effort: string|null }}
273
282
  */
274
283
  function buildDispatchEntry(
275
- { storyId, body, runTempDir, mainRepo, docsDigestPath, config },
284
+ {
285
+ storyId,
286
+ body,
287
+ runTempDir,
288
+ mainRepo,
289
+ docsDigestPath,
290
+ config,
291
+ effort = null,
292
+ },
276
293
  { buildChecklistFn, writeFileFn = fs.writeFileSync } = {},
277
294
  ) {
278
295
  // The same Story-scoped path single-story-init returns in its envelope.
@@ -295,7 +312,18 @@ function buildDispatchEntry(
295
312
  }),
296
313
  'utf8',
297
314
  );
298
- return { id: storyId, promptPath };
315
+ return { id: storyId, promptPath, effort };
316
+ }
317
+
318
+ /**
319
+ * @param {number[]} ids
320
+ * @param {(storyId: number) => Promise<string|null>} effortFn
321
+ * @returns {Promise<Map<number, string|null>>}
322
+ */
323
+ async function resolveEfforts(ids, effortFn) {
324
+ const unique = [...new Set(ids)];
325
+ const efforts = await Promise.all(unique.map((id) => effortFn(id)));
326
+ return new Map(unique.map((id, i) => [id, efforts[i] ?? null]));
299
327
  }
300
328
 
301
329
  /**
@@ -420,6 +448,7 @@ export async function runDeliverRunBeat(
420
448
  tickFn = runProbedStoriesWaveTick,
421
449
  resolveConfigFn = resolveConfig,
422
450
  ensureDocsDigestFn = ensureDocsDigest,
451
+ resumeEffortFn = resolveResumeEffort,
423
452
  mkdirFn = fs.mkdirSync,
424
453
  ...entryDeps
425
454
  } = deps;
@@ -475,6 +504,10 @@ export async function runDeliverRunBeat(
475
504
  const bodyById = new Map(
476
505
  records.map((record) => [record.id, record.body ?? '']),
477
506
  );
507
+ const effortById = await resolveEfforts(
508
+ [...readyIds, ...handoffIds],
509
+ (storyId) => resumeEffortFn(storyId, { config: resolved }),
510
+ );
478
511
  const ready = readyIds.map((storyId) =>
479
512
  buildDispatchEntry(
480
513
  {
@@ -484,6 +517,7 @@ export async function runDeliverRunBeat(
484
517
  mainRepo,
485
518
  docsDigestPath,
486
519
  config: resolved,
520
+ effort: effortById.get(storyId) ?? null,
487
521
  },
488
522
  entryDeps,
489
523
  ),
@@ -508,6 +542,7 @@ export async function runDeliverRunBeat(
508
542
  mainRepo,
509
543
  storyCount: ids.length,
510
544
  workerModel,
545
+ workerEffort: effortById.get(storyId) ?? null,
511
546
  }),
512
547
  })),
513
548
  done: tick.epilogueDue === true,
@@ -3,11 +3,18 @@
3
3
  * Pure: returns a string.
4
4
  */
5
5
 
6
+ import { auditFindingRecord } from '../findings/audit-finding-record.js';
7
+ import { semanticKeyFor } from '../findings/route-finding.js';
6
8
  import { SEVERITIES, sortBySeverity } from '../findings/severity.js';
7
- import { auditLabelFooterForFindings } from './audit-label-taxonomy.js';
9
+ import {
10
+ auditLabelFooterForFindings,
11
+ definesAuditLabel,
12
+ } from './audit-label-taxonomy.js';
13
+ import { auditLabelsForFindings } from './audit-lenses.js';
8
14
  import {
9
15
  renderFingerprintFooter,
10
16
  renderSemanticKeyFooter,
17
+ toCanonicalFinding,
11
18
  } from './finding-adapter.js';
12
19
  import { findingBullets, SEED_FINDING_FIELDS } from './finding-bullets.js';
13
20
 
@@ -126,6 +133,29 @@ function formatDedupFooters(groups) {
126
133
  .join('\n');
127
134
  }
128
135
 
136
+ /**
137
+ * One `audit-finding` record per fingerprinted finding, so an N>1 plan can
138
+ * attribute each identity to the Stories that cover its files instead of
139
+ * smearing the group footers across every Story. Seed-only.
140
+ *
141
+ * @param {object[]} groups
142
+ * @returns {string}
143
+ */
144
+ function formatFindingRecords(groups) {
145
+ return groups
146
+ .flatMap((g) => (Array.isArray(g.findings) ? g.findings : []))
147
+ .filter((f) => typeof f?.fingerprint?.full === 'string')
148
+ .map((f) =>
149
+ auditFindingRecord({
150
+ sha: f.fingerprint.full,
151
+ key: semanticKeyFor(toCanonicalFinding(f)),
152
+ label: auditLabelsForFindings([f]).find(definesAuditLabel) ?? null,
153
+ files: Array.isArray(f.files) ? f.files : [],
154
+ }),
155
+ )
156
+ .join('\n');
157
+ }
158
+
129
159
  function formatKeyFiles(groups) {
130
160
  const files = new Set();
131
161
  for (const g of groups) for (const f of g.files) files.add(f);
@@ -168,7 +198,12 @@ export function buildPlanSeedMarkdown({ groups, findings, sourceReports }) {
168
198
  const scope = formatFindingsList(findings);
169
199
  const files = formatKeyFiles(groups);
170
200
  const assumptions = formatKeyAssumptions(sourceReports);
171
- const dedupFooters = formatDedupFooters(groups);
201
+ const dedupFooters = [
202
+ formatDedupFooters(groups),
203
+ formatFindingRecords(groups),
204
+ ]
205
+ .filter(Boolean)
206
+ .join('\n');
172
207
 
173
208
  return [
174
209
  '# Idea Seed: Audit Remediation',
@@ -8,7 +8,13 @@ import path from 'node:path';
8
8
  import { resolveDependencyVersion } from '../dependency-version.js';
9
9
 
10
10
  const DEFAULT_MIN_TOKENS = 50;
11
- const DEFAULT_FORMATS = Object.freeze(['javascript']);
11
+ /** Mirrors the `gates.duplication.formats` schema default. */
12
+ const DEFAULT_FORMATS = Object.freeze([
13
+ 'javascript',
14
+ 'jsx',
15
+ 'typescript',
16
+ 'tsx',
17
+ ]);
12
18
 
13
19
  const require = createRequire(import.meta.url);
14
20
 
@@ -569,11 +569,17 @@ function buildDefaultDuplicationScorer({ cwd, config, quality, detect } = {}) {
569
569
  const ignoreGlobs = Array.isArray(dupCfg.ignoreGlobs)
570
570
  ? dupCfg.ignoreGlobs
571
571
  : [];
572
+ // Absent or empty falls through to the scanner's own default.
573
+ const formats =
574
+ Array.isArray(dupCfg.formats) && dupCfg.formats.length > 0
575
+ ? dupCfg.formats
576
+ : undefined;
572
577
  return async (_files, opts) => {
573
578
  const effectiveCwd = opts?.cwd ?? cwd ?? process.cwd();
574
579
  return scanDuplication({
575
580
  targetDirs,
576
581
  cwd: effectiveCwd,
582
+ formats,
577
583
  ignoreGlobs,
578
584
  detect: detect ?? resolveDetectClones(),
579
585
  });
@@ -177,6 +177,20 @@ export function parseWorkerModel(value) {
177
177
  };
178
178
  }
179
179
 
180
+ /**
181
+ * The story-worker figures close records, raw — validated by the runner.
182
+ *
183
+ * @param {Record<string, unknown>} values
184
+ * @returns {{ workerTokens: unknown, workerModel: unknown, workerEffort: unknown }}
185
+ */
186
+ function workerFields(values) {
187
+ return {
188
+ workerTokens: values['worker-tokens'],
189
+ workerModel: values['worker-model'],
190
+ workerEffort: values['worker-effort'],
191
+ };
192
+ }
193
+
180
194
  /**
181
195
  * Throws when a validating flag parser rejects a value; error handlers use
182
196
  * {@link parseSprintArgsTolerant} instead of re-calling this.
@@ -210,6 +224,7 @@ export function parseSprintArgs(
210
224
  'override-review-block': { type: 'string' },
211
225
  'worker-tokens': { type: 'string' },
212
226
  'worker-model': { type: 'string' },
227
+ 'worker-effort': { type: 'string' },
213
228
  executor: { type: 'string' },
214
229
  cwd: { type: 'string' },
215
230
  'recut-of': { type: 'string' },
@@ -240,8 +255,7 @@ export function parseSprintArgs(
240
255
  overrideReviewBlock: tolerant
241
256
  ? tolerantOverrideReviewBlock(values['override-review-block'])
242
257
  : parseOverrideReviewBlock(values['override-review-block']),
243
- workerTokens: values['worker-tokens'],
244
- workerModel: values['worker-model'],
258
+ ...workerFields(values),
245
259
  executor: values.executor ?? null,
246
260
  cwd:
247
261
  (typeof values.cwd === 'string' && values.cwd.trim()) ||
@@ -173,7 +173,7 @@ const PREFIX_MEANINGS = Object.freeze([
173
173
  ],
174
174
  [
175
175
  'qa.environments',
176
- 'QA harness deployment target (baseUrl, per-environment sign-in seam, allowWrites gate).',
176
+ 'QA harness deployment target (baseUrl, per-environment sign-in seam, allowWrites gate, optional read-only database audit target).',
177
177
  ],
178
178
  ['qa.personas', 'QA harness persona / credential mapping.'],
179
179
  [
@@ -5,7 +5,7 @@ import { gateBase, LIST_OR_EXTENDER_OF_STRINGS } from './shared.js';
5
5
  export const DUPLICATION_GATE = {
6
6
  type: 'object',
7
7
  description:
8
- '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.',
8
+ 'Code-duplication (DRY) gate (Story #3664). Shares the gate base and adds the scan-scope extras: the `targetDirs` the duplication scanner walks, the jscpd `formats` it reads there, and `ignoreGlobs` to exclude files from the scan.',
9
9
  properties: {
10
10
  ...gateBase({
11
11
  enabled: false,
@@ -16,9 +16,17 @@ export const DUPLICATION_GATE = {
16
16
  targetDirs: {
17
17
  ...LIST_OR_EXTENDER_OF_STRINGS,
18
18
  description:
19
- "Directories whose JS sources 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).",
19
+ "Directories whose sources — the languages `formats` selects — 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).",
20
20
  default: ['src'],
21
21
  },
22
+ formats: {
23
+ type: 'array',
24
+ items: { type: 'string', minLength: 1 },
25
+ minItems: 1,
26
+ description:
27
+ "jscpd format names the duplication (DRY) gate scans under `targetDirs`. The default covers JavaScript, JSX, TypeScript and TSX; jscpd's `javascript` format alone reads only `.js`/`.es`/`.es6`/`.mjs`/`.cjs`. Names are jscpd's own vocabulary and are not restricted here. Widening the set adds rows, so re-seat the baseline with `npm run duplication:reanchor` after changing it.",
28
+ default: ['javascript', 'jsx', 'typescript', 'tsx'],
29
+ },
22
30
  ignoreGlobs: {
23
31
  type: 'array',
24
32
  items: { type: 'string', minLength: 1 },