@herbertgao/pi-extensions 2026.8.5 → 2026.8.6

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 (155) hide show
  1. package/README.md +5 -5
  2. package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +1 -1
  3. package/node_modules/@herbertgao/pi-cc-extensions/README.md +1 -1
  4. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/context.ts +74 -5
  5. package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/markdown-enhance.ts +48 -6
  6. package/node_modules/@herbertgao/pi-cc-extensions/package.json +3 -3
  7. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +10 -0
  8. package/node_modules/@herbertgao/pi-subagents/package.json +3 -3
  9. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +5 -2
  10. package/node_modules/@herbertgao/pi-subagents/src/ui/fleet-list.ts +15 -6
  11. package/node_modules/@herbertgao/pi-subagents/src/worktree.ts +9 -5
  12. package/node_modules/@juicesharp/rpiv-ask-user-question/README.md +2 -0
  13. package/node_modules/@juicesharp/rpiv-ask-user-question/ask-user-question.ts +20 -0
  14. package/node_modules/@juicesharp/rpiv-ask-user-question/docs/hosts.md +6 -0
  15. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +2 -2
  16. package/node_modules/@narumitw/pi-btw/README.md +24 -17
  17. package/node_modules/@narumitw/pi-btw/package.json +5 -5
  18. package/node_modules/@narumitw/pi-btw/src/btw.ts +4 -2
  19. package/node_modules/@narumitw/pi-btw/src/menu.ts +33 -13
  20. package/node_modules/@narumitw/pi-btw/src/settings.ts +22 -2
  21. package/node_modules/pi-lens/CHANGELOG.md +95 -0
  22. package/node_modules/pi-lens/dist/clients/advisory-provenance.js +314 -0
  23. package/node_modules/pi-lens/dist/clients/agent-nudge.js +14 -7
  24. package/node_modules/pi-lens/dist/clients/biome-client.js +121 -13
  25. package/node_modules/pi-lens/dist/clients/bus-events-logger.js +62 -6
  26. package/node_modules/pi-lens/dist/clients/bus-publish.js +11 -3
  27. package/node_modules/pi-lens/dist/clients/cascade-format.js +57 -2
  28. package/node_modules/pi-lens/dist/clients/console-guard-install.js +16 -4
  29. package/node_modules/pi-lens/dist/clients/dead-code-client.js +135 -30
  30. package/node_modules/pi-lens/dist/clients/dependency-checker.js +19 -7
  31. package/node_modules/pi-lens/dist/clients/diagnostic-dispositions.js +6 -4
  32. package/node_modules/pi-lens/dist/clients/diagnostics-publish.js +10 -3
  33. package/node_modules/pi-lens/dist/clients/dispatch/dispatcher.js +114 -10
  34. package/node_modules/pi-lens/dist/clients/dispatch/integration.js +101 -16
  35. package/node_modules/pi-lens/dist/clients/dispatch/runners/lsp.js +37 -4
  36. package/node_modules/pi-lens/dist/clients/dispatch/runners/utils/availability-policy.js +226 -0
  37. package/node_modules/pi-lens/dist/clients/dispatch/runners/utils/candidate-probe.js +69 -0
  38. package/node_modules/pi-lens/dist/clients/dispatch/runners/utils/runner-helpers.js +230 -50
  39. package/node_modules/pi-lens/dist/clients/dispatch/runners/utils/toolchain-availability.js +97 -0
  40. package/node_modules/pi-lens/dist/clients/disposition-publish.js +10 -3
  41. package/node_modules/pi-lens/dist/clients/eval-timestamp.js +17 -0
  42. package/node_modules/pi-lens/dist/clients/extension-log.js +296 -3
  43. package/node_modules/pi-lens/dist/clients/fix-worklog.js +5 -1
  44. package/node_modules/pi-lens/dist/clients/format-events-publish.js +39 -8
  45. package/node_modules/pi-lens/dist/clients/git-guard.js +18 -21
  46. package/node_modules/pi-lens/dist/clients/go-client.js +21 -39
  47. package/node_modules/pi-lens/dist/clients/govulncheck-client.js +116 -7
  48. package/node_modules/pi-lens/dist/clients/host-ports.js +1 -1
  49. package/node_modules/pi-lens/dist/clients/installer/index.js +5 -1
  50. package/node_modules/pi-lens/dist/clients/jscpd-client.js +4 -9
  51. package/node_modules/pi-lens/dist/clients/knip-client.js +51 -14
  52. package/node_modules/pi-lens/dist/clients/latency-logger.js +50 -1
  53. package/node_modules/pi-lens/dist/clients/lens-events.js +56 -25
  54. package/node_modules/pi-lens/dist/clients/lens-flag-registry.js +8 -0
  55. package/node_modules/pi-lens/dist/clients/live-bus-emitter.js +45 -2
  56. package/node_modules/pi-lens/dist/clients/lsp/aggregation.js +30 -4
  57. package/node_modules/pi-lens/dist/clients/lsp/cascade-tier.js +58 -13
  58. package/node_modules/pi-lens/dist/clients/lsp/client.js +169 -8
  59. package/node_modules/pi-lens/dist/clients/lsp/diagnostic-binding.js +29 -0
  60. package/node_modules/pi-lens/dist/clients/lsp/index.js +264 -66
  61. package/node_modules/pi-lens/dist/clients/lsp/server.js +247 -60
  62. package/node_modules/pi-lens/dist/clients/lsp/tsserver-sync.js +96 -0
  63. package/node_modules/pi-lens/dist/clients/lsp/wait-policy/classification.js +21 -5
  64. package/node_modules/pi-lens/dist/clients/lsp/wait-policy/strategies.js +18 -3
  65. package/node_modules/pi-lens/dist/clients/mcp/analyze.js +4 -0
  66. package/node_modules/pi-lens/dist/clients/mcp/session.js +30 -17
  67. package/node_modules/pi-lens/dist/clients/model-provider.js +53 -0
  68. package/node_modules/pi-lens/dist/clients/pipeline.js +29 -2
  69. package/node_modules/pi-lens/dist/clients/project-diagnostics/fresh-fetch.js +1 -1
  70. package/node_modules/pi-lens/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +23 -2
  71. package/node_modules/pi-lens/dist/clients/review-graph/query.js +24 -0
  72. package/node_modules/pi-lens/dist/clients/run-duration.js +55 -0
  73. package/node_modules/pi-lens/dist/clients/runtime-agent-end.js +153 -7
  74. package/node_modules/pi-lens/dist/clients/runtime-context.js +104 -11
  75. package/node_modules/pi-lens/dist/clients/runtime-coordinator.js +170 -22
  76. package/node_modules/pi-lens/dist/clients/runtime-session.js +28 -5
  77. package/node_modules/pi-lens/dist/clients/runtime-tool-result.js +124 -10
  78. package/node_modules/pi-lens/dist/clients/runtime-turn.js +388 -35
  79. package/node_modules/pi-lens/dist/clients/rust-client.js +21 -37
  80. package/node_modules/pi-lens/dist/clients/security-scan-client.js +88 -5
  81. package/node_modules/pi-lens/dist/clients/sg-runner.js +141 -23
  82. package/node_modules/pi-lens/dist/clients/smells-rollup.js +18 -11
  83. package/node_modules/pi-lens/dist/clients/startup-timing.js +7 -1
  84. package/node_modules/pi-lens/dist/clients/test-runner-client.js +431 -24
  85. package/node_modules/pi-lens/dist/clients/tool-policy.js +2 -0
  86. package/node_modules/pi-lens/dist/clients/tool-set-policy.js +76 -0
  87. package/node_modules/pi-lens/dist/clients/warm-attach.js +17 -0
  88. package/node_modules/pi-lens/dist/clients/word-index.js +305 -33
  89. package/node_modules/pi-lens/dist/index.js +4827 -1633
  90. package/node_modules/pi-lens/dist/mcp/server.js +8 -2
  91. package/node_modules/pi-lens/dist/tools/activate-tools.js +17 -5
  92. package/node_modules/pi-lens/dist/tools/ast-grep-replace.js +9 -4
  93. package/node_modules/pi-lens/dist/tools/lens-diagnostic-mark.js +5 -2
  94. package/node_modules/pi-lens/dist/tools/lens-diagnostics.js +3 -2
  95. package/node_modules/pi-lens/dist/tools/lsp-diagnostics.js +62 -7
  96. package/node_modules/pi-lens/dist/tools/symbol-search.js +1 -1
  97. package/node_modules/pi-lens/docs/agent-guide.md +38 -13
  98. package/node_modules/pi-lens/docs/ast-grep_rules_catalog.md +11 -3
  99. package/node_modules/pi-lens/docs/features.md +14 -1
  100. package/node_modules/pi-lens/docs/globalconfig.md +11 -0
  101. package/node_modules/pi-lens/docs/servercapabilities.md +1 -1
  102. package/node_modules/pi-lens/docs/settings.md +6 -0
  103. package/node_modules/pi-lens/docs/usage.md +23 -5
  104. package/node_modules/pi-lens/docs/word-index.md +35 -0
  105. package/node_modules/pi-lens/package.json +1 -1
  106. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-chained-type-assertions-test.yml +8 -0
  107. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-conditional-empty-object-spread-js-test.yml +9 -0
  108. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-conditional-empty-object-spread-test.yml +9 -0
  109. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-reflect-apply-js-test.yml +7 -0
  110. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-reflect-apply-test.yml +7 -0
  111. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-reflect-get-js-test.yml +8 -0
  112. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-reflect-get-test.yml +8 -0
  113. package/node_modules/pi-lens/rules/ast-grep-rules/rule-tests/no-unknown-laundering-test.yml +11 -0
  114. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-chained-type-assertions.yml +21 -0
  115. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-conditional-empty-object-spread-js.yml +21 -0
  116. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-conditional-empty-object-spread.yml +29 -0
  117. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-reflect-apply-js.yml +9 -0
  118. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-reflect-apply.yml +9 -0
  119. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-reflect-get-js.yml +13 -0
  120. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-reflect-get.yml +16 -0
  121. package/node_modules/pi-lens/rules/ast-grep-rules/rules/no-unknown-laundering.yml +27 -0
  122. package/node_modules/pi-lens/scripts/analyze-pi-lens-logs.mjs +79 -0
  123. package/node_modules/pi-lens/skills/pi-lens-ast-grep/SKILL.md +10 -11
  124. package/node_modules/pi-lens/skills/pi-lens-lsp-navigation/SKILL.md +22 -22
  125. package/node_modules/pi-lens/skills/pi-lens-write-ast-grep-rule/SKILL.md +8 -114
  126. package/node_modules/pi-lens/skills/pi-lens-write-ast-grep-rule/reference.md +129 -0
  127. package/node_modules/pi-lens/skills/pi-lens-write-tree-sitter-rule/SKILL.md +3 -1
  128. package/node_modules/pi-mcp-adapter/CHANGELOG.md +13 -0
  129. package/node_modules/pi-mcp-adapter/README.md +4 -1
  130. package/node_modules/pi-mcp-adapter/agent-dir.ts +12 -4
  131. package/node_modules/pi-mcp-adapter/cli.js +25 -4
  132. package/node_modules/pi-mcp-adapter/config.ts +4 -4
  133. package/node_modules/pi-mcp-adapter/direct-tools.ts +18 -15
  134. package/node_modules/pi-mcp-adapter/mcp-setup-panel.ts +2 -1
  135. package/node_modules/pi-mcp-adapter/metadata-cache.ts +18 -8
  136. package/node_modules/pi-mcp-adapter/package.json +2 -1
  137. package/node_modules/pi-mcp-adapter/request-headers-command.ts +336 -0
  138. package/node_modules/pi-mcp-adapter/server-manager.ts +5 -0
  139. package/node_modules/pi-mcp-adapter/tool-metadata.ts +38 -18
  140. package/node_modules/pi-mcp-adapter/types.ts +93 -10
  141. package/node_modules/pi-web-access/CHANGELOG.md +14 -0
  142. package/node_modules/pi-web-access/README.md +18 -12
  143. package/node_modules/pi-web-access/auth-fetch.ts +148 -0
  144. package/node_modules/pi-web-access/chrome-cookies.ts +110 -23
  145. package/node_modules/pi-web-access/curator-page.ts +5 -3
  146. package/node_modules/pi-web-access/curator-server.ts +2 -1
  147. package/node_modules/pi-web-access/extract.ts +106 -34
  148. package/node_modules/pi-web-access/fetch-params.ts +17 -3
  149. package/node_modules/pi-web-access/firecrawl.ts +172 -12
  150. package/node_modules/pi-web-access/gemini-search.ts +18 -4
  151. package/node_modules/pi-web-access/index.ts +120 -48
  152. package/node_modules/pi-web-access/package.json +2 -2
  153. package/node_modules/pi-web-access/summary-review.ts +11 -5
  154. package/node_modules/pi-web-access/youtube-extract.ts +2 -2
  155. package/package.json +9 -9
@@ -16,6 +16,7 @@ import * as path from "node:path";
16
16
  import { minimatch } from "./deps/minimatch.js";
17
17
  import { detectFileRole } from "./file-role.js";
18
18
  import { findGlobalBinary } from "./package-manager.js";
19
+ import { isMeasuredDuration, toMeasuredDurationMs } from "./run-duration.js";
19
20
  import { safeSpawn, safeSpawnAsync } from "./safe-spawn.js";
20
21
  // Source file → test file patterns (reverse lookup)
21
22
  const SOURCE_TO_TEST_PATTERNS = [
@@ -870,9 +871,17 @@ export class TestRunnerClient {
870
871
  runner,
871
872
  passed: json.numPassedTests || 0,
872
873
  failed: json.numFailedTests || 0,
873
- skipped: json.numSkippedTests || 0,
874
+ // #1452: `numSkippedTests` is absent from both reporters' JSON, so
875
+ // this read was always 0. `numPendingTests` is where a `test.skip`
876
+ // actually lands; `numTodoTests` is counted with it because the
877
+ // text parsers (pytest `N skipped`, mix `N excluded` + `N skipped`)
878
+ // also fold every not-run test into one `skipped` figure.
879
+ // `??` would accept a present 0, so a reporter that emits
880
+ // `numSkippedTests: 0` beside a real `numPendingTests` would
881
+ // reproduce the very defect this removes. Take the larger reading.
882
+ skipped: Math.max(json.numSkippedTests ?? 0, (json.numPendingTests || 0) + (json.numTodoTests || 0)),
874
883
  failures,
875
- duration: 0,
884
+ duration: this.jsonRunDurationMs(json.testResults),
876
885
  };
877
886
  }
878
887
  catch (err) {
@@ -881,6 +890,74 @@ export class TestRunnerClient {
881
890
  return this.emptyResult(testFile, "", runner, failed ? "Tests failed (could not parse output)" : undefined);
882
891
  }
883
892
  }
893
+ /**
894
+ * #1452: real run duration in ms from a vitest/jest `--json` payload.
895
+ *
896
+ * NOT `testResults[].perfStats`. That field exists on jest's INTERNAL
897
+ * `TestResult`, but the JSON reporter's `formatTestResults` projects it to
898
+ * per-suite `startTime`/`endTime` and drops it — measured absent from both
899
+ * vitest 4.1.10 and jest 30.4.2 output, so reading it would have left this
900
+ * at 0. The per-suite epoch pair is what both reporters actually emit.
901
+ *
902
+ * Wall-clock SPAN across suites (max end - min start), not a sum: suites in
903
+ * one payload may have run in parallel workers, and summing would report
904
+ * more elapsed time than the run took. With the single suite pi-lens
905
+ * actually produces (one test file per invocation) the two agree.
906
+ *
907
+ * The span excludes the runner's own startup: the top-level `startTime` is
908
+ * ~330ms earlier than the first suite's on this repo. What the per-suite
909
+ * pair then measures is NOT the same quantity across runners. On vitest it
910
+ * tracks test time closely (135ms span against 134ms of summed assertions),
911
+ * but jest stamps a suite's `startTime` before transform and module load,
912
+ * so the same fields give 5595ms against 128ms of assertions. Both are
913
+ * honest suite wall clock; neither is comparable to the other, and only the
914
+ * vitest figure is close to what pytest's `in 0.05s` or ExUnit's
915
+ * `Finished in 0.05 seconds` report.
916
+ *
917
+ * Falls back to the summed per-assertion `duration` when a reporter omits
918
+ * the suite pair. Never returns a negative or non-finite value — a garbled
919
+ * payload must degrade to "unmeasured", not to a wrong number.
920
+ *
921
+ * #1479: that degradation is now literal. This used to return 0 for a
922
+ * payload it could not read, which is the figure a sub-millisecond suite
923
+ * also produces, so the caller could not tell them apart. It returns
924
+ * `undefined` instead. A readable pair whose span is 0 still returns 0,
925
+ * because that is a measurement.
926
+ */
927
+ jsonRunDurationMs(suites) {
928
+ let minStart = Number.POSITIVE_INFINITY;
929
+ let maxEnd = Number.NEGATIVE_INFINITY;
930
+ let assertionTotal = 0;
931
+ for (const suite of suites || []) {
932
+ if (typeof suite.startTime === "number" &&
933
+ Number.isFinite(suite.startTime) &&
934
+ typeof suite.endTime === "number" &&
935
+ Number.isFinite(suite.endTime)) {
936
+ minStart = Math.min(minStart, suite.startTime);
937
+ maxEnd = Math.max(maxEnd, suite.endTime);
938
+ }
939
+ for (const assertion of suite.assertionResults || []) {
940
+ if (typeof assertion.duration === "number" &&
941
+ Number.isFinite(assertion.duration) &&
942
+ assertion.duration > 0) {
943
+ assertionTotal += assertion.duration;
944
+ }
945
+ }
946
+ }
947
+ const span = maxEnd - minStart;
948
+ if (Number.isFinite(span) && span > 0)
949
+ return Math.round(span);
950
+ if (assertionTotal > 0)
951
+ return Math.round(assertionTotal);
952
+ // Ordering above is unchanged from #1452 on purpose: a positive span
953
+ // still beats the assertion sum, and the sum still beats a suite pair
954
+ // that read as zero. Only the terminal case moved. A pair we could
955
+ // read whose span is 0 is a run that took under a millisecond — report
956
+ // it. Everything else was never measured.
957
+ if (Number.isFinite(span) && span === 0)
958
+ return 0;
959
+ return undefined;
960
+ }
884
961
  // --- Vitest Parser ---
885
962
  parseVitestOutput(stdout, stderr, testFile, cwd, runner) {
886
963
  return this.parseJsonTestOutput(stdout, stderr, testFile, cwd, runner);
@@ -899,7 +976,9 @@ export class TestRunnerClient {
899
976
  let passed = 0;
900
977
  let failed = 0;
901
978
  let skipped = 0;
902
- let duration = 0;
979
+ // #1479: undefined until pytest's own `in N.NNs` is read. `in 0.00s` is
980
+ // a real pytest summary, so 0 has to stay available as a measurement.
981
+ let duration;
903
982
  if (summaryMatch) {
904
983
  // Extract numbers from various patterns
905
984
  const passedMatch = output.match(/(\d+)\s+passed/);
@@ -909,7 +988,12 @@ export class TestRunnerClient {
909
988
  passed = passedMatch ? parseInt(passedMatch[1], 10) : 0;
910
989
  failed = failedMatch ? parseInt(failedMatch[1], 10) : 0;
911
990
  skipped = skippedMatch ? parseInt(skippedMatch[1], 10) : 0;
912
- duration = durationMatch ? parseFloat(durationMatch[1]) * 1000 : 0;
991
+ // Rounded, like `jsonRunDurationMs` and PHPUnit's legacy path:
992
+ // `in 2.01s` is 2009.9999999999998 in binary floating point, and
993
+ // the turn-end log prints the number as it stands.
994
+ // (Routing this through `toMeasuredDurationMs` is #1484, not this.)
995
+ if (durationMatch)
996
+ duration = Math.round(parseFloat(durationMatch[1]) * 1000);
913
997
  }
914
998
  // Parse individual failures: "FAILED tests/test_foo.py::test_something - AssertionError: ..."
915
999
  const failureRegex = /FAILED\s+(\S+::\S+)\s*-\s*(.+?)(?:\n|$)/g;
@@ -972,6 +1056,46 @@ export class TestRunnerClient {
972
1056
  while ((match = failureRegex.exec(output)) !== null) {
973
1057
  failures.push({ name: match[1], message: match[1] });
974
1058
  }
1059
+ // #1452: PHPUnit prints its own elapsed time and this parser dropped it,
1060
+ // so every PHPUnit run reported 0ms. Two shapes are accepted because the
1061
+ // summary changed across supported majors:
1062
+ // PHPUnit >= 9.3 "Time: 00:00.123, Memory: 8.00 MB" (HH:)MM:SS.mmm
1063
+ // PHPUnit <= 9.2 "Time: 1.23 seconds, Memory: 10.00MB" | "Time: 123 ms"
1064
+ // NOT VERIFIED AGAINST A LIVE PHPUnit — there is no PHP toolchain on the
1065
+ // box this was written on. Both shapes are covered by unit tests against
1066
+ // literal summary lines taken from the PHPUnit printers, and the parser
1067
+ // leaves duration UNMEASURED when neither matches (#1479 — it used to
1068
+ // leave 0, which the turn-end log printed as a measurement), so an
1069
+ // unrecognised summary degrades to "we do not know" rather than to a
1070
+ // wrong figure.
1071
+ let duration;
1072
+ const clockMatch = output.match(/^Time:\s*(?:(\d+):)?(\d{1,2}):(\d{2})(?:\.(\d{1,3}))?/im);
1073
+ if (clockMatch) {
1074
+ const hours = clockMatch[1] ? Number.parseInt(clockMatch[1], 10) : 0;
1075
+ const minutes = Number.parseInt(clockMatch[2], 10);
1076
+ const seconds = Number.parseInt(clockMatch[3], 10);
1077
+ // ".1" is a tenth, ".12" hundredths — pad rather than parseInt, or
1078
+ // "Time: 00:00.1" would read as 1ms instead of 100ms.
1079
+ const millis = clockMatch[4]
1080
+ ? Number.parseInt(clockMatch[4].padEnd(3, "0"), 10)
1081
+ : 0;
1082
+ duration = ((hours * 60 + minutes) * 60 + seconds) * 1000 + millis;
1083
+ }
1084
+ else {
1085
+ const legacyMatch = output.match(/^Time:\s*([\d.]+)\s*(seconds?|s|ms|milliseconds?|minutes?)\b/im);
1086
+ if (legacyMatch) {
1087
+ const value = Number.parseFloat(legacyMatch[1]);
1088
+ const unit = legacyMatch[2].toLowerCase();
1089
+ const scale = unit.startsWith("ms") || unit.startsWith("milli")
1090
+ ? 1
1091
+ : unit.startsWith("min")
1092
+ ? 60_000
1093
+ : 1000;
1094
+ if (Number.isFinite(value) && value > 0) {
1095
+ duration = Math.round(value * scale);
1096
+ }
1097
+ }
1098
+ }
975
1099
  return {
976
1100
  file: testFile,
977
1101
  sourceFile: "",
@@ -980,7 +1104,7 @@ export class TestRunnerClient {
980
1104
  failed,
981
1105
  skipped,
982
1106
  failures,
983
- duration: 0,
1107
+ duration,
984
1108
  error: exitCode !== 0 && passed === 0 && failed === 0
985
1109
  ? "PHPUnit runner error"
986
1110
  : undefined,
@@ -992,7 +1116,8 @@ export class TestRunnerClient {
992
1116
  let passed = 0;
993
1117
  let failed = 0;
994
1118
  let skipped = 0;
995
- let duration = 0;
1119
+ // #1479: undefined until ExUnit's own `Finished in N seconds` is read.
1120
+ let duration;
996
1121
  // Summary: "3 tests, 1 failure" (optionally ", N excluded" / ", N skipped")
997
1122
  const summaryMatch = output.match(/(\d+)\s+tests?,\s*(\d+)\s+failures?(?:,\s*(\d+)\s+excluded)?(?:,\s*(\d+)\s+skipped)?/i);
998
1123
  if (summaryMatch) {
@@ -1007,7 +1132,10 @@ export class TestRunnerClient {
1007
1132
  }
1008
1133
  const durationMatch = output.match(/Finished in\s+([\d.]+)\s+seconds?/i);
1009
1134
  if (durationMatch) {
1010
- duration = Number.parseFloat(durationMatch[1]) * 1000;
1135
+ // Rounded for the same reason pytest's is: `2.01` seconds is
1136
+ // 2009.9999999999998 ms unrounded, and that reaches the log.
1137
+ // (Routing this through `toMeasuredDurationMs` is #1484.)
1138
+ duration = Math.round(Number.parseFloat(durationMatch[1]) * 1000);
1011
1139
  }
1012
1140
  // Individual failures: " 1) test some behavior (MyModuleTest)"
1013
1141
  const failures = [];
@@ -1035,17 +1163,239 @@ export class TestRunnerClient {
1035
1163
  };
1036
1164
  }
1037
1165
  // --- Generic text parser for non-JSON runners ---
1166
+ /**
1167
+ * #1480: elapsed time for the runners `parseGenericRunnerOutput` handles.
1168
+ *
1169
+ * Before this, only go's `ok pkg 0.25s` was read and every other runner
1170
+ * reported a hardcoded 0. #1479 made the log tell "measured" from
1171
+ * "unmeasured", but this parser is the `default:` arm behind cargo, dotnet,
1172
+ * maven, gradle, rspec, minitest and every unrecognised runner, so all of
1173
+ * them still reported a number nobody measured. Each runner below prints
1174
+ * its elapsed time in the same summary block this parser already regexes
1175
+ * for pass/fail counts.
1176
+ *
1177
+ * Absent, not 0, is the answer when nothing is found — see
1178
+ * `TestResult.duration` and `run-duration.ts`. A probe that returned 0 here
1179
+ * would be claiming a measurement.
1180
+ *
1181
+ * One parser serves all runners, so the probe is selected BY RUNNER NAME.
1182
+ * Running every probe over every runner's output was the original shape of
1183
+ * this code, and it let gradle borrow a number: `BUILD SUCCESSFUL in 3s`
1184
+ * plus a preceding `... ok` line satisfied go's `ok <pkg> <n>s` probe, so
1185
+ * the whole-build wall clock got reported as test time — the exact wrong
1186
+ * number this function refuses to print. Gating on the runner makes that
1187
+ * structurally impossible rather than merely unlikely, and it matters most
1188
+ * for the `default:` arm of the switch, which is where an unrecognised or
1189
+ * custom runner's arbitrary output lands.
1190
+ *
1191
+ * Within a runner the patterns are still anchored where an anchor helps,
1192
+ * for the same reason #1452's PHPUnit `Time:` pattern is anchored: an
1193
+ * unanchored /m match takes the FIRST hit over stdout+stderr, and a failure
1194
+ * diff quoting "Finished in ..." would beat the real summary. Note what the
1195
+ * `^` in `^Finished in` does and does not buy. It rejects a decoy that is
1196
+ * INDENTED, which is what a quoted expectation or an assertion diff is; it
1197
+ * does NOT rank two column-0 matches, so an unindented decoy printed by the
1198
+ * suite itself would still win. It is a cheap filter for the common shape,
1199
+ * not a proof of uniqueness. And it is not an anchor to the counts line for
1200
+ * rspec or minitest: both print their elapsed time on a `Finished in ...`
1201
+ * line and their counts (`3 examples, 0 failures`, `1 runs, 1 assertions,
1202
+ * ...`) on a different line.
1203
+ *
1204
+ * KNOWN LIMIT — first summary only. cargo across multiple crates, `dotnet
1205
+ * test` across multiple assemblies, and `go test ./...` across multiple
1206
+ * packages each print one summary per unit, and these probes take the
1207
+ * first. A multi-unit run therefore UNDER-REPORTS its duration. That is
1208
+ * left as-is deliberately: the count parsers below have the same first-match
1209
+ * shape for those runners, so duration and counts describe the same scope.
1210
+ * Fixing one without the other would trade an under-report for an
1211
+ * inconsistency. Pinned by test so it stays a known limit, not an accident.
1212
+ *
1213
+ * Formats and how each was verified:
1214
+ *
1215
+ * - go — `ok example.com/pkg 0.253s`. Pre-existing pattern, unchanged
1216
+ * apart from the shared finite/non-negative guard.
1217
+ *
1218
+ * - cargo — `test result: ok. 3 passed; 0 failed; 1 ignored; 0 measured;
1219
+ * 0 filtered out; finished in 0.253s`. NOT VERIFIED AGAINST A LIVE CARGO
1220
+ * RUN — this box has no MSVC linker, so `cargo test` cannot link. Format
1221
+ * read out of the libtest printer shipped with the local rustc 1.94.1:
1222
+ * `library/test/src/formatters/pretty.rs` builds `"; finished in
1223
+ * {exec_time}"` and `library/test/src/time.rs` renders `TestSuiteExecTime`
1224
+ * as `{:.2}s`. Older rustc omits the suffix entirely; that degrades to
1225
+ * unmeasured.
1226
+ *
1227
+ * - dotnet/vstest — `Failed: 1, Passed: 2, Skipped: 0, Total: 3, Duration:
1228
+ * 1 m 30 s - t.dll (net8.0)`. NOT VERIFIED AGAINST A LIVE `dotnet test` —
1229
+ * NuGet restore has no network here. Format read out of the
1230
+ * vstest.console.dll shipped with the local .NET SDK 8.0.423, which holds
1231
+ * the literal `{0} - Failed: {1}, Passed: {2}, Skipped: {3}, Total: {4},
1232
+ * Duration: {5}` next to the unit literals `" h"`, `" m"`, `" s"`,
1233
+ * `" ms"`, `"< 1 ms"`. The duration is a space-joined token list, so it
1234
+ * is summed rather than read as one number.
1235
+ *
1236
+ * - maven/surefire — `Tests run: 4, Failures: 0, Errors: 0, Skipped: 0,
1237
+ * Time elapsed: 0.05 s -- in com.example.AppTest`. NOT VERIFIED AGAINST A
1238
+ * LIVE MAVEN — no mvn on this box. Summed across the per-class lines,
1239
+ * because surefire prints `Time elapsed` per test class and its final
1240
+ * `Results:` total carries no time. `[INFO] Total time: 3.4 s` is
1241
+ * deliberately NOT used: that is whole-build wall clock including compile,
1242
+ * which would report a wrong number rather than none. Surefire 2.x wrote
1243
+ * `sec` where 3.x writes `s`; both are accepted.
1244
+ *
1245
+ * EXPECT THIS TO BE ABSENT IN PRACTICE. pi-lens invokes `mvn test -q`
1246
+ * (see RUNNERS.maven above), and surefire logs its per-class `Tests run:
1247
+ * ..., Time elapsed: ...` lines at INFO, which `-q` suppresses. Only the
1248
+ * ERROR-level lines of a FAILING class survive, so a green maven run
1249
+ * typically reports unmeasured and a red one reports the failing classes'
1250
+ * time alone. REASONED, NOT RUN — there is no mvn on this box to confirm
1251
+ * it. Left in rather than dropped: it costs nothing, it is correct when
1252
+ * the output does carry the lines (a repo that sets `-Dsurefire.useFile`
1253
+ * or drops `-q` via `.mvn/maven.config`), and `unmeasured` is an honest
1254
+ * report of the quiet case.
1255
+ *
1256
+ * - rspec — `Finished in 0.32394 seconds (files took 0.49427 seconds to
1257
+ * load)`. VERIFIED against a live rspec-core 3.13.6 run on ruby 3.4.10.
1258
+ * The minutes form (`Finished in 2 minutes 15.14 seconds`) comes from
1259
+ * `RSpec::Core::Formatters::Helpers.format_duration` in the same
1260
+ * installed gem; rspec never prints hours. Load time trails the run time
1261
+ * on the same line and must not be read instead of it.
1262
+ *
1263
+ * - minitest — `Finished in 0.254594s, 7.8557 runs/s, 7.8557 assertions/s.`
1264
+ * VERIFIED against a live minitest 5.25.4 run on ruby 3.4.10. The format
1265
+ * string is `"Finished in %.6fs, ..."` in minitest.rb, always seconds.
1266
+ *
1267
+ * - gradle — deliberately left unmeasured, and now UNREACHABLE by any other
1268
+ * runner's probe rather than merely unmatched by it. Gradle's console
1269
+ * summary (`4 tests completed, 1 failed`) carries no elapsed time, and
1270
+ * `BUILD SUCCESSFUL in 3s` is whole-build wall clock including compile
1271
+ * and dependency resolution. Reporting that as test time would be a wrong
1272
+ * number; #1479 makes the absence legible in the log instead.
1273
+ */
1274
+ parseGenericRunnerDuration(output, runner) {
1275
+ switch (runner) {
1276
+ case "go":
1277
+ return this.parseGoDuration(output);
1278
+ case "cargo":
1279
+ return this.parseCargoDuration(output);
1280
+ case "dotnet":
1281
+ return this.parseDotnetDuration(output);
1282
+ case "maven":
1283
+ return this.parseMavenDuration(output);
1284
+ case "rspec":
1285
+ return this.parseRspecDuration(output);
1286
+ case "minitest":
1287
+ return this.parseMinitestDuration(output);
1288
+ default:
1289
+ // gradle and anything unrecognised: unmeasured, never
1290
+ // zero-as-measurement and never another runner's number.
1291
+ return undefined;
1292
+ }
1293
+ }
1294
+ /** go: `ok example.com/pkg 0.253s`. First package summary only. */
1295
+ parseGoDuration(output) {
1296
+ const goSummary = output.match(/ok\s+\S+\s+([\d.]+)s/m);
1297
+ if (!goSummary)
1298
+ return undefined;
1299
+ return toMeasuredDurationMs(Number.parseFloat(goSummary[1]) * 1000);
1300
+ }
1301
+ /** cargo: `...; 0 filtered out; finished in 0.25s`. First crate only. */
1302
+ parseCargoDuration(output) {
1303
+ const cargoTime = output.match(/^test result:.*?;\s*finished in\s+([\d.]+)\s*s\b/im);
1304
+ if (!cargoTime)
1305
+ return undefined;
1306
+ return toMeasuredDurationMs(Number.parseFloat(cargoTime[1]) * 1000);
1307
+ }
1308
+ /**
1309
+ * dotnet/vstest: `..., Total: 3, Duration: 1 m 30 s - t.dll (net8.0)`.
1310
+ *
1311
+ * Anchored to the counts line, and the tail stops at the ` - <dll>`
1312
+ * separator: without that stop an assembly name is scanned for unit tokens,
1313
+ * and a name like `Timeouts.30s.Tests.dll` adds 30 seconds of nothing.
1314
+ * First assembly only.
1315
+ */
1316
+ parseDotnetDuration(output) {
1317
+ const dotnetTime = output.match(/Failed:\s*\d+,\s*Passed:\s*\d+,\s*Skipped:\s*\d+,\s*Total:\s*\d+,\s*Duration:\s*([^\r\n-]+)/i);
1318
+ if (!dotnetTime)
1319
+ return undefined;
1320
+ // `< 1 ms` is vstest's "too fast to name a number", and under the
1321
+ // optional-duration contract 0 is exactly the right thing to say: the
1322
+ // run WAS measured and it rounds to 0 ms. The token scan below would
1323
+ // reach the same 0 by finding no tokens, but only by accident, and the
1324
+ // accident is indistinguishable from an unparseable tail — so the case
1325
+ // is spelled out.
1326
+ if (/^\s*</.test(dotnetTime[1]))
1327
+ return 0;
1328
+ let total = 0;
1329
+ let tokens = 0;
1330
+ // "ms" before "m", or "250 ms" scores as 250 minutes.
1331
+ const units = {
1332
+ ms: 1,
1333
+ s: 1000,
1334
+ m: 60_000,
1335
+ h: 3_600_000,
1336
+ };
1337
+ for (const token of dotnetTime[1].matchAll(/([\d.]+)\s*(ms|h|m|s)\b/gi)) {
1338
+ total += Number.parseFloat(token[1]) * units[token[2].toLowerCase()];
1339
+ tokens++;
1340
+ }
1341
+ // A tail we matched but could not read a single token out of is not a
1342
+ // zero-length run, it is an unrecognised format.
1343
+ if (tokens === 0)
1344
+ return undefined;
1345
+ return toMeasuredDurationMs(total);
1346
+ }
1347
+ /**
1348
+ * maven/surefire: summed across per-class `Time elapsed` lines.
1349
+ *
1350
+ * The guard is "did any line match", NOT "is the sum positive". Surefire
1351
+ * prints `Time elapsed: 0.00 s` for a trivial test class, and that is a
1352
+ * measurement of zero, not a failure to measure.
1353
+ */
1354
+ parseMavenDuration(output) {
1355
+ let surefireTotal = 0;
1356
+ let matched = false;
1357
+ for (const line of output.matchAll(/^.*Tests run:\s*\d+,.*?Time elapsed:\s*([\d.]+)\s*(?:s|sec|secs|seconds)\b.*$/gim)) {
1358
+ const seconds = Number.parseFloat(line[1]);
1359
+ if (!Number.isFinite(seconds) || seconds < 0)
1360
+ continue;
1361
+ surefireTotal += seconds;
1362
+ matched = true;
1363
+ }
1364
+ if (!matched)
1365
+ return undefined;
1366
+ return toMeasuredDurationMs(surefireTotal * 1000);
1367
+ }
1368
+ /** rspec: `Finished in 2 minutes 15.14 seconds (files took 0.5 ...)`. */
1369
+ parseRspecDuration(output) {
1370
+ const rspecTime = output.match(/^Finished in\s+(?:([\d.]+)\s+minutes?\s+)?([\d.]+)\s+seconds?/im);
1371
+ if (!rspecTime)
1372
+ return undefined;
1373
+ const minutes = rspecTime[1] ? Number.parseFloat(rspecTime[1]) : 0;
1374
+ return toMeasuredDurationMs(minutes * 60_000 + Number.parseFloat(rspecTime[2]) * 1000);
1375
+ }
1376
+ /**
1377
+ * minitest: `Finished in 0.254594s, 7.8557 runs/s, ...`.
1378
+ *
1379
+ * The trailing `,` is load-bearing, not decoration: it is what separates
1380
+ * minitest's own line from a bare `Finished in 99s` the suite under test
1381
+ * printed at column 0, which the `^` alone does not rank.
1382
+ */
1383
+ parseMinitestDuration(output) {
1384
+ const minitestTime = output.match(/^Finished in\s+([\d.]+)s\s*,/im);
1385
+ if (!minitestTime)
1386
+ return undefined;
1387
+ return toMeasuredDurationMs(Number.parseFloat(minitestTime[1]) * 1000);
1388
+ }
1038
1389
  parseGenericRunnerOutput(stdout, stderr, exitCode, testFile, runner) {
1039
1390
  const output = `${stdout}\n${stderr}`;
1040
1391
  const lower = output.toLowerCase();
1041
1392
  let passed = 0;
1042
1393
  let failed = exitCode === 0 ? 0 : 1;
1043
1394
  let skipped = 0;
1044
- let duration = 0;
1045
- const goSummary = output.match(/ok\s+\S+\s+([\d.]+)s/m);
1046
- if (goSummary) {
1047
- duration = Number.parseFloat(goSummary[1]) * 1000;
1048
- }
1395
+ // #1480: `number | undefined`, and sourced per runner. This used to be
1396
+ // `let duration = 0` with only go's probe able to move it, so every
1397
+ // other runner reported a zero it never measured.
1398
+ const duration = this.parseGenericRunnerDuration(output, runner);
1049
1399
  const cargoSummary = output.match(/test result:\s+\w+\.\s+(\d+)\s+passed;\s+(\d+)\s+failed;\s+(\d+)\s+ignored;/i);
1050
1400
  if (cargoSummary) {
1051
1401
  passed = Number.parseInt(cargoSummary[1], 10);
@@ -1058,13 +1408,41 @@ export class TestRunnerClient {
1058
1408
  passed = Number.parseInt(dotnetSummary[2], 10);
1059
1409
  skipped = Number.parseInt(dotnetSummary[3], 10);
1060
1410
  }
1061
- const mavenSummary = output.match(/Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)/i);
1062
- if (mavenSummary) {
1063
- const total = Number.parseInt(mavenSummary[1], 10);
1064
- const failures = Number.parseInt(mavenSummary[2], 10);
1065
- const errors = Number.parseInt(mavenSummary[3], 10);
1066
- skipped = Number.parseInt(mavenSummary[4], 10);
1067
- failed = failures + errors;
1411
+ // #1480 (adjacent, duration-independent): surefire prints one
1412
+ // `Tests run:` line PER TEST CLASS (those carry `Time elapsed:`) and
1413
+ // then a per-MODULE aggregate under `Results:` (which does not). Taking
1414
+ // the FIRST match scored a run by its first class alone — a two-class
1415
+ // run with a failure in the second class reported 0 failures.
1416
+ //
1417
+ // Taking the LAST match is just as wrong, in a worse direction. A
1418
+ // multi-module reactor run prints one `Results:` aggregate per module,
1419
+ // and the last is the last module: a `--fail-at-end` build whose first
1420
+ // module had 3 failures and whose second module was green would report
1421
+ // 0 failures, turning a red build into `PASS` in the turn-end log. That
1422
+ // is reachable without pi-lens passing the flag, because maven also
1423
+ // reads `.mvn/maven.config` and `MAVEN_ARGS`.
1424
+ //
1425
+ // So: SUM the aggregates. That makes counts reactor-wide, the same
1426
+ // scope `parseMavenDuration` sums its per-class times over. When no
1427
+ // aggregate is present (output truncated, or `Results:` suppressed) the
1428
+ // per-class lines sum to the same totals, so they are the fallback.
1429
+ const mavenLines = [
1430
+ ...output.matchAll(/^.*?Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+).*$/gim),
1431
+ ];
1432
+ const mavenAggregates = mavenLines.filter((line) => !/Time elapsed:/i.test(line[0]));
1433
+ const mavenScored = mavenAggregates.length > 0 ? mavenAggregates : mavenLines;
1434
+ if (mavenScored.length > 0) {
1435
+ let total = 0;
1436
+ let mavenFailed = 0;
1437
+ let mavenSkipped = 0;
1438
+ for (const line of mavenScored) {
1439
+ total += Number.parseInt(line[1], 10);
1440
+ mavenFailed +=
1441
+ Number.parseInt(line[2], 10) + Number.parseInt(line[3], 10);
1442
+ mavenSkipped += Number.parseInt(line[4], 10);
1443
+ }
1444
+ failed = mavenFailed;
1445
+ skipped = mavenSkipped;
1068
1446
  passed = Math.max(0, total - failed - skipped);
1069
1447
  }
1070
1448
  const rspecSummary = output.match(/(\d+)\s+examples?,\s+(\d+)\s+failures?/i);
@@ -1087,6 +1465,22 @@ export class TestRunnerClient {
1087
1465
  failed = Number.parseInt(gradleSummary[2], 10);
1088
1466
  passed = Math.max(0, total - failed);
1089
1467
  }
1468
+ // Captured BEFORE the guard below, which rewrites `failed` out of the
1469
+ // state this condition reads. Without this the runner-error string
1470
+ // silently became unreachable.
1471
+ const runnerError = exitCode !== 0 && failed === 0 && lower.includes("error")
1472
+ ? `Runner ${runner} exited with ${exitCode}`
1473
+ : undefined;
1474
+ // #1480 (adjacent): a non-zero exit is the runner saying the run
1475
+ // failed. Every count parser above can legitimately arrive at
1476
+ // `failed === 0` — a summary that only covers part of the run, a green
1477
+ // module of a red reactor build, a failure outside any test — and the
1478
+ // turn-end log would then print PASS over a build the runner rejected.
1479
+ // Trust the exit code: no parse of the text may talk it out of at least
1480
+ // one failure.
1481
+ if (exitCode !== 0 && failed === 0) {
1482
+ failed = 1;
1483
+ }
1090
1484
  if (passed === 0 && failed === 0 && skipped === 0 && exitCode === 0) {
1091
1485
  passed = 1;
1092
1486
  }
@@ -1116,9 +1510,7 @@ export class TestRunnerClient {
1116
1510
  skipped,
1117
1511
  failures,
1118
1512
  duration,
1119
- error: exitCode !== 0 && failed === 0 && lower.includes("error")
1120
- ? `Runner ${runner} exited with ${exitCode}`
1121
- : undefined,
1513
+ error: runnerError,
1122
1514
  };
1123
1515
  }
1124
1516
  // --- Formatting ---
@@ -1134,7 +1526,21 @@ export class TestRunnerClient {
1134
1526
  if (total === 0) {
1135
1527
  return ""; // No tests to report
1136
1528
  }
1137
- const durationStr = result.duration > 0 ? ` (${(result.duration / 1000).toFixed(2)}s)` : "";
1529
+ // #1479 deliberately does NOT change this surface. The agent-facing
1530
+ // string already suppressed the suffix for a 0, so an unmeasured run
1531
+ // and a zero-length one look the same here and always did. The issue
1532
+ // scopes the unmeasured/zero distinction to the turn-end log line;
1533
+ // widening it to the LLM prompt is a separate call about prompt noise.
1534
+ // #1480: the "is this a measurement at all" half of the test comes from
1535
+ // `run-duration.ts` so this surface cannot drift from the log's answer.
1536
+ // The `> 0` half is the scope decision above and stays local to it — it
1537
+ // is what suppresses the suffix for a measured zero, which is a choice
1538
+ // about prompt noise rather than about the duration contract. Routing
1539
+ // the first half through the shared predicate also stops a non-finite
1540
+ // duration rendering as ` (Infinitys)`.
1541
+ const durationStr = isMeasuredDuration(result.duration) && result.duration > 0
1542
+ ? ` (${(result.duration / 1000).toFixed(2)}s)`
1543
+ : "";
1138
1544
  if (result.failed === 0) {
1139
1545
  return `[Tests] ✓ ${result.passed}/${total} passed${durationStr} — ${result.runner}`;
1140
1546
  }
@@ -1283,7 +1689,8 @@ export class TestRunnerClient {
1283
1689
  failed: 0,
1284
1690
  skipped: 0,
1285
1691
  failures: [],
1286
- duration: 0,
1692
+ // #1479: no duration key at all. Nothing ran, so there is nothing
1693
+ // to report — this used to say 0, which reads as "ran, instantly".
1287
1694
  error,
1288
1695
  };
1289
1696
  }
@@ -1453,6 +1453,7 @@ export function getAutofixPolicyForFile(filePath, context = {}) {
1453
1453
  defaultWhenUnconfigured: true,
1454
1454
  gate: "smart-default",
1455
1455
  safe: true,
1456
+ scope: "cargo-project",
1456
1457
  };
1457
1458
  }
1458
1459
  if ([".json", ".jsonc"].includes(ext)) {
@@ -1595,6 +1596,7 @@ export function getAutofixPolicyForFile(filePath, context = {}) {
1595
1596
  defaultWhenUnconfigured: true,
1596
1597
  gate: "smart-default",
1597
1598
  safe: true,
1599
+ scope: "dart-project",
1598
1600
  };
1599
1601
  }
1600
1602
  return undefined;
@@ -0,0 +1,76 @@
1
+ import { logLatency } from "./latency-logger.js";
2
+ /**
3
+ * Whether the host will send this model deferred (searchable) tool
4
+ * definitions rather than the full inline list.
5
+ *
6
+ * Read the host's own decision off `ctx.model.compat` — pi resolves that
7
+ * flag from the model config (`core/model-config`, `compat.supportsToolReferences`)
8
+ * and it is the only capability signal a consumer can honestly observe.
9
+ * A missing flag means "unknown", which we report as false: this value only
10
+ * annotates the `tool_set_mutation` log line, so guessing high would make the
11
+ * log lie, while guessing low merely under-claims.
12
+ */
13
+ export function supportsDeferredTools(model) {
14
+ return model?.compat?.supportsToolReferences === true;
15
+ }
16
+ /**
17
+ * A fresh logical conversation — the only reasons that start with an empty
18
+ * activation memory. `undefined` is included because older hosts fire
19
+ * `session_start` with no `reason` at all.
20
+ *
21
+ * Every OTHER reason (fork/reload/resume) is a session REBUILD: the host
22
+ * constructs a brand-new AgentSession with `includeAllExtensionTools: true`
23
+ * (pi `core/agent-session.js`), so every registered pi-lens tool is active
24
+ * again by the time our handler runs, while pi-lens's own extension closure
25
+ * state survives. Those reasons must RESTORE the previous posture, not skip.
26
+ */
27
+ export function isFreshSessionStart(reason) {
28
+ return reason === undefined || reason === "startup" || reason === "new";
29
+ }
30
+ /**
31
+ * Compute the active-tool set pi-lens wants: everything currently active that
32
+ * is not a lazy tool, plus exactly the lazy tools the model activated in this
33
+ * logical session (`remembered`).
34
+ *
35
+ * On startup/new `remembered` is empty and this is the plain baseline shrink.
36
+ * On fork/reload/resume the host has just re-activated all registered tools,
37
+ * and this restores the parent's posture character-for-character — which both
38
+ * preserves the model's activations and keeps the advertised tool list equal
39
+ * to the one the prompt cache prefix was built from.
40
+ */
41
+ export function planToolSet(active, lazyNames, remembered) {
42
+ const desired = active.filter(
43
+ // Lazy tools are dropped here and re-appended below in REMEMBERED
44
+ // (= activation) order. Keeping them in the host's registration
45
+ // position would restore the right SET in the wrong ARRAY order, and
46
+ // the active-tools array is what serializes into the request's tool
47
+ // block — a transposition is a changed prefix, i.e. a cache miss.
48
+ (name) => !lazyNames.has(name));
49
+ // A remembered tool the host did not list as active still belongs in the
50
+ // set (defensive: the host controls what `getActiveTools` returns).
51
+ const desiredSet = new Set(desired);
52
+ for (const name of remembered) {
53
+ if (!desiredSet.has(name)) {
54
+ desired.push(name);
55
+ desiredSet.add(name);
56
+ }
57
+ }
58
+ const activeSet = new Set(active);
59
+ const removedCount = active.filter((name) => !desiredSet.has(name)).length;
60
+ const addedCount = desired.filter((name) => !activeSet.has(name)).length;
61
+ return {
62
+ desired,
63
+ addedCount,
64
+ removedCount,
65
+ changed: addedCount > 0 || removedCount > 0,
66
+ };
67
+ }
68
+ export function recordToolSetMutation(mutation) {
69
+ logLatency({
70
+ type: "phase",
71
+ filePath: "<pi-lens>",
72
+ phase: "tool_set_mutation",
73
+ durationMs: 0,
74
+ metadata: { ...mutation },
75
+ });
76
+ }