mandrel 2.111.0 → 2.112.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 (178) hide show
  1. package/.agents/agents/acceptance-critic.md +14 -0
  2. package/.agents/agents/auditor.md +14 -0
  3. package/.agents/agents/plan-critic.md +5 -0
  4. package/.agents/agents/story-worker.md +4 -1
  5. package/.agents/docs/agentrc-reference.json +22 -10
  6. package/.agents/docs/configuration.md +351 -37
  7. package/.agents/docs/execution-reference.md +11 -0
  8. package/.agents/rules/git-conventions-reference.md +7 -0
  9. package/.agents/schemas/agentrc.schema.json +174 -14
  10. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  11. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  12. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  13. package/.agents/schemas/baselines/crap.schema.json +37 -10
  14. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  15. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  16. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  17. package/.agents/schemas/crap-report.schema.json +6 -5
  18. package/.agents/schemas/story-deliver-terminal.schema.json +41 -2
  19. package/.agents/schemas/story-progress.schema.json +1 -1
  20. package/.agents/schemas/validation-evidence.schema.json +2 -2
  21. package/.agents/scripts/boot-sweep.js +41 -3
  22. package/.agents/scripts/coverage-capture.js +37 -3
  23. package/.agents/scripts/coverage-ratchet.js +106 -0
  24. package/.agents/scripts/evidence-gate.js +84 -21
  25. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  26. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  27. package/.agents/scripts/lib/baseline-loader.js +4 -2
  28. package/.agents/scripts/lib/baselines/codec.js +57 -0
  29. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  32. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  33. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  34. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  35. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  36. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  37. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  38. package/.agents/scripts/lib/baselines/reader.js +36 -9
  39. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  40. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  41. package/.agents/scripts/lib/baselines/writer.js +36 -21
  42. package/.agents/scripts/lib/changed-files.js +70 -6
  43. package/.agents/scripts/lib/child-exec.js +10 -0
  44. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  45. package/.agents/scripts/lib/close-lock-events.js +8 -3
  46. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  47. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  48. package/.agents/scripts/lib/close-validation/process.js +16 -7
  49. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  50. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  51. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  52. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  53. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  54. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  55. package/.agents/scripts/lib/config/explain.js +5 -2
  56. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  57. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  58. package/.agents/scripts/lib/config/git-roots.js +38 -4
  59. package/.agents/scripts/lib/config/handoff.js +24 -0
  60. package/.agents/scripts/lib/config/quality.js +26 -13
  61. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  62. package/.agents/scripts/lib/config-resolver.js +22 -2
  63. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  64. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  65. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  67. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  68. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  69. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  70. package/.agents/scripts/lib/coverage-capture.js +15 -0
  71. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  72. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  73. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  74. package/.agents/scripts/lib/crap-engine.js +3 -3
  75. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  76. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  77. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  78. package/.agents/scripts/lib/failure-rows.js +121 -0
  79. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  80. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  81. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  82. package/.agents/scripts/lib/gh-env.js +3 -6
  83. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  84. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  85. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  86. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  87. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  88. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  89. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  90. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  91. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  92. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  93. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  94. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  95. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  98. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  99. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  100. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  101. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  102. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  103. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  104. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  105. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  106. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  107. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  108. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  109. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  110. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  111. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  112. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  113. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  114. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  115. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  116. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  117. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  118. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  119. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +15 -3
  120. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  121. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  135. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  136. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  137. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  138. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  139. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  140. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  141. package/.agents/scripts/lib/orchestration/story-handoff.js +774 -196
  142. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  143. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  144. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  145. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  146. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  147. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  148. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  149. package/.agents/scripts/lib/suite-admission.js +20 -8
  150. package/.agents/scripts/lib/suite-sizing.js +146 -0
  151. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  152. package/.agents/scripts/merge-baseline.js +14 -3
  153. package/.agents/scripts/providers/github/comments.js +19 -3
  154. package/.agents/scripts/providers/github.js +1 -0
  155. package/.agents/scripts/review-dispositions-report.js +1 -1
  156. package/.agents/scripts/role-scope-guard.js +267 -0
  157. package/.agents/scripts/single-story-close.js +4 -4
  158. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  159. package/.agents/scripts/single-story-init.js +24 -4
  160. package/.agents/scripts/story-handoff.js +3 -3
  161. package/.agents/scripts/story-outcomes-report.js +231 -0
  162. package/.agents/scripts/story-review-compute.js +9 -5
  163. package/.agents/scripts/update-coverage-baseline.js +12 -2
  164. package/.agents/scripts/update-crap-baseline.js +9 -1
  165. package/.agents/workflows/helpers/code-review.md +63 -9
  166. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  167. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  168. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  169. package/.agents/workflows/helpers/deliver-story.md +7 -2
  170. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  171. package/docs/CHANGELOG.md +46 -0
  172. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  173. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  174. package/lib/cli/doctor-checks/llm-review.js +2 -11
  175. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  176. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  177. package/lib/cli/registry.js +5 -0
  178. package/package.json +1 -1
@@ -0,0 +1,187 @@
1
+ /**
2
+ * coverage-ratchet.js — CI's hand-back for a coverage capture deferred to CI.
3
+ * Adopt a CI-produced Istanbul artifact at the checked-out HEAD (placed at
4
+ * the configured coverage path and stamped exactly as a green local capture
5
+ * is), then score the per-file coverage and CRAP value ratchet over it.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ import {
12
+ computeContentDigest,
13
+ computeTreeDigest,
14
+ writeCaptureStamp,
15
+ } from './coverage-capture.js';
16
+ import { readHeadCommit } from './coverage-capture-delta.js';
17
+ import { captureGates } from './coverage-capture-passes.js';
18
+ import { gitSpawn } from './git-utils.js';
19
+
20
+ /** The `--scope` values: what the artifact measured. */
21
+ const SCOPES = new Set(['affected', 'full']);
22
+
23
+ /**
24
+ * @param {string[]} argv `process.argv.slice(2)`.
25
+ * @returns {{ artifact: string|null, head: string|null, scope: string, base: string|null, adoptOnly: boolean, error?: string }}
26
+ */
27
+ export function parseRatchetArgs(argv) {
28
+ const out = {
29
+ artifact: null,
30
+ head: null,
31
+ scope: 'affected',
32
+ base: null,
33
+ adoptOnly: false,
34
+ };
35
+ const valued = {
36
+ '--artifact': 'artifact',
37
+ '--head': 'head',
38
+ '--scope': 'scope',
39
+ '--base': 'base',
40
+ };
41
+ for (let i = 0; i < argv.length; i += 1) {
42
+ if (argv[i] === '--adopt-only') out.adoptOnly = true;
43
+ else if (valued[argv[i]]) out[valued[argv[i]]] = argv[++i] ?? null;
44
+ }
45
+ return { ...out, ...argError(out) };
46
+ }
47
+
48
+ /** @returns {{ error?: string }} */
49
+ function argError({ artifact, head, scope }) {
50
+ if (!artifact || !head)
51
+ return { error: '--artifact and --head are required' };
52
+ if (!SCOPES.has(scope))
53
+ return { error: `--scope must be affected or full, got "${scope}"` };
54
+ return {};
55
+ }
56
+
57
+ /** Tracked files with uncommitted changes, from `git status --porcelain`. */
58
+ function dirtyTracked(cwd, git) {
59
+ const res = git(cwd, 'status', '--porcelain', '--untracked-files=no');
60
+ if (res.status !== 0) return ['(git status failed)'];
61
+ return res.stdout.split('\n').filter((line) => line.trim().length > 0);
62
+ }
63
+
64
+ /** Why `artifact` cannot be adopted as Istanbul JSON, else `null`. */
65
+ function unreadableArtifact(artifact) {
66
+ try {
67
+ const parsed = JSON.parse(fs.readFileSync(artifact, 'utf8'));
68
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
69
+ ? null
70
+ : 'is not an Istanbul coverage-final.json object';
71
+ } catch (err) {
72
+ return `cannot be read as JSON (${err?.code ?? err?.message ?? err})`;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * The first reason the artifact may not be adopted here, else `null`: the
78
+ * declared head is not HEAD, a tracked file is dirty, or the artifact is
79
+ * missing or unparseable.
80
+ */
81
+ function adoptRefusal({ cwd, artifact, head, git, readHead }) {
82
+ const actual = readHead(cwd);
83
+ if (!actual || actual !== head) {
84
+ return `--head ${head} is not the checked-out HEAD (${actual ?? 'unreadable'}) — check out the ref the artifact was produced at`;
85
+ }
86
+ const dirty = dirtyTracked(cwd, git);
87
+ if (dirty.length > 0) {
88
+ return `tracked files are dirty, so the tree is not the one the artifact measured: ${dirty.join(', ')}`;
89
+ }
90
+ const unreadable = unreadableArtifact(artifact);
91
+ return unreadable ? `artifact ${artifact} ${unreadable}` : null;
92
+ }
93
+
94
+ /**
95
+ * Place the artifact at the configured coverage path and write the standard
96
+ * capture stamp for this tree, so every updater reads it as a green capture
97
+ * at HEAD. Returns the refusal reason, else `null`.
98
+ *
99
+ * @param {{ cwd: string, quality: { crap: object, coverage: object }, artifact: string, head: string, scope: 'affected'|'full', base: string, git?: Function, readHead?: Function }} opts
100
+ * @returns {string|null}
101
+ */
102
+ export function adoptArtifact({
103
+ cwd,
104
+ quality,
105
+ artifact,
106
+ head,
107
+ scope,
108
+ base,
109
+ git = gitSpawn,
110
+ readHead = readHeadCommit,
111
+ }) {
112
+ const source = path.resolve(cwd, artifact);
113
+ const refusal = adoptRefusal({ cwd, artifact: source, head, git, readHead });
114
+ if (refusal) return refusal;
115
+ const { crap, coverage } = captureGates(quality);
116
+ const target = path.resolve(cwd, coverage.coveragePath);
117
+ if (target !== source) {
118
+ fs.mkdirSync(path.dirname(target), { recursive: true });
119
+ fs.copyFileSync(source, target);
120
+ }
121
+ const written = writeCaptureStamp({
122
+ cwd,
123
+ coveragePath: coverage.coveragePath,
124
+ digest: computeContentDigest(cwd, crap.targetDirs),
125
+ treeDigest: computeTreeDigest(cwd, coverage.coveragePath),
126
+ commit: head,
127
+ ...(scope === 'affected' ? { scope, ref: base } : {}),
128
+ });
129
+ return written
130
+ ? null
131
+ : `no capture stamp could be written for ${coverage.coveragePath}`;
132
+ }
133
+
134
+ /**
135
+ * The value ratchet over the adopted artifact, in order: the changed files'
136
+ * coverage rows (working copy only), the CRAP preview, then the coverage and
137
+ * CRAP baselines gate.
138
+ *
139
+ * @param {string} scriptsDir @param {string} base
140
+ * @returns {Array<{ step: string, args: string[], env?: Record<string, string> }>}
141
+ */
142
+ export function ratchetSteps(scriptsDir, base) {
143
+ const script = (name) => path.join(scriptsDir, name);
144
+ return [
145
+ {
146
+ step: 'update-coverage-baseline',
147
+ args: [script('update-coverage-baseline.js'), '--diff-scope', base],
148
+ },
149
+ {
150
+ step: 'quality-preview-crap',
151
+ args: [
152
+ script('quality-preview.js'),
153
+ '--only',
154
+ 'crap',
155
+ '--changed-since',
156
+ base,
157
+ ],
158
+ },
159
+ {
160
+ step: 'check-baselines',
161
+ args: [
162
+ script('check-baselines.js'),
163
+ '--gate',
164
+ 'coverage,crap',
165
+ '--format',
166
+ 'text',
167
+ ],
168
+ env: { BASELINE_REF: base },
169
+ },
170
+ ];
171
+ }
172
+
173
+ /**
174
+ * Run each step with `run(args, env)`; the first non-zero exit is the
175
+ * failure, named.
176
+ *
177
+ * @param {ReturnType<typeof ratchetSteps>} steps
178
+ * @param {(args: string[], env?: Record<string, string>) => Promise<number>|number} run
179
+ * @returns {Promise<{ failedStep: string|null, status: number }>}
180
+ */
181
+ export async function scoreRatchet(steps, run) {
182
+ for (const { step, args, env } of steps) {
183
+ const status = await run(args, env);
184
+ if (status !== 0) return { failedStep: step, status };
185
+ }
186
+ return { failedStep: null, status: 0 };
187
+ }
@@ -9,20 +9,20 @@ import {
9
9
  } from './crap-coordinates.js';
10
10
 
11
11
  /**
12
- * Per-file half of `crapRowKey` (`${path}::${method}@${startLine}`).
12
+ * Per-file half of the CRAP row identity (`${path}::${method}`).
13
13
  *
14
- * @param {{method: string, startLine: number}} row
14
+ * @param {{method: string}} row
15
15
  * @returns {string}
16
16
  */
17
17
  function methodIdentityKey(row) {
18
- return `${row.method}@${row.startLine}`;
18
+ return row.method;
19
19
  }
20
20
 
21
21
  /**
22
22
  * Accepts both the in-memory `{file}` and on-disk `{path}` row shapes.
23
23
  *
24
- * @param {Array<{file?: string, path?: string, method: string, startLine: number, crap: number}>} baselineRows
25
- * @returns {Map<string, Map<string, {crap: number}>>} file → (method@startLine → row)
24
+ * @param {Array<{file?: string, path?: string, method: string, crap: number}>} baselineRows
25
+ * @returns {Map<string, Map<string, {crap: number}>>} file → (method → row)
26
26
  */
27
27
  function indexBaselineRowsByFile(baselineRows) {
28
28
  const byFile = new Map();
@@ -7,9 +7,9 @@ import {
7
7
  } from './crap-coordinates.js';
8
8
  import { deriveMethodIdentities } from './crap-method-identity.js';
9
9
  import { install as installAstCompat } from './escomplex-ast-compat.js';
10
- import { analyzeModule } from './escomplex-kernel.js';
10
+ import { analyzeModule, methodSiteOf } from './escomplex-kernel.js';
11
11
 
12
- export { COORDINATE_ORIGINAL, COORDINATE_TRANSPILED, crapFormula };
12
+ export { COORDINATE_ORIGINAL, crapFormula };
13
13
 
14
14
  /**
15
15
  * Returned for a source the kernel cannot parse — never `[]`, which would be
@@ -76,7 +76,7 @@ export function methodRowsFromReport(report, coverageForFile, mapLine = null) {
76
76
  const methods = report?.methods ?? [];
77
77
  // Derive identities over the whole list before skipping, so a skipped
78
78
  // method cannot shift its siblings' ordinals.
79
- const identities = deriveMethodIdentities(methods);
79
+ const identities = deriveMethodIdentities(methods, methods.map(methodSiteOf));
80
80
  const rows = [];
81
81
  for (const [i, m] of methods.entries()) {
82
82
  const rawStartLine = m?.lineStart;
@@ -6,16 +6,6 @@
6
6
  */
7
7
  const ESCOMPLEX_ANON_LABEL_RE = /^<anon method-\d+>$/;
8
8
 
9
- /**
10
- * True for a derived anonymous identity (ours or escomplex's).
11
- *
12
- * @param {unknown} method
13
- * @returns {boolean}
14
- */
15
- export function isAnonymousMethodLabel(method) {
16
- return typeof method === 'string' && method.startsWith('<anon ');
17
- }
18
-
19
9
  /**
20
10
  * A missing bound collapses to a zero-width span, never a drop, so the
21
11
  * method keeps a deterministic place in the scope tree.
@@ -29,62 +19,128 @@ function spanOf(m) {
29
19
  return { lineStart, lineEnd: Math.max(lineStart, lineEnd) };
30
20
  }
31
21
 
22
+ /** Anchor bytes that could not collide with segment syntax. */
23
+ const ANCHOR_UNSAFE_RE = /[^A-Za-z0-9_.$:-]/g;
24
+ const ANCHOR_MAX = 40;
25
+
32
26
  /**
33
- * Named methods keep their name. An anonymous one becomes `<anon {scope
34
- * path}>`, e.g. `<anon build/(files,opts)#0/(r)#0>`: each enclosing link is a
35
- * name, or a parameter list plus an ordinal among siblings with the same
36
- * parent and parameter list. Never derived from the body — that would re-key
37
- * a method on the very edit the gate must catch. Relies on escomplex's
38
- * pre-order emission (ancestors first) for a single-pass ancestor stack.
27
+ * @param {unknown} anchor
28
+ * @returns {string}
29
+ */
30
+ function sanitizeAnchor(anchor) {
31
+ if (typeof anchor !== 'string') return '';
32
+ return anchor.replace(ANCHOR_UNSAFE_RE, '_').slice(0, ANCHOR_MAX);
33
+ }
34
+
35
+ /**
36
+ * A label with every `#<ordinal>` stripped: what a row's identity is apart
37
+ * from its tie-breaks, for re-pairing on a key miss.
38
+ *
39
+ * @param {string} label
40
+ * @returns {string}
41
+ */
42
+ export function methodStem(label) {
43
+ return String(label).replace(/#\d+/g, '');
44
+ }
45
+
46
+ /**
47
+ * `<anchor>(<params>)#<ordinal>`, counting the ordinal in `ordinals`.
48
+ *
49
+ * @param {object} m
50
+ * @param {{anchor?: string|null}|undefined} site
51
+ * @param {string} parentPath
52
+ * @param {Map<string, number>} ordinals
53
+ * @returns {string}
54
+ */
55
+ function anonymousSegment(m, site, parentPath, ordinals) {
56
+ const params = Array.isArray(m?.paramNames) ? m.paramNames : [];
57
+ const head = `${sanitizeAnchor(site?.anchor)}(${params.join(',')})`;
58
+ // NUL can never appear in a scope path; keep it an escape (a raw NUL
59
+ // makes the file binary to git).
60
+ const bucket = `${parentPath}\u0000${head}`;
61
+ const ordinal = ordinals.get(bucket) ?? 0;
62
+ ordinals.set(bucket, ordinal + 1);
63
+ return `${head}#${ordinal}`;
64
+ }
65
+
66
+ /**
67
+ * Close the spans that ended before `lineStart`; the innermost still open
68
+ * is the line-span parent.
69
+ *
70
+ * @param {Array<{lineEnd: number, scopePath: string}>} openAncestors
71
+ * @param {number} lineStart
72
+ * @returns {string}
73
+ */
74
+ function innermostOpenPath(openAncestors, lineStart) {
75
+ while (openAncestors.length > 0 && openAncestors.at(-1).lineEnd < lineStart) {
76
+ openAncestors.pop();
77
+ }
78
+ return openAncestors.at(-1)?.scopePath ?? '';
79
+ }
80
+
81
+ /**
82
+ * The first holder of `scopePath` keeps it bare; each later one gets `#<n>`.
83
+ *
84
+ * @param {string} scopePath
85
+ * @param {Map<string, number>} seen
86
+ * @returns {string}
87
+ */
88
+ function disambiguate(scopePath, seen) {
89
+ const n = seen.get(scopePath) ?? 0;
90
+ seen.set(scopePath, n + 1);
91
+ return n === 0 ? scopePath : `${scopePath}#${n}`;
92
+ }
93
+
94
+ /**
95
+ * A method's identity is its scope path: the enclosing method segments
96
+ * joined by `/`, ending in its own segment, so a top-level named function
97
+ * keeps its bare name. An anonymous one is wrapped as `<anon {scope path}>`,
98
+ * e.g. `<anon build/arr.map(r)#0>`: its segment is a call-site anchor plus
99
+ * parameter list plus an ordinal among siblings sharing parent, anchor and
100
+ * parameters. A scope path seen earlier in the file gets `#<n>` (n from 1).
101
+ * Never derived from the body — that would re-key a method on the very edit
102
+ * the gate must catch.
103
+ *
104
+ * `sites[i]` (from the kernel's `methodSiteOf`) gives the exact enclosing
105
+ * method and anchor; without one, nesting falls back to line spans (relying
106
+ * on escomplex's pre-order emission) and there is no anchor.
39
107
  *
40
108
  * @param {Array<object>} methods `report.methods` from escomplex.
109
+ * @param {Array<{parent: object|null, anchor: string|null}|undefined>} [sites]
41
110
  * @returns {Array<{method: string, anonymous: boolean}>} Index-aligned with
42
111
  * `methods`.
43
112
  */
44
- export function deriveMethodIdentities(methods) {
113
+ export function deriveMethodIdentities(methods, sites = []) {
45
114
  const identities = [];
46
115
  /** @type {Array<{lineEnd: number, scopePath: string}>} */
47
116
  const openAncestors = [];
48
- /** Sibling counts keyed by `parent scope path` + `parameter list`. */
117
+ const pathOf = new Map();
118
+ /** Sibling counts keyed by parent path + anchor + parameter list. */
49
119
  const ordinals = new Map();
120
+ /** Collision counts per scope path, for the `#<n>` suffix. */
121
+ const seen = new Map();
50
122
 
51
- for (const m of methods ?? []) {
123
+ for (const [i, m] of (methods ?? []).entries()) {
52
124
  const { lineStart, lineEnd } = spanOf(m);
53
- while (
54
- openAncestors.length > 0 &&
55
- openAncestors[openAncestors.length - 1].lineEnd < lineStart
56
- ) {
57
- openAncestors.pop();
58
- }
59
- const parentPath =
60
- openAncestors.length > 0
61
- ? openAncestors[openAncestors.length - 1].scopePath
62
- : '';
63
-
125
+ const spanParent = innermostOpenPath(openAncestors, lineStart);
126
+ const site = sites?.[i];
127
+ const parentPath = site ? (pathOf.get(site.parent) ?? '') : spanParent;
64
128
  const name = typeof m?.name === 'string' ? m.name : '';
65
- let segment;
66
- let anonymous;
67
- if (name === '' || ESCOMPLEX_ANON_LABEL_RE.test(name)) {
68
- const params = Array.isArray(m?.paramNames) ? m.paramNames : [];
69
- const signature = `(${params.join(',')})`;
70
- // NUL can never appear in a scope path; keep it an escape (a raw NUL
71
- // makes the file binary to git).
72
- const bucket = `${parentPath}\u0000${signature}`;
73
- const ordinal = ordinals.get(bucket) ?? 0;
74
- ordinals.set(bucket, ordinal + 1);
75
- segment = `${signature}#${ordinal}`;
76
- anonymous = true;
77
- } else {
78
- segment = name;
79
- anonymous = false;
80
- }
129
+ const anonymous = name === '' || ESCOMPLEX_ANON_LABEL_RE.test(name);
130
+ const segment = anonymous
131
+ ? anonymousSegment(m, site, parentPath, ordinals)
132
+ : name;
81
133
 
82
- const scopePath = parentPath === '' ? segment : `${parentPath}/${segment}`;
134
+ const scopePath = disambiguate(
135
+ parentPath === '' ? segment : `${parentPath}/${segment}`,
136
+ seen,
137
+ );
83
138
  identities.push({
84
- method: anonymous ? `<anon ${scopePath}>` : name,
139
+ method: anonymous ? `<anon ${scopePath}>` : scopePath,
85
140
  anonymous,
86
141
  });
87
142
  openAncestors.push({ lineEnd, scopePath });
143
+ if (m !== null && typeof m === 'object') pathOf.set(m, scopePath);
88
144
  }
89
145
 
90
146
  return identities;
@@ -0,0 +1,135 @@
1
+ /** Call-site anchors for unnamed functions, read from their AST parent chain. */
2
+
3
+ /** Nodes an anchor reads through: they do not change the call site. */
4
+ const TRANSPARENT_TYPES = new Set([
5
+ 'ParenthesizedExpression',
6
+ 'TSAsExpression',
7
+ 'TSSatisfiesExpression',
8
+ 'TSNonNullExpression',
9
+ 'TSTypeAssertion',
10
+ 'AwaitExpression',
11
+ ]);
12
+
13
+ const CALL_TYPES = new Set([
14
+ 'CallExpression',
15
+ 'NewExpression',
16
+ 'OptionalCallExpression',
17
+ ]);
18
+
19
+ const KEYED_VALUE_TYPES = new Set([
20
+ 'ObjectProperty',
21
+ 'Property',
22
+ 'ClassProperty',
23
+ 'ClassPrivateProperty',
24
+ 'ClassAccessorProperty',
25
+ 'PropertyDefinition',
26
+ ]);
27
+
28
+ /**
29
+ * A static property name, or null for a computed non-literal one.
30
+ *
31
+ * @param {object} key
32
+ * @param {boolean} computed
33
+ * @returns {string|null}
34
+ */
35
+ function staticKey(key, computed) {
36
+ if (key?.type === 'StringLiteral') return key.value;
37
+ if (key?.type === 'NumericLiteral') return String(key.value);
38
+ if (computed) return null;
39
+ if (key?.type === 'Identifier') return key.name;
40
+ if (key?.type === 'PrivateName') return key.id?.name ?? null;
41
+ return null;
42
+ }
43
+
44
+ /**
45
+ * `a.b.c` for a static member chain; a non-static link truncates the chain
46
+ * to the static properties after it.
47
+ *
48
+ * @param {object} expr
49
+ * @returns {string|null}
50
+ */
51
+ function memberChain(expr) {
52
+ if (expr?.type === 'Identifier') return expr.name;
53
+ if (expr?.type === 'ThisExpression') return 'this';
54
+ if (TRANSPARENT_TYPES.has(expr?.type)) return memberChain(expr.expression);
55
+ if (
56
+ expr?.type !== 'MemberExpression' &&
57
+ expr?.type !== 'OptionalMemberExpression'
58
+ ) {
59
+ return null;
60
+ }
61
+ const prop = staticKey(expr.property, expr.computed);
62
+ if (prop === null) return null;
63
+ const head = memberChain(expr.object);
64
+ return head === null ? prop : `${head}.${prop}`;
65
+ }
66
+
67
+ /**
68
+ * @param {object} call
69
+ * @returns {string|null}
70
+ */
71
+ function calleeAnchor(call) {
72
+ const callee = memberChain(call.callee);
73
+ if (callee === null) return null;
74
+ const first = call.arguments?.[0];
75
+ return first?.type === 'StringLiteral' ? `${callee}:${first.value}` : callee;
76
+ }
77
+
78
+ /** @param {object} attr @returns {string|null} */
79
+ function jsxAttributeName(attr) {
80
+ if (attr?.type !== 'JSXAttribute') return null;
81
+ const n = attr.name;
82
+ return n?.type === 'JSXNamespacedName'
83
+ ? `${n.namespace.name}:${n.name.name}`
84
+ : (n?.name ?? null);
85
+ }
86
+
87
+ /**
88
+ * Per parent type: the anchor for `child` under `parent`, where
89
+ * `ancestors[i]` is `parent`.
90
+ */
91
+ const ANCHOR_BY_PARENT = new Map(
92
+ Object.entries({
93
+ JSXExpressionContainer: (_parent, _child, ancestors, i) =>
94
+ jsxAttributeName(ancestors[i - 1]),
95
+ ArrayExpression: (parent, _child, ancestors, i) =>
96
+ anchorOf(parent, ancestors, i - 1),
97
+ VariableDeclarator: (parent, child) =>
98
+ parent.init === child && parent.id?.type === 'Identifier'
99
+ ? parent.id.name
100
+ : null,
101
+ AssignmentExpression: (parent, child) =>
102
+ parent.right === child ? memberChain(parent.left) : null,
103
+ }),
104
+ );
105
+ for (const type of CALL_TYPES) {
106
+ ANCHOR_BY_PARENT.set(type, (parent, child) =>
107
+ parent.arguments?.includes(child) ? calleeAnchor(parent) : null,
108
+ );
109
+ }
110
+ for (const type of KEYED_VALUE_TYPES) {
111
+ ANCHOR_BY_PARENT.set(type, (parent, child) =>
112
+ parent.value === child ? staticKey(parent.key, parent.computed) : null,
113
+ );
114
+ }
115
+
116
+ /**
117
+ * The call site of `node`, read from its parent chain; `ancestors[at]` is
118
+ * its parent.
119
+ *
120
+ * @param {object} node
121
+ * @param {object[]} ancestors
122
+ * @param {number} at
123
+ * @returns {string|null}
124
+ */
125
+ export function anchorOf(node, ancestors, at) {
126
+ let child = node;
127
+ let i = at;
128
+ while (i >= 0 && TRANSPARENT_TYPES.has(ancestors[i].type)) {
129
+ child = ancestors[i];
130
+ i -= 1;
131
+ }
132
+ const parent = ancestors[i];
133
+ const rule = parent ? ANCHOR_BY_PARENT.get(parent.type) : undefined;
134
+ return rule ? rule(parent, child, ancestors, i) : null;
135
+ }
@@ -14,6 +14,7 @@ import PluginSyntaxBabylon from 'escomplex-plugin-syntax-babylon/dist/PluginSynt
14
14
  import ASTWalker from 'typhonjs-ast-walker/dist/ASTWalker.js';
15
15
  import ModuleScopeControl from 'typhonjs-escomplex-commons/dist/module/report/control/ModuleScopeControl.js';
16
16
  import ModuleReport from 'typhonjs-escomplex-commons/dist/module/report/ModuleReport.js';
17
+ import { anchorOf } from './escomplex-anchor.js';
17
18
  import { install as installAstCompat } from './escomplex-ast-compat.js';
18
19
  import { describeParserMajorError } from './runtime-deps/parser-major.js';
19
20
 
@@ -103,6 +104,23 @@ function traitNewScope(syntax, node, parent) {
103
104
  return syntax.newScope.valueOf(node, parent) ?? null;
104
105
  }
105
106
 
107
+ /**
108
+ * Per method report: its enclosing method report and its call-site anchor.
109
+ * A side table, so no report gains a property (the parity corpus hashes
110
+ * them); `finalize()` keeps object identity, so lookups survive it.
111
+ */
112
+ const METHOD_SITES = new WeakMap();
113
+
114
+ /**
115
+ * @param {object} report A method report from {@link analyzeModule}.
116
+ * @returns {{parent: object|null, anchor: string|null}|undefined}
117
+ */
118
+ export function methodSiteOf(report) {
119
+ return report !== null && typeof report === 'object'
120
+ ? METHOD_SITES.get(report)
121
+ : undefined;
122
+ }
123
+
106
124
  /**
107
125
  * Event shapes are the displaced shell's: scope events lack `syntaxes`, and
108
126
  * name the scope `newScope` on entry but `scope` on exit.
@@ -118,6 +136,8 @@ function traitNewScope(syntax, node, parent) {
118
136
  function buildVisitor({ moduleReport, scopeControl, syntaxes, settings }) {
119
137
  const nodeBase = { moduleReport, scopeControl, syntaxes, settings };
120
138
  const scopeBase = { moduleReport, scopeControl, settings };
139
+ /** Every entered node; the walker pairs enter/exit, so it stays balanced. */
140
+ const ancestors = [];
121
141
  return {
122
142
  enterNode(node, parent) {
123
143
  const syntax = syntaxes[node.type];
@@ -132,12 +152,21 @@ function buildVisitor({ moduleReport, scopeControl, syntaxes, settings }) {
132
152
  if (newScope) {
133
153
  const scoped = { ...scopeBase, newScope, node, parent };
134
154
  dispatch('onModulePreScopeCreated', scoped);
135
- scopeControl.createScope(newScope);
155
+ const enclosing = scopeControl.getCurrentMethodReport() ?? null;
156
+ const report = scopeControl.createScope(newScope);
157
+ if (newScope.type === 'method') {
158
+ METHOD_SITES.set(report, {
159
+ parent: enclosing,
160
+ anchor: anchorOf(node, ancestors, ancestors.length - 1),
161
+ });
162
+ }
136
163
  dispatch('onModulePostScopeCreated', scoped);
137
164
  }
165
+ ancestors.push(node);
138
166
  return ignoreKeys;
139
167
  },
140
168
  exitNode(node, parent) {
169
+ ancestors.pop();
141
170
  const syntax = syntaxes[node.type];
142
171
  const newScope = traitNewScope(syntax, node, parent);
143
172
  if (newScope) {