mandrel 2.80.0 → 2.82.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 (48) hide show
  1. package/.agents/audit-checklists/security.md +15 -1
  2. package/.agents/docs/agentrc-reference.json +1 -0
  3. package/.agents/docs/configuration.md +3 -2
  4. package/.agents/docs/execution-reference.md +25 -5
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +12 -2
  7. package/.agents/schemas/audit-rules.json +10 -1
  8. package/.agents/scripts/deliver-run.js +43 -8
  9. package/.agents/scripts/lib/audit-to-stories/parse-audit-md.js +49 -24
  10. package/.agents/scripts/lib/baselines/duplication-scanner.js +16 -6
  11. package/.agents/scripts/lib/baselines/refresh-service.js +6 -0
  12. package/.agents/scripts/lib/bootstrap/manifest.js +128 -159
  13. package/.agents/scripts/lib/cli-args.js +16 -2
  14. package/.agents/scripts/lib/config/gates/duplication.schema.js +10 -2
  15. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  16. package/.agents/scripts/lib/observability/close-telemetry.js +17 -2
  17. package/.agents/scripts/lib/orchestration/complexity-gate.js +58 -11
  18. package/.agents/scripts/lib/orchestration/git-cleanup/phases/cli.js +31 -27
  19. package/.agents/scripts/lib/orchestration/git-cleanup/phases/render.js +25 -21
  20. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +51 -6
  21. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +177 -0
  22. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +174 -43
  23. package/.agents/scripts/lib/orchestration/plan-persist/supersede-ops.js +57 -15
  24. package/.agents/scripts/lib/orchestration/pr-watch-poll.js +107 -0
  25. package/.agents/scripts/lib/orchestration/pr-watch.js +168 -235
  26. package/.agents/scripts/lib/orchestration/reassert-status-column.js +102 -72
  27. package/.agents/scripts/lib/orchestration/resolve-stories.js +12 -3
  28. package/.agents/scripts/lib/orchestration/resume-effort.js +121 -0
  29. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +13 -2
  30. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +21 -3
  31. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-gate-steps.js +44 -2
  32. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +10 -2
  33. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +257 -0
  34. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +341 -0
  35. package/.agents/scripts/lib/orchestration/ticketing/reads.js +3 -0
  36. package/.agents/scripts/lib/orchestration/ticketing.js +0 -9
  37. package/.agents/scripts/plan-persist.js +20 -6
  38. package/.agents/scripts/providers/github/tickets.js +2 -1
  39. package/.agents/scripts/resolve-stories.js +8 -2
  40. package/.agents/scripts/single-story-close.js +11 -3
  41. package/.agents/workflows/audit-security.md +136 -49
  42. package/.agents/workflows/helpers/deliver-reference.md +7 -2
  43. package/.agents/workflows/helpers/deliver-story.md +5 -3
  44. package/.agents/workflows/helpers/plan-reference.md +42 -2
  45. package/.agents/workflows/mandrel-deliver.md +9 -4
  46. package/.agents/workflows/mandrel-plan.md +7 -1
  47. package/docs/CHANGELOG.md +35 -0
  48. package/package.json +2 -1
@@ -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
  },
@@ -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. |
@@ -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.
@@ -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": {
@@ -54,7 +54,16 @@
54
54
  "vulnerability",
55
55
  "cve",
56
56
  "password",
57
- "encrypt"
57
+ "encrypt",
58
+ "ssrf",
59
+ "deserializ",
60
+ "traversal",
61
+ "webhook",
62
+ "export",
63
+ "prompt injection",
64
+ "llm",
65
+ "mcp",
66
+ "tool call"
58
67
  ],
59
68
  "filePatterns": [
60
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,
@@ -69,6 +69,50 @@ function deriveDimension(fields, fallbackDimension) {
69
69
  return fallbackDimension;
70
70
  }
71
71
 
72
+ /**
73
+ * Strip wrapping quotes/brackets, trailing punctuation, and a `Location:`
74
+ * anchor (`:line`, `:line:col`, `:start-end`) from a raw token.
75
+ *
76
+ * @param {string} raw
77
+ * @returns {string}
78
+ */
79
+ function stripTokenDecoration(raw) {
80
+ return raw
81
+ .replace(/^[`'"([]+/, '')
82
+ .replace(/[`'")\].,;]+$/, '')
83
+ .trim()
84
+ .replace(/:\d+(?:-\d+)?(?::\d+)?$/, '');
85
+ }
86
+
87
+ /**
88
+ * Drop the `repoRoot` prefix (either separator) from a token, if present.
89
+ *
90
+ * @param {string} token
91
+ * @param {string} [repoRoot]
92
+ * @returns {string}
93
+ */
94
+ function relativiseToRoot(token, repoRoot) {
95
+ if (typeof repoRoot !== 'string' || repoRoot.length === 0) return token;
96
+ for (const sep of ['/', '\\']) {
97
+ const root = repoRoot.endsWith(sep) ? repoRoot : `${repoRoot}${sep}`;
98
+ if (token.startsWith(root)) return token.slice(root.length);
99
+ }
100
+ return token;
101
+ }
102
+
103
+ function isAbsoluteToken(token) {
104
+ return /^(?:[/\\]|[A-Za-z]:)/.test(token);
105
+ }
106
+
107
+ /**
108
+ * A separator-less token passes only as a bare file with a known extension,
109
+ * and only where `requireSeparator` does not forbid it.
110
+ */
111
+ function isAcceptedShape(token, requireSeparator) {
112
+ if (token.includes('/') || token.includes('\\')) return true;
113
+ return !requireSeparator && FILE_EXT.test(token);
114
+ }
115
+
72
116
  /**
73
117
  * Repo-relative path, or `null` for an absolute (outside `repoRoot`) or
74
118
  * degenerate token. A bare root-level file (`AGENTS.md`) is accepted in
@@ -82,32 +126,12 @@ function deriveDimension(fields, fallbackDimension) {
82
126
  */
83
127
  function normalisePathToken(raw, repoRoot, { requireSeparator = false } = {}) {
84
128
  if (typeof raw !== 'string') return null;
85
- const stripped = raw
86
- .replace(/^[`'"([]+/, '')
87
- .replace(/[`'")\].,;]+$/, '')
88
- .trim();
89
- // `Location:` anchors appear as `:line`, `:line:col`, and `:start-end`.
90
- const cleaned = stripped.replace(/:\d+(?:-\d+)?(?::\d+)?$/, '');
129
+ const cleaned = stripTokenDecoration(raw);
91
130
  if (!cleaned || cleaned === '.' || cleaned === '..') return null;
92
-
93
- let out = cleaned;
94
- if (typeof repoRoot === 'string' && repoRoot.length > 0) {
95
- for (const sep of ['/', '\\']) {
96
- const root = repoRoot.endsWith(sep) ? repoRoot : `${repoRoot}${sep}`;
97
- if (out.startsWith(root)) {
98
- out = out.slice(root.length);
99
- break;
100
- }
101
- }
102
- }
131
+ const out = relativiseToRoot(cleaned, repoRoot);
103
132
  // Still absolute ⇒ outside the repo; never a valid group key.
104
- if (out.startsWith('/') || out.startsWith('\\') || /^[A-Za-z]:/.test(out)) {
105
- return null;
106
- }
107
- const hasSeparator = out.includes('/') || out.includes('\\');
108
- if (requireSeparator && !hasSeparator) return null;
109
- if (!hasSeparator && !FILE_EXT.test(out)) return null;
110
- return out;
133
+ if (isAbsoluteToken(out)) return null;
134
+ return isAcceptedShape(out, requireSeparator) ? out : null;
111
135
  }
112
136
 
113
137
  /**
@@ -468,6 +492,7 @@ export const __testing = {
468
492
  isGroupingHeader,
469
493
  foldGroupingHeaders,
470
494
  normaliseSeverity,
495
+ normalisePathToken,
471
496
  extractFilePaths,
472
497
  normaliseTitle,
473
498
  deriveDimension,
@@ -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
 
@@ -53,16 +59,20 @@ export function relativisePath(sourceId, cwd) {
53
59
  }
54
60
 
55
61
  /**
56
- * A side with `end.line < start.line` counts nothing: its real span is
57
- * unrecoverable, and widening it recorded hundreds of phantom lines.
62
+ * A side ending before it starts, or past its file's counted length, counts
63
+ * nothing: its real span is unrecoverable (jscpd 4 can report the other
64
+ * file's end line), and widening or clamping it records phantom lines.
58
65
  *
59
66
  * @param {{ start?: { line?: number }, end?: { line?: number } }} dup
67
+ * @param {number} [maxLine] the file's counted length, when known
60
68
  * @returns {Array<number>} the 1-based line numbers the clone covers
61
69
  */
62
- function cloneLineNumbers(dup) {
70
+ function cloneLineNumbers(dup, maxLine) {
63
71
  const start = dup?.start?.line;
64
72
  const end = dup?.end?.line;
65
- if (!Number.isInteger(start) || !Number.isInteger(end)) return [];
73
+ if (!Number.isInteger(start) || !Number.isInteger(end) || end > maxLine) {
74
+ return [];
75
+ }
66
76
  const lines = [];
67
77
  for (let n = start; n <= end; n += 1) lines.push(n);
68
78
  return lines;
@@ -94,7 +104,7 @@ export function buildDuplicationRows(
94
104
  const file = relativisePath(side.sourceId, cwd);
95
105
  if (!file) continue;
96
106
  const set = dupLinesByFile.get(file) ?? new Set();
97
- for (const line of cloneLineNumbers(side)) set.add(line);
107
+ for (const n of cloneLineNumbers(side, counts.get(file))) set.add(n);
98
108
  dupLinesByFile.set(file, set);
99
109
  }
100
110
  }
@@ -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
  });