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
@@ -361,12 +361,13 @@ export class TicketGateway {
361
361
  *
362
362
  * @field-manifest POST /repos/{owner}/{repo}/issues/{n}/assignees: assignees
363
363
  * @field-manifest PATCH /repos/{owner}/{repo}/issues/{n}:
364
- * body, assignees, state, state_reason, labels
364
+ * title, body, assignees, state, state_reason, labels
365
365
  */
366
366
  /* node:coverage ignore next */
367
367
  async updateTicket(ticketId, mutations) {
368
368
  await this._addAssignees(ticketId, mutations.addAssignees);
369
369
  const patch = {};
370
+ if (mutations.title !== undefined) patch.title = mutations.title;
370
371
  if (mutations.body !== undefined) patch.body = mutations.body;
371
372
  if (mutations.assignees) patch.assignees = mutations.assignees;
372
373
  if (mutations.state !== undefined) patch.state = mutations.state;
@@ -32,6 +32,7 @@ import {
32
32
  readNativeBlockedBy,
33
33
  toStoryRecord,
34
34
  } from './lib/orchestration/resolve-stories.js';
35
+ import { resolveRunDispatchInputs } from './lib/orchestration/resume-effort.js';
35
36
  import { createProvider } from './lib/provider-factory.js';
36
37
  import { concurrentMap } from './lib/util/concurrent-map.js';
37
38
  import { paginateRest } from './providers/github/request-helpers.js';
@@ -189,12 +190,13 @@ export async function resolveForeignDone({ provider, dag, inSetIds }) {
189
190
  /**
190
191
  * @param {{ ids: string, native?: boolean, pretty?: boolean,
191
192
  * allowUnlabelled?: boolean }} args
192
- * @param {{ provider: object, config: object, stdout?: { write(s: string): void } }} deps
193
+ * @param {{ provider: object, config: object, stdout?: { write(s: string): void },
194
+ * countPriorBlocksFn?: Function }} deps
193
195
  * @returns {Promise<number>}
194
196
  */
195
197
  export async function runResolveStories(
196
198
  { ids: rawIds, native = true, pretty = false, allowUnlabelled = false },
197
- { provider, config, stdout = process.stdout },
199
+ { provider, config, stdout = process.stdout, countPriorBlocksFn },
198
200
  ) {
199
201
  const ids = parseIds(rawIds);
200
202
  const owner = config.github?.owner;
@@ -221,6 +223,10 @@ export async function runResolveStories(
221
223
  nativeEdges,
222
224
  foreignDone,
223
225
  warn: () => {},
226
+ ...(await resolveRunDispatchInputs(stories, {
227
+ config,
228
+ countFn: countPriorBlocksFn,
229
+ })),
224
230
  });
225
231
 
226
232
  stdout.write(
@@ -18,13 +18,17 @@
18
18
  * [--override-review-block <reason>]
19
19
  * [--worker-tokens <n>]
20
20
  * [--worker-model <model>]
21
+ * [--worker-effort <level>]
21
22
  *
22
23
  * `--worker-tokens <n>` is the story-worker's host-reported token total,
23
24
  * recorded best-effort in the close result's `telemetry` (absent or invalid →
24
25
  * `null` plus a warning; never a change of status or exit code).
25
26
  * `--worker-model <model>` is the dispatched story-worker's resolved model,
26
- * which deliver-run renders on a multi-Story close (`telemetry.workerModel`;
27
- * an inline close omits it and records `null`).
27
+ * which deliver-run renders on every worker-dispatched close
28
+ * (`telemetry.workerModel`; an inline close omits it and records `null`).
29
+ * `--worker-effort <level>` is the per-call effort a resumed story-worker ran
30
+ * at (`telemetry.workerEffort`), rendered beside it when the Story resumed
31
+ * after a prior block.
28
32
  * `--override-review-block <reason>` is the audited escape past a code-review
29
33
  * CRITICAL blocker (instead of a hand-merge with no record).
30
34
  * `--merge-watch-mode async` is passed per close by the orchestrator, the only
@@ -144,7 +148,11 @@ runAsCli(import.meta.url, main, {
144
148
  ],
145
149
  [
146
150
  '--worker-model <model>',
147
- 'The dispatched story-worker’s resolved model, recorded in the close result’s `telemetry.workerModel` beside `workerTokens`. deliver-run renders it on every close of a multi-Story run; an inline close omits it and records null. Best-effort: an invalid value records null with a warning and never changes the status or exit code.',
151
+ 'The dispatched story-worker’s resolved model, recorded in the close result’s `telemetry.workerModel` beside `workerTokens`. deliver-run renders it on every worker-dispatched close (a multi-Story run, or a one-Story resume); an inline close omits it and records null. Best-effort: an invalid value records null with a warning and never changes the status or exit code.',
152
+ ],
153
+ [
154
+ '--worker-effort <level>',
155
+ 'The per-call effort (low|medium|high|xhigh|max) the dispatched story-worker ran at, recorded in the close result’s `telemetry.workerEffort` beside `workerModel`. deliver-run renders it when the Story resumed after a prior block; absent, it records null. Best-effort: an invalid value records null with a warning and never changes the status or exit code.',
148
156
  ],
149
157
  ],
150
158
  notes: [
@@ -1,5 +1,5 @@
1
1
  ---
2
- description: 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.
2
+ description: 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.
3
3
  ---
4
4
 
5
5
  # Data Model & Persistence Audit
@@ -8,11 +8,15 @@ You are a Data Modeler & Database Reliability Engineer analyzing the persistence
8
8
  layer — ORM model definitions, the migrations they should produce, and the seed
9
9
  data — as a first-class artifact, finding where model, migrations, and runtime
10
10
  schema silently disagree, where an assumed invariant is not enforced by a
11
- constraint, and where a migration is unsafe against a live database. The shared lens machinery lives in
11
+ constraint, where a migration is unsafe against a live database, and where
12
+ schema exists that nothing uses. The shared lens machinery lives in
12
13
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
13
14
  `{{auditOutputDir}}/audit-data-model-results.md`. Dimension values:
14
15
  `Drift | Constraint Completeness | Migration Hygiene | Type Fidelity |
15
- Access-Pattern Fit`; the report adds a **Low-Hanging Fruit** section.
16
+ Access-Pattern Fit | Dead Schema`. Extra finding field: **Evidence:** (a
17
+ reference-count or introspection command plus a `measured`, `static`, or
18
+ `provisional` tag). The report adds a **Low-Hanging Fruit** section and a
19
+ **Live Schema Verification** section.
16
20
 
17
21
  ## Applicability
18
22
 
@@ -54,9 +58,13 @@ the consumer ships the tooling:
54
58
 
55
59
  - **ORM drift tooling (preferred):** When the consumer ships an ORM CLI, run its
56
60
  read-only drift/status command and treat its output as primary evidence —
57
- `prisma migrate diff` / `prisma migrate status`, `drizzle-kit check`, or
58
- `typeorm schema:log`. These report exactly where the model definitions and the
59
- migration history disagree without a live database.
61
+ `prisma migrate diff` / `prisma migrate status`, or `typeorm schema:log`. On
62
+ Drizzle, run `drizzle-kit generate --out <temp dir>` with the output pointed
63
+ under `{{auditOutputDir}}`: a non-empty generated migration is exactly the
64
+ model↔migration drift, and the repo's own migrations directory is never
65
+ written. Drizzle's snapshot-consistency check validates the snapshot chain,
66
+ not drift, so it is not drift evidence. None of these needs a live
67
+ database.
60
68
  - **Read-only file fallback:** When no ORM CLI is present (or it needs a live
61
69
  database this audit must not touch), fall back to reading the model
62
70
  definitions, the migration files, and the seed scripts directly. This
@@ -96,6 +104,73 @@ Evaluate the persistence layer along these five dimensions:
96
104
  unindexed foreign keys and unindexed frequent filter columns, relations that
97
105
  force N+1 access, and soft-delete rows that leak through default queries
98
106
  because no default scope excludes them.
107
+ 6. **Dead schema:** Is every table, column, index, and enum the schema defines
108
+ actually used, and does everything the code uses actually exist?
109
+ - **Unused schema:** a schema symbol with zero references in the **query
110
+ surface** — every source file minus the schema files themselves,
111
+ `**/migrations/**`, and seed/fixture files. A symbol referenced only from
112
+ tests is still reported, with that fact in Current State. Cite the
113
+ reference-count command in **Evidence**.
114
+ - **Schema gap:** the reverse — a table or column the code references that the
115
+ schema lacks. Unindexed foreign keys stay under Access-Pattern Fit.
116
+ - **Provisional until corroborated:** raw SQL strings, `select *`, and
117
+ JSON/builder access hide references from a static count, so a zero-count
118
+ finding is tagged `provisional` and never graded above Medium until the
119
+ live pass corroborates it.
120
+ - **Common identifiers are runtime-only:** a column whose name is a common
121
+ identifier (`id`, `name`, `createdAt`, `updatedAt`, and the like) matches
122
+ unrelated code, so the static pass never reports it.
123
+
124
+ The core's **Entry points & public API surface** and **Dynamic / framework
125
+ reachability** exclusions apply unchanged.
126
+
127
+ ## Step 3: Live Schema Verification (opt-in, manual runs only)
128
+
129
+ Static detection always runs; this pass corroborates it against a live
130
+ database. It reuses the shared scaffold in
131
+ [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md#runtime-pass) for
132
+ target resolution and the skip-never-fake rule. Scaffold steps 2 (route
133
+ sampling) and 4 (median-of-3) do not apply: schema introspection is
134
+ deterministic and has no routes.
135
+
136
+ **When it runs.** Only on a manual invocation — when the `{{changedFiles}}`
137
+ fence above is the literal token. A populated fence (a `/mandrel-deliver` close
138
+ lens or a plan-run audit) always reports `skipped — change-set scoped run`; a
139
+ database connection never enters the close gate.
140
+
141
+ **The target.** The resolved environment's `qa.environments.<env>.database`
142
+ block names the environment variable holding the connection string
143
+ (`urlEnv`) and opts the environment in (`allowAudit`). Read the connection
144
+ string from that variable only; never print, log, or write it into the report.
145
+
146
+ **The probe.** Run only these read-only steps:
147
+
148
+ - **Introspection diff:** introspect the live schema into
149
+ `{{auditOutputDir}}/live-schema/` with the ORM's read-only introspection
150
+ command (`drizzle-kit introspect`, or `prisma db pull` against a temp copy of
151
+ the schema file), then diff it against the committed schema. Each hunk is a
152
+ model↔live **Drift** finding tagged `measured`.
153
+ - **Migration ledger:** compare the repo's migration journal to the live
154
+ migrations table. Report applied-but-absent-from-repo, pending, and
155
+ hash-mismatched entries under **Migration Hygiene**.
156
+ - **Catalog statistics (Postgres):** read `pg_stat_user_tables` and
157
+ `pg_stat_user_indexes`. A table never scanned or an index never used
158
+ graduates the matching provisional **Dead Schema** finding to `measured`.
159
+ Columns have no catalog statistic and stay static. Note the statistics reset
160
+ time, since a recent reset makes zero scans meaningless.
161
+
162
+ **Skip reasons.** The pass is skipped, never faked, and the Executive Summary
163
+ names which:
164
+
165
+ | Condition | Reported as |
166
+ | --- | --- |
167
+ | The fence carries a change set | `skipped — change-set scoped run` |
168
+ | No `database` block on the resolved environment, or `allowAudit` is false | `skipped — no database target configured` |
169
+ | The variable is unset or the connection fails | `skipped — database unreachable` |
170
+ | No ORM introspection command is available | `skipped — ORM introspection unavailable` |
171
+
172
+ When no SQL client is on PATH, the catalog step alone reports `catalog client
173
+ unavailable` and Dead Schema findings stay provisional.
99
174
 
100
175
  ## Not-applicable report
101
176
 
@@ -118,9 +193,18 @@ _None — lens not applicable._
118
193
 
119
194
  ## Constraint (lens-specific carve-out)
120
195
 
121
- This lens is read-only over **repo-observable state only** — schema files,
122
- migrations, ORM config, and read-only ORM drift/status commands. It MUST NOT
123
- connect to, read from, or mutate a production database; it MUST NOT run a
124
- migration or a destructive ORM command. API-contract/serialization coverage is
196
+ This lens is read-only over repo-observable state — schema files, migrations,
197
+ ORM config, and read-only ORM drift/status commands — plus, in Step 3 only, an
198
+ opted-in database:
199
+
200
+ - It MUST NOT connect to a **production** database, under any configuration.
201
+ - It connects to any other database **only** when that environment opts in via
202
+ `allowAudit`, **only** through the environment variable named by `urlEnv`,
203
+ and **only** with read-only introspection and catalog `SELECT`s. Any direct
204
+ session it opens sets `default_transaction_read_only=on` first.
205
+ - It MUST NOT run a migration, a `push` / `migrate` / `generate` against the
206
+ live target, a destructive ORM command, or any statement that writes.
207
+ - Besides the report, its only writes are the generated drift output and the
208
+ introspected schema under `{{auditOutputDir}}`. API-contract/serialization coverage is
125
209
  out of scope (deferred `audit-contract-compat` territory), and runtime query
126
210
  profiling belongs to `audit-performance`, which owns measured behavior.
@@ -1,17 +1,22 @@
1
1
  ---
2
- description: Audit dependency CVEs, input-validation gaps, secrets handling, and auth boundaries; emit a structured High/Medium/Low findings report.
2
+ description: 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.
3
3
  ---
4
4
 
5
5
  # Security & Vulnerability Audit
6
6
 
7
- You are a Cybersecurity Architect & Penetration Tester conducting a
8
- comprehensive security review (OWASP Top 10, insecure configs, attack vectors).
9
- The shared lens machinery lives in
7
+ You are a Cybersecurity Architect conducting a comprehensive security review
8
+ (OWASP Top 10, insecure configs, attack vectors). The shared lens machinery
9
+ lives in
10
10
  [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
11
11
  `{{auditOutputDir}}/audit-security-results.md`. Extra finding fields: **CWE
12
- ID:** and **Baseline MUST:** (the violated `security-baseline.md` MUST). The
13
- report adds a **Defensive Recommendations** section (3–5 headers/configs/
14
- libraries to harden the app).
12
+ ID:**, **Baseline MUST:** (the violated MUST, or `none — trust-boundary
13
+ class`) and **Boundary:** (Step 2's six-clause gate). The report adds a
14
+ **Defensive Recommendations** section (3–5 hardening headers/configs/
15
+ libraries, plus every hardening note Step 2 demotes).
16
+
17
+ Tier B, the Boundary gate and the anchors are adapted, in Mandrel's words,
18
+ from Cloudflare's MIT-licensed `security-audit` skill — prose rubric only;
19
+ this lens stays one read-only auditor and never runs target code.
15
20
 
16
21
  ## Scope
17
22
 
@@ -30,23 +35,21 @@ Execution strategy.
30
35
 
31
36
  This lens does **not** grade against recalled OWASP lore. The authoritative
32
37
  rubric is [`../rules/security-baseline.md`](../rules/security-baseline.md) — the
33
- project's inviolable security MUSTs (Input Validation, Authentication,
34
- Authorization, Output & Rendering, Data Leakage & Logging, Transport & Headers,
35
- Secrets Management, Dependency Hygiene). Read it first. **Every finding MUST
36
- name the specific `security-baseline.md` MUST it violates** (e.g. "violates
37
- _Secrets Management_: 'Fallback or placeholder secrets MUST NOT be committed'").
38
- A finding that cannot be tied to a baseline MUST — or to a CWE where the
39
- baseline is silent — is out of scope for this lens.
38
+ project's inviolable security MUSTs. Read it first. **Every Tier A finding
39
+ MUST name the specific MUST it violates** (e.g. "violates _Secrets
40
+ Management_: 'Fallback or placeholder secrets MUST NOT be committed'"). **A
41
+ Tier B finding cites a CWE in `CWE ID` and writes `none — trust-boundary
42
+ class` in `Baseline MUST`** — the one sanctioned use of the CWE escape hatch.
43
+ A finding that fits neither tier is out of scope for this lens.
40
44
 
41
45
  ## Step 1: Detection Battery (Tool-First, Read-Only)
42
46
 
43
- Ground every finding in tool output, not vibes. Run the ladder below; each rung
44
- is **presence-gated** and **ecosystem-gated** per the core's
45
- [Ecosystem detection](helpers/audit-lens-core.md#ecosystem-detection): when a
46
- scanner for a detected ecosystem is absent, fall through to the next rung and
47
- note the missing tool as a `Security Misconfiguration` finding (recommend
48
- adopting it); a scanner for an undetected ecosystem is inapplicable and never a
49
- finding.
47
+ Ground every finding in tool output, not vibes. Each rung is **presence-** and
48
+ **ecosystem-gated** per the core's
49
+ [Ecosystem detection](helpers/audit-lens-core.md#ecosystem-detection): a
50
+ scanner absent for a detected ecosystem falls through to the next rung and is
51
+ noted as a `Security Misconfiguration` finding (recommend adopting it); one
52
+ for an undetected ecosystem is inapplicable and never a finding.
50
53
 
51
54
  1. **Dependency CVEs, per detected ecosystem.** Never recall CVEs from memory:
52
55
 
@@ -57,17 +60,16 @@ finding.
57
60
  cargo audit --json # Rust
58
61
  ```
59
62
 
60
- Each advisory reachable in production (`--omit=dev`; for Python, the
61
- runtime requirements, not dev extras) at `high` or `critical` is a
62
- _Vulnerable Components_ finding citing the advisory id and the violated
63
- _Dependency Hygiene_ MUST.
63
+ Each advisory reachable in production (`--omit=dev`; for Python, runtime
64
+ requirements only) at `high` or `critical` is a _Vulnerable Components_
65
+ finding citing the advisory id and the _Dependency Hygiene_ MUST.
64
66
 
65
67
  **Python static analysis.** On a detected Python ecosystem also run
66
- `bandit -r <srcDir> -f json` for injection / `eval` / `subprocess(shell=True)`
67
- / weak-crypto sinks — the Python counterpart of the grep battery below.
68
+ `bandit -r <srcDir> -f json` for injection / `eval` / `shell=True` /
69
+ weak-crypto sinks — the Python counterpart of the grep battery below.
68
70
 
69
- 2. **Secret scanning (`gitleaks` / `trufflehog`), with a grep fallback.** When
70
- `gitleaks` is installed, prefer it:
71
+ 2. **Secret scanning (`gitleaks` / `trufflehog`), with a grep fallback.**
72
+ Prefer `gitleaks` when installed:
71
73
 
72
74
  ```bash
73
75
  command -v gitleaks >/dev/null 2>&1 && gitleaks detect --no-banner --redact -v || \
@@ -76,7 +78,7 @@ finding.
76
78
  ```
77
79
 
78
80
  3. **Grep battery (deterministic fallback / augmentation).** Run these
79
- regardless — they are cheap and catch what a scanner's ruleset may miss:
81
+ regardless — cheap, and they catch what a scanner's ruleset misses:
80
82
 
81
83
  ```bash
82
84
  # Hardcoded key material (violates Secrets Management)
@@ -92,41 +94,126 @@ finding.
92
94
  ```
93
95
 
94
96
  4. **Manual surface review.** Then read the surfaces the battery flags plus:
95
- input-validation edges (API endpoints, form handlers — is input validated at
96
- the boundary with a strict schema?), auth/session handling (token storage,
97
- missing ownership checks on sensitive routes), and injection sinks
98
- (`dangerouslySetInnerHTML`, raw SQL, command execution). On Python, read
99
- the route decorators (Django views / DRF `permission_classes`, Flask /
100
- FastAPI routes and `Depends` guards) for missing ownership checks.
97
+ input-validation edges (is input schema-validated at the boundary?),
98
+ auth/session handling (token storage, missing ownership checks on
99
+ sensitive routes), and injection sinks (`dangerouslySetInnerHTML`, raw
100
+ SQL, command execution). On Python, read the route decorators (Django /
101
+ DRF `permission_classes`, Flask / FastAPI `Depends` guards) for missing
102
+ ownership checks.
101
103
 
102
104
  ## Step 2: Evaluation Dimensions
103
105
 
104
- Grade each finding against the `security-baseline.md` MUST it breaks (and the
105
- CWE where one applies):
106
+ ### Tier A — baseline-anchored (cite the MUST)
106
107
 
107
108
  1. **Injection:** SQL, NoSQL, OS Command, and Cross-Site Scripting (XSS) —
108
109
  _Output & Rendering_.
109
110
  2. **Broken Access Control:** Can a user access data they don't own? —
110
111
  _Authorization_.
111
- 3. **Cryptographic Failures:** Is sensitive data (passwords, PII) hashed or
112
- encrypted using modern standards? — _Authentication_ / _Data Leakage &
113
- Logging_.
114
- 4. **Security Misconfiguration:** Are there default passwords, verbose error
115
- messages in production, or insecure headers? — _Transport & Headers_.
116
- 5. **Vulnerable Components:** Are outdated libraries introducing risks? —
112
+ 3. **Cryptographic Failures:** Is sensitive data hashed or encrypted to
113
+ modern standards? — _Authentication_ / _Data Leakage & Logging_.
114
+ 4. **Security Misconfiguration:** Default passwords, verbose production
115
+ errors, insecure headers? — _Transport & Headers_.
116
+ 5. **Vulnerable Components:** Outdated libraries introducing risk? —
117
117
  _Dependency Hygiene_.
118
118
 
119
+ ### Tier B — trust-boundary classes (cite a CWE)
120
+
121
+ Each class names the sibling lens owning adjacent territory; when the only
122
+ defect is the sibling's, cite that lens and drop the finding here.
123
+
124
+ 1. **Business logic & state machines:** steps skipped, reordered or replayed;
125
+ partial failure leaving step 1 applied; numeric coercion (negative, zero,
126
+ overflow, string↔number); expiry and rate windows at exact instants; the
127
+ posture when config is missing, a flag is off or a migration is half
128
+ applied; stored data trusted because another path "validated it on the way
129
+ in". Check-then-act races and non-atomic writes are `/audit-performance`'s
130
+ Interleaving dimension, not this class.
131
+ 2. **Access-control depth:** whether the check that exists is the correct
132
+ one for this resource and this operation — a second path to the same
133
+ state change behind a weaker permission; a body field overriding what the permission model
134
+ restricts; authenticated-but-never-authorized endpoints; bulk, batch,
135
+ export and import paths skipping per-item checks. Shares the
136
+ _Authorization_ MUST with Tier A — merge rather than double-file.
137
+ 3. **Resource & file handling:** path traversal via symlinks, encoded
138
+ sequences or null bytes; SSRF via user-supplied fetch, webhook or callback
139
+ URLs and their redirects; unsafe deserialization; zip slip; temp files.
140
+ Install scripts and lockfile provenance are `/audit-dependencies`'s.
141
+ 4. **Cryptography & secrets misuse:** weak randomness for tokens or nonces;
142
+ timing-unsafe comparison; nonce/IV reuse; unauthenticated modes, missing
143
+ HMAC checks; error paths that fall back to no crypto. Hardcoded-secret
144
+ _presence_ is Step 1's rung and `/audit-privacy`'s — this is about _use_.
145
+ 5. **Feature abuse & data leakage:** export or backup including data above
146
+ the caller's level; import or restore bypassing validation or permissions;
147
+ search/filter/sort as an existence oracle; enumeration through differing
148
+ errors, timings or status codes; over-scoped preview tokens; cache
149
+ headers serving private content from a shared cache. PII-in-logs and
150
+ retention are `/audit-privacy`'s.
151
+ 6. **LLM & tool-binding boundaries** (ecosystem-gated: only when manifests
152
+ or imports show prompt assembly, a model API, tool/MCP definitions or
153
+ agent memory; otherwise omit silently): indirect prompt injection via
154
+ retrieved content; tool arguments reaching a downstream sink;
155
+ confused-deputy actions bound to the wrong principal; approval not bound
156
+ to the final action and resource; sub-agent or MCP trust inherited
157
+ unchecked; model output rendered or executed unsanitized.
158
+
159
+ ### The Boundary gate (every finding, both tiers)
160
+
161
+ Fill **Boundary:** as one line of six clauses: _lower-trust
162
+ principal → accepted input or action → intended control → crossed boundary →
163
+ affected principal or resource → observed or owner-observable result_. Three
164
+ rules follow:
165
+
166
+ - **An unfillable Boundary is not a finding.** A best practice that is merely
167
+ absent, with nobody and nothing concretely exposed, is a **hardening note**
168
+ under `## Defensive Recommendations`, never under `## Detailed Findings`.
169
+ - **Defense-in-depth gaps are hardening notes.** When one present layer
170
+ already prevents the crossing, a missing second layer is a note.
171
+ - **Severity never exceeds the demonstrated result.** A crash is not code
172
+ execution; self-impact is not privilege gain. A deployment fact absent from
173
+ the repo (proxy, provider, identity policy, CDN) is neither assumed present
174
+ nor absent: name it in `Current State`, grade on the demonstrated result
175
+ only, and let the self-cross-check keep or drop it on the ordinary bar.
176
+
177
+ ## Step 3: Severity anchors (security-anchored)
178
+
179
+ Grade on the shared scale, anchored to the Boundary result:
180
+
181
+ - **Critical** — no credentials needed and the result is code execution,
182
+ the whole data store, or any account the caller picks; or a leaked secret.
183
+ - **High** — an explicit control is wholly circumvented with real effect:
184
+ logging in as someone else, reading or writing another tenant's data,
185
+ persisted script that runs for other users, or RCE behind a login.
186
+ - **Medium** — a genuine crossing, but small: rare preconditions, few
187
+ affected records, or a narrow resource set.
188
+ - **Low** — internals that are not secret become visible, or the gain is
189
+ tiny for the effort.
190
+ - **Info** — real but negligible on its own; worth recording as a stepping
191
+ stone inside a larger finding.
192
+
193
+ The High/Medium line: is the control **wholly circumvented** for an action
194
+ that matters, or merely weakened? When you cannot name the concrete damage,
195
+ grade lower than instinct suggests.
196
+
119
197
  ## Report additions
120
198
 
121
- Beyond the shared skeleton (Executive Summary + Detailed Findings from the
122
- core), this lens's report carries its own title and a Defensive Recommendations
123
- section, and each finding adds the CWE ID / Baseline MUST fields:
199
+ Beyond the core's shared skeleton, this lens adds its title, a Defensive
200
+ Recommendations section and the CWE ID / Baseline MUST / Boundary fields:
124
201
 
125
202
  ```markdown
126
203
  # Security Audit Report
127
204
 
128
205
  ## Defensive Recommendations
129
206
 
130
- - [List 3-5 security headers, configurations, or libraries to implement to
131
- harden the app.]
207
+ - [3-5 headers, configs or libraries to harden the app, then every
208
+ hardening note the Boundary gate demoted.]
209
+
210
+ ### `path/to/primary-file.ext` — [Short title of the issue]
211
+
212
+ - **Dimension:** [a Tier A or Tier B dimension from Step 2]
213
+ - **Severity:** [Critical | High | Medium | Low | Info — per Step 3]
214
+ - **CWE ID:** [CWE-nnn]
215
+ - **Baseline MUST:** [the violated MUST | none — trust-boundary class]
216
+ - **Boundary:** [principal → input → control → crossed boundary → resource → result]
217
+ - [Location, Current State, Recommendation & Rationale (the smallest source
218
+ fix and why), Acceptance signal — per the core skeleton]
132
219
  ```
@@ -175,20 +175,35 @@ one-pager, and per-group even though the visible list is flat — they are the
175
175
  identity the next sweep matches on). `plan-persist` harvests them out of the seed on the
176
176
  `plan-context.json` envelope — which carries them apart from the seed text as
177
177
  `seed.provenance`, so an oversize seed cut for size keeps every footer — and
178
- appends them to **every** Story body it persists, via `carryProvenanceFooters`
178
+ appends them to the Story bodies it persists, via `carryProvenanceFooters`
179
179
  ([`lib/findings/route-finding.js`](../scripts/lib/findings/route-finding.js)).
180
- The carry is additive, union-preserving and idempotent, so a resumed persist
181
- cannot stack footers and a hand-authored fingerprint is never dropped.
180
+ The carry is additive and idempotent, so a resumed persist cannot stack
181
+ footers and a hand-authored fingerprint is never dropped.
182
+
183
+ **Which Story carries which finding.** Beside the group footers the seed
184
+ emits one seed-only `audit-finding` record per finding (sha, semantic key,
185
+ `audit::` label, files — primary first). A plan that persists **one** Story,
186
+ or a seed with no such records, stamps the union of every footer on every
187
+ Story. A plan that splits into **N>1** Stories attributes per Story instead:
188
+ an authored `provenance` wins outright; otherwise a Story owns each finding
189
+ whose primary file (or, when no Story covers the primary, any other file) its
190
+ `changes[]` covers by exact path or glob. A finding no Story covers is
191
+ **unattributed**: it is still stamped on every Story without an authored
192
+ `provenance`, and persist names it in its warnings as `unattributed audit
193
+ finding <sha12> (<file>) — carried on all N Stories`, so the smear is visible
194
+ rather than silent. The record itself is never stamped on a Story body.
182
195
 
183
196
  **The carry is fail-closed.** The footers are the only cross-run dedup memory,
184
197
  so a dropped one is a finding silently re-filed by the next sweep. An envelope
185
198
  whose seed was truncated and that carries no `seed.provenance` makes persist
186
199
  refuse before creating any Issue, naming the cause — regenerate the envelope.
187
200
 
188
- **Persist stamps the labels too.** It adds the seed's `audit::<dimension>`
189
- labels — the dedup corpus is listed by them, and an indexed run answers lookups
190
- from that pool without reaching the provider, so a footer alone leaves a
191
- plan-path Story invisible. Persist writes no file.
201
+ **Persist stamps the labels too.** It adds `audit::<dimension>` labels — the
202
+ dedup corpus is listed by them, and an indexed run answers lookups from that
203
+ pool without reaching the provider, so a footer alone leaves a plan-path Story
204
+ invisible. On the union path every Story gets the seed's union labels; under
205
+ N>1 attribution each Story gets the labels of the findings stamped on it (a
206
+ stamped sha with no seed record widens to the union). Persist writes no file.
192
207
 
193
208
  This is deliberately not an authoring step. If you find yourself copying a
194
209
  footer by hand, the carry is broken — fix it there rather than papering over it
@@ -22,8 +22,8 @@ a lens performs is its report artifact (plus, where a lens explicitly declares
22
22
  it, a single measurement/baseline artifact named in that lens's own
23
23
  Constraint). A lens that names a stricter or looser read-only carve-out in its
24
24
  own body (e.g. performance's non-mutating measurements, quality's permitted
25
- committed-baseline reads, data-model's no-database rule) refines this shared
26
- constraint for that lens only.
25
+ committed-baseline reads, data-model's opt-in read-only database carve-out)
26
+ refines this shared constraint for that lens only.
27
27
 
28
28
  ## Scope interpretation (Story / plan-run mode) {#scope-interpretation}
29
29
 
@@ -276,15 +276,18 @@ lens that has one, so a lens documents only its own probe.
276
276
  device profile, colour scheme — before finishing, so a following lens or QA
277
277
  run does not inherit it.
278
278
 
279
- **Skip reasons, and how to report them.** The pass is skipped, never faked, for
280
- either of two reasons, and the Executive Summary says which:
279
+ **Skip reasons, and how to report them.** The pass is skipped, never faked,
280
+ for any of the reasons below that applies to the lens's probe, and the
281
+ Executive Summary says which. A lens whose probe has further skip conditions
282
+ lists them in its own body:
281
283
 
282
284
  | Condition | Reported as |
283
285
  | --- | --- |
284
286
  | No `qa.environments` target is configured | `skipped — no target configured` |
285
287
  | The browser tooling is unavailable in this runtime | `skipped — browser tooling unavailable` |
288
+ | A database probe finds no opted-in `database` block on the target | `skipped — no database target configured` |
286
289
 
287
- The second is the one an unattended sweep meets: a scheduled run has no browser
290
+ The browser-tooling row is the one an unattended sweep meets: a scheduled run has no browser
288
291
  MCP server attached, so a lens that treated "cannot drive" as "nothing found"
289
292
  would report a clean runtime section it never ran. Do not invent a URL, do not
290
293
  start an arbitrary dev server, and do not fall back to a static-only claim
@@ -78,8 +78,13 @@ but not a cycle.
78
78
  unblocked it:
79
79
  `node .agents/scripts/update-ticket-state.js --ticket <id> --state agent::ready`.
80
80
  Do not poll the label yourself while waiting — the HITL pause is the operator's
81
- turn, not a slow beat. Before resuming, the operator raises session effort one
82
- step, and raises effort before switching models
81
+ turn, not a slow beat. Effort escalation on resume is automatic: the next beat's
82
+ `ready[]` entry for that Story carries `effort` (`high` after one prior block,
83
+ `xhigh` after two or more), which you pass as the Agent call's `effort`, and a
84
+ one-Story resume dispatches a worker for it. Only the inline fallback
85
+ (`delivery.routing.roleScopedAgents: false`, or a harness that cannot nest
86
+ spawns) keeps the operator step: raise session effort one step before resuming,
87
+ and raise effort before switching models
83
88
  ([effort escalation](../../docs/execution-reference.md#session-effort-and-model)).
84
89
 
85
90
  Each beat re-probes live state: it re-resolves the graph, classifies **done**
@@ -119,13 +119,15 @@ serialized against sibling Stories:
119
119
 
120
120
  ```bash
121
121
  node <main-repo>/.agents/scripts/single-story-close.js --story <storyId> --cwd <main-repo> \
122
- [--worker-tokens <n>] [--worker-model <model>]
122
+ [--worker-tokens <n>] [--worker-model <model>] [--worker-effort <level>]
123
123
  ```
124
124
 
125
125
  When the host reported a total-token figure for the story-worker's Agent
126
126
  dispatch, pass it as `--worker-tokens <n>` — close records it in its
127
- result's local `telemetry`; omit it when the host reports none. A
128
- multi-Story close command from deliver-run already carries `--worker-model`.
127
+ result's local `telemetry`; omit it when the host reports none. Every close
128
+ command deliver-run renders (a multi-Story run, or a one-Story resume) already
129
+ carries `--worker-model`, plus `--worker-effort` when the worker ran at a
130
+ resume effort.
129
131
 
130
132
  **The whole delivery tail** — gates, PR, merge wait, `agent::done` flip,
131
133
  post-land tail in one process. Never background it, never delegate it to a