Superpositional
AboutReview principlesPricingBlogGalleryAsk a RepoFAQ…

Real reviews of open-source pull requests

Read the reviews our automated pipeline produced across 5 repositories. Each includes the verdict, the exact commit reviewed and an independent judge’s score.

1 of 13, clap-rs/clap#6400
Ask this repo
Approved · 0 retained findingsclap-rs/clap#6400

fix(clap_complete_nushell): disable generating last arguments

Input

PR author’s description

<!-- Thanks for helping out! Please link the appropriate issue from your PR. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug…

PR diff

Current GitHub diff ↗
clap_complete_nushell/examples/test.rs · patch excerpt
+            clap::Command::new("last-hint").args([+                clap::Arg::new("first")+                    .value_parser(["bash", "fish", "zsh"])+                    .required(true),
Browse 7 changed files
clap_complete_nushell/examples/test.rs+9 −0
@@ -95,6 +95,15 @@ fn cli() -> clap::Command {             ]),             clap::Command::new("last")                 .args([clap::Arg::new("first"), clap::Arg::new("free").last(true)]),+            clap::Command::new("last-hint").args([+                clap::Arg::new("first")+                    .value_parser(["bash", "fish", "zsh"])+                    .required(true),+                clap::Arg::new("free")+                    .value_parser(["nushell", "powershell"])+                    .required(true)+                    .last(true),+            ]),             clap::Command::new("alias").args([                 clap::Arg::new("flag")                     .short('f')
clap_complete_nushell/tests/snapshots/last_args.nu+73 −0
@@ -0,0 +1,73 @@+module completions {++  export extern my-app [+    --help(-h)                # Print help+  ]++  export extern "my-app single" [+    --help(-h)                # Print help+    arg: string+  ]++  export extern "my-app multiple" [+    --help(-h)                # Print help+    ...args: string+  ]++  def "nu-complete my-app choice arg" [] {+    [ "bash" "zsh" "fish" ]+  }++  export extern "my-app choice" [+    --help(-h)                # Print help+    arg: string@"nu-complete my-app choice arg"+  ]++  def "nu-complete my-app multiple-choice args" [] {+    [ "bash" "zsh" "fish" ]+  }++  export extern "my-app multiple-choice" [+    --help(-h)                # Print help+    ...args: string@"nu-complete my-app multiple-choice args"+  ]++  export extern "my-app any-path" [+    --help(-h)                # Print help+    arg: path+  ]++  export extern "my-app multiple-any-path" [+    --help(-h)                # Print help+    ...args: path+  ]++  # Print this message or the help of the given subcommand(s)+  export extern "my-app help" [+  ]++  export extern "my-app help single" [+  ]++  export extern "my-app help multiple" [+  ]++  export extern "my-app help choice" [+  ]++  export extern "my-app help multiple-choice" [+  ]++  export extern "my-app help any-path" [+  ]++  export extern "my-app help multiple-any-path" [+  ]++  # Print this message or the help of the given subcommand(s)+  export extern "my-app help help" [+  ]++}++export use completions *
clap_complete_nushell/tests/common.rs+59 −0
@@ -267,6 +267,65 @@ pub(crate) fn value_hint_command(name: &'static str) -> Command {         ) } +pub(crate) fn last_args_command(name: &'static str) -> Command {+    Command::new(name).subcommands([+        Command::new("single")+            .arg(Arg::new("arg").required(true))+            .arg(Arg::new("last_arg").required(true).last(true)),+        Command::new("multiple")+            .arg(Arg::new("args").num_args(1..))+            .arg(Arg::new("last_args").num_args(1..).last(true)),+        Command::new("choice")+            .arg(+                Arg::new("arg")+                    .required(true)+                    .value_parser(["bash", "zsh", "fish"]),+            )+            .arg(+                Arg::new("last_arg")+                    .required(true)+                    .value_parser(["nushell", "powershell"])+                    .last(true),+            ),+        Command::new("multiple-choice")+            .arg(+                Arg::new("args")+                    .num_args(1..)+                    .value_parser(["bash", "zsh", "fish"]),+            )+            .arg(+                Arg::new("last_args")+                    .num_args(1..)+                    .value_parser(["nushell", "powershell"])+                    .last(true),+            ),+        Command::new("any-path")+            .arg(+                Arg::new("arg")+                    .required(true)+                    .value_hint(ValueHint::AnyPath),+            )+            .arg(+                Arg::new("last_arg")+                    .required(true)+                    .value_hint(ValueHint::AnyPath)+                    .last(true),+            ),+        Command::new("multiple-any-path")+            .arg(+                Arg::new("args")+                    .num_args(1..)+                    .value_hint(ValueHint::AnyPath),+            )+            .arg(+                Arg::new("last_args")+                    .num_args(1..)+                    .value_hint(ValueHint::AnyPath)+                    .last(true),+            ),+    ])+}+ pub(crate) fn assert_matches(     expected: impl IntoData,     generator: impl clap_complete::Generator,

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens advisories (not part of the checked findings):

  • complexity_maintainability: The diff adds two patterns that skip processing (continue) whenever a clap argument is marked as last(). This creates duplication of last-handling logic across core generator code (generate_completion and append_argument) and exposes fragility if the skip logic or its assumption about nushell support changes.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Complexity maintainabilityThe diff adds two patterns that skip processing (continue) whenever a clap argument is marked as last(). This creates duplication of last-handling logic across core generator code (generate_completion and append_argument) and exposes fragility if the skip logic or its assumption about nushell support changes.

    Recorded location clap_complete_nushell/src/lib.rs:208

  • Observation · Test strategyThe 'last-hint' subcommand is added in the code change but lacks dedicated behavioral tests in the diff; the new last-hint logic in lib.rs and its nushell completions snapshot should be verified by test cases.

    Recorded location clap_complete_nushell/src/lib.rs:133

Supporting evidence

Reviewed 27 Nov 2026Revision 7dd8df1b46027 changed files+218 −1Judge score 5/5
Approved · 0 retained findingsclap-rs/clap#6422

Fix fish indentations

Input

PR author’s description

<!-- Thanks for helping out! Please link the appropriate issue from your PR. If you don't have an issue, we'd recommend starting with one first so the PR can focus on the implementation (unless its an obvious bug…

PR diff

Current GitHub diff ↗
clap_complete/src/aot/shells/fish.rs · patch excerpt
-        "\-        # Print an optspec for argparse to handle cmd's options that are independent of any subcommand.\n\-        function {optspecs_fn_name}\n\-        \tstring join \\n{optspecs}\n\
Browse 10 changed files
clap_complete/src/aot/shells/fish.rs+28 −25
@@ -247,31 +247,34 @@ fn gen_subcommand_helpers(     let optspecs_fn_name = format!("__fish_{bin_name}_global_optspecs");     write!(         buf,-        "\-        # Print an optspec for argparse to handle cmd's options that are independent of any subcommand.\n\-        function {optspecs_fn_name}\n\-        \tstring join \\n{optspecs}\n\-        end\n\n\-        function {needs_fn_name}\n\-        \t# Figure out if the current invocation already has a command.\n\-        \tset -l cmd (commandline -opc)\n\-        \tset -e cmd[1]\n\-        \targparse -s ({optspecs_fn_name}) -- $cmd 2>/dev/null\n\-        \tor return\n\-        \tif set -q argv[1]\n\-        \t\t# Also print the command, so this can be used to figure out what it is.\n\-        \t\techo $argv[1]\n\-        \t\treturn 1\n\-        \tend\n\-        \treturn 0\n\-        end\n\n\-        function {using_fn_name}\n\-        \tset -l cmd ({needs_fn_name})\n\-        \ttest -z \"$cmd\"\n\-        \tand return 1\n\-        \tcontains -- $cmd[1] $argv\n\-        end\n\n\-    ").expect("failed to write completion file");+        "# Print an optspec for argparse to handle cmd's options that are independent of any subcommand.+function {optspecs_fn_name}+    string join \\n{optspecs}+end++function {needs_fn_name}+    # Figure out if the current invocation already has a command.+    set -l cmd (commandline -opc)+    set -e cmd[1]+    argparse -s ({optspecs_fn_name}) -- $cmd 2>/dev/null+    or return+    if set -q argv[1]+        # Also print the command, so this can be used to figure out what it is.+        echo $argv[1]+        return 1+    end+    return 0+end++function {using_fn_name}+    set -l cmd ({needs_fn_name})+    test -z \"$cmd\"+    and return 1+    contains -- $cmd[1] $argv+end++"+        ).expect("failed to write completion file"); }  fn value_completion(option: &Arg) -> String {
clap_complete/tests/snapshots/basic.fish+16 −16
@@ -1,27 +1,27 @@ # Print an optspec for argparse to handle cmd's options that are independent of any subcommand. function __fish_my_app_global_optspecs-	string join \n c v h/help+    string join \n c v h/help end  function __fish_my_app_needs_command-	# Figure out if the current invocation already has a command.-	set -l cmd (commandline -opc)-	set -e cmd[1]-	argparse -s (__fish_my_app_global_optspecs) -- $cmd 2>/dev/null-	or return-	if set -q argv[1]-		# Also print the command, so this can be used to figure out what it is.-		echo $argv[1]-		return 1-	end-	return 0+    # Figure out if the current invocation already has a command.+    set -l cmd (commandline -opc)+    set -e cmd[1]+    argparse -s (__fish_my_app_global_optspecs) -- $cmd 2>/dev/null+    or return+    if set -q argv[1]+        # Also print the command, so this can be used to figure out what it is.+        echo $argv[1]+        return 1+    end+    return 0 end  function __fish_my_app_using_subcommand-	set -l cmd (__fish_my_app_needs_command)-	test -z "$cmd"-	and return 1-	contains -- $cmd[1] $argv+    set -l cmd (__fish_my_app_needs_command)+    test -z "$cmd"+    and return 1+    contains -- $cmd[1] $argv end  complete -c my-app -n "__fish_my_app_needs_command" -s c
clap_complete/tests/snapshots/custom_bin_name.fish+16 −16
@@ -1,27 +1,27 @@ # Print an optspec for argparse to handle cmd's options that are independent of any subcommand. function __fish_bin_name_global_optspecs-	string join \n c v h/help+    string join \n c v h/help end  function __fish_bin_name_needs_command-	# Figure out if the current invocation already has a command.-	set -l cmd (commandline -opc)-	set -e cmd[1]-	argparse -s (__fish_bin_name_global_optspecs) -- $cmd 2>/dev/null-	or return-	if set -q argv[1]-		# Also print the command, so this can be used to figure out what it is.-		echo $argv[1]-		return 1-	end-	return 0+    # Figure out if the current invocation already has a command.+    set -l cmd (commandline -opc)+    set -e cmd[1]+    argparse -s (__fish_bin_name_global_optspecs) -- $cmd 2>/dev/null+    or return+    if set -q argv[1]+        # Also print the command, so this can be used to figure out what it is.+        echo $argv[1]+        return 1+    end+    return 0 end  function __fish_bin_name_using_subcommand-	set -l cmd (__fish_bin_name_needs_command)-	test -z "$cmd"-	and return 1-	contains -- $cmd[1] $argv+    set -l cmd (__fish_bin_name_needs_command)+    test -z "$cmd"+    and return 1+    contains -- $cmd[1] $argv end  complete -c bin-name -n "__fish_bin_name_needs_command" -s c

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens observations (not verified against the evidence ledger):

  • dependency_blast_radius: The PR rewriting the gen_subcommand_helpers template in Rust removes the original template markup that produced output with tabs, changing the syntax of the generated completion functions in all affected snapshots and thus breaking shell syntax expectations for any manually-editored templates or configurations that relied on the tab-based format.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Dependency blast radiusThe PR rewriting the gen_subcommand_helpers template in Rust removes the original template markup that produced output with tabs, changing the syntax of the generated completion functions in all affected snapshots and thus breaking shell syntax expectations for any manually-editored templates or configurations that relied on the tab-based format.
  • Observation · Dependency blast radiusThe try_generate function calls gen_subcommand_helpers, which in turn calls escape_string to produce completion assets; changes to gen_subcommand_helpers transitively affect user-facing completion generation unless the escape_string logic is updated in parallel.

    Recorded location clap_complete/src/aot/shells/fish.rs:12

Supporting evidence

Reviewed 27 Nov 2026Revision f90a96636ad310 changed files+172 −169Judge score 5/5
Approved · 0 retained findingsserde-rs/serde#2816

Implement serialize/deserialize for core::net instead of std::net

Input

PR author’s description

Implement serialize/deserialize for core::net instead of std::net, if running rust version newer than 1.77, where core::net was stabilized

Fixes #2760

PR diff

Current GitHub diff ↗
serde/src/de/impls.rs · patch excerpt
-#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))]
Browse 6 changed files
serde/src/de/impls.rs+17 −17
@@ -1604,7 +1604,7 @@ macro_rules! parse_ip_impl {     }; } -#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))] macro_rules! variant_identifier {     (         $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)@@ -1679,7 +1679,7 @@ macro_rules! variant_identifier {     } } -#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))] macro_rules! deserialize_enum {     (         $name:ident $name_kind:ident ($($variant:ident; $bytes:expr; $index:expr),*)@@ -1716,8 +1716,8 @@ macro_rules! deserialize_enum {     } } -#[cfg(feature = "std")]-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]+#[cfg(any(feature = "std", not(no_core_net)))]+#[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))] impl<'de> Deserialize<'de> for net::IpAddr {     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>     where@@ -1737,14 +1737,14 @@ impl<'de> Deserialize<'de> for net::IpAddr { }  parse_ip_impl! {-    #[cfg(feature = "std")]-    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]+    #[cfg(any(feature = "std", not(no_core_net)))]+    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))]     net::Ipv4Addr, "IPv4 address", 4 }  parse_ip_impl! {-    #[cfg(feature = "std")]-    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]+    #[cfg(any(feature = "std", not(no_core_net)))]+    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))]     net::Ipv6Addr, "IPv6 address", 16 } @@ -1770,8 +1770,8 @@ macro_rules! parse_socket_impl {     }; } -#[cfg(feature = "std")]-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]+#[cfg(any(feature = "std", not(no_core_net)))]+#[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))] impl<'de> Deserialize<'de> for net::SocketAddr {     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>     where@@ -1791,15 +1791,15 @@ impl<'de> Deserialize<'de> for net::SocketAddr { }  parse_socket_impl! {-    #[cfg(feature = "std")]-    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]+    #[cfg(any(feature = "std", not(no_core_net)))]+    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))]     net::SocketAddrV4, "IPv4 socket address",     |(ip, port)| net::SocketAddrV4::new(ip, port), }  parse_socket_impl! {-    #[cfg(feature = "std")]-    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]+    #[cfg(any(feature = "std", not(no_core_net)))]+    #[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))]     net::SocketAddrV6, "IPv6 socket address",     |(ip, port)| net::SocketAddrV6::new(ip, port, 0, 0), }@@ -3160,13 +3160,13 @@ atomic_impl! {     AtomicU64 "64" } -#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))] struct FromStrVisitor<T> {     expecting: &'static str,     ty: PhantomData<T>, } -#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))] impl<T> FromStrVisitor<T> {     fn new(expecting: &'static str) -> Self {         FromStrVisitor {@@ -3176,7 +3176,7 @@ impl<T> FromStrVisitor<T> {     } } -#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))] impl<'de, T> Visitor<'de> for FromStrVisitor<T> where     T: str::FromStr,
serde/src/ser/impls.rs+19 −29
@@ -773,28 +773,18 @@ impl Serialize for SystemTime { /// statically known to never have more than a constant `MAX_LEN` bytes. /// /// Panics if the `Display` impl tries to write more than `MAX_LEN` bytes.-#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))] macro_rules! serialize_display_bounded_length {     ($value:expr, $max:expr, $serializer:expr) => {{         let mut buffer = [0u8; $max];-        let remaining_len = {-            let mut remaining = &mut buffer[..];-            write!(remaining, "{}", $value).unwrap();-            remaining.len()-        };-        let written_len = buffer.len() - remaining_len;-        let written = &buffer[..written_len];--        // write! only provides fmt::Formatter to Display implementations, which-        // has methods write_str and write_char but no method to write arbitrary-        // bytes. Therefore `written` must be valid UTF-8.-        let written_str = str::from_utf8(written).expect("must be valid UTF-8");-        $serializer.serialize_str(written_str)+        let mut writer = crate::format::Buf::new(&mut buffer);+        write!(&mut writer, "{}", $value).unwrap();+        $serializer.serialize_str(writer.as_str())     }}; } -#[cfg(feature = "std")]-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]+#[cfg(any(feature = "std", not(no_core_net)))]+#[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))] impl Serialize for net::IpAddr {     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>     where@@ -818,15 +808,15 @@ impl Serialize for net::IpAddr {     } } -#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))] const DEC_DIGITS_LUT: &[u8] = b"\       0001020304050607080910111213141516171819\       2021222324252627282930313233343536373839\       4041424344454647484950515253545556575859\       6061626364656667686970717273747576777879\       8081828384858687888990919293949596979899"; -#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))] #[inline] fn format_u8(mut n: u8, out: &mut [u8]) -> usize {     if n >= 100 {@@ -847,7 +837,7 @@ fn format_u8(mut n: u8, out: &mut [u8]) -> usize {     } } -#[cfg(feature = "std")]+#[cfg(any(feature = "std", not(no_core_net)))] #[test] fn test_format_u8() {     let mut i = 0u8;@@ -864,8 +854,8 @@ fn test_format_u8() {     } } -#[cfg(feature = "std")]-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]+#[cfg(any(feature = "std", not(no_core_net)))]+#[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))] impl Serialize for net::Ipv4Addr {     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>     where@@ -889,8 +879,8 @@ impl Serialize for net::Ipv4Addr {     } } -#[cfg(feature = "std")]-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]+#[cfg(any(feature = "std", not(no_core_net)))]+#[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))] impl Serialize for net::Ipv6Addr {     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>     where@@ -906,8 +896,8 @@ impl Serialize for net::Ipv6Addr {     } } -#[cfg(feature = "std")]-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]+#[cfg(any(feature = "std", not(no_core_net)))]+#[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))] impl Serialize for net::SocketAddr {     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>     where@@ -931,8 +921,8 @@ impl Serialize for net::SocketAddr {     } } -#[cfg(feature = "std")]-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]+#[cfg(any(feature = "std", not(no_core_net)))]+#[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))] impl Serialize for net::SocketAddrV4 {     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>     where@@ -948,8 +938,8 @@ impl Serialize for net::SocketAddrV4 {     } } -#[cfg(feature = "std")]-#[cfg_attr(docsrs, doc(cfg(feature = "std")))]+#[cfg(any(feature = "std", not(no_core_net)))]+#[cfg_attr(docsrs, doc(cfg(any(feature = "std", not(no_core_net)))))] impl Serialize for net::SocketAddrV6 {     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>     where
serde/src/lib.rs+8 −1
@@ -238,8 +238,13 @@ mod lib {     #[cfg(feature = "std")]     pub use std::ffi::CString; +    #[cfg(all(not(no_core_net), not(feature = "std")))]+    pub use self::core::net;     #[cfg(feature = "std")]-    pub use std::{error, net};+    pub use std::net;++    #[cfg(feature = "std")]+    pub use std::error;      #[cfg(feature = "std")]     pub use std::collections::{HashMap, HashSet};@@ -305,6 +310,8 @@ mod integer128; pub mod de; pub mod ser; +mod format;+ #[doc(inline)] pub use crate::de::{Deserialize, Deserializer}; #[doc(inline)]

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens advisories (not part of the checked findings):

  • architectural_coherence: Replacing #[cfg(feature = "std")] with #[cfg(any(feature = "std", not(no_core_net)))] in variant_identifier, deserialize_enum, and net::IpAddr implementations creates a conditional deviation from the established std-only stabilization pattern for serde core types.

Lens coverage: 6 delivered

The recorded observation did not become a verified finding.

Evidence and perspectives

  • Observation · Architectural coherenceReplacing `#[cfg(feature = "std")]` with `#[cfg(any(feature = "std", not(no_core_net)))]` in variant_identifier, deserialize_enum, and net::IpAddr implementations creates a conditional deviation from the established std-only stabilization pattern for serde core types.

    Recorded location serde/src/de/impls.rs:698

Supporting evidence

Reviewed 27 Nov 2026Revision d940fe1b49346 changed files+53 −50Judge score 5/5
Approved · 0 retained findingsdrizzle-team/drizzle-orm#6584

Integrate Drizzle Postgres as a workspace package and run its CI from the monorepo

Input

PR author’s description

Drizzle Postgres moves into the monorepo as the workspace package @drizzle-team/postgres. It keeps its own version and its own releases. The history of the old minipg repository is not imported.

PR diff

Current GitHub diff ↗
postgres/playground/replication/repl-client.ts · patch excerpt
-// Minimal raw LOGICAL REPLICATION client — the playground prototype for drizzle-pulse support-// in Drizzle Postgres (like copy-client.ts was for COPY). Unix-socket + trust auth only (the local test-// cluster). Speaks: startup with replication=database, the walsender grammar over simple 'Q',-// CopyBoth streaming ('W'), XLogData/keepalive envelopes, standby-status acks, and a full
Browse 30 changed files
postgres/playground/replication/repl-client.ts+0 −371
@@ -1,371 +0,0 @@-// Minimal raw LOGICAL REPLICATION client — the playground prototype for drizzle-pulse support-// in Drizzle Postgres (like copy-client.ts was for COPY). Unix-socket + trust auth only (the local test-// cluster). Speaks: startup with replication=database, the walsender grammar over simple 'Q',-// CopyBoth streaming ('W'), XLogData/keepalive envelopes, standby-status acks, and a full-// pgoutput (proto v1 + messages) parser with per-relation column caching.-import { parseDataRow, Parser, parseRowDescription, type RawMessage, W } from '../../src/protocol.ts';--const PG_EPOCH_MS = 946684800000n; // 2000-01-01T00:00:00Z--// ---------- LSN helpers -----------export const lsnToString = (lsn: bigint): string =>-	`${(lsn >> 32n).toString(16).toUpperCase()}/${(lsn & 0xffffffffn).toString(16).toUpperCase()}`;-export const lsnFromString = (s: string): bigint => {-	const [hi, lo] = s.split('/');-	return (BigInt(parseInt(hi!, 16)) << 32n) | BigInt(parseInt(lo!, 16));-};--// ---------- pgoutput event model -----------export interface RelInfo {-	id: number;-	schema: string;-	name: string;-	replicaIdentity: string;-	columns: { name: string; oid: number; key: boolean }[];-}-export type Tuple = (string | null | { unchangedToast: true })[];-export type PgoutputEvent =-	| { kind: 'begin'; finalLsn: bigint; commitTime: Date; xid: number }-	| { kind: 'commit'; commitLsn: bigint; endLsn: bigint; commitTime: Date }-	| { kind: 'relation'; relation: RelInfo }-	| { kind: 'insert'; relation: RelInfo; new: Tuple }-	| { kind: 'update'; relation: RelInfo; old: Tuple | null; oldKind: 'key' | 'full' | null; new: Tuple }-	| { kind: 'delete'; relation: RelInfo; old: Tuple; oldKind: 'key' | 'full' }-	| { kind: 'truncate'; relations: RelInfo[]; cascade: boolean; restartIdentity: boolean }-	| { kind: 'message'; transactional: boolean; prefix: string; content: Buffer; lsn: bigint }-	| { kind: 'origin' | 'type' };--const frame = (type: string, payload: Buffer): Buffer => {-	const head = Buffer.allocUnsafe(5);-	head.write(type, 0, 'latin1');-	head.writeInt32BE(payload.length + 4, 1);-	return Buffer.concat([head, payload]);-};--interface BunSocket {-	write(data: Uint8Array): number;-	end(): void;-}--export class ReplClient {-	private sock!: BunSocket;-	private parser = new Parser();-	private q: RawMessage[] = [];-	private wake: (() => void) | null = null;-	private err: Error | null = null;-	private ended = false;-	private relations = new Map<number, RelInfo>(); // pgoutput 'R' cache — the decode registry--	lastReceivedLsn = 0n;-	flushedLsn = 0n; // what we've ACKED (confirmed_flush advances to this)--	static async connect(o: { unix: string; user: string; database: string }): Promise<ReplClient> {-		const c = new ReplClient();-		c.sock = (await Bun.connect({-			unix: o.unix,-			socket: {-				data: (_s: unknown, d: Uint8Array) => c.onData(d),-				error: (_s: unknown, e: Error) => {-					c.err = e;-					c.wake?.();-				},-				close: () => {-					if (!c.ended) c.err ??= new Error('replication connection closed');-					c.wake?.();-				},-			},-		})) as unknown as BunSocket;-		// THE one special bit of the handshake: replication=database selects the logical walsender-		c.write(W.startup({ user: o.user, database: o.database, replication: 'database' }));-		for (;;) {-			const m = await c.next();-			if (m.type === 'R' && m.body.readInt32BE(0) !== 0) throw new Error('trust auth only in the playground client');-			if (m.type === 'E') throw c.pgErr(m.body);-			if (m.type === 'Z') break;-		}-		return c;-	}--	private onData(d: Uint8Array): void {-		const msgs = this.parser.push(Buffer.from(d));-		if (msgs.length) this.q.push(...msgs);-		const r = this.wake;-		this.wake = null;-		r?.();-	}-	private async next(): Promise<RawMessage> {-		for (;;) {-			const m = this.q.shift();-			if (m) {-				if (m.type === 'S' || m.type === 'K' || m.type === 'N' || m.type === 'A') continue;-				return m;-			}-			if (this.err) throw this.err;-			await new Promise<void>((r) => {-				this.wake = r;-			});-		}-	}-	private write(b: Buffer): void {-		this.sock.write(b);-	}-	private pgErr(body: Buffer): Error {-		const f = new Map<string, string>();-		let off = 0;-		while (off < body.length && body[off] !== 0) {-			let e = off + 1;-			while (body[e] !== 0) e++;-			f.set(String.fromCharCode(body[off]!), body.toString('utf8', off + 1, e));-			off = e + 1;-		}-		return new Error(`${f.get('C')}: ${f.get('M')}`);-	}--	/** Simple-protocol command (walsender grammar or plain SQL) -> rows as text arrays. */-	async command(sql: string): Promise<{ columns: string[]; rows: (string | null)[][] }> {-		this.write(frame('Q', Buffer.from(sql + '\0', 'utf8')));-		let columns: string[] = [];-		const rows: (string | null)[][] = [];-		let err: Error | null = null;-		for (;;) {-			const m = await this.next();-			if (m.type === 'T') columns = parseRowDescription(m.body).map((f) => f.name);-			else if (m.type === 'D') rows.push(parseDataRow(m.body).map((c) => (c === null ? null : c.toString('utf8'))));-			else if (m.type === 'E') err = this.pgErr(m.body);-			else if (m.type === 'Z') break;-			else if (m.type === 'W') {-				this.q.unshift(m);-				break;-			} // CopyBothResponse: streaming starts — caller takes over-		}-		if (err) throw err;-		return { columns, rows };-	}--	async identify(): Promise<Record<string, string | null>> {-		const r = await this.command('IDENTIFY_SYSTEM');-		return Object.fromEntries(r.columns.map((c, i) => [c, r.rows[0]![i]!]));-	}--	/** CREATE_REPLICATION_SLOT ... LOGICAL pgoutput. Returns consistent point + exported snapshot. */-	async createSlot(-		name: string,-		opts: { temporary?: boolean; exportSnapshot?: boolean } = {},-	): Promise<{ slot: string; consistentPoint: bigint; snapshot: string | null }> {-		// legacy keyword form: works on PG 10-17 (the parenthesized `(SNAPSHOT 'export')` form is 15+ only)-		const sql = `CREATE_REPLICATION_SLOT ${name}${opts.temporary ? ' TEMPORARY' : ''} LOGICAL pgoutput ${-			opts.exportSnapshot ? 'EXPORT_SNAPSHOT' : 'NOEXPORT_SNAPSHOT'-		}`;-		const r = await this.command(sql);-		const row = Object.fromEntries(r.columns.map((c, i) => [c, r.rows[0]![i]]));-		return {-			slot: row.slot_name as string,-			consistentPoint: lsnFromString(row.consistent_point as string),-			snapshot: (row.snapshot_name as string | null) ?? null,-		};-	}--	/** START_REPLICATION -> async iterator of decoded pgoutput events. Handles keepalives and-	 *  sends standby-status acks (flushed = this.flushedLsn — the CONSUMER advances it via ack()). */-	async *start(-		slot: string,-		from: bigint,-		publications: string[],-		opts: { statusIntervalMs?: number } = {},-	): AsyncGenerator<PgoutputEvent> {-		const pubs = publications.map((p) => `"${p}"`).join(',');-		this.write(-			frame(-				'Q',-				Buffer.from(-					`START_REPLICATION SLOT ${slot} LOGICAL ${-						lsnToString(from)-					} (proto_version '1', publication_names '${pubs}', messages 'true')\0`,-					'utf8',-				),-			),-		);-		for (;;) { // wait for CopyBothResponse-			const m = await this.next();-			if (m.type === 'W') break;-			if (m.type === 'E') throw this.pgErr(m.body);-		}-		const status = setInterval(() => this.sendStatus(false), opts.statusIntervalMs ?? 5000);-		try {-			for (;;) {-				const m = await this.next();-				if (m.type === 'E') throw this.pgErr(m.body);-				if (m.type === 'c') break; // server CopyDone (e.g. timeline end) — not expected in logical-				if (m.type !== 'd') continue;-				const p = m.body;-				if (p[0] === 0x6b) { // 'k' keepalive: walEnd, clock, replyRequested-					this.lastReceivedLsn = p.readBigUInt64BE(1) > this.lastReceivedLsn-						? p.readBigUInt64BE(1)-						: this.lastReceivedLsn;-					if (p[17] === 1) this.sendStatus(false);-					continue;-				}-				if (p[0] !== 0x77) continue; // not XLogData-				const walStart = p.readBigUInt64BE(1);-				if (walStart > this.lastReceivedLsn) this.lastReceivedLsn = walStart;-				yield this.decode(p.subarray(25)); // 'w' + 3x int64 header = 25 bytes-			}-		} finally {-			clearInterval(status);-		}-	}--	/** Consumer acknowledgement: mark everything <= lsn durably processed, tell the server. */-	ack(lsn: bigint): void {-		if (lsn > this.flushedLsn) {-			this.flushedLsn = lsn;-			this.sendStatus(false);-		}-	}--	private sendStatus(reply: boolean): void {-		const b = Buffer.allocUnsafe(1 + 8 * 4 + 1);-		b.write('r', 0, 'latin1');-		b.writeBigUInt64BE(this.lastReceivedLsn, 1); // written-		b.writeBigUInt64BE(this.flushedLsn, 9); // flushed <- THE ack that releases WAL-		b.writeBigUInt64BE(this.flushedLsn, 17); // applied-		b.writeBigUInt64BE((BigInt(Date.now()) - PG_EPOCH_MS) * 1000n, 25);-		b[33] = reply ? 1 : 0;-		try {-			this.write(frame('d', b));-		} catch { /* socket gone; the stream loop will surface it */ }-	}--	// ---------- pgoutput (proto v1 + messages) -----------	private decode(b: Buffer): PgoutputEvent {-		const tag = String.fromCharCode(b[0]!);-		let off = 1;-		const cstr = (): string => {-			let e = off;-			while (b[e] !== 0) e++;-			const s = b.toString('utf8', off, e);-			off = e + 1;-			return s;-		};-		const tuple = (): Tuple => {-			const n = b.readInt16BE(off);-			off += 2;-			const out: Tuple = new Array(n);-			for (let i = 0; i < n; i++) {-				const k = b[off]!;-				off += 1;-				if (k === 0x6e) out[i] = null; // 'n'-				else if (k === 0x75) out[i] = { unchangedToast: true }; // 'u'-				else {-					const len = b.readInt32BE(off);-					off += 4;-					out[i] = b.toString('utf8', off, off + len);-					off += len;-				} // 't'-			}-			return out;-		};-		const rel = (id: number): RelInfo =>-			this.relations.get(id) ?? { id, schema: '?', name: `?${id}`, replicaIdentity: '?', columns: [] };-		const ts = (us: bigint): Date => new Date(Number(us / 1000n + PG_EPOCH_MS));-		switch (tag) {-			case 'B':-				return {-					kind: 'begin',-					finalLsn: b.readBigUInt64BE(1),-					commitTime: ts(b.readBigUInt64BE(9)),-					xid: b.readInt32BE(17),-				};-			case 'C':-				return {-					kind: 'commit',-					commitLsn: b.readBigUInt64BE(2),-					endLsn: b.readBigUInt64BE(10),-					commitTime: ts(b.readBigUInt64BE(18)),-				};-			case 'R': {-				const id = b.readInt32BE(off);-				off += 4;-				const schema = cstr(), name = cstr();-				const replicaIdentity = String.fromCharCode(b[off]!);-				off += 1;-				const n = b.readInt16BE(off);-				off += 2;-				const columns: RelInfo['columns'] = [];-				for (let i = 0; i < n; i++) {-					const key = b[off]! === 1;-					off += 1;-					const cname = cstr();-					const oid = b.readInt32BE(off);-					off += 8 /* oid + typmod */;-					columns.push({ name: cname, oid, key });-				}-				const info: RelInfo = { id, schema, name, replicaIdentity, columns };-				this.relations.set(id, info);-				return { kind: 'relation', relation: info };-			}-			case 'I': {-				const id = b.readInt32BE(off);-				off += 5 /* relid + 'N' */;-				return { kind: 'insert', relation: rel(id), new: tuple() };-			}-			case 'U': {-				const id = b.readInt32BE(off);-				off += 4;-				let old: Tuple | null = null, oldKind: 'key' | 'full' | null = null;-				let k = String.fromCharCode(b[off]!);-				off += 1;-				if (k === 'K' || k === 'O') {-					oldKind = k === 'K' ? 'key' : 'full';-					old = tuple();-					k = String.fromCharCode(b[off]!);-					off += 1;-				}-				return { kind: 'update', relation: rel(id), old, oldKind, new: tuple() }; // k === 'N' here-			}-			case 'D': {-				const id = b.readInt32BE(off);-				off += 4;-				const k = String.fromCharCode(b[off]!);-				off += 1;-				return { kind: 'delete', relation: rel(id), old: tuple(), oldKind: k === 'K' ? 'key' : 'full' };-			}-			case 'T': {-				const n = b.readInt32BE(off);-				off += 4;-				const flags = b[off]!;-				off += 1;-				const rels: RelInfo[] = [];-				for (let i = 0; i < n; i++) {-					rels.push(rel(b.readInt32BE(off)));-					off += 4;-				}-				return { kind: 'truncate', relations: rels, cascade: (flags & 1) !== 0, restartIdentity: (flags & 2) !== 0 };-			}-			case 'M': {-				const transactional = b[off]! === 1;-				off += 1;-				const lsn = b.readBigUInt64BE(off);-				off += 8;-				const prefix = cstr();-				const len = b.readInt32BE(off);-				off += 4;-				return { kind: 'message', transactional, prefix, content: b.subarray(off, off + len), lsn };-			}-			case 'O':-				return { kind: 'origin' };-			case 'Y':-				return { kind: 'type' };-			default:-				throw new Error(`unknown pgoutput message '${tag}'`);-		}-	}--	end(): void {-		this.ended = true;-		try {-			this.write(W.terminate());-		} catch { /* */ }-		this.sock.end();-	}-}
postgres/pnpm-lock.yaml+0 −3835
pnpm-lock.yaml+1757 −51

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens advisories (not part of the checked findings):

  • dependency_blast_radius: The workflow change FROM postgres/.github/workflows/publish.yml TO .github/workflows/postgres-ci.yml introduces a new workflow_call trigger that call sites (e.g., .github/workflows/postgres-publish.yml) must adapt to match the renamed job and the changed workflow_dispatch behavior.
  • dependency_blast_radius: Moving CI/CD configurations from postgres/.github/workflows/publish.yml to .github/workflows/postgres-ci.yml violates the direct workflow rule: the old path declared the npm trusted publisher for @drizzle/postgres; the new location lacks that declaration, and no downstream workflow declares a dependency on setTimeout.
  • dependency_blast_radius: The workflow SEPARATOR change removes pinned黝corkfrom both postgres.ci.yml and postgres.preview.yml, breaking job names, assertions, and runner stability without evidence that downstream callers have been updated.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Dependency blast radiusThe workflow SEPARATOR change removes pinned黝corkfrom both `postgres.ci.yml` and `postgres.preview.yml`, breaking job names, assertions, and runner stability without evidence that downstream callers have been updated.

    Recorded file .github/workflows/postgres-ci.yml · no line recorded

  • Observation · Failure HandlingUses unqualified env var fallback patterns that silently convert missing required configuration into empty strings, causing runtime failures far from misconfiguration source.

    Principle · Reject Invalid Required Configuration

    Recorded file postgres/src/connection.ts · no line recorded

Supporting evidence

Reviewed 27 Nov 2026Revision aa1b54a69e0430 changed files+1757 −10207Judge score 5/5
Approved · 0 retained findingsgithub/github-mcp-server#3323

Preserve versioned STDIO API user agents across MCP protocols

Input

PR author’s description

Summary

Give STDIO GitHub API requests a server/version user agent before any MCP handshake, retaining upstream client metadata per request across legacy and modern MCP protocols. Resolve usable build metadata for…

PR diff

Current GitHub diff ↗
internal/ghmcp/server_test.go · patch excerpt
++import (+	"context"+	"encoding/json"
Browse 9 changed files
internal/ghmcp/server_test.go+250 −0
@@ -1 +1,251 @@ package ghmcp++import (+	"context"+	"encoding/json"+	"net"+	"net/http"+	"net/http/httptest"+	"sync/atomic"+	"testing"+	"time"++	"github.com/github/github-mcp-server/pkg/github"+	"github.com/github/github-mcp-server/pkg/observability"+	"github.com/github/github-mcp-server/pkg/observability/metrics"+	"github.com/github/github-mcp-server/pkg/translations"+	"github.com/modelcontextprotocol/go-sdk/mcp"+	"github.com/stretchr/testify/assert"+	"github.com/stretchr/testify/require"+)++func TestCreateGitHubClientsGraphQLUserAgent(t *testing.T) {+	t.Parallel()+	for _, insiders := range []bool{false, true} {+		t.Run(map[bool]string{false: "release", true: "insiders"}[insiders], func(t *testing.T) {+			headers := make(chan http.Header, 1)+			api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+				headers <- r.Header.Clone()+				w.Header().Set("Content-Type", "application/json")+				_, _ = w.Write([]byte(`{"data":{"viewer":{"login":"octocat"}}}`))+			}))+			defer api.Close()+			cfg := github.MCPServerConfig{Version: "v1.2.3", Token: "fixture-token", InsidersMode: insiders}+			clients, err := createGitHubClients(cfg, newStaticAPIHostResolver(t, api.URL))+			require.NoError(t, err)+			var query struct {+				Viewer struct{ Login string }+			}+			require.NoError(t, clients.gql.Query(t.Context(), &query, nil))+			want := "github-mcp-server/v1.2.3"+			if insiders {+				want += " (insiders)"+			}+			header := <-headers+			assert.Equal(t, want, header.Get("User-Agent"))+			assert.Equal(t, "Bearer fixture-token", header.Get("Authorization"))+		})+	}+}++func TestStdioGraphQLUserAgent(t *testing.T) {+	t.Parallel()++	tests := []struct {+		name       string+		handshake  string+		clientInfo *mcp.Implementation+		version    string+		insiders   bool+		want       string+	}{+		{+			name: "SDK discovery", handshake: "sdk", version: "v1.2.3",+			clientInfo: &mcp.Implementation{Name: "test-client", Version: "4.5.6"},+			want:       "github-mcp-server/v1.2.3 (test-client/4.5.6)",+		},+		{+			name: "direct modern call", version: "v1.2.3",+			clientInfo: &mcp.Implementation{Name: "test-client", Version: "4.5.6"},+			want:       "github-mcp-server/v1.2.3 (test-client/4.5.6)",+		},+		{+			name: "modern call without optional client info", version: "v1.2.3",+			want: "github-mcp-server/v1.2.3",+		},+		{+			name: "legacy initialize", handshake: "legacy", version: "v1.2.3",+			clientInfo: &mcp.Implementation{Name: "test-client", Version: "4.5.6"},+			want:       "github-mcp-server/v1.2.3 (test-client/4.5.6)",+		},+		{+			name: "insiders", version: "v1.2.3", insiders: true,+			clientInfo: &mcp.Implementation{Name: "test-client", Version: "4.5.6"},+			want:       "github-mcp-server/v1.2.3 (test-client/4.5.6) (insiders)",+		},+		{+			name: "different server build", version: "v1.2.4",+			clientInfo: &mcp.Implementation{Name: "test-client", Version: "4.5.6"},+			want:       "github-mcp-server/v1.2.4 (test-client/4.5.6)",+		},+		{+			name: "HTTP comment delimiters", version: "v1.2.3",+			clientInfo: &mcp.Implementation{Name: `Editor (Preview) \client`, Version: `v(1)\build`},+			want:       `github-mcp-server/v1.2.3 (Editor \(Preview\) \\client/v\(1\)\\build)`,+		},+		{+			name: "modern control characters", version: "v1.2.3",+			clientInfo: &mcp.Implementation{Name: "editor(\x00)\\client\r\nX-Fake:1", Version: "1.0\tbeta\x7f"},+			want:       `github-mcp-server/v1.2.3 (editor\(\x00\)\\client\r\nX-Fake:1/1.0\tbeta\x7f)`,+		},+		{+			name: "SDK control characters", handshake: "sdk", version: "v1.2.3", insiders: true,+			clientInfo: &mcp.Implementation{Name: "editor(\x00)\\client\r\nX-Fake:1", Version: "1.0\tbeta\x7f"},+			want:       `github-mcp-server/v1.2.3 (editor\(\x00\)\\client\r\nX-Fake:1/1.0\tbeta\x7f) (insiders)`,+		},+		{+			name: "legacy control characters", handshake: "legacy", version: "v1.2.3",+			clientInfo: &mcp.Implementation{Name: "editor(\x00)\\client\r\nX-Fake:1", Version: "1.0\tbeta\x7f"},+			want:       `github-mcp-server/v1.2.3 (editor\(\x00\)\\client\r\nX-Fake:1/1.0\tbeta\x7f)`,+		},+		{+			name: "spaces and Unicode preserved", version: "v1.2.3",+			clientInfo: &mcp.Implementation{Name: "VS Code \u03b2", Version: "\u03b1 1.0"},+			want:       "github-mcp-server/v1.2.3 (VS Code \u03b2/\u03b1 1.0)",+		},+		{+			name: "empty client metadata", version: "v1.2.3",+			clientInfo: &mcp.Implementation{},+			want:       "github-mcp-server/v1.2.3 (/)",+		},+		{+			name: "quoted client metadata", version: "v1.2.3",+			clientInfo: &mcp.Implementation{Name: `"Editor"`, Version: `v"1`},+			want:       `github-mcp-server/v1.2.3 (\"Editor\"/v\"1)`,+		},+	}++	for _, tt := range tests {+		t.Run(tt.name, func(t *testing.T) {+			t.Parallel()+			ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+			defer cancel()++			headers := make(chan http.Header, 2)+			api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+				headers <- r.Header.Clone()+				w.Header().Set("Content-Type", "application/json")+				_, _ = w.Write([]byte(`{"data":{"repository":{"isPrivate":false,"issues":{"nodes":[],"totalCount":0,"pageInfo":{"hasNextPage":false,"endCursor":""}}}}}`))+			}))+			defer api.Close()++			cfg := github.MCPServerConfig{+				Version: tt.version, Token: "fixture-token", InsidersMode: tt.insiders,+				Translator: translations.NullTranslationHelper, Logger: discardLogger(),+			}+			clients, err := createGitHubClients(cfg, newStaticAPIHostResolver(t, api.URL))+			require.NoError(t, err)+			obs, err := observability.NewExporters(cfg.Logger, metrics.NewNoopMetrics())+			require.NoError(t, err)+			deps := github.NewBaseDeps(+				clients.rest, clients.gql, clients.raw, nil, cfg.Translator,+				github.FeatureFlags{}, 5000, createFeatureChecker(nil, tt.insiders), obs,+			)+			inv, err := github.NewInventory(cfg.Translator).+				WithToolsets([]string{}).WithTools([]string{"list_issues"}).Build()+			require.NoError(t, err)+			server, err := github.NewMCPServer(ctx, &cfg, deps, inv)+			require.NoError(t, err)+			server.AddReceivingMiddleware(addUserAgentsMiddleware(cfg))+			var initialized atomic.Bool+			server.AddReceivingMiddleware(func(next mcp.MethodHandler) mcp.MethodHandler {+				return func(ctx context.Context, method string, req mcp.Request) (mcp.Result, error) {+					if method == "initialize" {+						initialized.Store(true)+					}+					return next(ctx, method, req)+				}+			})++			serverConn, clientConn := net.Pipe()+			defer clientConn.Close()+			require.NoError(t, clientConn.SetDeadline(time.Now().Add(10*time.Second)))+			session, err := server.Connect(ctx, &mcp.IOTransport{Reader: serverConn, Writer: serverConn}, nil)+			require.NoError(t, err)+			defer session.Close()+			params := &mcp.CallToolParams{+				Name: "list_issues", Arguments: map[string]any{"owner": "owner", "repo": "repo"},+			}+			var changedClient bool+			if tt.handshake == "sdk" {+				client := mcp.NewClient(tt.clientInfo, nil)+				cs, err := client.Connect(ctx, &mcp.IOTransport{Reader: clientConn, Writer: clientConn}, nil)+				require.NoError(t, err)+				defer cs.Close()+				assert.Equal(t, "2026-07-28", cs.InitializeResult().ProtocolVersion)+				result, err := cs.CallTool(ctx, params)+				require.NoError(t, err)+				require.False(t, result.IsError, "%+v", result.Content)+			} else {+				encoder, decoder := json.NewEncoder(clientConn), json.NewDecoder(clientConn)+				id := 0+				call := func(method string, params any) json.RawMessage {+					t.Helper()+					id+++					require.NoError(t, encoder.Encode(map[string]any{+						"jsonrpc": "2.0", "id": id, "method": method, "params": params,+					}))+					var response struct {+						Result json.RawMessage `json:"result"`+						Error  json.RawMessage `json:"error"`+					}+					require.NoError(t, decoder.Decode(&response))+					require.Empty(t, response.Error)+					return response.Result+				}+				if tt.handshake == "legacy" {+					call("initialize", &mcp.InitializeParams{+						ProtocolVersion: "2025-11-25", Capabilities: &mcp.ClientCapabilities{},+						ClientInfo: tt.clientInfo,+					})+					require.NoError(t, encoder.Encode(map[string]any{+						"jsonrpc": "2.0", "method": "notifications/initialized",+					}))+				} else {+					params.Meta = mcp.Meta{+						mcp.MetaKeyProtocolVersion: "2026-07-28", mcp.MetaKeyClientCapabilities: map[string]any{},+					}+					if tt.clientInfo != nil {+						params.Meta[mcp.MetaKeyClientInfo] = tt.clientInfo+					}+				}+				var result mcp.CallToolResult+				require.NoError(t, json.Unmarshal(call("tools/call", params), &result))+				require.False(t, result.IsError, "%+v", result.Content)+				if tt.handshake != "legacy" {+					params.Meta[mcp.MetaKeyClientInfo] = &mcp.Implementation{Name: "other-client", Version: "7.8.9"}+					require.NoError(t, json.Unmarshal(call("tools/call", params), &result))+					require.False(t, result.IsError, "%+v", result.Content)+					changedClient = true+				}+			}++			assert.Equal(t, tt.handshake == "legacy", initialized.Load())+			select {+			case header := <-headers:+				assert.Equal(t, tt.want, header.Get("User-Agent"))+				assert.Equal(t, "Bearer fixture-token", header.Get("Authorization"))+				assert.Equal(t, "issue_fields, repo_issue_fields", header.Get("GraphQL-Features"))+			case <-ctx.Done():+				t.Fatal("GraphQL request did not reach the local HTTP server")+			}+			if changedClient {+				want := "github-mcp-server/" + tt.version + " (other-client/7.8.9)"+				if tt.insiders {+					want += " (insiders)"+				}+				assert.Equal(t, want, (<-headers).Get("User-Agent"))+			}+		})+	}+}
cmd/github-mcp-server/version_test.go+122 −0
@@ -0,0 +1,122 @@+package main++import (+	"runtime/debug"+	"strings"+	"testing"++	"github.com/stretchr/testify/assert"+)++func TestResolveServerVersion(t *testing.T) {+	t.Parallel()+	sha := strings.Repeat("a1", 20)+	otherSHA := strings.Repeat("b2", 20)+	source := &debug.BuildInfo{+		Main: debug.Module{Version: "(devel)"},+		Settings: []debug.BuildSetting{+			{Key: "vcs.revision", Value: sha}, {Key: "vcs.modified", Value: "false"},+		},+	}+	dirty := &debug.BuildInfo{+		Main: debug.Module{Version: "(devel)"},+		Settings: []debug.BuildSetting{+			{Key: "vcs.revision", Value: sha}, {Key: "vcs.modified", Value: "true"},+		},+	}+	tests := []struct {+		name     string+		release  string+		revision string+		info     *debug.BuildInfo+		want     string+	}{+		{name: "release unchanged", release: "v1.2.3", revision: sha, info: dirty, want: "v1.2.3"},+		{name: "release suffix unchanged", release: "v1.2.3-rc.1+build.4", want: "v1.2.3-rc.1+build.4"},+		{name: "release before invalid revision", release: "v1.2.3", revision: "short", info: dirty, want: "v1.2.3"},+		{name: "source build", release: "version", revision: "commit", info: source, want: "vcs-" + sha},+		{+			name: "source revision before inferred module version", release: "version", revision: "commit",+			info: &debug.BuildInfo{+				Main:     debug.Module{Version: "v1.2.4-0.20260916095829-a1a1a1a1a1a1+dirty"},+				Settings: dirty.Settings,+			},+			want: "vcs-" + sha + "-dirty",+		},+		{name: "dirty source", release: "version", revision: "commit", info: dirty, want: "vcs-" + sha + "-dirty"},+		{name: "Docker revision", release: "dev", revision: sha, want: "vcs-" + sha},+		{name: "Docker revision ignores context dirty state", release: "dev", revision: sha, info: dirty, want: "vcs-" + sha},+		{name: "linked revision ignores unrelated dirty state", release: "dev", revision: otherSHA, info: dirty, want: "vcs-" + otherSHA},+		{name: "linked revision precedence", release: "dev", revision: otherSHA, info: source, want: "vcs-" + otherSHA},+		{name: "SHA256", release: "dev", revision: strings.Repeat("ab", 32), want: "vcs-" + strings.Repeat("ab", 32)},+		{name: "canonical hex", release: "dev", revision: strings.ToUpper(sha), want: "vcs-" + sha},+		{name: "installed module", info: &debug.BuildInfo{Main: debug.Module{Version: "v1.2.3"}}, want: "v1.2.3"},+		{name: "absent build info", release: "version", revision: "commit", want: "dev"},+		{name: "missing VCS metadata", release: "dev", info: &debug.BuildInfo{}, want: "dev"},+		{name: "unknown placeholder", release: "unknown", want: "dev"},+		{name: "short revision", release: "dev", revision: "abcdef", want: "dev"},+		{name: "short revision falls through to VCS", release: "dev", revision: "abcdef", info: source, want: "vcs-" + sha},+		{name: "malformed linked revision falls through to VCS", release: "dev", revision: strings.Repeat("x", 40), info: source, want: "vcs-" + sha},+		{name: "malformed linked revision without VCS", release: "dev", revision: strings.Repeat("x", 40), want: "dev"},+		{+			name: "malformed VCS falls through to installed module",+			info: &debug.BuildInfo{+				Main:     debug.Module{Version: "v1.2.3"},+				Settings: []debug.BuildSetting{{Key: "vcs.revision", Value: "short"}},+			},+			want: "v1.2.3",+		},+		{+			name: "malformed VCS without installed module",+			info: &debug.BuildInfo{+				Main:     debug.Module{Version: "(devel)"},+				Settings: []debug.BuildSetting{{Key: "vcs.revision", Value: "short"}},+			},+			want: "dev",+		},+		{name: "invalid installed module", info: &debug.BuildInfo{Main: debug.Module{Version: "v1.2.3\n"}}, want: "dev"},+		{name: "placeholder installed module", info: &debug.BuildInfo{Main: debug.Module{Version: "(devel)"}}, want: "dev"},+		{name: "release whitespace", release: "v1.2.3 extra", want: "dev"},+		{name: "release newline", release: "v1.2.3\n", want: "dev"},+		{name: "release slash", release: "release/v1.2.3", want: "dev"},+		{name: "release non ASCII", release: "v1.2.3-\u00e9", want: "dev"},+		{name: "invalid release falls through to linked revision", release: "v1.2.3 extra", revision: otherSHA, info: dirty, want: "vcs-" + otherSHA},+		{name: "invalid release falls through to dirty VCS", release: "release/v1.2.3", info: dirty, want: "vcs-" + sha + "-dirty"},+	}+	for _, tt := range tests {+		t.Run(tt.name, func(t *testing.T) {+			assert.Equal(t, tt.want, resolveServerVersion(tt.release, tt.revision, tt.info))+		})+	}+}++func TestResolveServerVersionSkipsNullRevisions(t *testing.T) {+	t.Parallel()+	for _, revision := range []string{strings.Repeat("0", 40), strings.Repeat("0", 64)} {+		for _, modified := range []string{"false", "true"} {+			for _, linked := range []bool{false, true} {+				name := revision + "/modified=" + modified+				if linked {+					name += "/linked"+				}+				t.Run(name, func(t *testing.T) {+					info := &debug.BuildInfo{Settings: []debug.BuildSetting{+						{Key: "vcs.revision", Value: revision},+						{Key: "vcs.modified", Value: modified},+					}}+					commit := "commit"+					want := "dev"+					if linked {+						commit = revision+						info.Settings[0].Value = strings.Repeat("ab", 20)+						want = "vcs-" + strings.Repeat("ab", 20)+						if modified == "true" {+							want += "-dirty"+						}+					}+					assert.Equal(t, want, resolveServerVersion("dev", commit, info))+				})+			}+		}+	}+}
internal/ghmcp/server.go+35 −43
@@ -8,6 +8,7 @@ import ( 	"net/http" 	"os" 	"os/signal"+	"strconv" 	"strings" 	"syscall" 	"time"@@ -33,12 +34,10 @@ import (  // githubClients holds all the GitHub API clients created for a server instance. type githubClients struct {-	rest         *gogithub.Client-	restUATransp *transport.UserAgentTransport-	gql          *githubv4.Client-	gqlHTTP      *http.Client // retained for middleware to modify transport-	raw          *raw.Client-	repoAccess   *lockdown.RepoAccessCache+	rest       *gogithub.Client+	gql        *githubv4.Client+	raw        *raw.Client+	repoAccess *lockdown.RepoAccessCache }  // createGitHubClients creates all the GitHub API clients needed by the server.@@ -90,7 +89,7 @@ func createGitHubClients(cfg github.MCPServerConfig, apiHost utils.APIHostResolv 	// client per request (see pkg/github RequestDeps) and does not use this path. 	restUATransport := &transport.UserAgentTransport{ 		Transport: &transport.ETagTransport{Transport: http.DefaultTransport},-		Agent:     fmt.Sprintf("github-mcp-server/%s", cfg.Version),+		Agent:     stdioUserAgent(cfg, nil), 	} 	restClient, err := newRESTClient(cfg, restUATransport, restURL.String(), uploadURL.String(), allowedHosts) 	if err != nil {@@ -102,7 +101,10 @@ func createGitHubClients(cfg github.MCPServerConfig, apiHost utils.APIHostResolv 	gqlHTTPClient := &http.Client{ 		Transport: &transport.BearerAuthTransport{ 			Transport: &transport.GraphQLFeaturesTransport{-				Transport: http.DefaultTransport,+				Transport: &transport.UserAgentTransport{+					Transport: http.DefaultTransport,+					Agent:     stdioUserAgent(cfg, nil),+				}, 			}, 			Token:         cfg.Token, 			TokenProvider: cfg.TokenProvider,@@ -117,7 +119,7 @@ func createGitHubClients(cfg github.MCPServerConfig, apiHost utils.APIHostResolv 	// be large and are streamed rather than retained in memory. 	rawUATransport := &transport.UserAgentTransport{ 		Transport: http.DefaultTransport,-		Agent:     fmt.Sprintf("github-mcp-server/%s", cfg.Version),+		Agent:     stdioUserAgent(cfg, nil), 	} 	rawRESTClient, err := newRESTClient(cfg, rawUATransport, restURL.String(), uploadURL.String(), allowedHosts) 	if err != nil {@@ -141,12 +143,10 @@ func createGitHubClients(cfg github.MCPServerConfig, apiHost utils.APIHostResolv 	}  	return &githubClients{-		rest:         restClient,-		restUATransp: restUATransport,-		gql:          gqlClient,-		gqlHTTP:      gqlHTTPClient,-		raw:          rawClient,-		repoAccess:   repoAccessCache,+		rest:       restClient,+		gql:        gqlClient,+		raw:        rawClient,+		repoAccess: repoAccessCache, 	}, nil } @@ -232,7 +232,7 @@ func NewStdioMCPServer(ctx context.Context, cfg github.MCPServerConfig) (*mcp.Se 		return nil, fmt.Errorf("failed to create GitHub MCP server: %w", err) 	} -	ghServer.AddReceivingMiddleware(addUserAgentsMiddleware(cfg, clients.restUATransp, clients.gqlHTTP))+	ghServer.AddReceivingMiddleware(addUserAgentsMiddleware(cfg))  	return ghServer, nil }@@ -441,36 +441,28 @@ func createFeatureChecker(enabledFeatures []string, insidersMode bool) inventory 	} } -func addUserAgentsMiddleware(cfg github.MCPServerConfig, restUATransp *transport.UserAgentTransport, gqlHTTPClient *http.Client) func(next mcp.MethodHandler) mcp.MethodHandler {+func stdioUserAgent(cfg github.MCPServerConfig, client *mcp.Implementation) string {+	agent := fmt.Sprintf("github-mcp-server/%s", cfg.Version)+	if client != nil {+		comment := strconv.Quote(client.Name + "/" + client.Version)+		comment = comment[1 : len(comment)-1]+		comment = strings.NewReplacer("(", `\(`, ")", `\)`).Replace(comment)+		agent += " (" + comment + ")"+	}+	if cfg.InsidersMode {+		agent += " (insiders)"+	}+	return agent+}++func addUserAgentsMiddleware(cfg github.MCPServerConfig) func(next mcp.MethodHandler) mcp.MethodHandler { 	return func(next mcp.MethodHandler) mcp.MethodHandler { 		return func(ctx context.Context, method string, request mcp.Request) (result mcp.Result, err error) {-			if method != "initialize" {-				return next(ctx, method, request)-			}--			initializeRequest, ok := request.(*mcp.InitializeRequest)-			if !ok {-				return next(ctx, method, request)+			var client *mcp.Implementation+			if info, ok := request.(interface{ ClientInfo() *mcp.Implementation }); ok {+				client = info.ClientInfo() 			}--			message := initializeRequest-			userAgent := fmt.Sprintf(-				"github-mcp-server/%s (%s/%s)",-				cfg.Version,-				message.Params.ClientInfo.Name,-				message.Params.ClientInfo.Version,-			)-			if cfg.InsidersMode {-				userAgent += " (insiders)"-			}--			restUATransp.Agent = userAgent--			gqlHTTPClient.Transport = &transport.UserAgentTransport{-				Transport: gqlHTTPClient.Transport,-				Agent:     userAgent,-			}-+			ctx = transport.WithUserAgent(ctx, stdioUserAgent(cfg, client)) 			return next(ctx, method, request) 		} 	}

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

Supporting evidence

Reviewed 27 Nov 2026Revision 8aac24dd96bb9 changed files+560 −48Judge score 5/5
Approved · 0 retained findingsvitejs/vite#21626

feat: support bundled dev mode in ssr

Input

PR author’s description

<!-- - What is this PR solving? Write a clear and concise description. - Reference the issues it solves (e.g. `fixes #123`). - What other alternatives have you explored? - Are there any parts you think require more…

PR diff

Current GitHub diff ↗
packages/vite/src/node/ssr/fetchModule.ts · patch excerpt
-import { pathToFileURL } from 'node:url'+import path from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'
Browse 30 changed files
packages/vite/src/node/ssr/fetchModule.ts+210 −8
@@ -1,15 +1,24 @@-import { pathToFileURL } from 'node:url'+import path from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url' import type { FetchResult } from 'vite/module-runner'-import type { EnvironmentModuleNode, TransformResult } from '..'+import type { TransformResult } from '..' import {   MODULE_RUNNER_SOURCEMAPPING_SOURCE,   SOURCEMAPPING_URL, } from '../../shared/constants'-import { encodeSourceURL, unwrapId } from '../../shared/utils'+import type { ViteFetchResult } from '../../shared/invokeMethods'+import { cleanUrl, encodeSourceURL, unwrapId } from '../../shared/utils' import { tryNodeResolve } from '../plugins/resolve'+import type { BundledDev } from '../server/bundledDev' import type { DevEnvironment } from '../server/environment' import { genSourceMapUrl } from '../server/sourcemap'-import { isBuiltin, isExternalUrl, isFilePathESM } from '../utils'+import {+  isBuiltin,+  isExternalUrl,+  isFilePathESM,+  normalizePath,+} from '../utils'+import { ssrTransform } from './ssrTransform'  export interface FetchModuleOptions {   cached?: boolean@@ -43,7 +52,13 @@ export async function fetchModule(    // if there is no importer, the file is an entry point   // entry points are always internalized-  if (!isFileUrl && importer && url[0] !== '.' && url[0] !== '/') {+  if (+    !isFileUrl &&+    importer &&+    url[0] !== '.' &&+    url[0] !== '/' &&+    !isBundledChunkUrl(environment, url)+  ) {     const { isProduction, root } = environment.config     const { externalConditions, dedupe, preserveSymlinks } =       environment.config.resolve@@ -80,6 +95,12 @@ export async function fetchModule(    url = unwrapId(url) +  const bundledDev = environment.bundledDev++  if (bundledDev) {+    return fetchBundledModule(environment, bundledDev, url, importer, options)+  }+   const mod = await environment.moduleGraph.ensureEntryFromUrl(url)   const cached = !!mod.transformResult @@ -99,7 +120,7 @@ export async function fetchModule(   }    if (options.inlineSourceMap !== false) {-    result = inlineSourceMap(mod, result, options.startOffset)+    result = inlineSourceMap(mod.id!, result, options.startOffset)   }    // remove shebang@@ -115,13 +136,153 @@ export async function fetchModule(   } } +async function fetchBundledModule(+  environment: DevEnvironment,+  bundledDev: BundledDev,+  url: string,+  importer: string | undefined,+  options: FetchModuleOptions,+) {+  await bundledDev._waitForInitialBuildSuccess()++  if (url.startsWith('/@vite/lazy?')) {+    const { searchParams } = new URL(url, 'http://localhost')+    const moduleId = searchParams.get('id')!+    const clientId = searchParams.get('clientId')!+    const lazyResult = await bundledDev.triggerLazyBundling(moduleId, clientId)+    if (lazyResult == null) {+      throw new Error(`unknown request: ${url}`)+    }+    // This module is invalidated immediately, so url/id do not matter+    const result: ViteFetchResult = {+      code: lazyResult.code,+      url,+      id: moduleId!,+      file: cleanUrl(moduleId!),+      invalidate: false,+    }++    // See https://github.com/rolldown/rolldown/issues/8376+    const ssrResult = await ssrTransform(+      result.code,+      lazyResult.sourcemap ? JSON.parse(lazyResult.sourcemap) : null,+      url,+      result.code,+    )+    if (!ssrResult) {+      throw new Error(`[vite] cannot apply ssr transform to '${url}'.`)+    }+    result.code = ssrResult.code+    if (options.inlineSourceMap !== false) {+      result.code = inlineSourceMap(+        result.id,+        ssrResult,+        options.startOffset,+      ).code+    }+    return result+  }++  const outDir = normalizePath(+    path.resolve(environment.config.root, environment.config.build.outDir),+  )++  let fileName: string+  let facadeId: string | undefined++  // Assume this is an entry point that was specified in rolldownOptions.input+  if (!importer) {+    const resolvedEntry = await resolveBundledEntryFilename(+      bundledDev,+      environment.config.root,+      url,+    )+    if (!resolvedEntry) {+      const entrypoints = [...bundledDev.facadeToChunk.keys()]+      throw new Error(+        `[vite] Entrypoint '${url}' was not defined in the config. ` ++          (entrypoints.length+            ? `Available entry points: \n- ${[...bundledDev.facadeToChunk.keys()].join('\n- ')}`+            : `The build did not produce any chunks. Did it finish successfully? See the logs for more information.`),+      )+    }+    ;[facadeId, fileName] = resolvedEntry+  } else if (url[0] === '.') {+    // Importer is reported as a full path on the file system.+    // This happens because we provide the `file` attribute.+    if (importer.startsWith(outDir)) {+      importer = importer.slice(outDir.length + 1)+    }+    fileName = path.posix.join(path.posix.dirname(importer), url)+  } else {+    fileName = url+  }++  const memoryFile = bundledDev.memoryFiles.get(fileName)+  const code = memoryFile?.source+  if (code == null) {+    throw new Error(+      `[vite] the module '${url}' (chunk '${fileName}') ${+        importer ? ` imported from '${importer}'` : ''+      } was not bundled. Is server established?`,+    )+  }+  const map = memoryFile?.sourcemapPath+    ? bundledDev.memoryFiles.get(memoryFile.sourcemapPath)?.source.toString()+    : undefined+  const result: ViteFetchResult = {+    code: code.toString(),+    // To make sure dynamic imports resolve assets correctly.+    // (Dynamic import resolves relative urls with importer url)+    url: fileName,+    id: fileName,+    // The potential position on the file system.+    // We don't actually keep it there, it's virtual.+    file: normalizePath(path.resolve(outDir, fileName)),+    // chunks cannot be invalidated manually+    invalidate: false,+    // TODO: seems like rolldown uses `process.cwd()` instead of `config.root`+    // We need this because __rolldown_runtime__ keeps modules internally+    // And after HMR there is no other way to receive the updated exports+    rolldownModuleId: facadeId+      ? normalizePath(path.relative(process.cwd(), facadeId))+      : undefined,+  }+  // TODO: this should be done in rolldown, there is already a function for it+  // output.format = 'module-runner'+  // See https://github.com/rolldown/rolldown/issues/8376+  const ssrResult = await ssrTransform(+    result.code,+    map ? JSON.parse(map) : null,+    result.file!,+    result.code,+  )+  if (!ssrResult) {+    throw new Error(`[vite] cannot apply ssr transform to '${url}'.`)+  }+  result.code = ssrResult.code+  if (options.inlineSourceMap !== false) {+    result.code = inlineSourceMap(+      result.id,+      ssrResult,+      options.startOffset,+    ).code+  }++  // remove shebang+  if (result.code[0] === '#')+    result.code = result.code.replace(/^#!.*/, (s) => ' '.repeat(s.length))++  return result+}+ const OTHER_SOURCE_MAP_REGEXP = new RegExp(   `//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`,   'gm', )  function inlineSourceMap(-  mod: EnvironmentModuleNode,+  id: string,   result: TransformResult,   startOffset: number | undefined, ) {@@ -147,8 +308,49 @@ function inlineSourceMap(       }     : map   result.code = `${code.trimEnd()}\n//# sourceURL=${encodeSourceURL(-    mod.id!,+    id,   )}\n${MODULE_RUNNER_SOURCEMAPPING_SOURCE}\n//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)}\n`    return result }++function isBundledChunkUrl(environment: DevEnvironment, url: string) {+  return environment.bundledDev?.memoryFiles.has(url)+}++async function resolveBundledEntryFilename(+  environment: BundledDev,+  root: string,+  url: string,+): Promise<[facadeId: string | undefined, chunkName: string] | undefined> {+  if (environment.memoryFiles.has(url)) {+    return [undefined, url]+  }+  // Already resolved by the user to be a url+  if (environment.facadeToChunk.has(url)) {+    return [url, environment.facadeToChunk.get(url)!]+  }+  const facadeId = await environment.resolveEntryFacade(url)+  if (facadeId && environment.facadeToChunk.has(facadeId)) {+    return [facadeId, environment.facadeToChunk.get(facadeId)!]+  }+  const moduleId = normalizePath(+    url.startsWith('file://')+      ? // new URL(path)+        fileURLToPath(url)+      : // ./index.js+        // NOTE: we don't try to find it if extension is not passed+        // It will throw an error instead+        path.resolve(root, url),+  )+  if (environment.facadeToChunk.get(moduleId)) {+    return [moduleId, environment.facadeToChunk.get(moduleId)!]+  }+  if (url[0] === '/') {+    const tryAbsoluteUrl = path.posix.join(root, url)+    const absoluteChunk = environment.facadeToChunk.get(tryAbsoluteUrl)+    if (absoluteChunk) {+      return [tryAbsoluteUrl, absoluteChunk]+    }+  }+}
packages/vite/src/node/ssr/runtime/__tests__/server-runtime.spec.ts+316 −161
packages/vite/src/node/ssr/runtime/__tests__/utils.ts+96 −88
@@ -1,101 +1,109 @@ import fs from 'node:fs' import { dirname, resolve } from 'node:path' import { fileURLToPath } from 'node:url'-import { onTestFinished, test } from 'vitest'+import { test as base, onTestFinished } from 'vitest' import type { InlineConfig } from '../../../config' import type { ViteDevServer } from '../../../server' import { createServer } from '../../../server'-import type { ServerModuleRunnerOptions } from '../serverModuleRunner'-import { createServerModuleRunner } from '../serverModuleRunner'+import type { RunnableDevEnvironment } from '../../../server/environments/runnableEnvironment'+import {+  type ServerModuleRunnerOptions,+  createServerModuleRunner,+} from '../serverModuleRunner' -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -- infer the fixture context from the builder-export function createModuleRunnerTester(-  config: InlineConfig = {},-  runnerConfig: ServerModuleRunnerOptions = {},-) {-  function waitForWatcher(server: ViteDevServer) {-    return new Promise<void>((resolve) => {-      if ((server.watcher as any)._readyEmitted) {-        resolve()-      } else {-        server.watcher.once('ready', () => resolve())-      }-    })-  }--  return (-    test-      // eslint-disable-next-line no-empty-pattern-      .extend('server', async ({}, { onCleanup }) => {-        // @ts-ignore-        globalThis.__HMR__ = {}--        const server = await createServer({-          root: import.meta.dirname,-          logLevel: 'error',-          server: {-            middlewareMode: true,-            watch: null,-            ws: false,-          },-          ssr: {-            external: ['@vitejs/cjs-external', '@vitejs/esm-external'],-          },-          optimizeDeps: {-            disabled: true,-            noDiscovery: true,-            include: [],+export const runnerTest = base+  .extend('fullBundle', [] as string[])+  .extend('runnerOptions', undefined as ServerModuleRunnerOptions | undefined)+  .extend('config', {} as InlineConfig)+  .extend('server', async ({ config, fullBundle }, { onCleanup }) => {+    const server = await createServer({+      configFile: false,+      root: import.meta.dirname,+      logLevel: 'error',+      ssr: {+        external: ['@vitejs/cjs-external', '@vitejs/esm-external'],+      },+      environments: {+        ssr: {+          isBundled: fullBundle.length > 0,+        },+      },+      build: {+        rolldownOptions: {+          input: fullBundle,+          ...config.build?.rolldownOptions,+        },+        ...config.build,+      },+      optimizeDeps: {+        disabled: true,+        noDiscovery: true,+        include: [],+      },+      plugins: [+        {+          name: 'vite-plugin-virtual',+          resolveId(id) {+            if (id === 'virtual0:test') {+              return `\0virtual:test`+            }+            if (id === 'virtual:test') {+              return 'virtual:test'+            }+            if (id === 'virtual:normal') {+              return '\0' + id+            }           },-          plugins: [-            {-              name: 'vite-plugin-virtual',-              resolveId(id) {-                if (id === 'virtual0:test') {-                  return `\0virtual:test`-                }-                if (id === 'virtual:test') {-                  return 'virtual:test'-                }-                if (id === 'virtual:normal') {-                  return '\0' + id-                }-              },-              load(id) {-                if (id === `\0virtual:test`) {-                  return `export const msg = 'virtual0'`-                }-                if (id === `virtual:test`) {-                  return `export const msg = 'virtual'`-                }-                if (id === '\0virtual:normal') {-                  return 'export default "ok"'-                }-              },-            },-            ...(config.plugins ?? []),-          ],-          ...config,-        })-        onCleanup(() => server.close())-        return server-      })-      .extend('environment', ({ server }) => server.environments.ssr)-      .extend('runner', async ({ server, environment }, { onCleanup }) => {-        const runner = createServerModuleRunner(environment, {-          hmr: {-            logger: false,+          load(id) {+            if (id === `\0virtual:test`) {+              return `export const msg = 'virtual0'`+            }+            if (id === `virtual:test`) {+              return `export const msg = 'virtual'`+            }+            if (id === '\0virtual:normal') {+              return 'export default "ok"'+            }           },-          // don't override by default so Vitest source maps are correct-          sourcemapInterceptor: false,-          ...runnerConfig,-        })-        onCleanup(() => runner.close())-        if (config.server?.watch) {-          await waitForWatcher(server)-        }-        return runner-      })+        },+        ...(config.plugins ?? []),+      ],+      ...config,+      server: {+        middlewareMode: true,+        watch: null,+        ws: false,+        hmr: false,+        ...config.server,+      },+    })+    onCleanup(() => server.close())+    if (config.server?.watch) {+      await waitForWatcher(server)+    }+    return server+  })+  .extend(+    'environment',+    ({ server }) => server.environments.ssr as RunnableDevEnvironment,   )+  .extend('runner', ({ environment, runnerOptions }, { onCleanup }) => {+    if (runnerOptions) {+      const runner = createServerModuleRunner(environment, runnerOptions)+      onCleanup(() => runner.close())+      return runner+    }+    return environment.runner+  })++function waitForWatcher(server: ViteDevServer) {+  return new Promise<void>((resolve) => {+    if ((server.watcher as any)._readyEmitted) {+      resolve()+    } else {+      server.watcher.once('ready', () => resolve())+    }+  }) }  type FixtureEditor = {

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observation did not become a verified finding.

Evidence and perspectives

  • Observation · Test strategyThe new HMR test suite extends coverage to a mode (full bundle mode) not documented in the codebase; test setup uses test augmentation rather than explicit config, creating intention risk for the bundled-dev feature set without corresponding structural documentation.

    Recorded file packages/vite/src/node/ssr/runtime/__tests__/server-hmr.spec.ts · no line recorded

Supporting evidence

Reviewed 27 Nov 2026Revision b574e505f52b30 changed files+1641 −349Judge score 5/5
Approved · 0 retained findingsclap-rs/clap#6455

feat(complete): Expose possible value completers

Input

PR author’s description

Inspired by #6452

PR diff

Current GitHub diff ↗
clap_complete/src/engine/complete.rs · patch excerpt
+use super::ValueCandidates;
Browse 3 changed files
clap_complete/src/engine/complete.rs+40 −32
@@ -7,7 +7,9 @@ use super::ArgValueCandidates; use super::ArgValueCompleter; use super::CompletionCandidate; use super::SubcommandCandidates;+use super::ValueCandidates; use super::custom::complete_path;+use super::custom::possible_value_candidates;  /// Complete the given command, shell-agnostic pub fn complete(@@ -359,17 +361,16 @@ fn complete_arg_value(     if let Some(completer) = arg.get::<ArgValueCompleter>() {         values.extend(completer.complete_at(arg_index, value_os));     } else if let Some(completer) = arg.get::<ArgValueCandidates>() {-        values.extend(complete_custom_arg_value(value_os, completer));+        values.extend(complete_value_candidates(+            value_os,+            completer.value_candidates(),+        ));     } else if let Some(possible_values) = possible_values(arg) {         if let Ok(value) = value {-            values.extend(possible_values.into_iter().filter_map(|p| {-                let name = p.get_name();-                name.starts_with(value).then(|| {-                    CompletionCandidate::new(OsString::from(name))-                        .help(p.get_help().cloned())-                        .hide(p.is_hide_set())-                })-            }));+            values.extend(complete_candidates_str(+                value,+                possible_value_candidates(possible_values),+            ));         }     } else {         match arg.get_value_hint() {@@ -438,17 +439,36 @@ fn rsplit_delimiter<'s, 'o>(     Some((Some(prefix), Ok(value))) } -fn complete_custom_arg_value(+fn complete_value_candidates(     value: &OsStr,-    completer: &ArgValueCandidates,+    completer: &dyn ValueCandidates, ) -> Vec<CompletionCandidate> {-    debug!("complete_custom_arg_value: completer={completer:?}, value={value:?}");+    debug!("complete_value_candidates: value={value:?}");      let mut values = completer.candidates();     values.retain(|comp| comp.get_value().starts_with(&value.to_string_lossy()));     values } +fn complete_candidates_str(+    value: &str,+    mut values: Vec<CompletionCandidate>,+) -> Vec<CompletionCandidate> {+    debug!("complete_candidates_str: value={value:?}");++    values.retain(|comp| comp.get_value().starts_with(value));+    values+}++fn complete_value_candidates_str(+    value: &str,+    completer: &dyn ValueCandidates,+) -> Vec<CompletionCandidate> {+    debug!("complete_value_candidates_str: value={value:?}");++    complete_candidates_str(value, completer.candidates())+}+ fn complete_subcommand(value: &str, cmd: &clap::Command) -> Vec<CompletionCandidate> {     debug!(         "complete_subcommand: cmd={:?}, value={:?}",@@ -463,7 +483,10 @@ fn complete_subcommand(value: &str, cmd: &clap::Command) -> Vec<CompletionCandid     if cmd.is_allow_external_subcommands_set() {         let external_completer = cmd.get::<SubcommandCandidates>();         if let Some(completer) = external_completer {-            scs.extend(complete_external_subcommand(value, completer));+            scs.extend(complete_value_candidates_str(+                value,+                completer.value_candidates(),+            ));         }     } @@ -472,21 +495,6 @@ fn complete_subcommand(value: &str, cmd: &clap::Command) -> Vec<CompletionCandid     scs } -fn complete_external_subcommand(-    value: &str,-    completer: &SubcommandCandidates,-) -> Vec<CompletionCandidate> {-    debug!("complete_custom_arg_value: completer={completer:?}, value={value:?}");--    let mut values = Vec::new();-    let custom_arg_values = completer.candidates();-    values.extend(custom_arg_values);--    values.retain(|comp| comp.get_value().starts_with(value));--    values-}- /// Gets all the long options, their visible aliases and flags of a [`clap::Command`] with formatted `--` prefix. /// Includes `help` and `version` depending on the [`clap::Command`] settings. fn longs_and_visible_aliases(p: &clap::Command) -> Vec<CompletionCandidate> {@@ -556,13 +564,13 @@ fn populate_arg_candidate(candidate: CompletionCandidate, arg: &clap::Arg) -> Co }  /// Get the possible values for completion-fn possible_values(a: &clap::Arg) -> Option<Vec<clap::builder::PossibleValue>> {+fn possible_values(+    a: &clap::Arg,+) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {     if !a.get_num_args().expect("built").takes_values() {         None     } else {-        a.get_value_parser()-            .possible_values()-            .map(|pvs| pvs.collect())+        a.get_value_parser().possible_values()     } } 
clap_complete/src/engine/custom.rs+45 −0
@@ -1,5 +1,6 @@ use std::any::type_name; use std::ffi::OsStr;+use std::ffi::OsString; use std::sync::Arc;  use clap::builder::ArgExt;@@ -155,6 +156,10 @@ impl ArgValueCandidates {     pub fn candidates(&self) -> Vec<CompletionCandidate> {         self.0.candidates()     }++    pub(crate) fn value_candidates(&self) -> &dyn ValueCandidates {+        &*self.0+    } }  impl std::fmt::Debug for ArgValueCandidates {@@ -199,6 +204,10 @@ impl SubcommandCandidates {     pub fn candidates(&self) -> Vec<CompletionCandidate> {         self.0.candidates()     }++    pub(crate) fn value_candidates(&self) -> &dyn ValueCandidates {+        &*self.0+    } }  impl std::fmt::Debug for SubcommandCandidates {@@ -416,3 +425,39 @@ fn path_has_name(path: &std::path::Path) -> bool {     let trailing = *trailing as char;     !std::path::is_separator(trailing) && path.file_name().is_some() }++/// Create [`CompletionCandidate`]s for [`clap::builder::PossibleValue`]+///+/// This is implicitly applied for arguments with either a [`clap::builder::PossibleValuesParser`] or [`clap::builder::EnumValueParser`].+///+/// Using this explicitly is intended for arguments that also accept other value formats that need+/// to be completed and the completer is eager ([`ValueCandidates`]).+/// For lazy completion, see [`complete_possible_values`].+pub fn possible_value_candidates(+    values: impl IntoIterator<Item = clap::builder::PossibleValue>,+) -> Vec<CompletionCandidate> {+    values+        .into_iter()+        .map(|p| {+            CompletionCandidate::new(OsString::from(p.get_name()))+                .help(p.get_help().cloned())+                .hide(p.is_hide_set())+        })+        .collect()+}++/// Create [`CompletionCandidate`]s for [`clap::builder::PossibleValue`]+///+/// This is implicitly applied for arguments with either a [`clap::builder::PossibleValuesParser`] or [`clap::builder::EnumValueParser`].+///+/// Using this explicitly is intended for arguments that also accept other value formats that need+/// to be completed and the completer is lazy ([`ValueCompleter`]).+/// For eager completion, see [`possible_value_candidates`].+pub fn complete_possible_values(+    value: &OsStr,+    values: impl IntoIterator<Item = clap::builder::PossibleValue>,+) -> Vec<CompletionCandidate> {+    let mut values = possible_value_candidates(values);+    values.retain(|comp| comp.get_value().starts_with(&value.to_string_lossy()));+    values+}
clap_complete/src/engine/mod.rs+2 −0
@@ -14,3 +14,5 @@ pub use custom::PathCompleter; pub use custom::SubcommandCandidates; pub use custom::ValueCandidates; pub use custom::ValueCompleter;+pub use custom::complete_possible_values;+pub use custom::possible_value_candidates;

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens advisories (not part of the checked findings):

  • historical_risk: The changed code refactors 'complete_custom_arg_value' to 'complete_value_candidates' and 'complete_candidates_str', and changes this function's signature from taking 'ArgValueCandidates' to '&dyn ValueCandidates', meaning the public API is being modified at an unstable registry index.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Historical riskThe changed code refactors 'complete_custom_arg_value' to 'complete_value_candidates' and 'complete_candidates_str', and changes this function's signature from taking 'ArgValueCandidates' to '&dyn ValueCandidates', meaning the public API is being modified at an unstable registry index.

    Recorded location clap_complete/src/engine/complete.rs:441

  • Observation · Dependency blast radiusThe change introduces a new public dependency boundary by calling `complete_candidates_str` and `complete_value_candidates` which accept `&dyn ValueCandidates`, exposing the `ValueCandidates` trait to callers that previously only used `ArgValueCandidates`.

    Recorded location clap_complete/src/engine/complete.rs:14

Supporting evidence

Reviewed 27 Nov 2026Revision 2550f328b0c43 changed files+87 −32Judge score 5/5
Approved · 0 retained findingsdrizzle-team/drizzle-orm#6543

Build drizzle-kit as ESM only and share chunks between entry points

Input

PR author’s description

drizzle-kit now builds as ESM only, and all entry points share code through chunks. The build is two tsdown runs: one emits the JavaScript for bin, index, cli, api-* and payload/*, and one emits declarations…

PR diff

Current GitHub diff ↗
drizzle-kit/scripts/check-skills-revision.ts · patch excerpt
-const REPO_ROOT = resolve(__dirname, '..', '..');-const SKILLS_DIR = resolve(__dirname, '..', 'skills');+const REPO_ROOT = resolve(import.meta.dirname, '..', '..');+const SKILLS_DIR = resolve(import.meta.dirname, '..', 'skills');
Browse 21 changed files
drizzle-kit/scripts/check-skills-revision.ts+2 −2
@@ -3,8 +3,8 @@ import { existsSync } from 'node:fs'; import { resolve } from 'node:path'; import { parseSkillsRevision, readSkillsRevisionFromDisk } from './lib/read-skills-revision'; -const REPO_ROOT = resolve(__dirname, '..', '..');-const SKILLS_DIR = resolve(__dirname, '..', 'skills');+const REPO_ROOT = resolve(import.meta.dirname, '..', '..');+const SKILLS_DIR = resolve(import.meta.dirname, '..', 'skills'); const UMBRELLA_RELPATH = 'drizzle-kit/skills/drizzle/SKILL.md';  const sh = (cmd: string, args: string[]) => spawnSync(cmd, args, { cwd: REPO_ROOT, encoding: 'utf8' });
drizzle-kit/scripts/build.ts+47 −251
@@ -1,7 +1,7 @@ #!/usr/bin/env bun-import { existsSync, rmSync } from 'node:fs';+import { rmSync } from 'node:fs'; import * as fs from 'node:fs/promises';-import { rolldown } from 'rolldown';+import { createRequire } from 'node:module'; import { build as tsdown } from 'tsdown'; import pkg from '../package.json'; import { readSkillsRevisionFromDisk } from './lib/read-skills-revision';@@ -33,265 +33,61 @@ const driversPackages = [ 	'@duckdb/node-api', ]; -const external = [-	/^drizzle-orm\/?/,-	...driversPackages,-];--async function buildBundle(options: {-	name: string;-	input: string;-	outputName: string;-	format: 'cjs' | 'esm';-	banner?: string;-}) {-	const build = await rolldown({-		input: options.input,-		platform: 'node',-		external,-		tsconfig: 'tsconfig.json',-	});--	await build.write({-		dir: 'dist',-		format: options.format,-		entryFileNames: options.outputName,-		codeSplitting: false,-		banner: options.banner,-	});--	await build.close();-	console.log(`  Built ${options.outputName}`);-}--async function buildCli() {-	const build = await rolldown({-		input: './src/cli/index.ts',-		platform: 'node',-		external,-		tsconfig: 'tsconfig.json',-	});--	await build.write({-		dir: 'dist',-		format: 'cjs',-		entryFileNames: 'bin.cjs',-		banner: '#!/usr/bin/env node',-		codeSplitting: false,-	});--	await build.close();--	const binContent = await fs.readFile('dist/bin.cjs', 'utf8');-	const patched = binContent-		.replace(/process\.env\.DRIZZLE_KIT_VERSION/g, JSON.stringify(pkg.version))-		.replace(/process\.env\.DRIZZLE_KIT_SKILLS_REVISION/g, JSON.stringify(readSkillsRevisionFromDisk('./skills')));-	await fs.writeFile('dist/bin.cjs', patched);--	console.log('  Built bin.cjs');-}--// tsdown's `emitDtsOnly: true` still emits chunked .js files alongside the-// declarations. If tsdown writes to ./dist it overwrites rolldown's clean-// single-file bundles and produces a CJS entry that fails to load. Direct-// tsdown's output at a temp dir and copy only .d.ts / .d.mts back into ./dist.-const TSDOWN_TEMP_DIR = './dist/__dts-temp';--async function buildDeclarations() {-	// Use tsdown for declaration bundling - it handles path resolution and creates bundled .d.ts files-	await tsdown({-		entry: { index: './src/index.ts', cli: './src/cli-sdk/index.ts' },-		outDir: TSDOWN_TEMP_DIR,-		external: [...driversPackages, /^drizzle-orm\/?/],-		dts: { emitDtsOnly: true },-		format: ['cjs', 'es'],-		logLevel: 'silent',-		clean: false,-		outExtensions: (ctx) => {-			if (ctx.format === 'cjs') {-				return { dts: '.d.ts', js: '.js' };-			}-			return { dts: '.d.mts', js: '.mjs' };-		},-	});--	await tsdown({-		entry: {-			'api-postgres': './src/ext/api-postgres.ts',-			'api-mysql': './src/ext/api-mysql.ts',-			'api-sqlite': './src/ext/api-sqlite.ts',-			'payload-postgres': './src/payload/postgres.ts',-			'payload-mysql': './src/payload/mysql.ts',-			'payload-sqlite': './src/payload/sqlite.ts',-			'payload-mssql': './src/payload/mssql.ts',-		},-		outDir: TSDOWN_TEMP_DIR,-		external: ['drizzle-orm', ...driversPackages, /^drizzle-orm\/?/],-		dts: { emitDtsOnly: true },-		format: ['cjs', 'es'],-		logLevel: 'silent',-		clean: false,-		outExtensions: (ctx) => {-			if (ctx.format === 'cjs') {-				return { dts: '.d.ts', js: '.js' };-			}-			return { dts: '.d.mts', js: '.mjs' };-		},-	});--	console.log('  Built declarations');-}--async function copyDeclarationsAndCleanTemp() {-	const entries = await fs.readdir(TSDOWN_TEMP_DIR);-	await Promise.all(-		entries-			.filter((f) => f.endsWith('.d.ts') || f.endsWith('.d.mts'))-			.map((f) => fs.copyFile(`${TSDOWN_TEMP_DIR}/${f}`, `dist/${f}`)),-	);-	rmSync(TSDOWN_TEMP_DIR, { recursive: true, force: true });-}--async function postProcessApiFiles() {-	const apiFiles = [-		'dist/api-postgres.js',-		'dist/api-mysql.js',-		'dist/api-sqlite.js',-		'dist/payload-postgres.js',-		'dist/payload-mysql.js',-		'dist/payload-sqlite.js',-		'dist/payload-mssql.js',-	];-	await Promise.all(-		apiFiles.map(async (file) => {-			if (existsSync(file)) {-				const content = await fs.readFile(file, 'utf8');-				await fs.writeFile(file, content.replace(/await import\(/g, 'require('));-			}-		}),-	);-}+// The key of each entry is its export subpath, so `drizzle-kit/payload/postgres` resolves to+// `./payload/postgres.js` through the `./payload/*` pattern in package.json.+const entries = {+	index: './src/index.ts',+	cli: './src/cli-sdk/index.ts',+	'api-postgres': './src/ext/api-postgres.ts',+	'api-mysql': './src/ext/api-mysql.ts',+	'api-sqlite': './src/ext/api-sqlite.ts',+	'payload/postgres': './src/payload/postgres.ts',+	'payload/mysql': './src/payload/mysql.ts',+	'payload/sqlite': './src/payload/sqlite.ts',+	'payload/mssql': './src/payload/mssql.ts',+};++const commonOptions = {+	outDir: 'dist',+	format: 'esm',+	platform: 'node',+	fixedExtension: false,+	clean: false,+	deps: { neverBundle: [/^drizzle-orm\/?/, ...driversPackages] },+	outputOptions: { chunkFileNames: 'chunks/[name]-[hash].js' },+} satisfies Parameters<typeof tsdown>[0];  async function main() { 	const startTime = Date.now(); 	rmSync('dist', { recursive: true, force: true });  	await Promise.all([-		buildCli(),-		buildBundle({-			name: 'index-cjs',-			input: './src/index.ts',-			outputName: 'index.js',-			format: 'cjs',-		}),-		buildBundle({-			name: 'index-esm',-			input: './src/index.ts',-			outputName: 'index.mjs',-			format: 'esm',-		}),-		buildBundle({-			name: 'api-postgres-cjs',-			input: './src/ext/api-postgres.ts',-			outputName: 'api-postgres.js',-			format: 'cjs',-		}),-		buildBundle({-			name: 'api-postgres-esm',-			input: './src/ext/api-postgres.ts',-			outputName: 'api-postgres.mjs',-			format: 'esm',-		}),-		buildBundle({-			name: 'api-mysql-cjs',-			input: './src/ext/api-mysql.ts',-			outputName: 'api-mysql.js',-			format: 'cjs',-		}),-		buildBundle({-			name: 'api-mysql-esm',-			input: './src/ext/api-mysql.ts',-			outputName: 'api-mysql.mjs',-			format: 'esm',-		}),-		buildBundle({-			name: 'api-sqlite-cjs',-			input: './src/ext/api-sqlite.ts',-			outputName: 'api-sqlite.js',-			format: 'cjs',-		}),-		buildBundle({-			name: 'api-sqlite-esm',-			input: './src/ext/api-sqlite.ts',-			outputName: 'api-sqlite.mjs',-			format: 'esm',-		}),-		buildBundle({-			name: 'cli-cjs',-			input: './src/cli-sdk/index.ts',-			outputName: 'cli.js',-			format: 'cjs',-		}),-		buildBundle({-			name: 'cli-esm',-			input: './src/cli-sdk/index.ts',-			outputName: 'cli.mjs',-			format: 'esm',-		}),-		buildBundle({-			name: 'payload-postgres-cjs',-			input: './src/payload/postgres.ts',-			outputName: 'payload-postgres.js',-			format: 'cjs',-		}),-		buildBundle({-			name: 'payload-postgres-esm',-			input: './src/payload/postgres.ts',-			outputName: 'payload-postgres.mjs',-			format: 'esm',-		}),-		buildBundle({-			name: 'payload-mysql-cjs',-			input: './src/payload/mysql.ts',-			outputName: 'payload-mysql.js',-			format: 'cjs',-		}),-		buildBundle({-			name: 'payload-mysql-esm',-			input: './src/payload/mysql.ts',-			outputName: 'payload-mysql.mjs',-			format: 'esm',-		}),-		buildBundle({-			name: 'payload-sqlite-cjs',-			input: './src/payload/sqlite.ts',-			outputName: 'payload-sqlite.js',-			format: 'cjs',-		}),-		buildBundle({-			name: 'payload-sqlite-esm',-			input: './src/payload/sqlite.ts',-			outputName: 'payload-sqlite.mjs',-			format: 'esm',-		}),-		buildBundle({-			name: 'payload-mssql-cjs',-			input: './src/payload/mssql.ts',-			outputName: 'payload-mssql.js',-			format: 'cjs',-		}),-		buildBundle({-			name: 'payload-mssql-esm',-			input: './src/payload/mssql.ts',-			outputName: 'payload-mssql.mjs',-			format: 'esm',+		tsdown({+			...commonOptions,+			entry: { bin: './src/cli/index.ts', ...entries },+			// Bundled CommonJS dependencies read `__dirname` and `__filename`, which ESM does not define.+			shims: true,+			// The ESM entry of jiti loads its Babel transform through `createRequire`, which the bundler cannot+			// follow. The CommonJS entry uses a plain `require`, so the transform is bundled.+			alias: { jiti: createRequire(import.meta.url).resolve('jiti') },+			define: {+				'process.env.DRIZZLE_KIT_VERSION': JSON.stringify(pkg.version),+				'process.env.DRIZZLE_KIT_NODE_RANGE': JSON.stringify(pkg.engines.node),+				'process.env.DRIZZLE_KIT_SKILLS_REVISION': JSON.stringify(readSkillsRevisionFromDisk('./skills')),+			},+			banner: ({ fileName }) => fileName === 'bin.js' ? '#!/usr/bin/env node' : undefined,+			dts: false,+		}),+		// Declarations are built for the public entries only. Building them together with `bin` adds a+		// declaration for every module that only `bin` reaches, and no export points to `bin`.+		tsdown({+			...commonOptions,+			entry: entries,+			dts: { emitDtsOnly: true }, 		}),-		buildDeclarations(), 	]); -	await copyDeclarationsAndCleanTemp(); 	await Promise.all([-		postProcessApiFiles(), 		fs.copyFile('package.json', 'dist/package.json'), 		fs.cp('skills', 'dist/skills', { recursive: true }), 	]);
drizzle-kit/build.ts+0 −238
@@ -1,238 +0,0 @@-/// <reference types="bun-types" />-import * as esbuild from 'esbuild';-import { readFileSync, writeFileSync } from 'node:fs';-import * as tsup from 'tsup';-import pkg from './package.json';-import { readSkillsRevisionFromDisk } from './scripts/lib/read-skills-revision';--const driversPackages = [-	// postgres drivers-	'pg',-	'postgres',-	'@vercel/postgres',-	'@neondatabase/serverless',-	'@electric-sql/pglite',-	// dsql drivers-	'@aws/aurora-dsql-node-postgres-connector',-	'@aws/aurora-dsql-postgresjs-connector',-	//  mysql drivers-	'mysql2',-	'@planetscale/database',-	// sqlite drivers-	'@libsql/client',-	'better-sqlite3',-	'bun:sqlite',-	'@sqlitecloud/drivers',-	'@tursodatabase/database',-	'bun',-	// duckdb drivers-	'duckdb',-	'@duckdb/node-api',-	// aws drivers-	'@aws-sdk/client-rds-data', // https://github.com/drizzle-team/drizzle-orm/issues/5050-];--esbuild.buildSync({-	entryPoints: ['./src/cli/index.ts'],-	bundle: true,-	outfile: 'dist/bin.cjs',-	format: 'cjs',-	target: 'node16',-	platform: 'node',-	define: {-		'process.env.DRIZZLE_KIT_VERSION': `"${pkg.version}"`,-		'process.env.DRIZZLE_KIT_SKILLS_REVISION': `"${readSkillsRevisionFromDisk('./skills')}"`,-	},-	external: [-		'esbuild',-		'drizzle-orm',-		...driversPackages,-	],-	banner: {-		js: `#!/usr/bin/env node`,-	},-});--const main = async () => {-	await tsup.build({-		entryPoints: ['./src/index.ts'],-		outDir: './dist',-		external: driversPackages,-		splitting: false,-		dts: true,-		format: ['cjs', 'esm'],-		outExtension: (ctx) => {-			if (ctx.format === 'cjs') {-				return {-					dts: '.d.ts',-					js: '.js',-				};-			}-			return {-				dts: '.d.mts',-				js: '.mjs',-			};-		},-	});--	await tsup.build({-		entryPoints: ['./src/ext/api-postgres.ts', './src/ext/api-mysql.ts', './src/ext/api-sqlite.ts'],-		outDir: './dist',-		external: [-			'esbuild',-			'drizzle-orm',-			...driversPackages,-		],-		splitting: false,-		dts: true,-		format: ['cjs', 'esm'],-		banner: (ctx) => {-			/**-			 * fix dynamic require in ESM ("glob" -> "fs.realpath" requires 'fs' module)-			 * @link https://github.com/drizzle-team/drizzle-orm/issues/2853-			 */-			if (ctx.format === 'esm') {-				return {-					js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);",-				};-			}-			return;-		},-		outExtension: (ctx) => {-			if (ctx.format === 'cjs') {-				return {-					dts: '.d.ts',-					js: '.js',-				};-			}-			return {-				dts: '.d.mts',-				js: '.mjs',-			};-		},-	});--	writeFileSync(-		'./dist/api-postgres.js',-		readFileSync('./dist/api-postgres.js', 'utf8').replace(/await import\(/g, 'require('),-	);--	// await tsup.build({-	// 	entryPoints: [],-	// 	outDir: './dist',-	// 	external: ['bun:sqlite'],-	// 	splitting: false,-	// 	dts: true,-	// 	format: ['cjs', 'esm'],-	// 	banner: (ctx) => {-	// 		/**-	// 		 * fix dynamic require in ESM ("glob" -> "fs.realpath" requires 'fs' module)-	// 		 * @link https://github.com/drizzle-team/drizzle-orm/issues/2853-	// 		 */-	// 		if (ctx.format === 'esm') {-	// 			return {-	// 				js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);",-	// 			};-	// 		}-	// 		return;-	// 	},-	// 	outExtension: (ctx) => {-	// 		if (ctx.format === 'cjs') {-	// 			return {-	// 				dts: '.d.ts',-	// 				js: '.js',-	// 			};-	// 		}-	// 		return {-	// 			dts: '.d.mts',-	// 			js: '.mjs',-	// 		};-	// 	},-	// });--	writeFileSync(-		'./dist/api-mysql.js',-		readFileSync('./dist/api-mysql.js', 'utf8').replace(/await import\(/g, 'require('),-	);--	// await tsup.build({-	// 	entryPoints: [],-	// 	outDir: './dist',-	// 	external: ['bun:sqlite'],-	// 	splitting: false,-	// 	dts: true,-	// 	format: ['cjs', 'esm'],-	// 	banner: (ctx) => {-	// 		/**-	// 		 * fix dynamic require in ESM ("glob" -> "fs.realpath" requires 'fs' module)-	// 		 * @link https://github.com/drizzle-team/drizzle-orm/issues/2853-	// 		 */-	// 		if (ctx.format === 'esm') {-	// 			return {-	// 				js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);",-	// 			};-	// 		}-	// 		return;-	// 	},-	// 	outExtension: (ctx) => {-	// 		if (ctx.format === 'cjs') {-	// 			return {-	// 				dts: '.d.ts',-	// 				js: '.js',-	// 			};-	// 		}-	// 		return {-	// 			dts: '.d.mts',-	// 			js: '.mjs',-	// 		};-	// 	},-	// });--	writeFileSync(-		'./dist/api-sqlite.js',-		readFileSync('./dist/api-sqlite.js', 'utf8').replace(/await import\(/g, 'require('),-	);--	// await tsup.build({-	// 	entryPoints: ['./src/ext/api-singlestore.ts'],-	// 	outDir: './dist',-	// 	external: ['bun:sqlite'],-	// 	splitting: false,-	// 	dts: true,-	// 	format: ['cjs', 'esm'],-	// 	banner: (ctx) => {-	// 		/**-	// 		 * fix dynamic require in ESM ("glob" -> "fs.realpath" requires 'fs' module)-	// 		 * @link https://github.com/drizzle-team/drizzle-orm/issues/2853-	// 		 */-	// 		if (ctx.format === 'esm') {-	// 			return {-	// 				js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);",-	// 			};-	// 		}-	// 		return;-	// 	},-	// 	outExtension: (ctx) => {-	// 		if (ctx.format === 'cjs') {-	// 			return {-	// 				dts: '.d.ts',-	// 				js: '.js',-	// 			};-	// 		}-	// 		return {-	// 			dts: '.d.mts',-	// 			js: '.mjs',-	// 		};-	// 	},-	// });--	// writeFileSync(-	// 	'./dist/api-singlestore.js',-	// 	readFileSync('./dist/api-singlestore.js', 'utf8').replace(/await import\(/g, 'require('),-	// );-};--main().catch((e) => {-	console.error(e);-	process.exit(1);-});

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · DeliveryThe removed `await tsdown(...)` call at drizzle-kit/scripts/build.ts:60 makes the build operation fire-and-forget, so build errors are not caught and artifacts may be incomplete or missing, breaking the delivery path.

    Principle · Plan Rollout, Abort and Recovery

    Recorded location drizzle-kit/scripts/build.ts:60

  • Observation · Failure HandlingRemoved await on tsdown(…) makes tsdown errors fire-and-forget, converting failures into silent success and violating fail-fast by suppressing observable errors.

    Principle · Keep Failure Visible to the Caller

    Recorded location drizzle-kit/scripts/build.ts:60

Supporting evidence

Reviewed 27 Nov 2026Revision ad53f54f9f4621 changed files+204 −858Judge score 5/5
Approved · 0 retained findingsgithub/github-mcp-server#2941

Support singular Project Issue Field updates

Input

PR author’s description

Summary

Adds focused attached Issue Field support to singular update_project_item name-form writes. This PR is stacked on #2903.

PR diff

Current GitHub diff ↗
pkg/github/issues_granular.go · patch excerpt
+type setIssueFieldValueMutation struct {+	SetIssueFieldValue struct {+		Issue struct {+			ID  githubv4.ID
Browse 6 changed files
pkg/github/issues_granular.go+24 −30
@@ -1274,6 +1274,27 @@ type IssueFieldCreateOrUpdateInput struct { 	Suggest              *githubv4.Boolean `json:"suggest,omitempty"` } +type setIssueFieldValueMutation struct {+	SetIssueFieldValue struct {+		Issue struct {+			ID  githubv4.ID+			URL githubv4.String+		}+	} `graphql:"setIssueFieldValue(input: $input)"`+}++// SetIssueFieldValues updates Issue Field values and returns the updated issue.+func SetIssueFieldValues(ctx context.Context, gqlClient *githubv4.Client, input SetIssueFieldValueInput) (MinimalResponse, error) {+	var mutation setIssueFieldValueMutation+	if err := gqlClient.Mutate(ctx, &mutation, input, nil); err != nil {+		return MinimalResponse{}, err+	}+	return MinimalResponse{+		ID:  fmt.Sprintf("%v", mutation.SetIssueFieldValue.Issue.ID),+		URL: string(mutation.SetIssueFieldValue.Issue.URL),+	}, nil+}+ // GranularSetIssueFields creates a tool to set issue field values on an issue using GraphQL. func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.ServerTool { 	st := NewTool(@@ -1497,31 +1518,6 @@ func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.Serv 				return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to get issue", err), nil, nil 			} -			// Execute the setIssueFieldValue mutation-			var mutation struct {-				SetIssueFieldValue struct {-					Issue struct {-						ID     githubv4.ID-						Number githubv4.Int-						URL    githubv4.String-					}-					IssueFieldValues []struct {-						TextValue struct {-							Value string-						} `graphql:"... on IssueFieldTextValue"`-						SingleSelectValue struct {-							Name string-						} `graphql:"... on IssueFieldSingleSelectValue"`-						DateValue struct {-							Value string-						} `graphql:"... on IssueFieldDateValue"`-						NumberValue struct {-							Value float64-						} `graphql:"... on IssueFieldNumberValue"`-					}-				} `graphql:"setIssueFieldValue(input: $input)"`-			}- 			mutationInput := SetIssueFieldValueInput{ 				IssueID:     issueID, 				IssueFields: issueFields,@@ -1530,14 +1526,12 @@ func GranularSetIssueFields(t translations.TranslationHelperFunc) inventory.Serv 			// The rationale and suggest input fields on IssueFieldCreateOrUpdateInput 			// are gated behind the update_issue_suggestions GraphQL feature flag. 			ctxWithFeatures := ghcontext.WithGraphQLFeatures(ctx, "update_issue_suggestions")-			if err := gqlClient.Mutate(ctxWithFeatures, &mutation, mutationInput, nil); err != nil {+			response, err := SetIssueFieldValues(ctxWithFeatures, gqlClient, mutationInput)+			if err != nil { 				return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to set issue field values", err), nil, nil 			} -			r, err := json.Marshal(MinimalResponse{-				ID:  fmt.Sprintf("%v", mutation.SetIssueFieldValue.Issue.ID),-				URL: string(mutation.SetIssueFieldValue.Issue.URL),-			})+			r, err := json.Marshal(response) 			if err != nil { 				return utils.NewToolResultErrorFromErr("failed to marshal response", err), nil, nil 			}
pkg/github/projects.go+207 −31
@@ -10,6 +10,7 @@ import ( 	"strconv" 	"time" +	ghcontext "github.com/github/github-mcp-server/pkg/context" 	ghErrors "github.com/github/github-mcp-server/pkg/errors" 	"github.com/github/github-mcp-server/pkg/ifc" 	"github.com/github/github-mcp-server/pkg/inventory"@@ -1192,23 +1193,7 @@ func getProjectField(ctx context.Context, client *github.Client, owner, ownerTyp }  func getProjectItem(ctx context.Context, client *github.Client, owner, ownerType string, projectNumber int, itemID int64, fields []int64) (*mcp.CallToolResult, any, error) {-	var resp *github.Response-	var projectItem *github.ProjectV2Item-	var opts *github.GetProjectItemOptions-	var err error--	if len(fields) > 0 {-		opts = &github.GetProjectItemOptions{-			Fields: fields,-		}-	}--	if ownerType == "org" {-		projectItem, resp, err = client.Projects.GetOrganizationProjectItem(ctx, owner, projectNumber, itemID, opts)-	} else {-		projectItem, resp, err = client.Projects.GetUserProjectItem(ctx, owner, projectNumber, itemID, opts)-	}-+	projectItem, resp, err := fetchProjectItem(ctx, client, owner, ownerType, projectNumber, itemID, fields) 	if err != nil { 		return ghErrors.NewGitHubAPIErrorResponse(ctx, 			"failed to get project item",@@ -1234,8 +1219,29 @@ func getProjectItem(ctx context.Context, client *github.Client, owner, ownerType 	return utils.NewToolResultText(string(r)), nil, nil } +func fetchProjectItem(ctx context.Context, client *github.Client, owner, ownerType string, projectNumber int, itemID int64, fields []int64) (*github.ProjectV2Item, *github.Response, error) {+	var resp *github.Response+	var projectItem *github.ProjectV2Item+	var opts *github.GetProjectItemOptions+	var err error++	if len(fields) > 0 {+		opts = &github.GetProjectItemOptions{+			Fields: fields,+		}+	}++	if ownerType == "org" {+		projectItem, resp, err = client.Projects.GetOrganizationProjectItem(ctx, owner, projectNumber, itemID, opts)+	} else {+		projectItem, resp, err = client.Projects.GetUserProjectItem(ctx, owner, projectNumber, itemID, opts)+	}++	return projectItem, resp, err+}+ func updateProjectItem(ctx context.Context, client *github.Client, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int, itemID int64, fieldValue map[string]any) (*mcp.CallToolResult, any, error) {-	updatePayload, err := buildUpdateProjectItem(ctx, gqlClient, owner, ownerType, projectNumber, fieldValue)+	updatePayload, issueField, err := buildUpdateProjectItem(ctx, gqlClient, owner, ownerType, projectNumber, fieldValue) 	if err != nil { 		var structured *ghErrors.StructuredResolutionError 		if errors.As(err, &structured) {@@ -1244,6 +1250,47 @@ func updateProjectItem(ctx context.Context, client *github.Client, gqlClient *gi 		return utils.NewToolResultError(err.Error()), nil, nil 	} +	if issueField != nil {+		projectItem, resp, fetchErr := fetchProjectItem(ctx, client, owner, ownerType, projectNumber, itemID, nil)+		if fetchErr != nil {+			return ghErrors.NewGitHubAPIErrorResponse(ctx, "failed to get project item", resp, fetchErr), nil, nil+		}+		defer func() { _ = resp.Body.Close() }()+		if resp.StatusCode != http.StatusOK {+			body, readErr := io.ReadAll(resp.Body)+			if readErr != nil {+				return nil, nil, fmt.Errorf("failed to read response body: %w", readErr)+			}+			return ghErrors.NewGitHubAPIStatusErrorResponse(ctx, "failed to get project item", resp, body), nil, nil+		}++		issueID, resolveErr := projectItemIssueID(projectItem)+		if resolveErr != nil {+			var structured *ghErrors.StructuredResolutionError+			if errors.As(resolveErr, &structured) {+				return ghErrors.NewStructuredResolutionErrorResponse(structured), nil, nil+			}+			return utils.NewToolResultError(resolveErr.Error()), nil, nil+		}++		// The setIssueFieldValue mutation is gated behind the update_issue_suggestions+		// GraphQL feature flag, matching the set_issue_fields tool.+		ctxWithFeatures := ghcontext.WithGraphQLFeatures(ctx, "update_issue_suggestions")+		response, mutationErr := SetIssueFieldValues(ctxWithFeatures, gqlClient, SetIssueFieldValueInput{+			IssueID:     issueID,+			IssueFields: []IssueFieldCreateOrUpdateInput{*issueField},+		})+		if mutationErr != nil {+			return ghErrors.NewGitHubGraphQLErrorResponse(ctx, "failed to set issue field value", mutationErr), nil, nil+		}++		r, marshalErr := json.Marshal(response)+		if marshalErr != nil {+			return nil, nil, fmt.Errorf("failed to marshal response: %w", marshalErr)+		}+		return utils.NewToolResultText(string(r)), nil, nil+	}+ 	var resp *github.Response 	var updatedItem *github.ProjectV2Item @@ -1277,6 +1324,42 @@ func updateProjectItem(ctx context.Context, client *github.Client, gqlClient *gi 	return utils.NewToolResultText(string(r)), nil, nil } +func projectItemIssueID(item *github.ProjectV2Item) (githubv4.ID, error) {+	if item == nil {+		return nil, ghErrors.NewStructuredResolutionError(+			"missing_metadata",+			"",+			"project item metadata is missing",+			nil,+		)+	}++	contentType := ""+	if item.ContentType != nil {+		contentType = string(*item.ContentType)+	}+	if contentType != string(github.ProjectV2ItemContentTypeIssue) {+		return nil, ghErrors.NewStructuredResolutionError(+			"unsupported_item_type",+			contentType,+			"attached Issue Fields can only be updated on Issue project items",+			nil,+		)+	}++	content := item.GetContent()+	if content == nil || content.GetIssue() == nil || content.GetIssue().GetNodeID() == "" {+		return nil, ghErrors.NewStructuredResolutionError(+			"missing_metadata",+			contentType,+			"project Issue item is missing its Issue node ID",+			nil,+		)+	}++	return githubv4.ID(content.GetIssue().GetNodeID()), nil+}+ func deleteProjectItem(ctx context.Context, client *github.Client, owner, ownerType string, projectNumber int, itemID int64) (*mcp.CallToolResult, any, error) { 	var resp *github.Response 	var err error@@ -1614,25 +1697,25 @@ func validateAndConvertToInt64(value any) (int64, error) { 	} } -// buildUpdateProjectItem builds UpdateProjectItemOptions, resolving field names and SINGLE_SELECT option names server-side.-func buildUpdateProjectItem(ctx context.Context, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int, input map[string]any) (*github.UpdateProjectItemOptions, error) {+// buildUpdateProjectItem builds either a standard Project update or an attached Issue Field update.+func buildUpdateProjectItem(ctx context.Context, gqlClient *githubv4.Client, owner, ownerType string, projectNumber int, input map[string]any) (*github.UpdateProjectItemOptions, *IssueFieldCreateOrUpdateInput, error) { 	if input == nil {-		return nil, fmt.Errorf("updated_field must be an object")+		return nil, nil, fmt.Errorf("updated_field must be an object") 	}  	valueField, hasValue := input["value"] 	if !hasValue {-		return nil, fmt.Errorf("updated_field.value is required")+		return nil, nil, fmt.Errorf("updated_field.value is required") 	}  	idField, hasID := input["id"] 	nameField, hasName := input["name"]  	switch { 	case hasID && hasName:-		return nil, fmt.Errorf("updated_field must set either id or name, not both")+		return nil, nil, fmt.Errorf("updated_field must set either id or name, not both") 	case !hasID && !hasName:-		return nil, fmt.Errorf("updated_field requires either id or name")+		return nil, nil, fmt.Errorf("updated_field requires either id or name") 	}  	var (@@ -1644,24 +1727,37 @@ func buildUpdateProjectItem(ctx context.Context, gqlClient *githubv4.Client, own 		var err error 		fieldID, err = validateAndConvertToInt64(idField) 		if err != nil {-			return nil, fmt.Errorf("updated_field.id: %w", err)+			return nil, nil, fmt.Errorf("updated_field.id: %w", err) 		} 	} else { 		fieldName, ok := nameField.(string) 		if !ok || fieldName == "" {-			return nil, fmt.Errorf("updated_field.name must be a non-empty string")+			return nil, nil, fmt.Errorf("updated_field.name must be a non-empty string") 		} 		if gqlClient == nil {-			return nil, fmt.Errorf("internal error: gqlClient is required to resolve updated_field.name")+			return nil, nil, fmt.Errorf("internal error: gqlClient is required to resolve updated_field.name") 		} 		var err error 		resolved, err = resolveProjectFieldByName(ctx, gqlClient, owner, ownerType, projectNumber, fieldName, "") 		if err != nil {-			return nil, err+			return nil, nil, err+		}+		if supportsIssueFieldUpdate(resolved.DataType) {+			resolved, err = resolveIssueFieldForUpdate(ctx, gqlClient, owner, ownerType, projectNumber, resolved)+			if err != nil {+				return nil, nil, err+			}+			if resolved.IsIssueField {+				issueField, buildErr := buildIssueFieldUpdate(resolved, valueField)+				if buildErr != nil {+					return nil, nil, buildErr+				}+				return nil, issueField, nil+			} 		} 		parsedID, parseErr := parseInt64(resolved.ID) 		if parseErr != nil {-			return nil, fmt.Errorf("resolved field %q has non-numeric ID %q; pass updated_field.id directly", resolved.Name, resolved.ID)+			return nil, nil, fmt.Errorf("resolved field %q has non-numeric ID %q; pass updated_field.id directly", resolved.Name, resolved.ID) 		} 		fieldID = parsedID 	}@@ -1681,7 +1777,7 @@ func buildUpdateProjectItem(ctx context.Context, gqlClient *githubv4.Client, own 					} 				} 				if !known {-					return nil, optErr+					return nil, nil, optErr 				} 			} 		}@@ -1694,7 +1790,87 @@ func buildUpdateProjectItem(ctx context.Context, gqlClient *githubv4.Client, own 		}}, 	} -	return payload, nil+	return payload, nil, nil+}++func supportsIssueFieldUpdate(dataType string) bool {+	switch dataType {+	case "TEXT", "NUMBER", "DATE", "SINGLE_SELECT":+		return true+	default:+		return false+	}+}++func buildIssueFieldUpdate(field *ResolvedField, value any) (*IssueFieldCreateOrUpdateInput, error) {+	if !supportsIssueFieldUpdate(field.DataType) {+		return nil, ghErrors.NewStructuredResolutionError(+			"unsupported_field_type",+			field.Name,+			fmt.Sprintf("attached Issue Field %q has unsupported data type %q", field.Name, field.DataType),+			nil,+		)+	}++	if field.IssueFieldID == "" {+		return nil, ghErrors.NewStructuredResolutionError(+			"missing_field_metadata",+			field.Name,+			fmt.Sprintf("attached Issue Field %q is missing its Issue Field node ID", field.Name),+			nil,+		)+	}++	input := &IssueFieldCreateOrUpdateInput{FieldID: githubv4.ID(field.IssueFieldID)}+	if value == nil {+		input.Delete = githubv4.NewBoolean(githubv4.Boolean(true))+		return input, nil+	}++	switch field.DataType {+	case "TEXT":+		text, ok := value.(string)+		if !ok {+			return nil, invalidIssueFieldValue(field, "value must be a string")+		}+		input.TextValue = githubv4.NewString(githubv4.String(text))+	case "NUMBER":+		number, ok := toFloat64(value)+		if !ok {+			return nil, invalidIssueFieldValue(field, "value must be a number")+		}+		input.NumberValue = githubv4.NewFloat(githubv4.Float(number))+	case "DATE":+		date, ok := value.(string)+		if !ok {+			return nil, invalidIssueFieldValue(field, "value must be a date string in YYYY-MM-DD format")+		}+		if _, err := time.Parse(time.DateOnly, date); err != nil {+			return nil, invalidIssueFieldValue(field, "value must be a valid date in YYYY-MM-DD format")+		}+		input.DateValue = githubv4.NewString(githubv4.String(date))+	case "SINGLE_SELECT":+		optionName, ok := value.(string)+		if !ok || optionName == "" {+			return nil, invalidIssueFieldValue(field, "value must be a non-empty option name")+		}+		optionID, err := resolveSingleSelectOptionByName(field, optionName)+		if err != nil {+			return nil, err+		}+		input.SingleSelectOptionID = githubv4.NewID(githubv4.ID(optionID))+	}++	return input, nil+}++func invalidIssueFieldValue(field *ResolvedField, hint string) error {+	return ghErrors.NewStructuredResolutionError(+		"invalid_field_value",+		field.Name,+		fmt.Sprintf("invalid value for attached Issue Field %q: %s", field.Name, hint),+		nil,+	) }  func extractPaginationOptionsFromArgs(args map[string]any) (github.ListProjectsPaginationOptions, error) {
pkg/github/granular_tools_test.go+39 −156
@@ -1798,6 +1798,27 @@ func TestGranularUnresolveReviewThread(t *testing.T) { }  func TestGranularSetIssueFields(t *testing.T) {+	t.Run("mutation selects only issue identity", func(t *testing.T) {+		transport := &sequencedGraphQLTransport{+			t: t,+			responses: []func(capturedGraphQLRequest) (int, string){+				func(req capturedGraphQLRequest) (int, string) {+					assert.Contains(t, req.Query, "issue{id,url}")+					assert.NotContains(t, req.Query, "issueFieldValues")+					assert.NotContains(t, req.Query, "number")+					return http.StatusOK, `{"data":{"setIssueFieldValue":{"issue":{"id":"ISSUE_123","url":"https://github.com/owner/repo/issues/5"}}}}`+				},+			},+		}+		_, err := SetIssueFieldValues(context.Background(), githubv4.NewClient(&http.Client{Transport: transport}), SetIssueFieldValueInput{+			IssueID: githubv4.ID("ISSUE_123"),+			IssueFields: []IssueFieldCreateOrUpdateInput{{+				FieldID: githubv4.ID("FIELD_1"), TextValue: githubv4.NewString("hello"),+			}},+		})+		require.NoError(t, err)+	})+ 	t.Run("successful set with text value", func(t *testing.T) { 		matchers := []githubv4mock.Matcher{ 			// Mock the issue ID query@@ -1822,29 +1843,7 @@ func TestGranularSetIssueFields(t *testing.T) { 			), 			// Mock the setIssueFieldValue mutation 			githubv4mock.NewMutationMatcher(-				struct {-					SetIssueFieldValue struct {-						Issue struct {-							ID     githubv4.ID-							Number githubv4.Int-							URL    githubv4.String-						}-						IssueFieldValues []struct {-							TextValue struct {-								Value string-							} `graphql:"... on IssueFieldTextValue"`-							SingleSelectValue struct {-								Name string-							} `graphql:"... on IssueFieldSingleSelectValue"`-							DateValue struct {-								Value string-							} `graphql:"... on IssueFieldDateValue"`-							NumberValue struct {-								Value float64-							} `graphql:"... on IssueFieldNumberValue"`-						}-					} `graphql:"setIssueFieldValue(input: $input)"`-				}{},+				setIssueFieldValueMutation{}, 				SetIssueFieldValueInput{ 					IssueID: githubv4.ID("ISSUE_123"), 					IssueFields: []IssueFieldCreateOrUpdateInput{@@ -1858,9 +1857,8 @@ func TestGranularSetIssueFields(t *testing.T) { 				githubv4mock.DataResponse(map[string]any{ 					"setIssueFieldValue": map[string]any{ 						"issue": map[string]any{-							"id":     "ISSUE_123",-							"number": 5,-							"url":    "https://github.com/owner/repo/issues/5",+							"id":  "ISSUE_123",+							"url": "https://github.com/owner/repo/issues/5", 						}, 					}, 				}),@@ -1997,29 +1995,7 @@ func TestGranularSetIssueFields(t *testing.T) { 				}), 			), 			githubv4mock.NewMutationMatcher(-				struct {-					SetIssueFieldValue struct {-						Issue struct {-							ID     githubv4.ID-							Number githubv4.Int-							URL    githubv4.String-						}-						IssueFieldValues []struct {-							TextValue struct {-								Value string-							} `graphql:"... on IssueFieldTextValue"`-							SingleSelectValue struct {-								Name string-							} `graphql:"... on IssueFieldSingleSelectValue"`-							DateValue struct {-								Value string-							} `graphql:"... on IssueFieldDateValue"`-							NumberValue struct {-								Value float64-							} `graphql:"... on IssueFieldNumberValue"`-						}-					} `graphql:"setIssueFieldValue(input: $input)"`-				}{},+				setIssueFieldValueMutation{}, 				SetIssueFieldValueInput{ 					IssueID: githubv4.ID("ISSUE_123"), 					IssueFields: []IssueFieldCreateOrUpdateInput{@@ -2034,9 +2010,8 @@ func TestGranularSetIssueFields(t *testing.T) { 				githubv4mock.DataResponse(map[string]any{ 					"setIssueFieldValue": map[string]any{ 						"issue": map[string]any{-							"id":     "ISSUE_123",-							"number": 5,-							"url":    "https://github.com/owner/repo/issues/5",+							"id":  "ISSUE_123",+							"url": "https://github.com/owner/repo/issues/5", 						}, 					}, 				}),@@ -2111,29 +2086,7 @@ func TestGranularSetIssueFields(t *testing.T) { 				}), 			), 			githubv4mock.NewMutationMatcher(-				struct {-					SetIssueFieldValue struct {-						Issue struct {-							ID     githubv4.ID-							Number githubv4.Int-							URL    githubv4.String-						}-						IssueFieldValues []struct {-							TextValue struct {-								Value string-							} `graphql:"... on IssueFieldTextValue"`-							SingleSelectValue struct {-								Name string-							} `graphql:"... on IssueFieldSingleSelectValue"`-							DateValue struct {-								Value string-							} `graphql:"... on IssueFieldDateValue"`-							NumberValue struct {-								Value float64-							} `graphql:"... on IssueFieldNumberValue"`-						}-					} `graphql:"setIssueFieldValue(input: $input)"`-				}{},+				setIssueFieldValueMutation{}, 				SetIssueFieldValueInput{ 					IssueID: githubv4.ID("ISSUE_123"), 					IssueFields: []IssueFieldCreateOrUpdateInput{@@ -2148,9 +2101,8 @@ func TestGranularSetIssueFields(t *testing.T) { 				githubv4mock.DataResponse(map[string]any{ 					"setIssueFieldValue": map[string]any{ 						"issue": map[string]any{-							"id":     "ISSUE_123",-							"number": 5,-							"url":    "https://github.com/owner/repo/issues/5",+							"id":  "ISSUE_123",+							"url": "https://github.com/owner/repo/issues/5", 						}, 					}, 				}),@@ -2225,29 +2177,7 @@ func TestGranularSetIssueFields(t *testing.T) { 				}), 			), 			githubv4mock.NewMutationMatcher(-				struct {-					SetIssueFieldValue struct {-						Issue struct {-							ID     githubv4.ID-							Number githubv4.Int-							URL    githubv4.String-						}-						IssueFieldValues []struct {-							TextValue struct {-								Value string-							} `graphql:"... on IssueFieldTextValue"`-							SingleSelectValue struct {-								Name string-							} `graphql:"... on IssueFieldSingleSelectValue"`-							DateValue struct {-								Value string-							} `graphql:"... on IssueFieldDateValue"`-							NumberValue struct {-								Value float64-							} `graphql:"... on IssueFieldNumberValue"`-						}-					} `graphql:"setIssueFieldValue(input: $input)"`-				}{},+				setIssueFieldValueMutation{}, 				SetIssueFieldValueInput{ 					IssueID: githubv4.ID("ISSUE_123"), 					IssueFields: []IssueFieldCreateOrUpdateInput{@@ -2262,9 +2192,8 @@ func TestGranularSetIssueFields(t *testing.T) { 				githubv4mock.DataResponse(map[string]any{ 					"setIssueFieldValue": map[string]any{ 						"issue": map[string]any{-							"id":     "ISSUE_123",-							"number": 5,-							"url":    "https://github.com/owner/repo/issues/5",+							"id":  "ISSUE_123",+							"url": "https://github.com/owner/repo/issues/5", 						}, 					}, 				}),@@ -2316,29 +2245,7 @@ func TestGranularSetIssueFields(t *testing.T) { 				}), 			), 			githubv4mock.NewMutationMatcher(-				struct {-					SetIssueFieldValue struct {-						Issue struct {-							ID     githubv4.ID-							Number githubv4.Int-							URL    githubv4.String-						}-						IssueFieldValues []struct {-							TextValue struct {-								Value string-							} `graphql:"... on IssueFieldTextValue"`-							SingleSelectValue struct {-								Name string-							} `graphql:"... on IssueFieldSingleSelectValue"`-							DateValue struct {-								Value string-							} `graphql:"... on IssueFieldDateValue"`-							NumberValue struct {-								Value float64-							} `graphql:"... on IssueFieldNumberValue"`-						}-					} `graphql:"setIssueFieldValue(input: $input)"`-				}{},+				setIssueFieldValueMutation{}, 				SetIssueFieldValueInput{ 					IssueID: githubv4.ID("ISSUE_123"), 					IssueFields: []IssueFieldCreateOrUpdateInput{@@ -2354,9 +2261,8 @@ func TestGranularSetIssueFields(t *testing.T) { 				githubv4mock.DataResponse(map[string]any{ 					"setIssueFieldValue": map[string]any{ 						"issue": map[string]any{-							"id":     "ISSUE_123",-							"number": 5,-							"url":    "https://github.com/owner/repo/issues/5",+							"id":  "ISSUE_123",+							"url": "https://github.com/owner/repo/issues/5", 						}, 					}, 				}),@@ -2408,29 +2314,7 @@ func TestGranularSetIssueFields(t *testing.T) { 				}), 			), 			githubv4mock.NewMutationMatcher(-				struct {-					SetIssueFieldValue struct {-						Issue struct {-							ID     githubv4.ID-							Number githubv4.Int-							URL    githubv4.String-						}-						IssueFieldValues []struct {-							TextValue struct {-								Value string-							} `graphql:"... on IssueFieldTextValue"`-							SingleSelectValue struct {-								Name string-							} `graphql:"... on IssueFieldSingleSelectValue"`-							DateValue struct {-								Value string-							} `graphql:"... on IssueFieldDateValue"`-							NumberValue struct {-								Value float64-							} `graphql:"... on IssueFieldNumberValue"`-						}-					} `graphql:"setIssueFieldValue(input: $input)"`-				}{},+				setIssueFieldValueMutation{}, 				SetIssueFieldValueInput{ 					IssueID: githubv4.ID("ISSUE_123"), 					IssueFields: []IssueFieldCreateOrUpdateInput{@@ -2444,9 +2328,8 @@ func TestGranularSetIssueFields(t *testing.T) { 				githubv4mock.DataResponse(map[string]any{ 					"setIssueFieldValue": map[string]any{ 						"issue": map[string]any{-							"id":     "ISSUE_123",-							"number": 5,-							"url":    "https://github.com/owner/repo/issues/5",+							"id":  "ISSUE_123",+							"url": "https://github.com/owner/repo/issues/5", 						}, 					}, 				}),

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens advisories (not part of the checked findings):

  • architectural_coherence: A new test uses GraphQL "setIssueFieldValue" mutation with field selection overrides inconsistent with the canonical "SetIssueFieldValues" implementation, which omits field selection in its issued mutation query.
  • dependency_blast_radius: The updateProjectItem function calls SetIssueFieldValues, a function called from granular projects tools and projects features, exposing a hidden dependency of project item updates on the setIssueFieldValue capability.
  • dependency_blast_radius: Granular issue tools inherit GitHub feature flags propagated through the context (e.g., update_issue_suggestions), causing granular tools to fail or behave unexpectedly when the feature flag is unavailable.
  • historical_risk: The file pkg/github/issues_granular.go has occurred 6 times in trajectory data, exceeding the threshold for high-frequency changes, indicating a change hotspot.
  • historical_risk: The file pkg/github/issues_granular.go contains 26 code entities (functions, types, test functions) in a single file of 1707 lines, indicating structural complexity accumulation typical of high-frequency change areas.

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Data ConsistencyThe setIssueFieldValue mutation response shape is changed to return only issue{id, url} instead of issue{id, number, url}. Existing callers that read the number field from the response will receive a zero/empty value, causing silent data loss.

    Principle · Keep Serialized Contracts Compatible

    Recorded location pkg/github/issues_granular.go:1286

  • Observation · Historical riskThe file pkg/github/issues_granular.go has occurred 6 times in trajectory data, exceeding the threshold for high-frequency changes, indicating a change hotspot.

    Recorded location pkg/github/issues_granular.go:1276

Supporting evidence

Reviewed 27 Nov 2026Revision c75319cd2fb16 changed files+798 −217Judge score 4/5
Approved · 0 retained findingsvitejs/vite#23765

feat: migrate to `dev.sourcemap.css` from `css.devSourcemap`

Input

PR author’s description

Make dev.sourcemap.css work and deprecate css.devSourcemap

required for https://github.com/vitejs/vite/pull/23166 and maybe https://github.com/vitejs/vite/issues/9825

PR diff

Current GitHub diff ↗
packages/vite/src/node/config.ts · patch excerpt
-  'sourcemapIgnoreList'+  'sourcemap' | 'sourcemapIgnoreList'
Browse 6 changed files
packages/vite/src/node/config.ts+33 −2
@@ -275,8 +275,9 @@ function defaultCreateDevEnvironment(name: string, config: ResolvedConfig) {  export type ResolvedDevEnvironmentOptions = Omit<   Required<DevEnvironmentOptions>,-  'sourcemapIgnoreList'+  'sourcemap' | 'sourcemapIgnoreList' > & {+  sourcemap: { js: boolean; css: boolean }   sourcemapIgnoreList: Exclude<     DevEnvironmentOptions['sourcemapIgnoreList'],     false | undefined@@ -970,6 +971,7 @@ export function resolveDevEnvironmentOptions(   consumer: 'client' | 'server' | undefined,   // Backward compatibility   preTransformRequest?: boolean,+  cssDevSourcemap?: boolean, ): ResolvedDevEnvironmentOptions {   const resolved = mergeWithDefaults(     {@@ -987,13 +989,23 @@ export function resolveDevEnvironmentOptions(   )   return {     ...resolved,+    sourcemap: normalizeDevSourcemap(resolved.sourcemap, cssDevSourcemap),     sourcemapIgnoreList:       resolved.sourcemapIgnoreList === false         ? () => false         : resolved.sourcemapIgnoreList,   } } +function normalizeDevSourcemap(+  sourcemap: DevEnvironmentOptions['sourcemap'],+  cssDefault = false,+): ResolvedDevEnvironmentOptions['sourcemap'] {+  return typeof sourcemap === 'boolean'+    ? { js: sourcemap, css: sourcemap }+    : { js: sourcemap?.js ?? true, css: sourcemap?.css ?? cssDefault }+}+ function resolveEnvironmentOptions(   options: EnvironmentOptions,   alias: Alias[],@@ -1003,6 +1015,7 @@ function resolveEnvironmentOptions(   environmentName: string,   isBuild: boolean,   isBundledDev: boolean,+  cssDevSourcemap: boolean | undefined,   // Backward compatibility   isSsrTargetWebworkerSet?: boolean,   preTransformRequests?: boolean,@@ -1064,6 +1077,7 @@ function resolveEnvironmentOptions(       environmentName,       consumer,       preTransformRequests,+      cssDevSourcemap,     ),     build: resolveBuildEnvironmentOptions(       options.build ?? {},@@ -1091,7 +1105,13 @@ export function getDefaultEnvironmentOptions(       mainFields: undefined,       conditions: undefined,     },-    dev: config.dev,+    dev:+      typeof config.dev?.sourcemap === 'boolean'+        ? {+            ...config.dev,+            sourcemap: normalizeDevSourcemap(config.dev.sourcemap),+          }+        : config.dev,     build: config.build,   } }@@ -1592,6 +1612,14 @@ export async function resolveConfig(     )   } +  if (config.css?.devSourcemap !== undefined) {+    logger.warn(+      colors.yellow(+        `The \`css.devSourcemap\` option is deprecated. Please use \`dev.sourcemap.css\` instead.`,+      ),+    )+  }+   const tsconfigPathsPlugin = userPlugins.find(     (p) =>       p.name === 'vite-tsconfig-paths' ||@@ -1753,6 +1781,7 @@ export async function resolveConfig(       environmentName,       isBuild,       isBundledDev,+      config.css?.devSourcemap,       config.ssr?.target === 'webworker',       config.server?.preTransformRequests,     )@@ -1770,6 +1799,8 @@ export async function resolveConfig(     // default environment options     undefined,     undefined,+    undefined,+    config.css?.devSourcemap,   )    const resolvedBuildOptions = resolveBuildEnvironmentOptions(
packages/vite/src/node/__tests__/config.spec.ts+62 −0
@@ -1806,6 +1806,68 @@ test('build and environments.client.build has the same reference', async () => {   ) }) +test('css.devSourcemap is deprecated in favor of dev.sourcemap.css', async () => {+  const logger = createLogger('silent')+  const warn = vi.spyOn(logger, 'warn')+  const resolved = await resolveConfig(+    {+      configFile: false,+      customLogger: logger,+      css: { devSourcemap: true },+      dev: { sourcemap: { js: false } },+      environments: {+        inherited: {},+        inheritedWithJsOverride: { dev: { sourcemap: { js: true } } },+        custom: { dev: { sourcemap: { css: false } } },+      },+    },+    'serve',+  )++  expect(resolved.dev.sourcemap).toStrictEqual({ js: false, css: true })+  expect(resolved.environments.client.dev.sourcemap).toStrictEqual({+    js: false,+    css: true,+  })+  expect(resolved.environments.inherited.dev.sourcemap).toStrictEqual({+    js: false,+    css: true,+  })+  expect(+    resolved.environments.inheritedWithJsOverride.dev.sourcemap,+  ).toStrictEqual({+    js: true,+    css: true,+  })+  expect(resolved.environments.custom.dev.sourcemap).toStrictEqual({+    js: false,+    css: false,+  })+  expect(warn).toHaveBeenCalledWith(+    expect.stringContaining(+      'The `css.devSourcemap` option is deprecated. Please use `dev.sourcemap.css` instead.',+    ),+  )+})++test('dev.sourcemap.css takes precedence over css.devSourcemap', async () => {+  const resolved = await resolveConfig(+    {+      configFile: false,+      logLevel: 'silent',+      css: { devSourcemap: true },+      dev: { sourcemap: { css: false } },+    },+    'serve',+  )++  expect(resolved.dev.sourcemap).toStrictEqual({ js: true, css: false })+  expect(resolved.environments.client.dev.sourcemap).toStrictEqual({+    js: true,+    css: false,+  })+})+ test('preTransformRequests', async () => {   async function testConfig(inlineConfig: InlineConfig) {     return Object.fromEntries(
packages/vite/src/node/plugins/css.ts+11 −11
@@ -172,6 +172,7 @@ export interface CSSOptions {    * Enables css sourcemaps during dev    * @default false    * @experimental+   * @deprecated Use `dev.sourcemap.css` instead.    */   devSourcemap?: boolean @@ -216,7 +217,7 @@ const _cssConfigDefaults = Object.freeze({   // preprocessorOptions   preprocessorMaxWorkers: true,   // postcss-  /** @experimental */+  /** @deprecated @experimental */   devSourcemap: false,   // lightningcss } satisfies CSSOptions)@@ -641,7 +642,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {          if (config.command === 'serve') {           const getContentWithSourcemap = async (content: string) => {-            if (config.css.devSourcemap) {+            if (this.environment.config.dev.sourcemap.css) {               const sourcemap = this.getCombinedSourcemap()               if (sourcemap.mappings) {                 await injectSourcesContent(@@ -1477,15 +1478,15 @@ async function compileCSSPreprocessors(   deps?: Set<string> }> {   const { config } = environment-  const { preprocessorOptions, devSourcemap } = config.css+  const { preprocessorOptions } = config.css   const atImportResolvers = getAtImportResolvers(     environment.getTopLevelConfig(),   )   const opts = {     ...(preprocessorOptions && preprocessorOptions[lang]),     // important: set this for relative import resolving     filename: cleanUrl(id),-    enableSourcemap: devSourcemap ?? false,+    enableSourcemap: config.dev.sourcemap.css,   }    const preProcessor = workerController[lang]@@ -1602,15 +1603,15 @@ async function compileCSS(   if (!transformResult) {     return {       code: resolvedCode,-      map: config.css.devSourcemap ? preprocessorMap : { mappings: '' },+      map: config.dev.sourcemap.css ? preprocessorMap : { mappings: '' },       deps,     }   }    return {     ...transformResult,     code: resolvedCode,-    map: config.css.devSourcemap+    map: config.dev.sourcemap.css       ? combineSourcemapsIfExists(           cleanUrl(id),           typeof transformResult.map === 'string'@@ -1640,7 +1641,7 @@ async function compilePostCSS(   | undefined > {   const { config } = environment-  const { modules: modulesOptions, devSourcemap } = config.css+  const { modules: modulesOptions } = config.css   const isModule = modulesOptions !== false && cssModuleRE.test(id)   // although at serve time it can work without processing, we do need to   // crawl them in order to register watch dependencies.@@ -1796,7 +1797,7 @@ async function compilePostCSS(     { ...postcssOptions, parser: postcssParser },     deps,     environment.logger,-    devSourcemap,+    config.dev.sourcemap.css,   )   return { ...result, modules } }@@ -1807,7 +1808,6 @@ async function transformSugarSS(   code: string, ) {   const { config } = environment-  const { devSourcemap } = config.css    const sssParser = await loadSss(config.root)   const result = await runPostCSS(@@ -1817,7 +1817,7 @@ async function transformSugarSS(     { parser: sssParser },     undefined,     environment.logger,-    devSourcemap,+    config.dev.sourcemap.css,   )   return result }@@ -3480,7 +3480,7 @@ async function compileLightningCSS(           sourceMap:             config.command === 'build'               ? !!config.build.sourcemap-              : config.css.devSourcemap,+              : config.dev.sourcemap.css,           analyzeDependencies: { preserveImports: true },           cssModules: cssModuleRE.test(id)             ? (config.css.lightningcss?.cssModules ?? true)

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

The recorded observation did not become a verified finding.

Evidence and perspectives

  • Observation · Architectural coherenceThe changed documentation for `dev.sourcemap` uses singular 'sourcemap' for the combined JS and CSS configuration option while the existing CSS configuration section uses plural 'sourcemaps' ('css.preprocessorOptions.sourcemap'), creating a language inconsistency within the same file.

    Recorded location docs/config/shared-options.md:459

Supporting evidence

Reviewed 27 Nov 2026Revision c0c6e91a00426 changed files+117 −20Judge score 5/5
Approved · 0 retained findingsdrizzle-team/drizzle-orm#6587

Make two copies of Drizzle Postgres compatible and require Effect 4.0.6

Input

PR author’s description

A project can hold two copies of Drizzle Postgres: a standalone package and a bundled copy, possibly of different versions. This PR makes objects and errors from one copy work with the other copy, both at runtime and in…

PR diff

Current GitHub diff ↗
postgres/src/aurora.ts · patch excerpt
+import { addBrand } from './brand.ts';
Browse 29 changed files
postgres/src/aurora.ts+3 −0
@@ -20,6 +20,7 @@ // arrayValue parameters, so a raw JS array is sent as a PG '{…}' literal string. Array RESULTS arrive as // typed arrayValue lists that cannot carry NULL elements — the Data API drops them, so a decoded array // silently loses its NULLs (a limitation of the wire format, not recoverable client-side).+import { addBrand } from './brand.ts'; import { buildDecoders } from './decode.ts'; import { type CodegenCol, INSTANT_OIDS, tagArrayCol } from './decode.ts'; import { arrayLiteral } from './encode.ts';@@ -684,6 +685,8 @@ export class AuroraClient { 	async end(): Promise<void> {/* nothing to close */} } +addBrand(AuroraClient, 'AuroraClient');+ function beginOptions(o: TxOptions): string { 	if (typeof o === 'string') { 		const s = o.replace(/[^a-zA-Z ]/g, '').trim();
pnpm-lock.yaml+46 −46
@@ -155,7 +155,7 @@ importers:         version: 1.5.0-r.1       '@effect/sql':         specifier: ^0.48.5-        version: 0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5)+        version: 0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6)       '@electric-sql/pglite':         specifier: ^0.5.8         version: 0.5.8@@ -942,8 +942,8 @@ importers:         specifier: ^2.1.11         version: 2.1.11       effect:-        specifier: 4.0.5-        version: 4.0.5+        specifier: 4.0.6+        version: 4.0.6       fast-check:         specifier: ^4.8.0         version: 4.10.2@@ -988,7 +988,7 @@ importers:     dependencies:       drizzle-beta:         specifier: npm:drizzle-orm@1.0.0-beta.21-        version: drizzle-orm@1.0.0-beta.21(2936b306b5a4bc63c6f0967a948b83fb)+        version: drizzle-orm@1.0.0-beta.21(299663ac89549d2c0d9648148b63aa00)       drizzle-seed:         specifier: workspace:../drizzle-seed/dist         version: link:../drizzle-seed/dist@@ -6422,8 +6422,8 @@ packages:   effect@4.0.0:     resolution: {integrity: sha512-ooc1TG5t+FfzgYnFz2ff6BBKyZ7EwBRVXC7c4RhQUAD6/TZ2gTXXMeb4WX7a19ozQo4J73/QW+S00YAIresoMQ==} -  effect@4.0.5:-    resolution: {integrity: sha512-BY4/28NlpOd99yzmV741xbVGmp+1U7tks4oB7F/Png64bTa5tm5eCA6W0RiXsnuLDDoJpjfVSo4Dnq4BZb/89Q==}+  effect@4.0.6:+    resolution: {integrity: sha512-Tc3mkzuLR6t6P9dhLt0D2GrxYtmU5td4XEJEiXCmILz53IRIfJyHsKZWjTA3xEjiwpNTtXBgI4iqYPxMztBDrw==}    electron-to-chromium@1.5.260:     resolution: {integrity: sha512-ov8rBoOBhVawpzdre+Cmz4FB+y66Eqrk6Gwqd8NGxuhv99GQ8XqMAr351KEkOt7gukXWDg6gJWEMKgL2RLMPtA==}@@ -12359,15 +12359,15 @@ snapshots:       '@duckdb/node-bindings-win32-arm64': 1.5.0-r.1       '@duckdb/node-bindings-win32-x64': 1.5.0-r.1 -  '@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5)':+  '@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6)':     dependencies:-      '@effect/platform': 0.93.5(effect@4.0.5)-      effect: 4.0.5+      '@effect/platform': 0.93.5(effect@4.0.6)+      effect: 4.0.6       uuid: 11.1.0 -  '@effect/platform@0.93.5(effect@4.0.5)':+  '@effect/platform@0.93.5(effect@4.0.6)':     dependencies:-      effect: 4.0.5+      effect: 4.0.6       find-my-way-ts: 0.1.6       msgpackr: 1.11.9       multipasta: 0.2.7@@ -12392,12 +12392,12 @@ snapshots:     transitivePeerDependencies:       - '@types/node' -  '@effect/sql-pg@0.49.7(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(@effect/platform@0.93.5(effect@4.0.5))(@effect/sql@0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(effect@4.0.5)':+  '@effect/sql-pg@0.49.7(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(@effect/platform@0.93.5(effect@4.0.6))(@effect/sql@0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(effect@4.0.6)':     dependencies:-      '@effect/experimental': 0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5)-      '@effect/platform': 0.93.5(effect@4.0.5)-      '@effect/sql': 0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5)-      effect: 4.0.5+      '@effect/experimental': 0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6)+      '@effect/platform': 0.93.5(effect@4.0.6)+      '@effect/sql': 0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6)+      effect: 4.0.6       pg: 8.22.0       pg-connection-string: 2.9.1       pg-cursor: 2.21.0(pg@8.22.0)@@ -12433,11 +12433,11 @@ snapshots:       '@effect/wa-sqlite': 0.1.2       effect: 4.0.0 -  '@effect/sql@0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5)':+  '@effect/sql@0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6)':     dependencies:-      '@effect/experimental': 0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5)-      '@effect/platform': 0.93.5(effect@4.0.5)-      effect: 4.0.5+      '@effect/experimental': 0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6)+      '@effect/platform': 0.93.5(effect@4.0.6)+      effect: 4.0.6       uuid: 11.1.0    '@effect/vitest@4.0.0(effect@4.0.0)(vitest@5.0.0(@opentelemetry/api@1.9.0)(@types/node@25.5.0)(vite@7.2.4(@types/node@25.5.0)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(tsx@4.20.6)(yaml@2.9.0)))':@@ -13006,7 +13006,7 @@ snapshots:       resolve: 1.22.11       resolve-from: 5.0.0       resolve.exports: 2.0.3-      semver: 7.7.4+      semver: 7.8.5       send: 0.19.1       slugify: 1.6.6       source-map-support: 0.5.21@@ -13016,7 +13016,7 @@ snapshots:       terminal-link: 2.1.1       undici: 6.22.0       wrap-ansi: 7.0.0-      ws: 8.18.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)+      ws: 8.21.0(bufferutil@4.0.8)(utf-8-validate@6.0.3)     optionalDependencies:       react-native: 0.82.1(@babel/core@7.28.5)(@types/react@18.3.27)(bufferutil@4.0.8)(react@18.3.1)(utf-8-validate@6.0.3)     transitivePeerDependencies:@@ -13082,7 +13082,7 @@ snapshots:       resolve: 1.22.11       resolve-from: 5.0.0       resolve.exports: 2.0.3-      semver: 7.7.4+      semver: 7.8.5       send: 0.19.1       slugify: 1.6.6       source-map-support: 0.5.21@@ -13092,7 +13092,7 @@ snapshots:       terminal-link: 2.1.1       undici: 6.22.0       wrap-ansi: 7.0.0-      ws: 8.18.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)+      ws: 8.21.0(bufferutil@4.0.8)(utf-8-validate@6.0.3)     optionalDependencies:       react-native: 0.82.1(@babel/core@7.28.5)(bufferutil@4.0.8)(react@18.3.1)(utf-8-validate@6.0.3)     transitivePeerDependencies:@@ -13159,7 +13159,7 @@ snapshots:       resolve: 1.22.11       resolve-from: 5.0.0       resolve.exports: 2.0.3-      semver: 7.7.4+      semver: 7.8.5       send: 0.19.1       slugify: 1.6.6       source-map-support: 0.5.21@@ -13169,7 +13169,7 @@ snapshots:       terminal-link: 2.1.1       undici: 6.22.0       wrap-ansi: 7.0.0-      ws: 8.18.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)+      ws: 8.21.0(bufferutil@4.0.8)(utf-8-validate@6.0.3)     optionalDependencies:       react-native: 0.82.1(@babel/core@7.28.5)(bufferutil@4.0.8)(react@18.3.1)(utf-8-validate@6.0.3)     transitivePeerDependencies:@@ -13196,7 +13196,7 @@ snapshots:       getenv: 2.0.0       glob: 10.5.0       resolve-from: 5.0.0-      semver: 7.7.4+      semver: 7.8.5       slash: 3.0.0       slugify: 1.6.6       xcode: 3.0.1@@ -13218,7 +13218,7 @@ snapshots:       require-from-string: 2.0.2       resolve-from: 5.0.0       resolve-workspace-root: 2.0.0-      semver: 7.7.4+      semver: 7.8.5       slugify: 1.6.6       sucrase: 3.35.0     transitivePeerDependencies:@@ -13269,7 +13269,7 @@ snapshots:       minimatch: 9.0.5       p-limit: 3.1.0       resolve-from: 5.0.0-      semver: 7.7.4+      semver: 7.8.5     transitivePeerDependencies:       - supports-color @@ -13282,7 +13282,7 @@ snapshots:       parse-png: 2.1.0       resolve-from: 5.0.0       resolve-global: 1.0.0-      semver: 7.7.4+      semver: 7.8.5       temp-dir: 2.0.0       unique-string: 2.0.0 @@ -13293,7 +13293,7 @@ snapshots:    '@expo/mcp-tunnel@0.1.0(@modelcontextprotocol/sdk@1.29.0(zod@3.25.1))(bufferutil@4.0.8)(utf-8-validate@6.0.3)':     dependencies:-      ws: 8.18.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)+      ws: 8.21.0(bufferutil@4.0.8)(utf-8-validate@6.0.3)       zod: 3.25.76       zod-to-json-schema: 3.25.2(zod@3.25.76)     optionalDependencies:@@ -13304,7 +13304,7 @@ snapshots:    '@expo/mcp-tunnel@0.1.0(@modelcontextprotocol/sdk@1.29.0(zod@3.25.76))(bufferutil@4.0.8)(utf-8-validate@6.0.3)':     dependencies:-      ws: 8.18.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)+      ws: 8.21.0(bufferutil@4.0.8)(utf-8-validate@6.0.3)       zod: 3.25.76       zod-to-json-schema: 3.25.2(zod@3.25.76)     optionalDependencies:@@ -13316,7 +13316,7 @@ snapshots:    '@expo/mcp-tunnel@0.1.0(@modelcontextprotocol/sdk@1.29.0(zod@4.3.4))(bufferutil@4.0.8)(utf-8-validate@6.0.3)':     dependencies:-      ws: 8.18.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)+      ws: 8.21.0(bufferutil@4.0.8)(utf-8-validate@6.0.3)       zod: 3.25.76       zod-to-json-schema: 3.25.2(zod@3.25.76)     optionalDependencies:@@ -13468,7 +13468,7 @@ snapshots:       debug: 4.4.3       expo: 54.0.25(@babel/core@7.28.5)(@modelcontextprotocol/sdk@1.29.0(zod@3.25.1))(bufferutil@4.0.8)(react-native@0.82.1(@babel/core@7.28.5)(@types/react@18.3.27)(bufferutil@4.0.8)(react@18.3.1)(utf-8-validate@6.0.3))(react@18.3.1)(utf-8-validate@6.0.3)       resolve-from: 5.0.0-      semver: 7.7.4+      semver: 7.8.5       xml2js: 0.6.0     transitivePeerDependencies:       - supports-color@@ -13484,7 +13484,7 @@ snapshots:       debug: 4.4.3       expo: 54.0.25(@babel/core@7.28.5)(@modelcontextprotocol/sdk@1.29.0(zod@3.25.76))(bufferutil@4.0.8)(react-native@0.82.1(@babel/core@7.28.5)(bufferutil@4.0.8)(react@18.3.1)(utf-8-validate@6.0.3))(react@18.3.1)(utf-8-validate@6.0.3)       resolve-from: 5.0.0-      semver: 7.7.4+      semver: 7.8.5       xml2js: 0.6.0     transitivePeerDependencies:       - supports-color@@ -13501,7 +13501,7 @@ snapshots:       debug: 4.4.3       expo: 54.0.25(@babel/core@7.28.5)(@modelcontextprotocol/sdk@1.29.0(zod@4.3.4))(bufferutil@4.0.8)(react-native@0.82.1(@babel/core@7.28.5)(bufferutil@4.0.8)(react@18.3.1)(utf-8-validate@6.0.3))(react@18.3.1)(utf-8-validate@6.0.3)       resolve-from: 5.0.0-      semver: 7.7.4+      semver: 7.8.5       xml2js: 0.6.0     transitivePeerDependencies:       - supports-color@@ -14178,7 +14178,7 @@ snapshots:   '@napi-rs/wasm-runtime@1.1.1':     dependencies:       '@emnapi/core': 1.8.1-      '@emnapi/runtime': 1.8.1+      '@emnapi/runtime': 1.11.3       '@tybys/wasm-util': 0.10.1     optional: true @@ -14453,7 +14453,7 @@ snapshots:       metro: 0.83.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)       metro-config: 0.83.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)       metro-core: 0.83.3-      semver: 7.7.4+      semver: 7.8.5     transitivePeerDependencies:       - bufferutil       - supports-color@@ -16800,15 +16800,15 @@ snapshots:       sql.js: 1.13.0       sqlite3: 5.1.7 -  drizzle-orm@1.0.0-beta.21(2936b306b5a4bc63c6f0967a948b83fb):+  drizzle-orm@1.0.0-beta.21(299663ac89549d2c0d9648148b63aa00):     dependencies:       '@types/mssql': 9.1.11       mssql: 12.1.1     optionalDependencies:       '@aws-sdk/client-rds-data': 3.940.0       '@cloudflare/workers-types': 5.20261019.1-      '@effect/sql': 0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5)-      '@effect/sql-pg': 0.49.7(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(@effect/platform@0.93.5(effect@4.0.5))(@effect/sql@0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(@effect/platform@0.93.5(effect@4.0.5))(effect@4.0.5))(effect@4.0.5)+      '@effect/sql': 0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6)+      '@effect/sql-pg': 0.49.7(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(@effect/platform@0.93.5(effect@4.0.6))(@effect/sql@0.48.5(@effect/experimental@0.57.8(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(@effect/platform@0.93.5(effect@4.0.6))(effect@4.0.6))(effect@4.0.6)       '@electric-sql/pglite': 0.5.8       '@libsql/client': 0.18.0(bufferutil@4.0.8)(utf-8-validate@6.0.3)       '@libsql/client-wasm': 0.10.0@@ -16860,7 +16860,7 @@ snapshots:    effect@4.0.0: {} -  effect@4.0.5: {}+  effect@4.0.6: {}    electron-to-chromium@1.5.260: {} @@ -17835,7 +17835,7 @@ snapshots:       '@petamoriken/float16': 3.9.3       debug: 4.4.3       env-paths: 3.0.0-      semver: 7.7.4+      semver: 7.8.5       shell-quote: 1.8.3       which: 4.0.0     transitivePeerDependencies:@@ -19456,7 +19456,7 @@ snapshots:     dependencies:       hosted-git-info: 7.0.2       proc-log: 4.2.0-      semver: 7.7.4+      semver: 7.8.5       validate-npm-package-name: 5.0.1    npm-run-path@5.3.0:@@ -20107,7 +20107,7 @@ snapshots:       react-refresh: 0.14.2       regenerator-runtime: 0.13.11       scheduler: 0.26.0-      semver: 7.7.4+      semver: 7.8.5       stacktrace-parser: 0.1.11       whatwg-fetch: 3.6.20       ws: 6.2.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)@@ -20155,7 +20155,7 @@ snapshots:       react-refresh: 0.14.2       regenerator-runtime: 0.13.11       scheduler: 0.26.0-      semver: 7.7.4+      semver: 7.8.5       stacktrace-parser: 0.1.11       whatwg-fetch: 3.6.20       ws: 6.2.3(bufferutil@4.0.8)(utf-8-validate@6.0.3)
integration-tests/tests/packed/packed-package.test.ts+72 −2
@@ -1,6 +1,7 @@ import { composeHint, optionalEnv } from '@drizzle/test-utils'; import { execFile } from 'node:child_process';-import { cpSync, existsSync, mkdtempSync, rmSync } from 'node:fs';+import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { createRequire } from 'node:module'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { promisify } from 'node:util';@@ -11,13 +12,27 @@ const exec = promisify(execFile);  const ormDist = resolve(import.meta.dirname, '../../../drizzle-orm/dist'); const postgresDir = resolve(import.meta.dirname, '../../../postgres');+const instanceofScript = resolve(import.meta.dirname, 'instanceof.js');+const tsc = createRequire(import.meta.url).resolve('typescript/bin/tsc');+// The consumer projects have no `@types/node` of their own, so tsc reads the one installed here.+const nodeTypeRoots = resolve(import.meta.dirname, '../../node_modules/@types');  const connectionString = optionalEnv('PG_CONNECTION_STRING', composeHint('postgres'));  // The Node that runs the consumer projects. CI sets it from the matrix of Node versions, because vitest // needs a newer Node than the oldest versions in the engines range. const consumerNode = process.env['CONSUMER_NODE'] || 'node'; +const bothDirections = { firstIsSecond: true, secondIsFirst: true };+const instanceofInBothDirections = {+	isSameClass: false,+	Pool: bothDirections,+	Connection: bothDirections,+	PgError: bothDirections,+	MyPool: { isFirstPool: true, isSecondPool: true, poolIsMyPool: false },+	unbranded: [],+};+ async function pack(packageDir: string, destination: string): Promise<string> { 	const { stdout } = await exec('npm', ['pack', packageDir, '--json', '--pack-destination', destination]); 	// npm 12 prints an object keyed by package name, older npm prints an array.@@ -26,14 +41,24 @@ async function pack(packageDir: string, destination: string): Promise<string> { }  // Copies a template to a temporary dir and installs the packages that `install` returns into it.+// `versions` rewrites the version in the manifests of installed packages. // Returns a getter, because the dir exists only after `beforeAll` has run.-function useConsumer(template: string, install: (consumer: string) => Promise<string[]>): () => string {+function useConsumer(+	template: string,+	install: (consumer: string) => Promise<string[]>,+	versions: Record<string, string> = {},+): () => string { 	let consumer: string | undefined;  	beforeAll(async () => { 		consumer = mkdtempSync(join(tmpdir(), `drizzle-${template}-`)); 		cpSync(resolve(import.meta.dirname, template), consumer, { recursive: true }); 		await exec('npm', ['install', '--no-audit', '--no-fund', ...await install(consumer)], { cwd: consumer });++		for (const [name, version] of Object.entries(versions)) {+			const manifest = join(consumer, 'node_modules', name, 'package.json');+			writeFileSync(manifest, JSON.stringify({ ...JSON.parse(readFileSync(manifest, 'utf8')), version }));+		} 	}, 300_000);  	afterAll(() => {@@ -67,6 +92,25 @@ async function runWorker(cwd: string): Promise<string> { 	} } +async function typeCheck(file: string, cwd: string): Promise<string> {+	const args = [+		'--noEmit',+		'--strict',+		'--skipLibCheck',+		'--module',+		'nodenext',+		'--target',+		'es2022',+		'--typeRoots',+		nodeTypeRoots,+		'--types',+		'node',+		file,+	];+	const { stdout } = await exec('node', [tsc, ...args], { cwd }).catch((error) => error);+	return stdout;+}+ const runtimes: Record<string, (cwd: string) => Promise<string>> = { 	node: (cwd) => runScript(consumerNode, ['main.js'], cwd), 	bun: (cwd) => runScript('bun', ['main.js'], cwd),@@ -98,3 +142,29 @@ describe.skipIf(!connectionString)('packed drizzle-orm with standalone @drizzle/ 		expect(JSON.parse(output)).toEqual([{ value: 'ok' }]); 	}); });++describe.skipIf(!connectionString)('two packed copies of @drizzle/postgres', () => {+	const consumer = useConsumer(+		'two-postgres-copies',+		async (dir) => {+			requirePostgresBuild();+			cpSync(instanceofScript, join(dir, 'instanceof.js'));+			const postgres = await pack(postgresDir, dir);+			return [postgres, `postgres-copy@file:${postgres}`];+		},+		// TypeScript treats two packages with the same name and version as one package,+		// so the copy gets another version, as a copy from another release would have.+		{ 'postgres-copy': '0.0.0' },+	);++	test('instanceof works in both directions for every exported class', async () => {+		const output = await runScript('node', ['instanceof.js', '@drizzle/postgres', 'postgres-copy'], consumer());+		const { exportedClasses, ...result } = JSON.parse(output);+		expect(result).toEqual(instanceofInBothDirections);+		expect(exportedClasses).toBeGreaterThanOrEqual(22);+	});++	test('a Pool and a Connection from one copy type-check as the other copy', async () => {+		expect(await typeCheck('types.ts', consumer())).toBe('');+	});+});

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens advisories (not part of the checked findings):

  • test_strategy: The diff adds an integration test suite for Effect 4.0.6 and ^4 with bun test test/integration/effect-*.test.ts (15‑minute timeout), but the unit test file postgres/test/unit/brand.test.ts is a source‑scan script that does not exercise actual Schema behavior, leaving the Effect runtime bridging and subpath exports prone to silent regression if Effect's SQL modules change behavior.

Lens coverage: 6 delivered

The recorded observation did not become a verified finding.

Evidence and perspectives

  • Observation · Test strategyThe diff adds an integration test suite for Effect 4.0.6 and `^4` with `bun test test/integration/effect-*.test.ts` (15‑minute timeout), but the unit test file `postgres/test/unit/brand.test.ts` is a source‑scan script that does not exercise actual Schema behavior, leaving the Effect runtime bridging and subpath exports prone to silent regression if Effect's SQL modules change behavior.

    Recorded file .github/workflows/postgres-ci.yml · no line recorded

Supporting evidence

Reviewed 27 Nov 2026Revision d3563cd18dc029 changed files+442 −55Judge score 5/5
Approved · 0 retained findingsgithub/github-mcp-server#2900

feat(http): add --authorization-server flag to override OAuth AS URL

Input

PR author’s description

Summary

Adds a --authorization-server CLI flag (and GITHUB_AUTHORIZATION_SERVER env var) to the http subcommand, allowing operators to override the authorization server URL advertised in the OAuth Protected…

PR diff

Current GitHub diff ↗
pkg/http/server.go · patch excerpt
+	// AuthorizationServer overrides the authorization server URL advertised in the+	// OAuth Protected Resource Metadata (/.well-known/oauth-protected-resource).+	// When set, this URL is used instead of the one derived from the GitHub host.+	// Useful when deploying behind an OAuth proxy (e.g. for GHES, which does not
Browse 6 changed files
pkg/http/server.go+17 −5
@@ -53,6 +53,13 @@ type ServerConfig struct { 	// This is used to restore the original path when a proxy strips a base path before forwarding. 	ResourcePath string +	// AuthorizationServer overrides the authorization server URL advertised in the+	// OAuth Protected Resource Metadata (/.well-known/oauth-protected-resource).+	// When set, this URL is used instead of the one derived from the GitHub host.+	// Useful when deploying behind an OAuth proxy (e.g. for GHES, which does not+	// natively support RFC 8414 / RFC 7591 / PKCE).+	AuthorizationServer string+ 	// TrustProxyHeaders indicates whether X-Forwarded-Host and X-Forwarded-Proto 	// should be honored when constructing OAuth resource metadata URLs. Only 	// enable this when the server is deployed behind a trusted proxy that sets@@ -190,11 +197,7 @@ func RunHTTPServer(cfg ServerConfig) error { 	}  	// Register OAuth protected resource metadata endpoints-	oauthCfg := &oauth.Config{-		BaseURL:           cfg.BaseURL,-		ResourcePath:      cfg.ResourcePath,-		TrustProxyHeaders: cfg.TrustProxyHeaders,-	}+	oauthCfg := newOAuthConfig(cfg)  	serverOptions := []HandlerOption{ 		WithInventoryFactory(inventoryFactory),@@ -256,6 +259,15 @@ func RunHTTPServer(cfg ServerConfig) error { 	return nil } +func newOAuthConfig(cfg ServerConfig) *oauth.Config {+	return &oauth.Config{+		BaseURL:             cfg.BaseURL,+		ResourcePath:        cfg.ResourcePath,+		TrustProxyHeaders:   cfg.TrustProxyHeaders,+		AuthorizationServer: cfg.AuthorizationServer,+	}+}+ // resolveListenAddress returns the address string passed to http.Server. // When host is empty the server binds to all interfaces on the given port; // otherwise host and port are joined into a single address.
pkg/http/server_test.go+34 −0
@@ -9,6 +9,7 @@ import (  	ghcontext "github.com/github/github-mcp-server/pkg/context" 	"github.com/github/github-mcp-server/pkg/github"+	"github.com/github/github-mcp-server/pkg/http/oauth" 	"github.com/github/github-mcp-server/pkg/inventory" 	"github.com/github/github-mcp-server/pkg/utils" 	"github.com/stretchr/testify/assert"@@ -44,6 +45,39 @@ func TestRunHTTPServerRejectsInvalidStaticTools(t *testing.T) { 	} } +func TestNewOAuthConfig(t *testing.T) {+	tests := []struct {+		name                string+		authorizationServer string+	}{+		{+			name: "unset preserves host-derived authorization server",+		},+		{+			name:                "explicit override is propagated",+			authorizationServer: "https://oauth-proxy.example.com",+		},+	}++	for _, tt := range tests {+		t.Run(tt.name, func(t *testing.T) {+			cfg := newOAuthConfig(ServerConfig{+				BaseURL:             "https://mcp.example.com",+				ResourcePath:        "/mcp",+				TrustProxyHeaders:   true,+				AuthorizationServer: tt.authorizationServer,+			})++			assert.Equal(t, &oauth.Config{+				BaseURL:             "https://mcp.example.com",+				ResourcePath:        "/mcp",+				TrustProxyHeaders:   true,+				AuthorizationServer: tt.authorizationServer,+			}, cfg)+		})+	}+}+ func TestInitGlobalToolScopeMapUsesHost(t *testing.T) { 	tests := []struct { 		name     string
docs/streamable-http.md+27 −0
@@ -92,6 +92,33 @@ github-mcp-server http --trust-proxy-headers  Equivalent environment variable: `GITHUB_TRUST_PROXY_HEADERS=1`. Only enable this when the upstream proxy is trusted to set or strip these headers; otherwise prefer `--base-url`. When `--base-url` is set, it always takes precedence and `--trust-proxy-headers` has no effect. +### With an OAuth Proxy (GHES / non-standard authorization server)++When deploying against GitHub Enterprise Server, GHES does not natively support the OAuth extensions required by MCP (RFC 8414 metadata discovery, RFC 7591 Dynamic Client Registration, PKCE). In this case you can run a separate OAuth proxy that implements the MCP OAuth spec and forwards authentication to GHES. Use `--authorization-server` to advertise the proxy's URL in the protected resource metadata instead of the one derived from `--gh-host`:++```bash+github-mcp-server http \+  --gh-host https://github.example.com \+  --base-url https://mcp.example.com \+  --authorization-server https://mcp.example.com/oauth-proxy+```++The `authorization_servers` field in the protected resource metadata will then point at your proxy:++```json+{+  "resource": "https://mcp.example.com",+  "authorization_servers": [+    "https://mcp.example.com/oauth-proxy"+  ],+  ...+}+```++Equivalent environment variable: `GITHUB_AUTHORIZATION_SERVER=https://mcp.example.com/oauth-proxy`.++When neither the flag nor environment variable is set, the server preserves the existing behavior and derives the authorization server from `--gh-host`. The override only changes the URL advertised in OAuth protected resource metadata; it does not change token validation or the GitHub API host.+ ## Client Configuration  ### Using OAuth Authentication

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens advisories (not part of the checked findings):

  • historical_risk: main_test.go:TestAuthorizationServerConfigurationIsHTTPOnly tests that the authorization-server flag is HTTP-only, suggesting historical OAuth URL injection bugs in similar flags.

Lens disagreements (not adjudicated):

  • complexity_maintainability vs change_quality on seed:input-document — complexity_maintainability and change_quality disagree on this entity
  • change_quality vs test_strategy on seed:input-document — change_quality and test_strategy disagree on this entity

Lens coverage: 6 delivered

The recorded observations did not become verified findings.

Evidence and perspectives

  • Observation · Historical riskmain_test.go:TestAuthorizationServerConfigurationIsHTTPOnly tests that the authorization-server flag is HTTP-only, suggesting historical OAuth URL injection bugs in similar flags.

    Recorded location cmd/github-mcp-server/main_test.go:44

  • Observation · Architectural coherenceTests for AuthorizationServer configuration are split between main.go and oauth_test.go with different verification strategies: main_test.go verifies HTTP-only constraint while oauth_test.go tests default URL fallback, creating inconsistent testing patterns for the same configuration feature.

    Recorded location cmd/github-mcp-server/main_test.go:44

Supporting evidence

Reviewed 27 Nov 2026Revision 2aea819e3fb86 changed files+115 −6Judge score 5/5
Approved · 0 retained findingsvitejs/vite#23690

feat(module-runner): align stacktrace with v8

Input

PR author’s description

Updated the CallSiteToString function to align with the latest v8 code. https://github.com/v8/v8/blob/19173cde61d86c96da741e10e4ccbb20e11794ad/src/objects/call-site-info.cc#L741-L881

PR diff

Current GitHub diff ↗
packages/vite/rolldown.config.ts · patch excerpt
-  plugins: [bundleSizeLimit(55), enableSourceMapsInWatchModePlugin()],+  plugins: [bundleSizeLimit(56), enableSourceMapsInWatchModePlugin()],
Browse 5 changed files
packages/vite/rolldown.config.ts+1 −1
@@ -154,7 +154,7 @@ const moduleRunnerConfig = defineConfig({     /^rolldown\//,     ...Object.keys(pkg.dependencies),   ],-  plugins: [bundleSizeLimit(55), enableSourceMapsInWatchModePlugin()],+  plugins: [bundleSizeLimit(56), enableSourceMapsInWatchModePlugin()],   output: {     ...(sharedNodeOptions.output as OutputOptions),     minify: {
packages/vite/src/module-runner/sourcemap/interceptor.ts+33 −17
@@ -258,12 +258,21 @@ function mapEvalOrigin(origin: string): string {   return origin } -// This is copied almost verbatim from the V8 source code at-// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The-// implementation of wrapCallSite() used to just forward to the actual source-// code of CallSite.prototype.toString but unfortunately a new release of V8-// did something to the prototype chain and broke the shim. The only fix I-// could find was copy/paste.+const identifierRE =+  /^(?!.*[\u{10000}-\u{10FFFF}])[$_\p{ID_Start}][$\p{ID_Continue}\p{Join_Control}]*$/u++function stringEndsWithMethodName(subject: string, pattern: string): boolean {+  return (+    subject === pattern ||+    subject.endsWith(`.${pattern}`) ||+    subject.endsWith(` ${pattern}`)+  )+}++// Keep this aligned with V8's stack frame serialization:+// https://github.com/v8/v8/blob/19173cde61d86c96da741e10e4ccbb20e11794ad/src/objects/call-site-info.cc#L741-L881+// Cloned call sites need a local toString implementation so source-mapped+// locations retain V8's native stack frame formatting. function CallSiteToString(this: CallSite) {   let fileName   let fileLocation = ''@@ -294,28 +303,35 @@ function CallSiteToString(this: CallSite) {    let line = ''   const functionName = this.getFunctionName()+  if (this.isAsync()) {+    line += 'async '+    const promiseIndex = this.getPromiseIndex()+    if (promiseIndex != null) {+      line += functionName ? `Promise.${functionName}` : '<anonymous>'+      line += ` (index ${promiseIndex})`+      return line+    }+  }   let addSuffix = true   const isConstructor = this.isConstructor()   const isMethodCall = !(this.isToplevel() || isConstructor)   if (isMethodCall) {-    let typeName = this.getTypeName()-    // Fixes shim to be backward compatible with Node v0 to v4-    if (typeName === '[object Object]') typeName = 'null'-+    const typeName = this.getTypeName()     const methodName = this.getMethodName()     if (functionName) {-      if (typeName && functionName.indexOf(typeName) !== 0)+      if (+        typeName &&+        identifierRE.test(functionName) &&+        functionName !== typeName+      )         line += `${typeName}.`        line += functionName-      if (-        methodName &&-        functionName.indexOf(`.${methodName}`) !==-          functionName.length - methodName.length - 1-      )+      if (methodName && !stringEndsWithMethodName(functionName, methodName))         line += ` [as ${methodName}]`     } else {-      line += `${typeName}.${methodName || '<anonymous>'}`+      if (typeName) line += `${typeName}.`+      line += methodName || '<anonymous>'     }   } else if (isConstructor) {     line += `new ${functionName || '<anonymous>'}`
packages/vite/src/node/ssr/runtime/__tests__/fixtures/has-error-method-names.ts+33 −0
@@ -0,0 +1,33 @@+const object = {+  get foo(): never {+    throw new Error('getter')+  },+}++class F {+  m(): never {+    throw new Error('method')+  }+}++Object.defineProperty(F.prototype.m, 'name', { value: 'Foo' })++class AstralName {+  m(): never {+    throw new Error('astral name')+  }+}++Object.defineProperty(AstralName.prototype.m, 'name', { value: '𐐀' })++export function callGetter(): void {+  object.foo+}++export function callAliasedMethod(): void {+  new F().m()+}++export function callAstralNamedMethod(): void {+  new AstralName().m()+}

→ Outcome

Why this verdict

approve — No checked defect was established by the available proof adapters.

Lens coverage: 6 delivered

Supporting evidence

Reviewed 27 Nov 2026Revision c2003370cc835 changed files+107 −18Judge score 5/5
AboutReview principlesSupportPrivacyContact
(C) 2026 Superpositional>
Member of the NVIDIA Inception Program