Commit 1c40cface6c for nodejs

commit 1c40cface6c9d5b1e093b52292e47e5249f5a780
Author: Joyee Cheung <joyeec9h3@gmail.com>
Date:   Tue Nov 17 10:51:42 2026 +0100

    inspector: support attaching to a running process in probe mode

    Probe mode currently only launches a new process from the entry point
    script. This change lets it attach to an already-running process, so a
    long-lived application can be inspected without restarting it.

    Running `node inspect --probe` without specifying an entry point script
    instructs Node.js to attach to a running Node.js process and probe.
    The way attaching is done is specified through command line arguments:

    - `--pid <pid>` activates the target's inspector (if it's not already
      activated) and connects to it.
    - `--host <host>` and `--port <port>` specify an address where an
      inspector is listening. The host defaults to 127.0.0.1 and the
      port defaults to 9229.

    When the session ends, probe mode resumes and detaches instead of
    killing a process it does not own. The report now includes a top-level
    `target` field describing what was probed, and each probe contains a
    `locations` field about where it bound.

    An attach session ends when a probe reaches `--max-hit`
    (reported as `completed`), when the target finishes on its
    own (`completed`, or `miss` with the pending probes, and the target is
    then allowed to exit), or when `--timeout` fires (reported as
    `timeout`, the probing process exit with 0 and reports the hits recorded
    so far).

    `--timeout` now is also applied to the startup phase in both modes, so
    a target that never responds before the breakpoints are bound is
    reported as an error instead of hanging.

    Signed-off-by: Joyee Cheung <joyeec9h3@gmail.com>
    PR-URL: https://github.com/nodejs/node/pull/67201
    Reviewed-By: Jan Martin <jan.krems@gmail.com>
    Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
    Reviewed-By: James M Snell <jasnell@gmail.com>

diff --git a/doc/api/debugger.md b/doc/api/debugger.md
index c7490af8292..04db8523ed7 100644
--- a/doc/api/debugger.md
+++ b/doc/api/debugger.md
@@ -237,6 +237,11 @@ added:
   - v26.1.0
   - v24.16.0
 changes:
+  - version: REPLACEME
+    pr-url: https://github.com/nodejs/node/pull/67201
+    description: Add `--pid <pid>` and `--host <host>`/`--port <port>` to probe a process that's
+        already running. The report now includes a top-level `target` field to describe what was
+        probed, and a `locations` field showing which probe is bound to which location.
   - version:
      - v26.6.0
      - v24.20.0
@@ -270,8 +275,10 @@ changes:
 `node inspect` supports a non-interactive probe mode for inspecting runtime values
 in an application via the flag `--probe`.

-Currently, probe mode only supports launching a new process from the entry point
-script specified on the command line.
+There are two ways to use probe mode:
+
+* Launch a new process and probe it by specifying the entry point script.
+* Attach to and probe a running process using `--pid <pid>` or `--host <host>`/`--port <port>`.

 The probe mode sets one or more source breakpoints, evaluates specified
 expressions whenever the execution reaches a breakpoint, and prints one
@@ -281,10 +288,18 @@ printf-style debugging without having to modify the application code and
 clean up afterwards. It also supports structured JSON output for tool use.

 ```console
+# To launch a new process and probe it:
 $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>]
               [--probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>] ...]
               [--json] [--preview] [--timeout=<ms>] [--port=<port>]
               [--] [<node-option> ...] <script> [<script-args> ...]
+
+# To activate the inspector in an already-running process and probe it:
+$ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --pid <pid> [--host <host>] [--port <port>]
+
+# To probe a running process whose inspector is already listening for connections:
+$ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --host <host> [--port <port>]
+$ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --port <port> [--host <host>]
 ```

 * `--probe <file>:<line>[:<col>]`: Source location of the probe. When execution
@@ -300,17 +315,32 @@ $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--ma
   is treated as false.
 * `--max-hit <n>`: An optional per-probe limit on the number of times the probe
   can be hit. When not specified, there's no hit limit. When any probe reaches
-  its hit limit, the probing process will detach and report the results. The process
-  being probed will continue to run. If any other probe is never reached by the time
-  the session ends, it will be reported as a missed probe.
-* `--timeout=<ms>`: A global wall-clock deadline for the entire probe session.
-  The default is `30000`. This can be used to probe a long-running application
-  that can be terminated externally.
+  its hit limit, the probing session finishes and reports the results. If the
+  probed process was launched by probe mode, it's then terminated. If the process
+  was already running before being attached for probing, it is resumed and left running.
+  If any other probe is never reached by the time the session ends, the missed probes will
+  be reported.
+* `--timeout=<ms>`: A deadline in milliseconds. The default is `30000`. It is
+  applied first to the target responding to the inspector and binding the
+  probes, then to the probing session itself, so a run can take up to about
+  twice the limit to time out. If the target does not respond in time during startup,
+  the report ends with an `error` and the probing process exits with a non-zero
+  code. If the process was attached to instead of launched by probe mode,
+  `--timeout` is an alternative to `--max-hit` for ending a probing session
+  without terminating the probed process.
 * `--json`: If used, prints a structured JSON report instead of the default text report.
 * `--preview`: If used, non-primitive values will include CDP property previews for
   object-like JSON probe values.
-* `--port=<port>`: Selects the local inspector port where the probing session
-  will listen. Defaults to `0`, which requests a random port.
+* `--port=<port>`: When the probe mode launches the probed process, it specifies the port
+  the launched child process' inspector listens on and defaults to `0`, which requests a
+  random port. When the probe mode attaches to a running process, this specifies the port to connect to
+  and defaults to `9229`, while `0` is invalid.
+* `--host <host>`: In attach mode, the host to connect to. Defaults to
+  `127.0.0.1`. It is an error to combine it with an entry point script.
+* `--pid <pid>`: Attach to a running Node.js process by PID instead of
+  launching a child. This activates the inspector of the target process if it
+  is not active yet, then connects to `--host`:`--port`. See
+  [Attaching to a running process](#attaching-to-a-running-process).
 * `--` is optional unless the child needs its own Node.js flags.

 Additional rules about the composition of the options:
@@ -339,6 +369,65 @@ $ node inspect --probe app.js:10 --expr "user"
                --json --preview -- --no-warnings app.js --arg-for-app=foo
 ```

+### Attaching to a running process
+
+When the entry point script is not specified and `--probe` is used, probe mode can attach
+to a process that is already running instead of launching a child process.
+This is useful for probing a long-running application, when users want to inspect runtime
+values without restarting it.
+
+When `--pid` is specified, probe mode activates the inspector of the process by
+sending `SIGUSR1` on POSIX platforms. The process must be a Node.js process,
+otherwise it may be terminated by `SIGUSR1`. The probing process will retry
+connecting using `--host` and `--port` until the timeout fires.
+If `--pid` is not specified, the inspector in the target process must already be listening.
+If the connection is refused, an error is reported immediately.
+
+```console
+# Probing a process by PID, which may not already have the inspector listening.
+# End the probing session when the specified probe is reached 5 times.
+$ node inspect --probe app.js:42 --expr "req.url" --max-hit 5 --pid 12345
+
+# Probing a process that's already listening for inspector connections at 127.0.0.1:9229.
+# End the probing session when the specified timeout is reached.
+$ node inspect --probe app.js:42 --expr "req.url" --timeout 50000 --host 127.0.0.1 --port 9229
+```
+
+Probing by attaching to a process differs from launching one in several ways.
+
+* The scripts are already loaded in the process when the breakpoints are bound,
+  and the `locations` field for each probe in the report shows where it bound.
+  An empty list indicates that no loaded script matched the probe, e.g.
+  when there's a typo in the path or the line.
+* When the probing session ends, it resumes and detaches from the probed process.
+  The target should continue running and **its inspector will remain activated**.
+  Probe mode does not kill a process it did not launch.
+* If the target is waiting for `--inspect-brk` or `--inspect-wait` when the
+  session attaches to it, these would be released so that the probes can run.
+* An attach session ends when one of the following happens:
+  * A probe reaches `--max-hit`. The report ends with `completed`.
+  * The target finishes on its own. The report ends with `completed`, or
+    with `miss` when some probes are never hit. The target is then allowed to
+    exit.
+  * The target exits with an uncaught exception. The report ends with `probe_target_exit`
+    and an `error` that describes the exception. The probing process exits with code 0.
+  * `--timeout` fires. The report ends with `timeout` and the hits recorded
+    so far, and the probing process exits with code 0. If a probe expression
+    is still running at that point, the session reports an `error` and exits
+    with code 1 instead. The expression is terminated after at most another
+    `--timeout`, unless it is blocked inside a native call, and the target
+    then resumes.
+  * The target does not respond during startup within `--timeout`, for
+    example because its main thread is blocked for synchronous work. The
+    report then ends with an `error`, and the probing process exits with code 1.
+* If the target is killed during the session, the session ends with an
+  `error`. If it's attached via `--pid`, this is reported as
+  `probe_target_exit` with exit code 0. If it's attached via `--host` and `--port`,
+  an exit cannot be distinguished from a network failure, so it is reported as
+  `probe_failure` with a non-zero exit code.
+* The target's stdout and stderr are not captured, so the terminal `error`
+  events have no `error.stderr` field.
+
 ### Probe output format

 When the probe session ends, the probing process prints a final report of all the probe hits and results.
@@ -380,12 +469,19 @@ When `--json` is used, the output shape looks like this:

 ```console
 $ node inspect --json --probe cli.js:5 --expr 'rss' cli.js
-{"v":2,"probes":[{"expr":"rss","target":{"suffix":"cli.js","line":5}}],"results":[{"probe":0,"event":"hit","hit":1,"location":{"url":"file:///path/to/cli.js","line":5,"column":3},"result":{"type":"number","value":55443456,"description":"55443456"}},{"probe":0,"event":"hit","hit":2,"location":{"url":"file:///path/to/cli.js","line":5,"column":3},"result":{"type":"number","value":55574528,"description":"55574528"}},{"event":"completed"}]}
+{"v":2,"target":{"argv":["cli.js"]},"probes":[{"expr":"rss","target":{"suffix":"cli.js","line":5},"locations":[{"url":"file:///path/to/cli.js","line":5,"column":3}]}],"results":[{"probe":0,"event":"hit","hit":1,"location":{"url":"file:///path/to/cli.js","line":5,"column":3},"result":{"type":"number","value":55443456,"description":"55443456"}},{"probe":0,"event":"hit","hit":2,"location":{"url":"file:///path/to/cli.js","line":5,"column":3},"result":{"type":"number","value":55574528,"description":"55574528"}},{"event":"completed"}]}
 ```

 ```json
 {
   "v": 2, // Probe JSON schema version.
+  "target": {
+    // Describes what was probed. The shape depends on how the session was started:
+    //   launch mode: { "argv": ["cli.js"] }
+    //   --pid <pid>: { "pid": 12345, "host": "127.0.0.1", "port": 9229 }
+    //   --host/--port: { "host": "127.0.0.1", "port": 9229 }
+    "argv": ["cli.js"]
+  },
   "probes": [
     {
       "expr": "rss", // The expression paired with --probe.
@@ -397,7 +493,13 @@ $ node inspect --json --probe cli.js:5 --expr 'rss' cli.js
         // from the target and will be reported in each hit's `location` field.
         "suffix": "cli.js",
         "line": 5
-      }
+      },
+      // Locations where the probe's breakpoint is bound. The shape is the same as the `location`
+      // of a hit. There is one entry per matching script, and it's empty when no loaded script
+      // matches the target, or when the session ends before the probe is bound.
+      "locations": [
+        { "url": "file:///path/to/cli.js", "line": 5, "column": 3 }
+      ]
       // `condition` is present only when the probe was given a --cond expression.
       // `maxHit` is present only when the probe was given a --max-hit limit.
     }
@@ -477,18 +579,23 @@ $ node inspect --json --probe cli.js:5 --expr 'rss' cli.js

 ### Output and exit codes

-Probe mode only prints the final probe report to stdout, and otherwise silences
-stdout/stderr from the child process. When the probing session ends,
+Probe mode only prints the final probe report to stdout. If the probed process is launched by
+probe mode, the stdout/stderr of the child process is silenced. When the probing session ends,
 the probing process typically exits with code `0` and prints a final report to
 stdout. If the child process exits with a non-zero code before the probe
 session ends, or the probe session cannot complete for another reason, the
 final report records a terminal `error` event.

-When `error.code` is `'probe_failure'` or `'probe_timeout'`, the probing process
-exits with a non-zero code, indicating recorded hits may be incomplete.
-In this case, `error.message` will contain recovery hints, and `error.probe`,
-when present, is an index into the report's `probes` array that identifies
-the possible culprit probe on a best-effort basis to help guide debugging.
+When `error.code` is `'probe_failure'`, the probing process exits with a
+non-zero code, indicating recorded hits may be incomplete. In this case,
+`error.message` will contain recovery hints, and `error.probe`, when present,
+is an index into the report's `probes` array that identifies the possible
+culprit probe on a best-effort basis to help guide debugging.
+
+When `error.code` is `'probe_timeout'`, the probing process exits with a
+non-zero code if it launched the process, and with `0` if it attached to a
+running process, where the timeout is considered a normal end of the session. See
+[Attaching to a running process](#attaching-to-a-running-process).

 Invalid arguments and fatal launch or connect failures may cause the
 probing process to exit with a non-zero code and print an error message
diff --git a/lib/internal/debugger/inspect.js b/lib/internal/debugger/inspect.js
index c42fd78085f..227f9e5390e 100644
--- a/lib/internal/debugger/inspect.js
+++ b/lib/internal/debugger/inspect.js
@@ -271,10 +271,12 @@ const kInspectArgOptions = {
   'cond': { type: 'string' },
   'expr': { type: 'string' },
   'help': { type: 'boolean', short: 'h' },
+  'host': { type: 'string' },
   'json': { type: 'boolean' },
-  // Port, timeout, and max-hit use type 'string' because parseArgs has no
-  // numeric type; the values are parsed to integers by parseProbeTokens().
+  // Port, timeout, max-hit, and pid use type 'string' because parseArgs has
+  // no numeric type; the values are parsed to integers by parseProbeTokens().
   'max-hit': { type: 'string' },
+  'pid': { type: 'string' },
   'port': { type: 'string' },
   'preview': { type: 'boolean' },
   'probe': { type: 'string' },
@@ -310,6 +312,10 @@ function parseInspectMode(args) {
         }
         return { mode: 'probe', tokens, args };
       }
+      // These are only accepted in probe mode.
+      if (token.name === 'host' || token.name === 'pid') {
+        return { mode: 'probe', tokens, args };
+      }
     }
     if (token.kind === 'option-terminator' || token.kind === 'positional') {
       break;
diff --git a/lib/internal/debugger/inspect_client.js b/lib/internal/debugger/inspect_client.js
index 1e5794ecc3a..e305f95b55d 100644
--- a/lib/internal/debugger/inspect_client.js
+++ b/lib/internal/debugger/inspect_client.js
@@ -348,6 +348,9 @@ class Client extends EventEmitter {

       this._socket = socket;
       socket.on('data', this.handleChunk);
+      // A target that is terminated can reset the connection. Ignore the error and
+      // let the 'close' event handle it.
+      socket.on('error', (error) => debuglog('socket error %o', error));
       socket.on('close', () => {
         this.emit('close');
       });
diff --git a/lib/internal/debugger/inspect_helpers.js b/lib/internal/debugger/inspect_helpers.js
index f77a4c8d189..351e48e7e5f 100644
--- a/lib/internal/debugger/inspect_helpers.js
+++ b/lib/internal/debugger/inspect_helpers.js
@@ -261,10 +261,10 @@ function writeInspectUsageAndExit(invokedAs, message, exitCode) {
   }
   out.write(`Usage: ${invokedAs} [--port=<port>] [<node-option> ...]
                       [<script> [<script-args>] | <host>:<port> | -p <pid>]
-       ${invokedAs} --probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>]
-                      [--probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>] ...]
-                      [--json] [--preview] [--timeout=<ms>] [--port=<port>]
-                      [--] [<node-option> ...] <script> [<script-args> ...]
+       ${invokedAs} --probe <file>:<line>[:<col>] --expr <expr>
+                      [<probe-option> ...]
+                      [<script> [<script-args> ...]
+                        | --pid <pid> | --host <host> | --port <port>]

 Interactive mode: Starts a live debugging session.

@@ -284,11 +284,35 @@ Semantics:
 Non-interactive probe mode: Evaluates expressions whenever execution reaches
 specified source locations and prints all the evaluation results to stdout.

-Example:
+Usage:
+  # Launch a script and probe it:
+  $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>]
+                 [--probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>] ...]
+                 [--json] [--preview] [--timeout=<ms>] [--port=<port>]
+                 [--] [<node-option> ...] <script> [<script-args> ...]
+
+  # Activate the inspector in a running process and probe it:
+  $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --pid <pid> [--host <host>] [--port <port>]
+
+  # Probe a running process whose inspector is already listening:
+  $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --host <host> [--port <port>]
+  $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --port <port> [--host <host>]
+
+Examples:
+  # Launch app.js with --no-warnings. Print "user" whenever line 10 runs, and
+  # "config.options" whenever column 15 of line 5 in src/utils.js runs:
   $ node inspect --probe app.js:10 --expr "user"
                  --probe src/utils.js:5:15 --expr "config.options"
                  --json --preview -- --no-warnings app.js --arg-for-app=foo

+  # Attach to the Node.js process with PID 12345, activating its inspector if
+  # needed, and detach once line 42 of app.js has run 5 times:
+  $ node inspect --probe app.js:42 --expr "req.url" --max-hit 5 --pid 12345
+
+  # Attach to the process whose inspector listens at 127.0.0.1:9229, and
+  # detach after 50 seconds:
+  $ node inspect --probe app.js:42 --expr "req.url" --timeout 50000 --host 127.0.0.1 --port 9229
+
 Options:
   --probe <file>:<line>[:<col>]
                     Source location of the probe. <file> is matched as a
@@ -305,13 +329,20 @@ Options:
                     records a hit when <expr> is truthy at the location. A
                     condition that throws is treated as false.
   --max-hit <n>     Per-probe limit on evaluated hits. When not specified,
-                    there's no hit limit. When any probe reaches its hit LIMIT,
-                    the probing process will detach and report the results.
-                    The probed process will continue to run.
+                    there's no hit limit. When any probe reaches its hit limit,
+                    the session finishes and reports the results. If the
+                    process is launched by the probe mode, it is then
+                    terminated, otherwise it is resumed and left to run.
   --json            Output JSON if specified, otherwise human-readable text.
   --preview         Include V8 object previews in JSON output.
-  --timeout <ms>    Global session timeout (default: 30000).
-  --port <port>     Inspector port for the debuggee (default: 0 = random).
+  --timeout <ms>    Deadline in milliseconds (default: 30000), applied first to
+                    startup and probe binding, then to the probing session.
+  --port <port>     Inspector port of the probed process. Defaults to 0 (random)
+                    when launching a script, and to 9229 when attaching to a
+                    running process.
+  --host <host>     Inspector host of the process to attach to (default: 127.0.0.1).
+  --pid <pid>       PID of the Node.js process to attach to. Its inspector is
+                    activated with SIGUSR1 if needed.

 Semantics:
 * Multiple --probe/--expr pairs are allowed. Same-location --probes share
@@ -322,6 +353,10 @@ Semantics:
 * --probe utils.js:<line>[:<col>] matches every loaded utils.js. Pass a
   fuller path e.g. src/utils.js to narrow the match.
 * Use -- before any Node.js flags intended for the child process.
+* When an entry point script is given, the probed process is launched.
+  Otherwise, --pid and/or --host:--port specifies the target to attach to.
+  The probing session ends when --max-hit or --timeout is reached, or
+  when the target process finishes.
 * Target errors are surfaced in the report as a terminal 'error' event.
   The probing process exits 0 unless it encounters an error itself.

diff --git a/lib/internal/debugger/inspect_probe.js b/lib/internal/debugger/inspect_probe.js
index 3b77a46f1ba..b233048513e 100644
--- a/lib/internal/debugger/inspect_probe.js
+++ b/lib/internal/debugger/inspect_probe.js
@@ -8,8 +8,10 @@ const {
   ArrayPrototypePush,
   ArrayPrototypeSlice,
   ArrayPrototypeSome,
+  DateNow,
   FunctionPrototypeBind,
   JSONStringify,
+  MathMax,
   NumberIsNaN,
   NumberParseInt,
   ObjectEntries,
@@ -26,6 +28,7 @@ const {
 } = primordials;

 const { clearTimeout, setTimeout } = require('timers');
+const { setTimeout: _setTimeout } = require('timers/promises');
 const { SideEffectFreeRegExpPrototypeSymbolReplace } = require('internal/util');
 const debug = require('internal/util/debuglog').debuglog('inspect_probe');

@@ -45,6 +48,8 @@ const {
 } = internalBinding('errors');

 const kProbeDefaultTimeout = 30000;
+const kProbeConnectRetryDelay = 250;
+const kProbeReapPollInterval = 50;
 const kProbeVersion = 2;
 const kProbeDisconnectSentinel = 'Waiting for the debugger to disconnect...';
 const kProbeAttachedSentinel = 'Debugger attached.';
@@ -59,6 +64,11 @@ const kStartupTeardownAdvice =
   'The target startup may have torn down the inspector. If startup does ' +
   'not touch the inspector, this is likely a Node.js bug. Please file an issue.';
 const kReviewProbeExprAdvice = 'If the failure repeats, review the probe expression.';
+const kTargetExitedDuringEvaluation = {
+  __proto__: null,
+  reason: 'Target process exited during probe evaluation',
+  advice: kReviewProbeExprAdvice,
+};
 const kDigitsRegex = /^\d+$/;
 const kInspectPortRegex = /^--inspect-port=(\d+)$/;

@@ -82,6 +92,7 @@ const kInspectPortRegex = /^--inspect-port=(\d+)$/;
  * Per-breakpoint state keyed by V8 `breakpointId` from `Debugger.setBreakpointByUrl`.
  * @typedef {object} BreakpointDefinition
  * @property {number[]} probeIndices Indices into probes that bound to this breakpoint.
+ * @property {Location[]} locations Where the breakpoint is resolved so far.
  */

 /**
@@ -93,6 +104,7 @@ const kInspectPortRegex = /^--inspect-port=(\d+)$/;
  *   Scoped to the location, so probes sharing a location all carry the same value.
  * @property {number} maxHit Per-probe hit limit from --max-hit. Infinity when unlimited.
  * @property {number} hits Count of hits observed.
+ * @property {Location[]} [locations] Shared with the BreakpointDefinition once it's bound.
  */

 function probeReachedLimit(probe) {
@@ -262,6 +274,15 @@ function formatHitLocation(location) {
   return `${location.url}:${location.line}:${location.column}`;
 }

+function indentAndPush(lines, header, text) {
+  ArrayPrototypePush(lines, `  ${header}`);
+  const split = RegExpPrototypeSymbolSplit(/\r\n|\r|\n/g, text);
+  for (let i = 0; i < split.length; i++) {
+    if (split[i] === '' && i === split.length - 1) { continue; }
+    ArrayPrototypePush(lines, `  ${split[i]}`);
+  }
+}
+
 // Built human-readable text output for probe reports.
 function buildProbeTextReport(report) {
   const lines = [];
@@ -304,17 +325,11 @@ function buildProbeTextReport(report) {
     if (result.event === 'error') {
       ArrayPrototypePush(lines, result.error.message);
       if (result.error.stderr !== undefined) {
-        ArrayPrototypePush(lines, '  [stderr]');
-        const stderrLines = RegExpPrototypeSymbolSplit(
-          /\r\n|\r|\n/g,
-          result.error.stderr,
-        );
-        for (let i = 0; i < stderrLines.length; i++) {
-          if (stderrLines[i] === '' && i === stderrLines.length - 1) {
-            continue;
-          }
-          ArrayPrototypePush(lines, `  ${stderrLines[i]}`);
-        }
+        indentAndPush(lines, '[stderr]', result.error.stderr);
+      }
+      const exception = result.error.details?.exception;
+      if (exception !== undefined) {
+        indentAndPush(lines, '[exception]', exception.exception?.description ?? exception.text);
       }
     }
   }
@@ -323,7 +338,9 @@ function buildProbeTextReport(report) {
 }

 function parseProbeTokens(tokens, args) {
-  let port = 0;
+  let port;
+  let host;
+  let pid;
   let preview = false;
   let timeout = kProbeDefaultTimeout;
   let json = false;
@@ -378,6 +395,21 @@ function parseProbeTokens(tokens, args) {
         }
         port = parseUnsignedInteger(token.value, 'inspector port', true);
         break;
+      case 'pid':
+        if (token.value === undefined) {
+          throw new ERR_DEBUGGER_STARTUP_ERROR(`Missing value for ${token.rawName}`);
+        }
+        pid = parseUnsignedInteger(token.value, 'pid');
+        if (pid > 0x7fffffff) {
+          throw new ERR_DEBUGGER_STARTUP_ERROR(`Invalid pid: ${token.value}`);
+        }
+        break;
+      case 'host':
+        if (token.value === undefined || token.value === '') {
+          throw new ERR_DEBUGGER_STARTUP_ERROR(`Missing value for ${token.rawName}`);
+        }
+        host = token.value;
+        break;
       case 'preview':
         preview = true;
         break;
@@ -455,14 +487,31 @@ function parseProbeTokens(tokens, args) {
   }

   const childArgv = ArrayPrototypeSlice(args, childStartIndex);
+
+  // If the script is not specified, --pid, --host or --port indicates we should attach.
+  if (childArgv.length === 0 && (pid !== undefined || port !== undefined || host !== undefined)) {
+    host ??= '127.0.0.1';
+    port ??= 9229;
+    if (port === 0) {
+      throw new ERR_DEBUGGER_STARTUP_ERROR('Cannot attach to port 0');
+    }
+    return { host, port, preview, timeout, json, probes, childArgv, attach: true, pid };
+  }
+
   if (childArgv.length === 0) {
-    throw new ERR_DEBUGGER_STARTUP_ERROR('Probe mode requires a child script');
+    throw new ERR_DEBUGGER_STARTUP_ERROR(
+      'Probe mode requires an entry point script, or --pid, --port or --host to attach to a running process');
+  }
+
+  if (pid !== undefined || host !== undefined) {
+    throw new ERR_DEBUGGER_STARTUP_ERROR('--pid and --host cannot be used together with an entry point script');
   }

   if (!sawSeparator && StringPrototypeStartsWith(childArgv[0], '-')) {
     throw new ERR_DEBUGGER_STARTUP_ERROR('Use -- before child Node.js flags in probe mode');
   }

+  port ??= 0;
   let skipPortPreflight = port === 0;
   for (const arg of childArgv) {
     const inspectPortMatch = RegExpPrototypeExec(kInspectPortRegex, arg);
@@ -486,13 +535,25 @@ function parseProbeTokens(tokens, args) {
     probes,
     childArgv,
     skipPortPreflight,
+    attach: false,
   };
 }

+function processExists(pid) {
+  try {
+    process.kill(pid, 0);
+    return true;
+  } catch (e) {
+    // EPERM means the process exists but belongs to another user.
+    return e.code !== 'ESRCH';
+  }
+}
+
 class ProbeInspectorSession {
   constructor(options) {
     this.options = options;
     this.client = new InspectClient();
+    // Null in attach mode.
     this.child = null;
     this.cleanupStarted = false;
     this.childStderr = '';
@@ -501,6 +562,13 @@ class ProbeInspectorSession {
     // True once the inspector WebSocket connects. Event handlers ignore
     // pre-connect exits/closes so launch/connect failures report through run().
     this.connected = false;
+    // When the target process is attached to, a Debugger.paused event can arrive before all
+    // breakpoints are bound. Save the pause to handle later, only the first one needs to be stored
+    // since a paused target cannot pause again until resumed.
+    this.pendingPause = null;
+    // When the target process is only attached to and terminates due to an uncaught exception,
+    // this captures the details for the report.
+    this.uncaughtException = null;
     // True once breakpoints are bound and the target is released from --inspect-brk
     // via `Runtime.runIfWaitingForDebugger`.
     // Distinguishes "exited before user code ran" from "exited during the live session".
@@ -513,6 +581,8 @@ class ProbeInspectorSession {
     this.scriptIdToUrl = new SafeMap();
     this.results = [];
     this.timeout = null;
+    // When the current phase (startup, then the probe session) times out.
+    this.timeoutEnd = 0;
     // The currently-awaited CDP request, or null when no request is in flight.
     /** @type {{ method: string, probe: { index: number, location: Location } | null } | null} */
     this.inFlight = null;
@@ -527,9 +597,11 @@ class ProbeInspectorSession {
                                       ({ expr, target, condition, maxHit: maxHit ?? Infinity, hits: 0 }));
     this.onChildOutput = FunctionPrototypeBind(this.onChildOutput, this);
     this.onChildExit = FunctionPrototypeBind(this.onChildExit, this);
+    this.onExceptionThrown = FunctionPrototypeBind(this.onExceptionThrown, this);
     this.onClientClose = FunctionPrototypeBind(this.onClientClose, this);
     this.onPaused = FunctionPrototypeBind(this.onPaused, this);
     this.onScriptParsed = FunctionPrototypeBind(this.onScriptParsed, this);
+    this.onWaitingForDisconnect = FunctionPrototypeBind(this.onWaitingForDisconnect, this);
   }

   // Marking the probing process to exit with 0, recorded hits are trustworthy.
@@ -551,21 +623,36 @@ class ProbeInspectorSession {
       this.timeout = null;
     }
     this.resolveCompletion({ exitCode, terminal });
+    // Reject requests that are still waiting for a reply, which a closed socket never responds to.
+    // If the process is only attached to, this also releases the target, since V8 removes our
+    // breakpoints and resumes it if paused.
+    this.client.reset();
   }

+  // Both exitCode and signal are null for an attached target, because its exit status is unknown.
   getProbeTargetExitEvent(exitCode, signal) {
     const pending = this.getPendingProbeIndices();
-    const how = signal !== null ? `with signal ${signal}` : `with code ${exitCode}`;
+    let how = '';
+    if (signal !== null) {
+      how = ` with signal ${signal}`;
+    } else if (exitCode !== null) {
+      how = ` with code ${exitCode}`;
+    } else if (this.uncaughtException !== null) {
+      how = ' with an uncaught exception';
+    }
     const status = pending.length === 0 ?
       'target completion' : `probes: ${formatPendingProbeLocations(this.probes, pending)}`;
     const error = {
       __proto__: null,
       code: 'probe_target_exit',
-      message: `Target exited ${how} before ${status}`,
+      message: `Target exited${how} before ${status}`,
     };
     if (exitCode !== null) { error.exitCode = exitCode; }
     if (signal !== null) { error.signal = signal; }
-    error.stderr = trimProbeChildStderr(this.childStderr);
+    if (!this.options.attach) { error.stderr = trimProbeChildStderr(this.childStderr); }
+    if (this.uncaughtException !== null) {
+      error.details = { __proto__: null, exception: trimRemoteObject(this.uncaughtException) };
+    }
     return { event: 'error', pending, error };
   }

@@ -600,10 +687,7 @@ class ProbeInspectorSession {
     if (!this.connected) { return; }
     if (this.finished) { return; }
     if (this.inFlight !== null && this.inFlight.probe !== null) {
-      this.recordInspectorFailure({
-        reason: 'Target process exited during probe evaluation',
-        advice: kReviewProbeExprAdvice,
-      });
+      this.recordInspectorFailure(kTargetExitedDuringEvaluation);
       return;
     }
     if (this.started && code === 0 && signal === null) {
@@ -621,18 +705,48 @@ class ProbeInspectorSession {
     if (this.disconnectRequested) { return; }
     if (this.finished) { return; }

-    if (this.child.exitCode !== null || this.child.signalCode !== null) {
+    if (this.child !== null && (this.child.exitCode !== null || this.child.signalCode !== null)) {
       this.onChildExit(this.child.exitCode, this.child.signalCode);
       return;
     }
-    if (!this.started) {
+    this.reportLostConnection();
+  }
+
+  async reportLostConnection() {
+    const { pid } = this.options;
+    if (pid !== undefined) {
+      // When --pid is used, report a lost connection as a target exit. The socket closes as
+      // soon as the target is terminated, but the process stays visible until it is reaped
+      // so keep checking until the timeout before concluding that it is still running.
+      while (!this.finished && DateNow() < this.timeoutEnd && processExists(pid)) {
+        await _setTimeout(kProbeReapPollInterval);
+      }
+      if (this.finished) { return; }
+      if (!processExists(pid)) {
+        if (this.inFlight !== null && this.inFlight.probe !== null) {
+          this.recordInspectorFailure(kTargetExitedDuringEvaluation);
+        } else {
+          this.finishWithTrustedResult(this.getProbeTargetExitEvent(null, null));
+        }
+        return;
+      }
+      this.recordInspectorFailure({
+        reason: `Inspector connection lost while target process ${pid} is still running`,
+        advice: 'The target may have closed its inspector. If the failure persists, check the target.',
+      });
+      return;
+    }
+    // The launched process should only drop the connection when its inspector is torn down, in this case
+    // the failure would be attributed to the startup or to the activity that was in flight.
+    // An attached target could also have been killed, which we cannot distinguish.
+    if (!this.options.attach && !this.started) {
       this.recordInspectorFailure({
         reason: 'Inspector connection lost before probes started',
         advice: kStartupTeardownAdvice,
       });
       return;
     }
-    if (this.inFlight !== null) {
+    if (!this.options.attach && this.inFlight !== null) {
       if (this.inFlight.probe !== null || this.lastProbeIndex !== null) {
         this.recordInspectorFailure({
           reason: 'Inspector connection lost during probe activity',
@@ -654,6 +768,29 @@ class ProbeInspectorSession {
     });
   }

+  onExceptionThrown({ exceptionDetails }) {
+    debug('uncaught exception thrown in target: %s', exceptionDetails?.text);
+    this.uncaughtException = exceptionDetails;
+  }
+
+  // Only emitted for an attached target, when it finishes on its own.
+  // TODO(joyeecheung): handle process.exit(1) from the target and targets that finish
+  // before the breakpoints are bound.
+  onWaitingForDisconnect() {
+    if (this.finished) { return; }
+    if (this.inFlight !== null && this.inFlight.probe !== null) {
+      this.recordInspectorFailure(kTargetExitedDuringEvaluation);
+      return;
+    }
+    if (this.uncaughtException !== null) {
+      this.finishWithTrustedResult(this.getProbeTargetExitEvent(null, null));
+      return;
+    }
+    debug('target is waiting for the debugger to disconnect');
+    const pending = this.getPendingProbeIndices();
+    this.finishWithTrustedResult(pending.length === 0 ? { event: 'completed' } : { event: 'miss', pending });
+  }
+
   onPaused(params) {
     debug('paused: finished=%d, reason=%s hitBreakpoints=%j', this.finished, params.reason, params.hitBreakpoints);
     this.handlePaused(params).catch((error) => {
@@ -671,7 +808,11 @@ class ProbeInspectorSession {
     // Ignore pauses that arrive before breakpoint setup is complete. Once
     // startup is marked complete, `Runtime.runIfWaitingForDebugger` may surface
     // the initial --inspect-brk pause, which the normal resume path handles.
-    if (!this.started) { return; }
+    if (!this.started) {
+      // An attached process is running, so queue its pauses in case there are more breakpoints to be bound.
+      if (this.options.attach) { this.pendingPause = params; }
+      return;
+    }

     const hitBreakpoints = params.hitBreakpoints;
     if (hitBreakpoints === undefined || hitBreakpoints.length === 0) {
@@ -686,15 +827,7 @@ class ProbeInspectorSession {
       return;
     }

-    const { scriptId, lineNumber, columnNumber } = topFrame.location;
-    // `Debugger.scriptParsed` should always precede a pause for the same script.
-    // It should only be undefined if there's a bug (even in that case, just omit it).
-    const location = {
-      url: this.scriptIdToUrl.get(scriptId),
-      // CDP locations are 0-based, locations in public report are 1-based.
-      line: lineNumber + 1,
-      column: columnNumber + 1,
-    };
+    const location = this.toReportLocation(topFrame.location);
     for (const breakpointId of hitBreakpoints) {
       // The breakpoint ID is stable even for scripts parsed after the initial resolution
       // so we can count on it here.
@@ -710,8 +843,6 @@ class ProbeInspectorSession {

     // Finish proactively as soon as any probe reaches its hit limit. All probes
     // hit in this pause are recorded first, then the session ends.
-    // TODO(joyeecheung): When we implement attach mode, this teardown must
-    // resume-and-detach rather than kill, since the target is not ours.
     if (!this.finished && ArrayPrototypeSome(this.probes, probeReachedLimit)) {
       this.finishWithTrustedResult({ event: 'completed' });
       return;
@@ -723,9 +854,15 @@ class ProbeInspectorSession {
   async evaluateProbe(callFrameId, probeIndex, location) {
     if (this.finished) { return; }
     const probe = this.probes[probeIndex];
+    const params = { callFrameId, expression: probe.expr, generatePreview: true };
+    if (this.options.attach) {
+      // Apply the timeout because an attached process would keep running the expression
+      // even if the probing session has finished.
+      params.timeout = this.options.timeout;
+    }
     const evaluation = await this.callCdp(
       'Debugger.evaluateOnCallFrame',
-      { callFrameId, expression: probe.expr, generatePreview: true },
+      params,
       { __proto__: null, index: probeIndex, location },
     );
     this.lastProbeIndex = probeIndex;
@@ -772,10 +909,7 @@ class ProbeInspectorSession {
         // Only the in-flight evaluation gets attribution. Other rejections
         // under disconnect are downstream noise.
         if (probe !== null) {
-          this.recordInspectorFailure({
-            reason: 'Target process exited during probe evaluation',
-            advice: kReviewProbeExprAdvice,
-          });
+          this.recordInspectorFailure(kTargetExitedDuringEvaluation);
         }
         throw kInspectorFailedSentinel;
       }
@@ -868,7 +1002,7 @@ class ProbeInspectorSession {
       message: `${reason}${suffix}. ${advice}`,
     };
     if (attribution !== null) { error.probe = attribution; }
-    error.stderr = trimProbeChildStderr(this.childStderr);
+    if (!this.options.attach) { error.stderr = trimProbeChildStderr(this.childStderr); }

     let details;
     if (failedCdpMethod !== null) {
@@ -884,11 +1018,35 @@ class ProbeInspectorSession {
     this.finishWithUnreliableResult({ event: 'error', pending, error });
   }

+  restartTimeoutFromNow() {
+    this.timeoutEnd = DateNow() + this.options.timeout;
+  }
+
   startTimeout() {
+    this.restartTimeoutFromNow();
     this.timeout = setTimeout(() => {
       debug('timeout fired: finished=%s, inFlight=%j, lastProbeIndex=%s',
             this.finished, this.inFlight, this.lastProbeIndex);
       if (this.finished) { return; }
+      if (this.options.attach) {
+        // TODO(joyeecheung): if an evaluation is still running on timeout, give it a short period
+        // to finish, and check that V8 terminates it before reporting.
+        if (this.inFlight !== null && this.inFlight.probe !== null) {
+          this.recordInspectorFailure({
+            reason: 'Probe session timed out',
+            advice: 'The probe expression was still running when the timeout fired. The target resumes once it is ' +
+              'terminated, after at most another `--timeout`. If the failure persists, review the probe expressions.',
+          });
+          return;
+        }
+        // If the process is attached, timeout is considered a normal end of session, so it is not a failure.
+        const pending = this.getPendingProbeIndices();
+        const waiting = pending.length === 0 ? '' :
+          ` waiting for probes: ${formatPendingProbeLocations(this.probes, pending)}`;
+        const message = `Session timed out after ${this.options.timeout}ms${waiting}, detaching from the target`;
+        this.finishWithTrustedResult({ event: 'timeout', pending, error: { code: 'probe_timeout', message } });
+        return;
+      }
       if (this.inFlight !== null) {
         const hasProbeAttribution =
           this.inFlight.probe !== null || this.lastProbeIndex !== null;
@@ -915,10 +1073,16 @@ class ProbeInspectorSession {
   }

   attachListeners() {
-    this.child.on('exit', this.onChildExit);
+    if (this.child !== null) {
+      this.child.on('exit', this.onChildExit);
+    }
     this.client.on('close', this.onClientClose);
     this.client.on('Debugger.paused', this.onPaused);
     this.client.on('Debugger.scriptParsed', this.onScriptParsed);
+    if (this.options.attach) {
+      this.client.on('NodeRuntime.waitingForDisconnect', this.onWaitingForDisconnect);
+      this.client.on('Runtime.exceptionThrown', this.onExceptionThrown);
+    }
   }

   onScriptParsed(params) {
@@ -928,6 +1092,20 @@ class ProbeInspectorSession {
     // This map grows by the number of scripts parsed, which is limited, and is just a
     // small string -> string map. The lifetime is bounded by probe timeout etc. so cleanup is overkill.
     this.scriptIdToUrl.set(params.scriptId, params.url);
+    // Scripts parsed after bindBreakpoints() report the locations they resolve in resolvedBreakpoints.
+    // TODO(joyeecheung): we may be missing the location if scriptParsed arrives in the same batch as
+    // the setBreakpointByUrl response. Buffer unknown IDs instead.
+    for (const { breakpointId, location } of params.resolvedBreakpoints ?? []) {
+      const definition = this.breakpointDefinitions.get(breakpointId);
+      if (definition !== undefined) { ArrayPrototypePush(definition.locations, this.toReportLocation(location)); }
+    }
+  }
+
+  // `Debugger.scriptParsed` should always precede a pause for the same script.
+  // The URL should only be undefined if there's a bug (even in that case, just omit it).
+  toReportLocation({ scriptId, lineNumber, columnNumber }) {
+    // CDP locations are 0-based, locations in public report are 1-based.
+    return { url: this.scriptIdToUrl.get(scriptId), line: lineNumber + 1, column: columnNumber + 1 };
   }

   async bindBreakpoints() {
@@ -974,7 +1152,9 @@ class ProbeInspectorSession {
       const result = await this.callCdp('Debugger.setBreakpointByUrl', params);
       debug('breakpoint set: id=%s urlRegex=%s locations=%j',
             result.breakpointId, params.urlRegex, result.locations);
-      this.breakpointDefinitions.set(result.breakpointId, { probeIndices });
+      const locations = ArrayPrototypeMap(result.locations ?? [], (location) => this.toReportLocation(location));
+      for (const probeIndex of probeIndices) { this.probes[probeIndex].locations = locations; }
+      this.breakpointDefinitions.set(result.breakpointId, { probeIndices, locations });
     }
   }

@@ -995,11 +1175,15 @@ class ProbeInspectorSession {
       code: exitCode,
       report: {
         v: kProbeVersion,
-        probes: ArrayPrototypeMap(this.probes, ({ expr, target, maxHit, condition }) => {
+        target: this.options.attach ?
+          { pid: this.options.pid, host: this.options.host, port: this.options.port } :
+          { argv: this.options.childArgv },
+        probes: ArrayPrototypeMap(this.probes, ({ expr, target, maxHit, condition, locations }) => {
           const probe = { expr, target };
           if (condition !== undefined) { probe.condition = condition; }
           // Omit an unlimited maxHit, as Infinity would serialize to null in JSON.
           if (maxHit !== Infinity) { probe.maxHit = maxHit; }
+          probe.locations = locations ?? [];
           return probe;
         }),
         results,
@@ -1020,8 +1204,6 @@ class ProbeInspectorSession {

     if (this.child === null) { return; }

-    // TODO(joyeecheung): When we implement attach mode, this teardown must
-    // resume-and-detach rather than kill, since the target is not ours.
     if (this.child.exitCode === null && this.child.signalCode === null) {
       this.child.kill();
     }
@@ -1029,27 +1211,70 @@ class ProbeInspectorSession {

   async run() {
     try {
-      const { childArgv, host, port, skipPortPreflight } = this.options;
-      const { 0: child, 1: actualPort, 2: actualHost } =
-        await launchChildProcess(childArgv,
-                                 host,
-                                 port,
-                                 this.onChildOutput,
-                                 { skipPortPreflight });
-      this.child = child;
+      const { attach, pid } = this.options;
+      let { host, port } = this.options;
+      if (attach) {
+        // When attaching, the timeout also covers the time spent by the target process to activate the inspector.
+        this.restartTimeoutFromNow();
+        if (pid !== undefined) {
+          try {
+            process._debugProcess(pid);  // Activates the inspector e.g. with SIGUSR1 on POSIX.
+          } catch (e) {
+            if (e.code !== 'ESRCH') { throw e; }
+            throw new ERR_DEBUGGER_STARTUP_ERROR(`Target process ${pid} does not exist`);
+          }
+        }
+      } else {
+        const { childArgv, skipPortPreflight } = this.options;
+        const { 0: child, 1: actualPort, 2: actualHost } =
+          await launchChildProcess(childArgv, host, port, this.onChildOutput, { skipPortPreflight });
+        this.child = child;
+        host = actualHost;
+        port = actualPort;
+      }
       // On Debugger.enable, V8 emits Debugger.scriptParsed for all existing scripts.
       // Attach the listener early to make sure we don't miss any events.
       this.attachListeners();

-      await this.client.connect(actualPort, actualHost);
+      // A --pid target may still be starting its inspector. Retry until the timeout.
+      // TODO(joyeecheung): A port that accepts connections but never answers HTTP can stall here, because the startup
+      // timeout only fires after it is connected. Limiting it requires InspectClient to abort its pending requests.
+      for (;;) {
+        try {
+          await this.client.connect(port, host);
+          break;
+        } catch (error) {
+          if (!attach) { throw error; }
+          if (pid === undefined) {
+            throw new ERR_DEBUGGER_STARTUP_ERROR(`Could not attach to ${host}:${port}: ${error.message}`);
+          }
+          if (!processExists(pid)) {
+            throw new ERR_DEBUGGER_STARTUP_ERROR(`Target process ${pid} exited before it could be attached`);
+          }
+          if (DateNow() >= this.timeoutEnd) {
+            throw new ERR_DEBUGGER_STARTUP_ERROR(
+              `Could not attach to ${host}:${port} within ${this.options.timeout}ms: ${error.message}`);
+          }
+          await _setTimeout(kProbeConnectRetryDelay);
+        }
+      }
       this.connected = true;
+      if (!attach) {
+        // If launching a new child process, start the timeout after it is connected.
+        this.restartTimeoutFromNow();
+      }
+      // If the main thread of the target is blocked, it may never answer the requests below.
+      this.timeout = setTimeout(() => {
+        this.recordInspectorFailure({
+          reason: `Timed out after ${this.options.timeout}ms waiting for the target to respond`,
+          advice: 'Its main thread may be blocked in synchronous work. Try increasing `--timeout`.',
+        });
+      }, MathMax(this.timeoutEnd - DateNow(), 0));
+      this.timeout.unref();

       try {
         try {
-          await waitForDebugger(
-            this.client,
-            (method) => this.callCdp(method),
-          );
+          if (!attach) { await waitForDebugger(this.client, (method) => this.callCdp(method)); }
         } catch (err) {
           // A close event may have completed the structured report while the
           // readiness helper was rejecting its disconnect race.
@@ -1057,10 +1282,25 @@ class ProbeInspectorSession {
           throw err;
         }
         await this.callCdp('Runtime.enable');
+        // The port may be occupied, for example, by a second process with inspector listening on the default port.
+        if (pid !== undefined) {
+          const { result } = await this.callCdp('Runtime.evaluate', { expression: 'process.pid' });
+          if (result.value !== pid) {
+            throw new ERR_DEBUGGER_STARTUP_ERROR(`The inspector at ${host}:${port} belongs to process ${result.value}, ` +
+              `not to --pid ${pid}. Pass the port that the inspector of the target listens on with --port`);
+          }
+        }
         await this.callCdp('Debugger.enable');
+        if (attach) {
+          // Get a NodeRuntime.waitingForDisconnect event when the target finishes, so the session can
+          // end and let it exit.
+          await this.callCdp('NodeRuntime.notifyWhenWaitingForDisconnect', { enabled: true });
+        }
         await this.bindBreakpoints();
         this.started = true;
+        clearTimeout(this.timeout);
         this.startTimeout();
+        if (this.pendingPause !== null) { await this.handlePaused(this.pendingPause); }
         await this.callCdp('Runtime.runIfWaitingForDebugger');
       } catch (err) {
         if (err !== kInspectorFailedSentinel) { throw err; }
diff --git a/test/common/child_process.js b/test/common/child_process.js
index 59505e5824d..3e73fc937a7 100644
--- a/test/common/child_process.js
+++ b/test/common/child_process.js
@@ -160,6 +160,7 @@ function spawnSyncAndAssert(...args) {
 }

 module.exports = {
+  checkOutput,
   cleanupStaleProcess,
   logAfterTime,
   kExpiringChildRunTime,
diff --git a/test/common/debugger-probe.js b/test/common/debugger-probe.js
index b8302de3695..f10dcf05b50 100644
--- a/test/common/debugger-probe.js
+++ b/test/common/debugger-probe.js
@@ -1,7 +1,131 @@
 'use strict';

 const assert = require('assert');
-const { spawnSyncAndExit } = require('./child_process');
+const { spawn } = require('child_process');
+const { once } = require('events');
+const { checkOutput, spawnSyncAndExit } = require('./child_process');
+const fixtures = require('./fixtures');
+
+const kListeningRegex = /Debugger listening on ws:\/\/\[?(.+?)\]?:(\d+)\//;
+const kReadyRegex = /^PROBE_READY$/m;
+// Logged by the probe session when NODE_DEBUG=inspect_probe once the probes are bound.
+const kStartedLine = 'CDP <- Runtime.runIfWaitingForDebugger';
+
+function logProcessOutput(tag, { child, stdout, stderr }) {
+  console.error(`${tag} --- stderr ---`);
+  console.error(stderr);
+  console.error(`${tag} --- stdout ---`);
+  console.error(stdout);
+  console.error(`${tag} status = ${child.exitCode}, signal = ${child.signalCode}`);
+}
+
+// Starts test/fixtures/debugger/<name> with the Node.js with args and env.
+// Resolves once it prints `PROBE_READY`, the returned target will continue collecting
+// the output of the process, so that it can be printed when a probe session fails.
+function startTarget(name, { args = ['--inspect=127.0.0.1:0'], env } = {}) {
+  const child = spawn(process.execPath, [...args, fixtures.path('debugger', name)],
+                      { env: { ...process.env, ...env } });
+  // Only targets with the inspector activated would print the listening address at startup.
+  const expectListening = args.some((arg) => arg === '--inspect' || arg.startsWith('--inspect='));
+  // Prevent a failed assertion from leaving a long-running target alive.
+  process.on('exit', () => child.kill());
+  child.stdout.setEncoding('utf8');
+  child.stderr.setEncoding('utf8');
+  const target = {
+    child, stdout: '', stderr: '',
+    exited: once(child, 'exit').then(([code, signal]) => ({ code, signal })),
+  };
+  return new Promise((resolve, reject) => {
+    let ready = false;
+    function check() {
+      if (ready || !kReadyRegex.test(target.stdout)) { return; }
+      // PROBE_READY message may appear before the listening line on stderr.
+      // Keep waiting until the listening line is found on stderr.
+      const match = kListeningRegex.exec(target.stderr);
+      if (expectListening && match === null) { return; }
+      ready = true;
+      target.host = match?.[1];
+      target.port = match && Number(match[2]);
+      child.removeListener('exit', onExit);
+      resolve(target);
+    }
+
+    function onExit() {
+      logProcessOutput(`[target ${child.pid}]:`, target);
+      reject(new Error(`Target ${name} exited before it was ready`));
+    }
+    child.stdout.on('data', (chunk) => { target.stdout += chunk; check(); });
+    child.stderr.on('data', (chunk) => { target.stderr += chunk; check(); });
+    child.once('exit', onExit);
+  });
+}
+
+// Runs `node inspect --json <args>` and checks the passed expectations. On failure,
+// print the output of the probe process and of `target` (if given).
+// `onStarted` is called once the probes are bound.
+async function runProbe(args, { target, onStarted, status, report: expectedReport, stderr: stderrCheck }) {
+  const argv = ['inspect', '--json', ...args];
+  const child = spawn(process.execPath, argv, { env: { ...process.env, NODE_DEBUG: 'inspect_probe' } });
+  child.stdout.setEncoding('utf8');
+  child.stderr.setEncoding('utf8');
+  const probe = { child, stdout: '', stderr: '' };
+  child.stdout.on('data', (chunk) => { probe.stdout += chunk; });
+  child.stderr.on('data', (chunk) => {
+    probe.stderr += chunk;
+    if (onStarted !== undefined && probe.stderr.includes(kStartedLine)) {
+      onStarted(target);
+      onStarted = undefined;
+    }
+  });
+  // Unlike 'exit', 'close' is emitted after stdout and stderr are fully read.
+  const [code] = await once(child, 'close');
+
+  const failures = [];
+  if (code !== status) {
+    failures.push(`- probe process exited with status ${code}, expected ${status}`);
+  }
+  let report = null;
+  if (probe.stdout !== '') {
+    try {
+      report = JSON.parse(probe.stdout);
+    } catch {
+      failures.push('- stdout is not a JSON report');
+    }
+  }
+  if (expectedReport === null) {
+    if (report !== null) { failures.push('- expected no report'); }
+  } else if (report === null) {
+    failures.push('- no report was printed');
+  } else {
+    try {
+      assertProbeJson(report, expectedReport);
+    } catch (error) {
+      failures.push(`- report did not match:\n${error.message}`);
+    }
+  }
+  if (stderrCheck !== undefined) {
+    const { passed, reason } = checkOutput(probe.stderr, stderrCheck);
+    if (!passed) { failures.push(`- stderr ${reason}`); }
+  }
+  if (failures.length === 0) { return { report, stderr: probe.stderr }; }
+
+  logProcessOutput(`[probe ${child.pid}]:`, probe);
+  if (target !== undefined) { logProcessOutput(`[target ${target.child.pid}]:`, target); }
+  const error = new Error(failures.join('\n'));
+  error.command = `${process.execPath} ${argv.join(' ')}`;
+  throw error;
+}
+
+// Starts test/fixtures/debugger/<name>, runs `node inspect` against its --host and --port,
+// check the expectations, and kills the process afterwards.
+async function runAttachedProbe(name, probeArgs, { target: targetOptions, ...options } = {}) {
+  const target = await startTarget(name, targetOptions);
+  const result = await runProbe([...probeArgs, '--host', target.host, '--port', `${target.port}`],
+                                { ...options, target });
+  target.child.kill();
+  await target.exited;
+  return result;
+}

 // Work around a pre-existing inspector issue: if the debuggee exits too quickly
 // the inspector can crash while tearing down. For now normalize the crash
@@ -60,6 +184,8 @@ function normalizeProbeReport(value) {
   return value;
 }

+// If expected omits `target` or probe `locations`, assertProbeJson only checks for their presence
+// but not the exact values.
 function assertProbeJson(output, expected) {
   const normalized = typeof output === 'string' ? JSON.parse(output) : output;
   const lastResult = normalized.results?.[normalized.results.length - 1];
@@ -70,6 +196,20 @@ function assertProbeJson(output, expected) {
     normalized.results[normalized.results.length - 1] = expected.results.at(-1);
   }

+  if (!Object.hasOwn(expected, 'target')) {
+    assert.notStrictEqual(normalized.target, undefined);
+    delete normalized.target;
+  }
+  if (Array.isArray(normalized.probes) && Array.isArray(expected.probes)) {
+    for (let i = 0; i < normalized.probes.length; i++) {
+      if (expected.probes[i] !== undefined && !Object.hasOwn(expected.probes[i], 'locations')) {
+        assert.strictEqual(Array.isArray(normalized.probes[i].locations), true,
+                           `probes[${i}].locations must be an array`);
+        delete normalized.probes[i].locations;
+      }
+    }
+  }
+
   assert.deepStrictEqual(normalizeProbeReport(normalized), normalizeProbeReport(expected));
 }

@@ -101,4 +241,7 @@ module.exports = {
   assertProbeJson,
   assertProbeCliError,
   assertProbeText,
+  runAttachedProbe,
+  runProbe,
+  startTarget,
 };
diff --git a/test/fixtures/debugger/probe-attach-blocked.js b/test/fixtures/debugger/probe-attach-blocked.js
new file mode 100644
index 00000000000..ff44cc40836
--- /dev/null
+++ b/test/fixtures/debugger/probe-attach-blocked.js
@@ -0,0 +1,5 @@
+'use strict';
+// Blocked the main thread with a synchronous read until its stdin is closed, so it
+// cannot answer inspector requests.
+require('fs').writeSync(1, 'PROBE_READY\n');
+require('fs').readSync(0, Buffer.alloc(1));
diff --git a/test/fixtures/debugger/probe-attach-busy.js b/test/fixtures/debugger/probe-attach-busy.js
new file mode 100644
index 00000000000..a74ba1a8812
--- /dev/null
+++ b/test/fixtures/debugger/probe-attach-busy.js
@@ -0,0 +1,10 @@
+'use strict';
+// Runs tick() continuously, so a breakpoint in tick() pauses the target as soon as it is bound.
+let count = 0;
+function tick() {
+  count++;
+  setImmediate(tick);
+}
+
+tick();
+console.log('PROBE_READY');
diff --git a/test/fixtures/debugger/probe-attach-finishes.js b/test/fixtures/debugger/probe-attach-finishes.js
new file mode 100644
index 00000000000..49d998146d6
--- /dev/null
+++ b/test/fixtures/debugger/probe-attach-finishes.js
@@ -0,0 +1,11 @@
+'use strict';
+// Runs tick() once when its stdin is closed, or throw if PROBE_ATTACH_THROW is set.
+let count = 0;
+function tick() {
+  count++;
+  if (process.env.PROBE_ATTACH_THROW) throw new Error('boom');
+}
+
+process.stdin.on('end', tick);
+process.stdin.resume();
+console.log('PROBE_READY');
diff --git a/test/fixtures/debugger/probe-attach-loop.js b/test/fixtures/debugger/probe-attach-loop.js
new file mode 100644
index 00000000000..6859bcd19e1
--- /dev/null
+++ b/test/fixtures/debugger/probe-attach-loop.js
@@ -0,0 +1,10 @@
+'use strict';
+// Increments a counter on a timer so probes have a changing value
+// to read, and prints `PROBE_READY` once the timer is scheduled.
+let count = 0;
+function tick() {
+  count++;
+}
+
+setInterval(tick, 50);
+console.log('PROBE_READY');
diff --git a/test/parallel/test-debugger-probe-attach-invalid.js b/test/parallel/test-debugger-probe-attach-invalid.js
new file mode 100644
index 00000000000..36fa5b231bb
--- /dev/null
+++ b/test/parallel/test-debugger-probe-attach-invalid.js
@@ -0,0 +1,17 @@
+// Tests that probe mode rejects invalid --pid, --host and --port usage.
+'use strict';
+
+const common = require('../common');
+common.skipIfInspectorDisabled();
+
+const { assertProbeCliError } = require('../common/debugger-probe');
+
+const probe = ['--probe', 'app.js:1', '--expr', 'x'];
+
+assertProbeCliError([...probe, '--pid', '123', 'app.js'], /--pid and --host cannot be used together with an entry point script/);
+assertProbeCliError([...probe, '--host', '127.0.0.1', 'app.js'], /--pid and --host cannot be used together with an entry point script/);
+
+assertProbeCliError([...probe, '--port', '0'], /Cannot attach to port 0/);
+assertProbeCliError(probe,
+                    /Probe mode requires an entry point script, or --pid, --port or --host to attach to a running process/);
+assertProbeCliError([...probe, '--pid', 'abc'], /Invalid pid: abc/);
diff --git a/test/parallel/test-debugger-probe-attach-pause-early.js b/test/parallel/test-debugger-probe-attach-pause-early.js
new file mode 100644
index 00000000000..ee918117554
--- /dev/null
+++ b/test/parallel/test-debugger-probe-attach-pause-early.js
@@ -0,0 +1,28 @@
+// Tests that a target pausing at a breakpoint while the session is still binding the next one
+// still works. The pause should be handled once all the probes are bound.
+'use strict';
+
+const common = require('../common');
+common.skipIfInspectorDisabled();
+
+const fixtures = require('../common/fixtures');
+const { runAttachedProbe } = require('../common/debugger-probe');
+
+// Line 5 runs continuously, so the breakpoint pauses the target before line 10 is bound.
+runAttachedProbe('probe-attach-busy.js', [
+  '--probe', 'probe-attach-busy.js:5', '--expr', 'typeof count', '--max-hit', '1',
+  '--probe', 'probe-attach-busy.js:10', '--expr', '1',
+], {
+  status: 0,
+  report: {
+    v: 2,
+    probes: [
+      { expr: 'typeof count', target: { suffix: 'probe-attach-busy.js', line: 5 }, maxHit: 1 },
+      { expr: '1', target: { suffix: 'probe-attach-busy.js', line: 10 } },
+    ],
+    results: [{
+      probe: 0, event: 'hit', hit: 1, result: { type: 'string', value: 'number' },
+      location: { url: fixtures.fileURL('debugger', 'probe-attach-busy.js').href, line: 5, column: 3 },
+    }, { event: 'completed' }],
+  },
+}).then(common.mustCall());
diff --git a/test/parallel/test-debugger-probe-attach-refused.js b/test/parallel/test-debugger-probe-attach-refused.js
new file mode 100644
index 00000000000..d5da1330409
--- /dev/null
+++ b/test/parallel/test-debugger-probe-attach-refused.js
@@ -0,0 +1,39 @@
+// Tests attach failures result in an error instead of a report. Without --pid the target
+// should already be listening, so a failed connection should be an immediate error.
+// An inspector that belongs to another process should be rejected.
+'use strict';
+
+const common = require('../common');
+common.skipIfInspectorDisabled();
+
+const net = require('net');
+const { once } = require('events');
+const { runProbe, startTarget } = require('../common/debugger-probe');
+
+async function main() {
+  // Create a port that will refuse connections.
+  const server = net.createServer((socket) => socket.resetAndDestroy());
+  await once(server.listen(0, '127.0.0.1'), 'listening');
+  const { port } = server.address();
+
+  await runProbe(['--probe', 'app.js:1', '--expr', '1', '--port', `${port}`], {
+    status: 1,
+    report: null,
+    stderr: new RegExp(`Could not attach to 127\\.0\\.0\\.1:${port}: `),
+  });
+  server.close();
+
+  const other = await startTarget('probe-attach-loop.js');
+  const target = await startTarget('probe-attach-loop.js', { args: ['--inspect-port=0'] });
+  await runProbe(['--probe', 'app.js:1', '--expr', '1', '--pid', `${target.child.pid}`, '--port', `${other.port}`], {
+    target,
+    status: 1,
+    report: null,
+    stderr: new RegExp(`The inspector at 127\\.0\\.0\\.1:${other.port} belongs to process ${other.child.pid}, ` +
+      `not to --pid ${target.child.pid}\\.`),
+  });
+  other.child.kill();
+  target.child.kill();
+}
+
+main().then(common.mustCall());
diff --git a/test/parallel/test-debugger-probe-attach-startup-timeout.js b/test/parallel/test-debugger-probe-attach-startup-timeout.js
new file mode 100644
index 00000000000..0f490c9da96
--- /dev/null
+++ b/test/parallel/test-debugger-probe-attach-startup-timeout.js
@@ -0,0 +1,28 @@
+// Tests that --timeout limits the startup of an attach session when the main thread of
+// the target is blocked and does not answer Runtime.enable.
+'use strict';
+
+const common = require('../common');
+common.skipIfInspectorDisabled();
+
+const { runAttachedProbe } = require('../common/debugger-probe');
+
+runAttachedProbe('probe-attach-blocked.js', [
+  '--timeout', '1000', '--probe', 'probe-attach-blocked.js:5', '--expr', '1',
+], {
+  status: 1,
+  report: {
+    v: 2,
+    probes: [{ expr: '1', target: { suffix: 'probe-attach-blocked.js', line: 5 }, locations: [] }],
+    results: [{
+      event: 'error',
+      error: {
+        code: 'probe_failure',
+        message: 'Timed out after 1000ms waiting for the target to respond before probes: probe-attach-blocked.js:5. ' +
+          'Its main thread may be blocked in synchronous work. Try increasing `--timeout`.',
+        details: { lastCdpMethod: 'Runtime.enable' },
+      },
+      pending: [0],
+    }],
+  },
+}).then(common.mustCall());
diff --git a/test/parallel/test-debugger-probe-attach-target-completes.js b/test/parallel/test-debugger-probe-attach-target-completes.js
new file mode 100644
index 00000000000..2649ea44f45
--- /dev/null
+++ b/test/parallel/test-debugger-probe-attach-target-completes.js
@@ -0,0 +1,38 @@
+// Tests that an attach session exits normally when the target finishes on its own, instead of
+// waiting for --timeout. Probes that never are hit should be reported as missed.
+'use strict';
+
+const common = require('../common');
+common.skipIfInspectorDisabled();
+
+const assert = require('assert');
+const fixtures = require('../common/fixtures');
+const { runProbe, startTarget } = require('../common/debugger-probe');
+
+async function main() {
+  const target = await startTarget('probe-attach-finishes.js');
+  // Closing its stdin makes the target run line 5 once and exit. Line 11 only runs at startup.
+  await runProbe([
+    '--probe', 'probe-attach-finishes.js:5', '--expr', 'count',
+    '--probe', 'probe-attach-finishes.js:11', '--expr', '1',
+    '--host', target.host, '--port', `${target.port}`,
+  ], {
+    target,
+    onStarted: () => target.child.stdin.end(),
+    status: 0,
+    report: {
+      v: 2,
+      probes: [
+        { expr: 'count', target: { suffix: 'probe-attach-finishes.js', line: 5 } },
+        { expr: '1', target: { suffix: 'probe-attach-finishes.js', line: 11 } },
+      ],
+      results: [{
+        probe: 0, event: 'hit', hit: 1, result: { type: 'number', value: 0, description: '0' },
+        location: { url: fixtures.fileURL('debugger', 'probe-attach-finishes.js').href, line: 5, column: 3 },
+      }, { event: 'miss', pending: [1] }],
+    },
+  });
+  assert.deepStrictEqual(await target.exited, { code: 0, signal: null });
+}
+
+main().then(common.mustCall());
diff --git a/test/parallel/test-debugger-probe-attach-target-crashes.js b/test/parallel/test-debugger-probe-attach-target-crashes.js
new file mode 100644
index 00000000000..df84532653f
--- /dev/null
+++ b/test/parallel/test-debugger-probe-attach-target-crashes.js
@@ -0,0 +1,61 @@
+// Tests that if the target is terminated by an uncaught exception, the attach session reports
+// probe_target_exit with the exception, instead of as completed.
+'use strict';
+
+const common = require('../common');
+common.skipIfInspectorDisabled();
+
+const assert = require('assert');
+const fixtures = require('../common/fixtures');
+const { runProbe, startTarget } = require('../common/debugger-probe');
+
+const url = fixtures.fileURL('debugger', 'probe-attach-finishes.js').href;
+const path = fixtures.path('debugger', 'probe-attach-finishes.js');
+
+async function main() {
+  const target = await startTarget('probe-attach-finishes.js', { env: { PROBE_ATTACH_THROW: '1' } });
+  // Closing its stdin makes the target run line 5 once and throw. Line 11 only runs at startup.
+  await runProbe([
+    '--probe', 'probe-attach-finishes.js:5', '--expr', 'count',
+    '--probe', 'probe-attach-finishes.js:11', '--expr', '1',
+    '--host', target.host, '--port', `${target.port}`,
+  ], {
+    target,
+    onStarted: () => target.child.stdin.end(),
+    status: 0,
+    report: {
+      v: 2,
+      probes: [
+        { expr: 'count', target: { suffix: 'probe-attach-finishes.js', line: 5 } },
+        { expr: '1', target: { suffix: 'probe-attach-finishes.js', line: 11 } },
+      ],
+      results: [{
+        probe: 0, event: 'hit', hit: 1, result: { type: 'number', value: 0, description: '0' },
+        location: { url, line: 5, column: 3 },
+      }, {
+        event: 'error',
+        pending: [1],
+        error: {
+          code: 'probe_target_exit',
+          message: 'Target exited with an uncaught exception before probes: probe-attach-finishes.js:11',
+          details: {
+            exception: {
+              exceptionId: 1,
+              text: 'Uncaught',
+              lineNumber: 5,
+              columnNumber: 37,
+              scriptId: '<scriptId>',
+              url: path,
+              stackTrace: { callFrames: '<callFrames>' },
+              exception: { type: 'object', subtype: 'error', description: 'Error: boom\n<stack>' },
+              executionContextId: 1,
+            },
+          },
+        },
+      }],
+    },
+  });
+  assert.deepStrictEqual(await target.exited, { code: 1, signal: null });
+}
+
+main().then(common.mustCall());
diff --git a/test/parallel/test-debugger-probe-attach-timeout.js b/test/parallel/test-debugger-probe-attach-timeout.js
new file mode 100644
index 00000000000..22a0daec63a
--- /dev/null
+++ b/test/parallel/test-debugger-probe-attach-timeout.js
@@ -0,0 +1,37 @@
+// Tests that an attach session without --max-hit ends at --timeout with exit code 0.
+// It should list the probes that are never hit. The `locations` distinguish a probe
+// that does not get hit from a probe that does not match any script.
+'use strict';
+
+const common = require('../common');
+common.skipIfInspectorDisabled();
+
+const fixtures = require('../common/fixtures');
+const { runAttachedProbe } = require('../common/debugger-probe');
+
+const timeout = common.platformTimeout(2000);
+
+// Line 10 only runs at startup.
+runAttachedProbe('probe-attach-loop.js', [
+  '--timeout', `${timeout}`,
+  '--probe', 'probe-attach-loop.js:10', '--expr', '1',
+  '--probe', 'no-such-file.js:14', '--expr', '1',
+], {
+  status: 0,
+  report: {
+    v: 2,
+    probes: [{
+      expr: '1', target: { suffix: 'probe-attach-loop.js', line: 10 },
+      locations: [{ url: fixtures.fileURL('debugger', 'probe-attach-loop.js').href, line: 10, column: 1 }],
+    }, { expr: '1', target: { suffix: 'no-such-file.js', line: 14 }, locations: [] }],
+    results: [{
+      event: 'timeout',
+      pending: [0, 1],
+      error: {
+        code: 'probe_timeout',
+        message: `Session timed out after ${timeout}ms waiting for probes: probe-attach-loop.js:10, ` +
+          'no-such-file.js:14, detaching from the target',
+      },
+    }],
+  },
+}).then(common.mustCall());
diff --git a/test/parallel/test-debugger-probe-attach.js b/test/parallel/test-debugger-probe-attach.js
new file mode 100644
index 00000000000..8643b2d5e88
--- /dev/null
+++ b/test/parallel/test-debugger-probe-attach.js
@@ -0,0 +1,56 @@
+// Tests a --host/--port attach session that hits a probe in a script loaded before it attached,
+// and ends at --max-hit. The target should continue running, so a second session can still attach
+// to it. Killing the target during that session is reported as a probe failure, because without
+// --pid an exit cannot be distinguished from a network failure.
+'use strict';
+const common = require('../common');
+common.skipIfInspectorDisabled();
+
+const fixtures = require('../common/fixtures');
+const { runProbe, startTarget } = require('../common/debugger-probe');
+
+const url = fixtures.fileURL('debugger', 'probe-attach-loop.js').href;
+const location = { url, line: 6, column: 3 };
+const hit = (n) => ({ probe: 0, event: 'hit', hit: n, location, result: { type: 'string', value: 'number' } });
+
+async function main() {
+  const target = await startTarget('probe-attach-loop.js');
+  const attachArgs = ['--host', target.host, '--port', `${target.port}`];
+  await runProbe(['--probe', 'probe-attach-loop.js:6', '--expr', 'typeof count', '--max-hit', '2', ...attachArgs], {
+    target,
+    status: 0,
+    report: {
+      v: 2,
+      target: { host: target.host, port: target.port },
+      probes: [{
+        expr: 'typeof count', target: { suffix: 'probe-attach-loop.js', line: 6 }, maxHit: 2, locations: [location],
+      }],
+      results: [hit(1), hit(2), { event: 'completed' }],
+    },
+  });
+
+  // Line 10 only runs at startup, so this session should wait until the target is killed.
+  await runProbe(['--probe', 'probe-attach-loop.js:10', '--expr', '1', ...attachArgs], {
+    target,
+    onStarted: () => target.child.kill('SIGKILL'),
+    status: 1,
+    report: {
+      v: 2,
+      probes: [{
+        expr: '1', target: { suffix: 'probe-attach-loop.js', line: 10 }, locations: [{ url, line: 10, column: 1 }],
+      }],
+      results: [{
+        event: 'error',
+        pending: [0],
+        error: {
+          code: 'probe_failure',
+          message: 'Inspector connection lost before probes: probe-attach-loop.js:10. The target was likely ' +
+            "terminated externally. If the failure persists, check the target's process environment.",
+        },
+      }],
+    },
+  });
+  await target.exited;
+}
+
+main().then(common.mustCall());
diff --git a/test/parallel/test-debugger-probe-bound-never-hit.js b/test/parallel/test-debugger-probe-bound-never-hit.js
index cc3ef278d27..f0da697e9b2 100644
--- a/test/parallel/test-debugger-probe-bound-never-hit.js
+++ b/test/parallel/test-debugger-probe-bound-never-hit.js
@@ -1,4 +1,5 @@
 // Tests that probing an unreachable line produces a `miss` with no hit events.
+// The probe should be bound successfully, so the report should show its resolved location.
 'use strict';

 const common = require('../common');
@@ -9,6 +10,7 @@ const { spawnSyncAndAssert } = require('../common/child_process');
 const { assertProbeJson } = require('../common/debugger-probe');

 const cwd = fixtures.path('debugger');
+const fixtureUrl = fixtures.fileURL('debugger', 'probe-bound-never-hit.js').href;

 spawnSyncAndAssert(process.execPath, [
   'inspect',
@@ -23,6 +25,7 @@ spawnSyncAndAssert(process.execPath, [
       probes: [{
         expr: '1',
         target: { suffix: 'probe-bound-never-hit.js', line: 4 },
+        locations: [{ url: fixtureUrl, line: 4, column: 3 }],
       }],
       results: [{
         event: 'miss',
diff --git a/test/parallel/test-debugger-probe-json.js b/test/parallel/test-debugger-probe-json.js
index f0808d1f625..901f9194107 100644
--- a/test/parallel/test-debugger-probe-json.js
+++ b/test/parallel/test-debugger-probe-json.js
@@ -27,10 +27,13 @@ spawnSyncAndAssert(process.execPath, [
   stdout(output) {
     assertProbeJson(output, {
       v: 2,
+      target: { argv: ['probe.js'] },
+      // The script is parsed after the breakpoints are bound, so the locations
+      // come from the resolution reported from parsing the script.
       probes: [
-        { expr: 'index', target: { suffix: 'probe.js', line: 8 } },
-        { expr: 'total', target: { suffix: 'probe.js', line: 8 } },
-        { expr: 'finalValue', target: { suffix: 'probe.js', line: 12 } },
+        { expr: 'index', target: { suffix: 'probe.js', line: 8 }, locations: [locationAt8] },
+        { expr: 'total', target: { suffix: 'probe.js', line: 8 }, locations: [locationAt8] },
+        { expr: 'finalValue', target: { suffix: 'probe.js', line: 12 }, locations: [locationAt12] },
       ],
       results: [
         {
diff --git a/test/parallel/test-debugger-probe-late-resolution.js b/test/parallel/test-debugger-probe-late-resolution.js
index a66dd15a15f..ca443834dbd 100644
--- a/test/parallel/test-debugger-probe-late-resolution.js
+++ b/test/parallel/test-debugger-probe-late-resolution.js
@@ -26,8 +26,16 @@ spawnSyncAndAssert(process.execPath, [
     assertProbeJson(output, {
       v: 2,
       probes: [
-        { expr: 'value', target: { suffix: 'probe-late-target.mjs', line: 3 } },
-        { expr: 'value', target: { suffix: 'probe-late-target.cjs', line: 5 } },
+        {
+          expr: 'value',
+          target: { suffix: 'probe-late-target.mjs', line: 3 },
+          locations: [{ url: esmUrl, line: 3, column: 3 }],
+        },
+        {
+          expr: 'value',
+          target: { suffix: 'probe-late-target.cjs', line: 5 },
+          locations: [{ url: cjsUrl, line: 5, column: 3 }],
+        },
       ],
       results: [
         {
diff --git a/test/parallel/test-debugger-probe-miss.js b/test/parallel/test-debugger-probe-miss.js
index 99ccbd72a4d..8660b17638c 100644
--- a/test/parallel/test-debugger-probe-miss.js
+++ b/test/parallel/test-debugger-probe-miss.js
@@ -1,4 +1,5 @@
-// This tests that probe sessions report unresolved breakpoints as misses.
+// Tests that when breakpoints that are not resolved for a probe session should be
+// reported as misses with an empty array as its locations.
 'use strict';

 const common = require('../common');
@@ -22,6 +23,7 @@ spawnSyncAndAssert(process.execPath, [
       probes: [{
         expr: '42',
         target: { suffix: 'probe-miss.js', line: 99 },
+        locations: [],
       }],
       results: [{
         event: 'miss',
diff --git a/test/parallel/test-debugger-probe-startup-disconnect.js b/test/parallel/test-debugger-probe-startup-disconnect.js
index 68c8432dc55..dfcfccaa7bd 100644
--- a/test/parallel/test-debugger-probe-startup-disconnect.js
+++ b/test/parallel/test-debugger-probe-startup-disconnect.js
@@ -22,7 +22,7 @@ client.callMethod = common.mustCall((method) => {
   setImmediate(() => client.emit('close'));
   return new Promise(() => {});
 });
-client.reset = common.mustCall();
+client.reset = common.mustCallAtLeast();

 const session = new ProbeInspectorSession({
   childArgv: ['-e', ''],
@@ -30,6 +30,7 @@ const session = new ProbeInspectorSession({
   port: 0,
   probes: [probe],
   skipPortPreflight: true,
+  timeout: 30000,
 });
 session.client = client;

diff --git a/test/sequential/test-debugger-probe-attach-pid.js b/test/sequential/test-debugger-probe-attach-pid.js
new file mode 100644
index 00000000000..ba72253dd60
--- /dev/null
+++ b/test/sequential/test-debugger-probe-attach-pid.js
@@ -0,0 +1,54 @@
+// Tests that when a probe session starts by attaching to a process with --pid,
+// which activates inspector in the target process, should stop the probe session after
+// reaching --max-hit.
+'use strict';
+
+const common = require('../common');
+common.skipIfInspectorDisabled();
+
+const fixtures = require('../common/fixtures');
+const { runProbe, startTarget } = require('../common/debugger-probe');
+
+async function main() {
+  const target = await startTarget('probe-attach-loop.js', { args: [`--inspect-port=${common.PORT}`] });
+  const { pid } = target.child;
+  const attachArgs = ['--pid', `${pid}`, '--port', `${common.PORT}`];
+  await runProbe(['--probe', 'probe-attach-loop.js:6', '--expr', 'typeof count', '--max-hit', '1', ...attachArgs], {
+    target,
+    status: 0,
+    report: {
+      v: 2,
+      target: { pid, host: '127.0.0.1', port: common.PORT },
+      probes: [{ expr: 'typeof count', target: { suffix: 'probe-attach-loop.js', line: 6 }, maxHit: 1 }],
+      results: [{
+        probe: 0, event: 'hit', hit: 1, result: { type: 'string', value: 'number' },
+        location: { url: fixtures.fileURL('debugger', 'probe-attach-loop.js').href, line: 6, column: 3 },
+      }, { event: 'completed' }],
+    },
+  });
+
+  // The target should be left running after --max-hit is reached and it is detached.
+  // We should be able to attach a second session to it. Killing the target at this point
+  // should result in a probe_target_exit with exit code 0
+  // Line 10 only runs at startup, so this session should wait until the target is killed.
+  await runProbe(['--probe', 'probe-attach-loop.js:10', '--expr', '1', ...attachArgs], {
+    target,
+    onStarted: () => target.child.kill('SIGKILL'),
+    status: 0,
+    report: {
+      v: 2,
+      probes: [{ expr: '1', target: { suffix: 'probe-attach-loop.js', line: 10 } }],
+      results: [{
+        event: 'error',
+        pending: [0],
+        error: {
+          code: 'probe_target_exit',
+          message: 'Target exited before probes: probe-attach-loop.js:10',
+        },
+      }],
+    },
+  });
+  await target.exited;
+}
+
+main().then(common.mustCall());