carrick 0.3.154 → 0.3.155

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 (150) hide show
  1. package/bin/carrick.mjs +26 -4
  2. package/dist/cli.d.ts +6 -0
  3. package/dist/cli.js +1 -0
  4. package/dist/cli.js.map +1 -1
  5. package/dist/contract.d.ts +10 -0
  6. package/dist/contract.js.map +1 -1
  7. package/dist/facts/diff.d.ts +27 -0
  8. package/dist/facts/diff.js +134 -0
  9. package/dist/facts/diff.js.map +1 -0
  10. package/dist/facts/enabled.d.ts +2 -0
  11. package/dist/facts/enabled.js +9 -0
  12. package/dist/facts/enabled.js.map +1 -0
  13. package/dist/facts/fetch.d.ts +48 -0
  14. package/dist/facts/fetch.js +235 -0
  15. package/dist/facts/fetch.js.map +1 -0
  16. package/dist/facts/files.d.ts +21 -0
  17. package/dist/facts/files.js +58 -0
  18. package/dist/facts/files.js.map +1 -0
  19. package/dist/facts/lines.d.ts +70 -0
  20. package/dist/facts/lines.js +335 -0
  21. package/dist/facts/lines.js.map +1 -0
  22. package/dist/facts/match.d.ts +91 -0
  23. package/dist/facts/match.js +1122 -0
  24. package/dist/facts/match.js.map +1 -0
  25. package/dist/facts/peers.d.ts +48 -0
  26. package/dist/facts/peers.js +143 -0
  27. package/dist/facts/peers.js.map +1 -0
  28. package/dist/facts/refresh-run.d.ts +2 -0
  29. package/dist/facts/refresh-run.js +18 -0
  30. package/dist/facts/refresh-run.js.map +1 -0
  31. package/dist/facts/rules/packages.d.ts +16 -0
  32. package/dist/facts/rules/packages.js +157 -0
  33. package/dist/facts/rules/packages.js.map +1 -0
  34. package/dist/facts/rules/same-name.d.ts +28 -0
  35. package/dist/facts/rules/same-name.js +131 -0
  36. package/dist/facts/rules/same-name.js.map +1 -0
  37. package/dist/facts/store.d.ts +119 -0
  38. package/dist/facts/store.js +341 -0
  39. package/dist/facts/store.js.map +1 -0
  40. package/dist/git-remote.d.ts +6 -0
  41. package/dist/git-remote.js +37 -0
  42. package/dist/git-remote.js.map +1 -0
  43. package/dist/hook/apply-patch.d.ts +23 -0
  44. package/dist/hook/apply-patch.js +92 -0
  45. package/dist/hook/apply-patch.js.map +1 -1
  46. package/dist/hook/bash-targets.d.ts +8 -0
  47. package/dist/hook/bash-targets.js +23 -11
  48. package/dist/hook/bash-targets.js.map +1 -1
  49. package/dist/hook/edit-flow.d.ts +29 -2
  50. package/dist/hook/edit-flow.js +80 -29
  51. package/dist/hook/edit-flow.js.map +1 -1
  52. package/dist/hook/late.d.ts +29 -0
  53. package/dist/hook/late.js +121 -26
  54. package/dist/hook/late.js.map +1 -1
  55. package/dist/hook/post-bash.js +45 -22
  56. package/dist/hook/post-bash.js.map +1 -1
  57. package/dist/hook/post-edit.d.ts +16 -1
  58. package/dist/hook/post-edit.js +177 -13
  59. package/dist/hook/post-edit.js.map +1 -1
  60. package/dist/hook/post-read.js +8 -12
  61. package/dist/hook/post-read.js.map +1 -1
  62. package/dist/hook/post-search.d.ts +2 -0
  63. package/dist/hook/post-search.js +25 -0
  64. package/dist/hook/post-search.js.map +1 -0
  65. package/dist/hook/probe.d.ts +18 -3
  66. package/dist/hook/probe.js +30 -6
  67. package/dist/hook/probe.js.map +1 -1
  68. package/dist/hook/rechecks.d.ts +66 -11
  69. package/dist/hook/rechecks.js +115 -29
  70. package/dist/hook/rechecks.js.map +1 -1
  71. package/dist/hook/refresh.d.ts +9 -0
  72. package/dist/hook/refresh.js +10 -0
  73. package/dist/hook/refresh.js.map +1 -1
  74. package/dist/hook/reuse.d.ts +16 -2
  75. package/dist/hook/reuse.js +49 -6
  76. package/dist/hook/reuse.js.map +1 -1
  77. package/dist/hook/session-key.d.ts +12 -0
  78. package/dist/hook/session-key.js +30 -0
  79. package/dist/hook/session-key.js.map +1 -0
  80. package/dist/hook/session-start.js +14 -7
  81. package/dist/hook/session-start.js.map +1 -1
  82. package/dist/hook/stop-wait.d.ts +2 -9
  83. package/dist/hook/stop-wait.js +96 -113
  84. package/dist/hook/stop-wait.js.map +1 -1
  85. package/dist/hook/stop.js +13 -8
  86. package/dist/hook/stop.js.map +1 -1
  87. package/dist/hook/subagent-stop.d.ts +2 -0
  88. package/dist/hook/subagent-stop.js +45 -0
  89. package/dist/hook/subagent-stop.js.map +1 -0
  90. package/dist/hook/timings.d.ts +72 -0
  91. package/dist/hook/timings.js +175 -0
  92. package/dist/hook/timings.js.map +1 -0
  93. package/dist/hook/user-prompt.js +17 -13
  94. package/dist/hook/user-prompt.js.map +1 -1
  95. package/dist/hook/worktree.d.ts +11 -0
  96. package/dist/hook/worktree.js +27 -1
  97. package/dist/hook/worktree.js.map +1 -1
  98. package/dist/init/repo-copies.d.ts +6 -0
  99. package/dist/init/repo-copies.js +7 -3
  100. package/dist/init/repo-copies.js.map +1 -1
  101. package/dist/init/repos.d.ts +2 -2
  102. package/dist/init/repos.js +1 -34
  103. package/dist/init/repos.js.map +1 -1
  104. package/dist/init/settings.js +25 -13
  105. package/dist/init/settings.js.map +1 -1
  106. package/dist/render.d.ts +8 -33
  107. package/dist/render.js +31 -122
  108. package/dist/render.js.map +1 -1
  109. package/package.json +6 -6
  110. package/plugin/.claude-plugin/plugin.json +1 -1
  111. package/plugin/hooks/hooks.json +44 -3
  112. package/sidecar/dist/src/capture/anchors.d.ts +12 -1
  113. package/sidecar/dist/src/capture/anchors.js +28 -47
  114. package/sidecar/dist/src/capture/api.d.ts +41 -1
  115. package/sidecar/dist/src/capture/augmentations.d.ts +2 -0
  116. package/sidecar/dist/src/capture/augmentations.js +1 -1
  117. package/sidecar/dist/src/capture/check-classify.d.ts +12 -1
  118. package/sidecar/dist/src/capture/check-classify.js +43 -0
  119. package/sidecar/dist/src/capture/check-deep.d.ts +44 -1
  120. package/sidecar/dist/src/capture/check-deep.js +161 -2
  121. package/sidecar/dist/src/capture/check.js +23 -2
  122. package/sidecar/dist/src/capture/checkout.d.ts +9 -3
  123. package/sidecar/dist/src/capture/checkout.js +12 -5
  124. package/sidecar/dist/src/capture/deep-walk.d.ts +25 -0
  125. package/sidecar/dist/src/capture/deep-walk.js +41 -0
  126. package/sidecar/dist/src/capture/deno-project.d.ts +22 -0
  127. package/sidecar/dist/src/capture/deno-project.js +48 -1
  128. package/sidecar/dist/src/capture/index.d.ts +2 -1
  129. package/sidecar/dist/src/capture/index.js +14 -4
  130. package/sidecar/dist/src/capture/machinery.d.ts +8 -53
  131. package/sidecar/dist/src/capture/machinery.js +10 -157
  132. package/sidecar/dist/src/capture/self-check.d.ts +7 -0
  133. package/sidecar/dist/src/capture/self-check.js +44 -1
  134. package/sidecar/dist/src/capture/site-node.d.ts +166 -0
  135. package/sidecar/dist/src/capture/site-node.js +570 -0
  136. package/sidecar/dist/src/capture/tool-env.d.ts +12 -0
  137. package/sidecar/dist/src/capture/tool-env.js +26 -0
  138. package/sidecar/dist/src/library-claims.js +211 -20
  139. package/sidecar/dist/src/node-index.d.ts +2 -0
  140. package/sidecar/dist/src/node-index.js +5 -1
  141. package/sidecar/dist/src/position-rows.d.ts +39 -4
  142. package/sidecar/dist/src/position-rows.js +233 -16
  143. package/sidecar/dist/src/project-loader.js +13 -5
  144. package/sidecar/dist/src/retype.d.ts +13 -0
  145. package/sidecar/dist/src/retype.js +126 -0
  146. package/sidecar/dist/src/type-inferrer.d.ts +33 -145
  147. package/sidecar/dist/src/type-inferrer.js +68 -524
  148. package/sidecar/dist/src/types.d.ts +55 -2
  149. package/sidecar/dist/src/validators.d.ts +800 -142
  150. package/sidecar/dist/src/validators.js +11 -1
@@ -33,10 +33,10 @@ import { callInto, calledFunction, narrowByArguments } from './argument-modes.js
33
33
  import { functionAtLine } from './function-line-index.js';
34
34
  import { attributedDeclaration, installedPackageOf } from './declaration-attribution.js';
35
35
  import { endLineOf, startLineOf } from './line-index.js';
36
- import { callsOf, descendantsOf, descendantsOnLine, descendantsOnLines, wrap, } from './node-index.js';
36
+ import { callsOf, descendantsOf, descendantsOnLine, descendantsOnLines, wrap, wrapCompilerNode, } from './node-index.js';
37
37
  import { elapsedMs, inferTiming, phaseClock, timedPhase } from './infer-timing.js';
38
38
  import { importedNameOf, packageNameOf } from './library-claims.js';
39
- import { constituentsOf } from './capture/index.js';
39
+ import { constituentsOf, isFrameworkMachinery, nodeByLocatorText, normalizeLocatorText, symbolDeclaredOutside, typeIsOrContainsMachinery, } from './capture/index.js';
40
40
  import { StatedParams } from './stated-params.js';
41
41
  import { bindingToleratesAbsence, handlerToleratesAbsentBody } from './absent-body.js';
42
42
  import { replaceFileText } from './program-files.js';
@@ -96,52 +96,6 @@ const BUILTIN_ANCHOR_SYMBOLS = new Set([
96
96
  'RegExp',
97
97
  'Error',
98
98
  ]);
99
- /**
100
- * Strongly-discriminating member names of HTTP transport machinery — the
101
- * fetch/DOM `Response` & `Request`, a Node `http.ServerResponse`, a framework
102
- * reply object. A type declared in a lib or installed-dependency origin that carries
103
- * a subset of these is framework machinery, never a user contract: the
104
- * PRODUCER-side structural mirror of the consumer `machineryIndicators`
105
- * (ExtractionConfig), used to reject a wrapper envelope whose response field is
106
- * a raw `Response` (carrick#371) instead of emitting it as a comparable type.
107
- *
108
- * Framework-agnostic by construction: no framework NAME appears here, only the
109
- * shared HTTP-message surface. The names are deliberately the ones no
110
- * JSON payload ever carries (`ok`, `redirected`, `bodyUsed`, `arrayBuffer`,
111
- * `writeHead`, ...), so the origin gate + `MACHINERY_INDICATOR_THRESHOLD` never
112
- * fire on real data. Kept in lockstep with the capture-seam mirror
113
- * `capture/machinery.ts` (the seam forbids sharing a module across it, same as
114
- * `BUILTIN_ANCHOR_SYMBOLS` mirrors `socket_io.rs`). Exported so a drift-guard
115
- * test (`machinery-indicator-mirror.test.ts`) asserts the two sets stay equal.
116
- */
117
- export const MACHINERY_MEMBER_INDICATORS = new Set([
118
- // fetch / DOM Response & Request body-consumer surface
119
- 'ok',
120
- 'redirected',
121
- 'bodyUsed',
122
- 'arrayBuffer',
123
- 'blob',
124
- 'formData',
125
- 'clone',
126
- 'json',
127
- 'statusText',
128
- // FROZEN (old path, 2026-10-21): the reply-object half below only (the
129
- // fetch half above and the threshold stay). Deletions and safety fixes
130
- // only. Fixes for wrong or missing types go in labelled reply objects
131
- // (carrick#2472 C4) and the language library rows (carrick#2445). Delete
132
- // when a delete-and-replay on the four repos moves no row wrongly, after
133
- // carrick-cloud#2379 and carrick#2445 (carrick#2472, C6).
134
- // Node http ServerResponse / reply-object surface
135
- 'statusCode',
136
- 'statusMessage',
137
- 'setHeader',
138
- 'getHeader',
139
- 'removeHeader',
140
- 'writeHead',
141
- 'flushHeaders',
142
- ]);
143
- /** Machinery needs at least this many indicator members to be recognized. */
144
- const MACHINERY_INDICATOR_THRESHOLD = 3;
145
99
  /**
146
100
  * True when a binary expression COMPARES rather than assigns or computes: its
147
101
  * value is a `boolean` the operator manufactured, never a payload
@@ -201,6 +155,8 @@ const WRAPPER_CALL_MAX_DEPTH = 3;
201
155
  * the branch an error path, whose shape is not the endpoint's contract.
202
156
  */
203
157
  const STATUS_MEMBER_NAMES = ['status', 'statusCode'];
158
+ /** An error or redirect send carries no body the route's contract describes. */
159
+ const isDroppedResponseStatus = (status) => status === 'error' || status === 'redirect';
204
160
  /**
205
161
  * The reasons an `unknown` answer is a decision, not a failure to read: the
206
162
  * list `DECIDED_ABSTAIN_REASONS` in `src/engine/type_compat_v2.rs` holds
@@ -312,83 +268,6 @@ function typeText(type, enclosingNode) {
312
268
  * `text` is `string`, alone or beside `null` and `undefined` in either order:
313
269
  * the only payload a raw-text read publishes (carrick#1842).
314
270
  */
315
- /**
316
- * Source text with every plain string literal written in double quotes:
317
- * `'/a'`, `"/a"` and an interpolation-free `` `/a` `` are one value, so text
318
- * that differs only in its quotes compares equal (carrick#2056).
319
- *
320
- * The text is read left to right, pairing quotes the way the scanner does,
321
- * so a template's closing backtick never pairs with the next template's
322
- * opening one. A literal holding a quote, a backslash or an interpolation is
323
- * copied as it is, and so is an unterminated one with everything after it.
324
- */
325
- export function canonicalStringQuotes(text) {
326
- const isQuote = (ch) => ch === "'" || ch === '"' || ch === '`';
327
- // The index just past the literal opening at `start`, or -1.
328
- const literalEnd = (start) => {
329
- const quote = text[start];
330
- let j = start + 1;
331
- while (j < text.length) {
332
- const ch = text[j];
333
- if (ch === '\\') {
334
- j += 2;
335
- }
336
- else if (ch === quote) {
337
- return j + 1;
338
- }
339
- else if (quote === '`' && ch === '$' && text[j + 1] === '{') {
340
- const close = codeEnd(j + 2);
341
- if (close < 0)
342
- return -1;
343
- j = close + 1;
344
- }
345
- else {
346
- j++;
347
- }
348
- }
349
- return -1;
350
- };
351
- // The index of the `}` that closes an interpolation whose code starts at `start`, or -1.
352
- const codeEnd = (start) => {
353
- let depth = 0;
354
- let j = start;
355
- while (j < text.length) {
356
- const ch = text[j];
357
- if (isQuote(ch)) {
358
- const end = literalEnd(j);
359
- if (end < 0)
360
- return -1;
361
- j = end;
362
- continue;
363
- }
364
- if (ch === '{')
365
- depth++;
366
- if (ch === '}') {
367
- if (depth === 0)
368
- return j;
369
- depth--;
370
- }
371
- j++;
372
- }
373
- return -1;
374
- };
375
- let out = '';
376
- let i = 0;
377
- while (i < text.length) {
378
- if (!isQuote(text[i])) {
379
- out += text[i];
380
- i++;
381
- continue;
382
- }
383
- const end = literalEnd(i);
384
- if (end < 0)
385
- return out + text.slice(i);
386
- const body = text.slice(i + 1, end - 1);
387
- out += /['"`\\]|\$\{/.test(body) ? text.slice(i, end) : `"${body}"`;
388
- i = end;
389
- }
390
- return out;
391
- }
392
271
  function isBareStringText(text) {
393
272
  const members = text.split('|').map((member) => member.trim());
394
273
  return (members.includes('string') &&
@@ -1501,11 +1380,11 @@ export class TypeInferrer {
1501
1380
  return { param: byName, node: byName };
1502
1381
  }
1503
1382
  // 2. Whole binding pattern, whitespace-normalized.
1504
- const normalizedTarget = this.normalizeWhitespace(paramName);
1383
+ const normalizedTarget = normalizeLocatorText(paramName);
1505
1384
  for (const param of params) {
1506
1385
  const nameNode = param.getNameNode();
1507
1386
  if ((Node.isObjectBindingPattern(nameNode) || Node.isArrayBindingPattern(nameNode)) &&
1508
- this.normalizeWhitespace(nameNode.getText()) === normalizedTarget) {
1387
+ normalizeLocatorText(nameNode.getText()) === normalizedTarget) {
1509
1388
  return { param, node: param };
1510
1389
  }
1511
1390
  }
@@ -1538,7 +1417,7 @@ export class TypeInferrer {
1538
1417
  return declared;
1539
1418
  }
1540
1419
  this.log(`Line ${request.line_number} is a route registration; following handler return`);
1541
- return this.buildFunctionReturnInferredType(request, atLine.handler, extractionConfig, true);
1420
+ return (this.buildFunctionReturnInferredType(request, atLine.handler, extractionConfig, true) ?? this.labelledSendBodies(request, atLine.handler));
1542
1421
  }
1543
1422
  // carrick#807: the request named an expression and the file holds none
1544
1423
  // that matches. Where its line declares the handler, that handler is
@@ -2068,13 +1947,8 @@ export class TypeInferrer {
2068
1947
  // carrick#2472 C2: the service's labels answer first. A labelled send is
2069
1948
  // a send, an unlabelled member of a labelled reply object is a setter;
2070
1949
  // where no label speaks, the structural reading decides.
2071
- const labelledSend = (candidate) => this.statedParams.sendAt(this.peelTransparentExpression(candidate));
2072
- const isLabelledSend = (candidate) => {
2073
- const labelled = labelledSend(candidate);
2074
- return labelled !== undefined && labelled !== 'setter';
2075
- };
2076
1950
  const isSend = (candidate) => {
2077
- const labelled = labelledSend(candidate);
1951
+ const labelled = this.statedParams.sendAt(this.peelTransparentExpression(candidate));
2078
1952
  if (labelled !== undefined)
2079
1953
  return labelled !== 'setter';
2080
1954
  return this.isResponseSend(candidate, extractionConfig);
@@ -2099,7 +1973,7 @@ export class TypeInferrer {
2099
1973
  const locatedBranch = locatingBranches.find((branch) => contains(branch, site));
2100
1974
  if (!locatedBranch)
2101
1975
  return undefined;
2102
- const dropped = (status) => status === 'error' || status === 'redirect';
1976
+ const dropped = isDroppedResponseStatus;
2103
1977
  const siteStatus = this.responseSiteStatus(site, true);
2104
1978
  if (!tied && !dropped(siteStatus))
2105
1979
  return undefined;
@@ -2112,7 +1986,7 @@ export class TypeInferrer {
2112
1986
  // FROZEN (old path, 2026-10-21): the `statementEndsFunctionPath` test
2113
1987
  // here; see that method.
2114
1988
  .filter((s) => s.send === locatedBranch ||
2115
- isLabelledSend(s.send) ||
1989
+ this.isLabelledSend(s.send) ||
2116
1990
  this.statementEndsFunctionPath(s.statement, func))
2117
1991
  .map((s) => s.send),
2118
1992
  ];
@@ -2264,6 +2138,35 @@ export class TypeInferrer {
2264
2138
  inferred.response_modes = { reads: sorted };
2265
2139
  return inferred;
2266
2140
  }
2141
+ /** A call the service's labels name a body send; a labelled setter is not one (carrick#2472 C2). */
2142
+ isLabelledSend(candidate) {
2143
+ const labelled = this.statedParams.sendAt(this.peelTransparentExpression(candidate));
2144
+ return labelled !== undefined && labelled !== 'setter';
2145
+ }
2146
+ /**
2147
+ * carrick#4081: a line-only row at a registration whose handler returns
2148
+ * nothing. Its body is what the handler sends: every labelled send it makes
2149
+ * as a statement, error and redirect sends dropped, the success bodies
2150
+ * joined, as `inferFromResponseSites` reads them from a located send. Only
2151
+ * labelled sends count; an unlabelled one leaves the row unread. A reply
2152
+ * parameter that states its payload answers first (`withStatedReply`), so
2153
+ * this yields to it.
2154
+ */
2155
+ labelledSendBodies(request, handler) {
2156
+ if (!this.statedParams.readsReplies || this.statedParams.reply(handler))
2157
+ return null;
2158
+ const survivors = this.responseSendStatements(handler, (candidate) => this.isLabelledSend(candidate))
2159
+ .map((s) => s.send)
2160
+ .filter((send) => !isDroppedResponseStatus(this.responseSiteStatus(send, true)));
2161
+ if (survivors.length === 0)
2162
+ return null;
2163
+ const recovered = this.recoverPayloadFromResponseExpressions(survivors, false, this.wireFormatFor(request));
2164
+ if (!recovered)
2165
+ return null;
2166
+ this.log(`Route at ${request.file_path}:${request.line_number} returns nothing; ` +
2167
+ 'publishing the success bodies its handler sends through labelled sends');
2168
+ return this.inferredFromRecoveredPayload(request, recovered);
2169
+ }
2267
2170
  /**
2268
2171
  * The response sends `func` makes as statements (`res.status(409).json(e);`),
2269
2172
  * for a handler that sends through a parameter and returns nothing. Only the
@@ -5355,84 +5258,21 @@ export class TypeInferrer {
5355
5258
  * envelope `{ response: Response; error?: undefined } | { ...; error: Error }`
5356
5259
  * was captured as the response contract. Machinery is never a comparable
5357
5260
  * contract, so a response path that resolves here abstains (honest `unknown`)
5358
- * rather than emit a concrete-but-false type.
5359
- *
5360
- * DETECTS, exactly (see `typeIsOrContainsMachinery`):
5361
- * 1. the type itself is machinery (`typeIsFrameworkMachinery`);
5362
- * 2. a union/intersection member is machinery (the envelope union);
5363
- * 3. a DIRECT property's type is machinery, ONE level of descent only
5364
- * (`{ response: Response; error }`).
5365
- *
5366
- * DELIBERATELY NOT DETECTED — listed so this comment never overstates the
5367
- * guarantee (an overstated safety comment is what bit sibling PR #442). Each is
5368
- * a non-regression: it leaves the pre-existing verdict unchanged and never
5369
- * manufactures a new wrong one, tracked as a follow-up:
5370
- * - machinery nested deeper than one property level (a property whose type
5371
- * is itself a nested object wrapping the machinery);
5372
- * - a property typed `Promise<Response>` (the property type is NOT awaited /
5373
- * Promise-unwrapped before the machinery check);
5374
- * - an array element type: `Response[]` is not descended to its element;
5375
- * - `interface X extends Response` declared in USER source — the origin gate
5376
- * is lib/installed-dependency only, so a user-declared subtype reads as a real
5377
- * contract, not machinery;
5378
- * - a function / call-signature return type: the response paths that call
5379
- * this resolve a handler's RETURN (an envelope/object), never a function
5380
- * value, so no call-signature descent happens here. The capture-seam
5381
- * mirror `capture/machinery.ts` DOES descend call signatures — that is
5382
- * where the wrapper-FUNCTION type the Infer fallback resolves is caught.
5383
- *
5384
- * The origin gate in `typeIsFrameworkMachinery` keeps a user object whose
5385
- * fields merely share a member name from tripping.
5261
+ * rather than emit a concrete-but-false type. The capture asks the same
5262
+ * question of the same function (`capture/site-node.ts`, carrick#3500), which
5263
+ * states what it detects and what it does not.
5386
5264
  */
5387
5265
  typeIsOrContainsResponseMachinery(type) {
5388
- return this.typeIsOrContainsMachinery(type, 0);
5266
+ return typeIsOrContainsMachinery(this.checker(), type.compilerType, this.declaredOutside);
5389
5267
  }
5390
- typeIsOrContainsMachinery(type, depth) {
5391
- if (this.typeIsFrameworkMachinery(type)) {
5392
- return true;
5393
- }
5394
- // Union/intersection: any envelope member wrapping machinery taints it.
5395
- if (type.isUnion()) {
5396
- return type
5397
- .getUnionTypes()
5398
- .some((part) => this.typeIsOrContainsMachinery(part, depth));
5399
- }
5400
- if (type.isIntersection()) {
5401
- return type
5402
- .getIntersectionTypes()
5403
- .some((part) => this.typeIsOrContainsMachinery(part, depth));
5404
- }
5405
- // One level of property descent: `{ response: Response; error?: undefined }`.
5406
- if (depth < 1) {
5407
- for (const prop of type.getProperties()) {
5408
- const decl = prop.getDeclarations()[0];
5409
- if (!decl)
5410
- continue;
5411
- const propType = prop.getTypeAtLocation(decl);
5412
- if (this.typeIsOrContainsMachinery(propType, depth + 1)) {
5413
- return true;
5414
- }
5415
- }
5416
- }
5417
- return false;
5418
- }
5419
- /**
5420
- * True when `type` itself is an HTTP-machinery type: it structurally carries
5421
- * at least `MACHINERY_INDICATOR_THRESHOLD` of the strongly-discriminating
5422
- * `MACHINERY_MEMBER_INDICATORS`, AND its symbol is declared in a lib
5423
- * (`lib.dom.d.ts`, ...) or installed-dependency origin. Both gates are required —
5424
- * the indicator subset alone essentially never matches a JSON payload, and
5425
- * the origin gate makes certain a user's own local type sharing those member
5426
- * names is never mistaken for framework machinery (the advisor's guard).
5427
- */
5428
5268
  /**
5429
5269
  * Blueprint row N8: true when `type` is framework machinery by where it is
5430
5270
  * declared, never by its name. Either it passes the structural test
5431
- * (`typeIsFrameworkMachinery`: the transport's members, declared by a
5432
- * library or an installed package), or an installed package the store
5433
- * labels a server framework declares it (`frameworkPackages`), which also
5434
- * covers app and router instances that carry no reply members. A
5435
- * service's own `Context` or `Router` is neither.
5271
+ * (`isFrameworkMachinery` in `capture/site-node.ts`: the transport's
5272
+ * members, declared by a library or an installed package), or an installed
5273
+ * package the store labels a server framework declares it
5274
+ * (`frameworkPackages`), which also covers app and router instances that
5275
+ * carry no reply members. A service's own `Context` or `Router` is neither.
5436
5276
  */
5437
5277
  isFrameworkMachinery(type) {
5438
5278
  if (this.typeIsFrameworkMachinery(type)) {
@@ -5445,65 +5285,28 @@ export class TypeInferrer {
5445
5285
  return declaring !== undefined && this.frameworkPackages.has(importedNameOf(declaring));
5446
5286
  }
5447
5287
  typeIsFrameworkMachinery(type) {
5448
- if (!this.hasMachineryIndicatorThreshold(type)) {
5449
- return false;
5450
- }
5451
- const symbol = type.getSymbol() ?? type.getAliasSymbol();
5452
- return this.symbolIsLibOrExternalOrigin(symbol);
5288
+ return isFrameworkMachinery(this.checker(), type.compilerType, this.declaredOutside);
5453
5289
  }
5454
- /**
5455
- * True once the type carries at least `MACHINERY_INDICATOR_THRESHOLD` DISTINCT
5456
- * `MACHINERY_MEMBER_INDICATORS` (own + apparent). Deduplicates by name (own and
5457
- * apparent property lists overlap) and early-returns the moment the threshold
5458
- * is reached — the callers only need the boolean, never the full count.
5459
- */
5460
- hasMachineryIndicatorThreshold(type) {
5461
- const matched = new Set();
5462
- const consider = (name) => {
5463
- if (MACHINERY_MEMBER_INDICATORS.has(name)) {
5464
- matched.add(name);
5465
- }
5466
- return matched.size >= MACHINERY_INDICATOR_THRESHOLD;
5467
- };
5468
- for (const prop of type.getProperties()) {
5469
- if (consider(prop.getName()))
5470
- return true;
5471
- }
5472
- for (const prop of type.getApparentProperties()) {
5473
- if (consider(prop.getName()))
5474
- return true;
5475
- }
5476
- return false;
5290
+ checker() {
5291
+ return this.project.getTypeChecker().compilerObject;
5477
5292
  }
5478
5293
  /**
5479
- * True when the symbol is declared in a runtime/library origin
5294
+ * Whether a declaration's file is a runtime/library origin
5480
5295
  * (`isExternalOrigin`): a TypeScript lib, an installed dependency however
5481
5296
  * the program resolved it, or the runtime declarations Carrick materialises
5482
5297
  * under `.carrick/deno/` — framework/runtime machinery, not user source.
5298
+ * The program is read per call: the project adds source files lazily and
5299
+ * rebuilds it.
5300
+ */
5301
+ declaredOutside = (sourceFile) => isExternalOrigin(this.project.getProgram().compilerObject, sourceFile, this.repoRoot, externalImportsOf(this.project));
5302
+ /**
5303
+ * True when the symbol is declared in a runtime/library origin
5304
+ * (`declaredOutside`), itself or through the import alias it stands for.
5483
5305
  * Works on a bare checkout: the DOM `Response`/`Request` resolve from the
5484
- * bundled `lib.dom.d.ts` even with no installed dependencies. The program is
5485
- * read per call: the project adds source files lazily and rebuilds it.
5306
+ * bundled `lib.dom.d.ts` even with no installed dependencies.
5486
5307
  */
5487
5308
  symbolIsLibOrExternalOrigin(symbol) {
5488
- if (!symbol) {
5489
- return false;
5490
- }
5491
- const program = this.project.getProgram().compilerObject;
5492
- for (const decl of symbol.getDeclarations()) {
5493
- if (isExternalOrigin(program, decl.getSourceFile().compilerNode, this.repoRoot, externalImportsOf(this.project))) {
5494
- return true;
5495
- }
5496
- }
5497
- try {
5498
- const aliased = symbol.getAliasedSymbol?.();
5499
- if (aliased && aliased !== symbol) {
5500
- return this.symbolIsLibOrExternalOrigin(aliased);
5501
- }
5502
- }
5503
- catch {
5504
- // Ignore errors when resolving the aliased symbol.
5505
- }
5506
- return false;
5309
+ return symbolDeclaredOutside(this.checker(), symbol?.compilerSymbol, this.declaredOutside);
5507
5310
  }
5508
5311
  /**
5509
5312
  * Check if a type has machinery indicator properties/methods.
@@ -9900,24 +9703,16 @@ export class TypeInferrer {
9900
9703
  }
9901
9704
  }
9902
9705
  /**
9903
- * Find a node by matching expression text near a target line.
9904
- *
9905
- * Strategy:
9906
- * 1. Get all descendant nodes within [lineNumber - searchRadius, lineNumber + searchRadius]
9907
- * 2. Normalize whitespace for comparison
9908
- * 3. Try exact match first (after normalization), prefer closest to target line
9909
- * 4. Fall back to substring match (LLM text in node text, or vice versa)
9910
- * 5. Return smallest matching node closest to target line
9706
+ * Find a node by matching expression text near a target line: the shared
9707
+ * locator (`nodeByLocatorText`, carrick#3500) over every node that starts
9708
+ * within `searchRadius` lines of it, the one the capture runs too.
9911
9709
  */
9912
9710
  findNodeByText(sourceFile, expressionText, lineNumber, searchRadius = 5) {
9913
- // Only the window's nodes are wrapped: `matchByText` keeps no other.
9914
9711
  const inWindow = lineNumber
9915
9712
  ? descendantsOnLines(sourceFile, lineNumber - searchRadius, lineNumber + searchRadius)
9916
9713
  : descendantsOf(sourceFile);
9917
- const nodes = inWindow
9918
- .filter((entry) => entry.kind !== SyntaxKind.SyntaxList)
9919
- .map((entry) => wrap(sourceFile, entry));
9920
- return this.matchByText(nodes, expressionText, lineNumber, searchRadius);
9714
+ const found = nodeByLocatorText(sourceFile.compilerNode, inWindow.filter((entry) => entry.kind !== SyntaxKind.SyntaxList).map((entry) => entry.node), expressionText, lineNumber, searchRadius);
9715
+ return found === undefined ? undefined : wrapCompilerNode(sourceFile, found);
9921
9716
  }
9922
9717
  /**
9923
9718
  * Find a CallExpression by matching expression text near a target line.
@@ -9926,259 +9721,8 @@ export class TypeInferrer {
9926
9721
  const inWindow = lineNumber
9927
9722
  ? callsOf(sourceFile).filter((entry) => entry.line >= lineNumber - searchRadius && entry.line <= lineNumber + searchRadius)
9928
9723
  : callsOf(sourceFile);
9929
- const callExpressions = inWindow.map((entry) => wrap(sourceFile, entry));
9930
- return this.matchByText(callExpressions, expressionText, lineNumber, searchRadius);
9931
- }
9932
- /**
9933
- * Shared text-matching logic for node resolution.
9934
- * Normalizes whitespace once per candidate, then tries exact match,
9935
- * then substring match (preferring containing matches).
9936
- */
9937
- matchByText(nodes, expressionText, lineNumber, searchRadius = 5) {
9938
- const normalizedTarget = this.normalizeWhitespace(expressionText);
9939
- if (!normalizedTarget)
9940
- return undefined;
9941
- // Filter to nodes within the search window and pre-compute normalized text
9942
- const candidates = (lineNumber
9943
- ? nodes.filter((node) => {
9944
- const nodeLine = startLineOf(node);
9945
- return nodeLine >= lineNumber - searchRadius && nodeLine <= lineNumber + searchRadius;
9946
- })
9947
- : nodes).map((node) => ({ node, text: this.normalizeWhitespace(node.getText()) }));
9948
- if (candidates.length === 0)
9949
- return undefined;
9950
- // Try exact match (normalized whitespace)
9951
- const exactMatches = candidates.filter((c) => c.text === normalizedTarget);
9952
- if (exactMatches.length > 0) {
9953
- return this.pickBestMatch(exactMatches.map((c) => c.node), lineNumber);
9954
- }
9955
- // A bare identifier target must match a node exactly: substring matching
9956
- // would bind `users` to `usersCsv` (or to any enclosing node that merely
9957
- // contains the identifier somewhere) and report a confidently wrong type.
9958
- // Failing here is correct — the caller records an error and the alias
9959
- // pads to `unknown` downstream.
9960
- if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(normalizedTarget)) {
9961
- return undefined;
9962
- }
9963
- // A locator that elides members (`body: { a: x, ... }`) stands for the
9964
- // whole node it opens: the text before the elision is where the source
9965
- // opens. Never a node the text merely contains, which is one member of the
9966
- // payload it names.
9967
- // An opening shorter than this (`{`) names no node in particular.
9968
- const MIN_ELIDED_OPENING_LEN = 8;
9969
- const elidedOpening = this.elidedLocatorOpening(normalizedTarget);
9970
- if (elidedOpening !== undefined) {
9971
- if (elidedOpening.length < MIN_ELIDED_OPENING_LEN)
9972
- return undefined;
9973
- const opened = candidates.filter((c) => c.text.startsWith(elidedOpening));
9974
- if (opened.length === 0)
9975
- return undefined;
9976
- if (lineNumber !== undefined) {
9977
- const distance = (c) => Math.abs(startLineOf(c.node) - lineNumber);
9978
- const nearest = Math.min(...opened.map(distance));
9979
- return this.pickBestMatch(opened.filter((c) => distance(c) === nearest).map((c) => c.node), lineNumber);
9980
- }
9981
- return this.pickBestMatch(opened.map((c) => c.node), lineNumber);
9982
- }
9983
- // Fall back to substring match
9984
- // For the reverse direction (target contains node text), require a minimum node text
9985
- // length to avoid matching tiny identifiers like "res" or "body" too broadly.
9986
- // Also require the node to cover at least half of the target: the reverse
9987
- // branch exists for a locator with minor syntactic drift around the true
9988
- // node, not for binding to a fragment. Without the floor, a 100+ char
9989
- // locator whose exact match failed would bind to the smallest embedded
9990
- // sub-expression (pickBestMatch prefers small nodes), e.g. the 8-char
9991
- // literal "active" inside a res.json object payload (#335).
9992
- //
9993
- // A node the text itself places strictly inside what it names is a
9994
- // fragment, however much of the text it covers (carrick#2056): the
9995
- // `new URLSearchParams(…)` inside a call's URL argument, or the object a
9996
- // callback nested in the named object returns. Only the node the text
9997
- // names, or a wrapper the text adds around it, may be bound this way. A
9998
- // fragment still points at what the text names where the source agrees
9999
- // with the text up to it: the enclosing node of the named kind whose text
10000
- // opens with the text's own opening up to the fragment (`new Response(`
10001
- // before a payload, when the text dropped the call's second argument).
10002
- const MIN_REVERSE_MATCH_LEN = 8;
10003
- const MIN_REVERSE_MATCH_COVERAGE = 0.5;
10004
- const containingMatches = candidates.filter((c) => c.text.includes(normalizedTarget));
10005
- if (containingMatches.length > 0) {
10006
- // A text that is only a wrapped call's first line (`load({`) is held by
10007
- // every sibling that opens alike, and the smallest of them is not the
10008
- // one the locator names (carrick#2114). The nodes whose own text OPENS
10009
- // with the text are the ones a first line names: among those the stated
10010
- // line decides, then size. A fragment from the middle of a node opens
10011
- // nothing, and stays on the smallest node holding it.
10012
- const opening = lineNumber === undefined
10013
- ? []
10014
- : containingMatches.filter((c) => c.text.startsWith(normalizedTarget));
10015
- if (lineNumber !== undefined && opening.length > 0) {
10016
- const distance = (c) => Math.abs(startLineOf(c.node) - lineNumber);
10017
- const nearest = Math.min(...opening.map(distance));
10018
- return this.pickBestMatch(opening.filter((c) => distance(c) === nearest).map((c) => c.node), lineNumber);
10019
- }
10020
- return this.pickBestMatch(containingMatches.map((c) => c.node), lineNumber);
10021
- }
10022
- const reverseMatches = candidates.filter((c) => c.text.length >= MIN_REVERSE_MATCH_LEN &&
10023
- c.text.length >= normalizedTarget.length * MIN_REVERSE_MATCH_COVERAGE &&
10024
- normalizedTarget.includes(c.text));
10025
- if (reverseMatches.length === 0)
10026
- return undefined;
10027
- const named = this.locatorNames(normalizedTarget);
10028
- if (!named) {
10029
- return this.pickBestMatch(reverseMatches.map((c) => c.node), lineNumber);
10030
- }
10031
- const textOf = new Map(candidates.map((c) => [c.node, c.text]));
10032
- const bound = new Set();
10033
- for (const c of reverseMatches) {
10034
- if (named.texts.has(c.text)) {
10035
- bound.add(c.node);
10036
- continue;
10037
- }
10038
- const at = normalizedTarget.indexOf(c.text, named.rootStart + 1);
10039
- if (at < 0)
10040
- continue;
10041
- const opening = normalizedTarget.slice(named.rootStart, at);
10042
- const enclosing = c.node.getFirstAncestor((ancestor) => ancestor.getKind() === named.rootKind &&
10043
- textOf.get(ancestor)?.startsWith(opening) === true);
10044
- if (enclosing)
10045
- bound.add(enclosing);
10046
- }
10047
- return bound.size > 0 ? this.pickBestMatch([...bound], lineNumber) : undefined;
10048
- }
10049
- /**
10050
- * The text a locator opens with before an elision, or `undefined` when the
10051
- * locator has none. An elision is `...` followed only by closing brackets
10052
- * (`{ a: x, ... }`); `...rest` is a spread and source text. An opening too
10053
- * short to tell nodes apart is judged by the caller.
10054
- */
10055
- elidedLocatorOpening(normalizedTarget) {
10056
- const match = /^(.*?)[\s,]*\.\.\.[\s,)}\]]*$/s.exec(normalizedTarget);
10057
- if (!match)
10058
- return undefined;
10059
- return match[1];
10060
- }
10061
- /**
10062
- * What a locator's text names, read off its own parse (carrick#2056):
10063
- *
10064
- * - `texts`: the normalized text of the expression it names and of each
10065
- * wrapper it carries around it (`return`, a `const x =` binding, a label,
10066
- * `await`, parentheses, a cast, `satisfies`, `!`). A node strictly inside
10067
- * that expression is not among them;
10068
- * - `rootKind` and `rootStart`: the innermost of those, its kind, and where
10069
- * its text starts in the locator.
10070
- *
10071
- * `null` when the text does not parse as one expression or one statement:
10072
- * there is no structure to read, and the caller keeps its text rule.
10073
- */
10074
- locatorNames(normalizedTarget) {
10075
- const parsed = (source) => {
10076
- const file = ts.createSourceFile('locator.ts', source, ts.ScriptTarget.Latest, true);
10077
- const diagnostics = file
10078
- .parseDiagnostics;
10079
- return diagnostics && diagnostics.length === 0 && file.statements.length === 1 ? file : null;
10080
- };
10081
- // An object literal is a block as a statement, so try the text as an
10082
- // expression first.
10083
- const EXPRESSION_OPENING = '(\n';
10084
- const asExpression = parsed(`${EXPRESSION_OPENING}${normalizedTarget}\n);`);
10085
- let node;
10086
- let file = asExpression;
10087
- let offset = 0;
10088
- if (asExpression) {
10089
- const statement = asExpression.statements[0];
10090
- if (ts.isExpressionStatement(statement) && ts.isParenthesizedExpression(statement.expression)) {
10091
- node = statement.expression.expression;
10092
- offset = EXPRESSION_OPENING.length;
10093
- }
10094
- }
10095
- else {
10096
- file = parsed(normalizedTarget);
10097
- node = file?.statements[0];
10098
- }
10099
- if (!file || !node)
10100
- return null;
10101
- const texts = new Set();
10102
- let root;
10103
- while (node) {
10104
- if (ts.isLabeledStatement(node)) {
10105
- node = node.statement;
10106
- }
10107
- else if (ts.isExpressionStatement(node) || ts.isReturnStatement(node)) {
10108
- node = node.expression;
10109
- }
10110
- else if (ts.isVariableStatement(node)) {
10111
- const declarations = node.declarationList.declarations;
10112
- node = declarations.length === 1 ? declarations[0].initializer : undefined;
10113
- }
10114
- else {
10115
- texts.add(this.normalizeWhitespace(node.getText(file)));
10116
- root = node;
10117
- node =
10118
- ts.isParenthesizedExpression(node) ||
10119
- ts.isAwaitExpression(node) ||
10120
- ts.isAsExpression(node) ||
10121
- ts.isSatisfiesExpression(node) ||
10122
- ts.isNonNullExpression(node) ||
10123
- ts.isTypeAssertionExpression(node)
10124
- ? node.expression
10125
- : undefined;
10126
- }
10127
- }
10128
- if (!root)
10129
- return null;
10130
- return { texts, rootKind: root.kind, rootStart: root.getStart(file) - offset };
10131
- }
10132
- /**
10133
- * Pick the best match from a set of candidate nodes:
10134
- * smallest range, then closest to target line.
10135
- */
10136
- pickBestMatch(nodes, targetLine) {
10137
- return nodes.reduce((best, current) => {
10138
- const bestRange = best.getEnd() - best.getStart();
10139
- const currentRange = current.getEnd() - current.getStart();
10140
- // Prefer smaller nodes
10141
- if (currentRange !== bestRange) {
10142
- return currentRange < bestRange ? current : best;
10143
- }
10144
- // Tie-break by proximity to target line
10145
- if (targetLine !== undefined) {
10146
- const bestDist = Math.abs(startLineOf(best) - targetLine);
10147
- const currentDist = Math.abs(startLineOf(current) - targetLine);
10148
- return currentDist < bestDist ? current : best;
10149
- }
10150
- return best;
10151
- });
10152
- }
10153
- /**
10154
- * Normalize whitespace for text comparison:
10155
- * collapse runs of whitespace into single spaces, trim.
10156
- *
10157
- * Also strips trailing commas before `}` `)` `]`: multi-line source
10158
- * literals carry them but the LLM's single-line locator print does not,
10159
- * and that one comma used to defeat exact AND containment matching for
10160
- * the payload and every enclosing node (#335). Applied symmetrically to
10161
- * node text and target, so both sides compare equal.
10162
- *
10163
- * Also strips the space left AFTER `(` `[` `{` by the collapse: a
10164
- * multi-line call whose arguments start on the next line normalizes to
10165
- * `f( x)` while the LLM's compact print is `f(x)`, and that one space
10166
- * defeated exact matching for the call and every enclosing node — the
10167
- * opening-delimiter mirror of the #335 trailing comma (#336). Symmetric
10168
- * for the same reason.
10169
- */
10170
- normalizeWhitespace(text) {
10171
- const collapsed = text
10172
- .replace(/\s+/g, ' ')
10173
- // A member chain broken before its dot (`client\n .list(…)`) reads the
10174
- // same as `client.list(…)`; a space around `.` / `?.` means nothing
10175
- // (carrick#1162).
10176
- .replace(/\s*(\?\.|\.)\s*/g, '$1')
10177
- .replace(/\s*,?\s*([}\)\]])/g, '$1')
10178
- .replace(/([\(\[{])\s+/g, '$1')
10179
- .trim();
10180
- // A string literal reads the same in any quotes (carrick#2056).
10181
- return canonicalStringQuotes(collapsed);
9724
+ const found = nodeByLocatorText(sourceFile.compilerNode, inWindow.map((entry) => entry.node), expressionText, lineNumber, searchRadius);
9725
+ return found === undefined ? undefined : wrapCompilerNode(sourceFile, found);
10182
9726
  }
10183
9727
  /**
10184
9728
  * Format a human-readable location string for error messages.