Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

docs(llm): disclose what the server-side LLM layer sends, and test the zero-request opt-out (MUL-6369) (#7199)

Bohan Jiangbb8a04f3a124
diff --git a/.env.example b/.env.example
index 28c9d0e6b7..4e435d93c6 100644
--- a/.env.example
+++ b/.env.example
@@ -76,10 +76,36 @@ MULTICA_RUNTIME_RECONNECT_GRACE=3h
# e.g. "127.0.0.1/32" for a same-host reverse proxy, or the CDN's
# announced ranges for cloud deployments.
MULTICA_TRUSTED_PROXIES=
-# Basic LLM API layer (MUL-4238). Backs server-internal LLM helpers such as
-# chat title generation (the generic OpenAI-compatible passthrough endpoints
-# were removed in MUL-4309 — LLM access is internal-only). When both API key
-# and base URL are empty the layer is disabled and callers fall back silently.
+# Server-side assist layer (MUL-4238). These variables govern the LLM calls the
+# API process makes on its own — every one of them goes through server/pkg/llm,
+# and that package stays inert until an API key or a base URL is set here.
+# Access is internal-only: the generic OpenAI-compatible passthrough endpoints
+# were removed in MUL-4309.
+#
+# This is NOT the deployment's only path from chat content to a model. Running
+# an agent is a separate one: the daemon executes an AI coding tool with that
+# tool's own credentials, and does not forward these MULTICA_LLM_* settings to
+# it. (The task-scoped Multica connection variables the agent needs — server
+# URL, task token — are injected by the daemon separately.) Nothing below
+# governs that path.
+#
+# Once configured, the layer has exactly two consumers, and this is what each
+# one sends upstream:
+# - Chat auto-titling: the first user message of a new chat session, verbatim
+# and uncapped. Attachments are never included.
+# - Chat follow-up questions (the suggestion buttons under an agent reply):
+# the tail of the conversation — up to 6 messages, with the reply being
+# answered capped at 3000 characters (2000 head + 1000 tail) and each
+# older message at 800.
+#
+# Leaving BOTH the API key and the base URL empty is a fully supported
+# configuration, and the right one when policy forbids this layer sending chat
+# content anywhere: it is disabled, makes zero upstream requests, and neither
+# feature above sends anything. Nothing breaks — chats keep the title the
+# client derives from the first message (30 characters, no model involved) and
+# the follow-up question buttons simply never appear. server/pkg/llm asserts
+# both the zero-request behaviour and the two-consumer list above, so neither
+# can drift from this comment silently.
# - API key for the upstream (OpenAI or any OpenAI-compatible gateway).
MULTICA_LLM_API_KEY=
# - Base URL of the upstream. Leave unset to use OpenAI's default
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 91c7b1fb83..a5105eef17 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -187,7 +187,16 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s
| `MULTICA_LLM_BASE_URL` | 空 | OpenAI 互換の endpoint |
| `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | リクエストがモデルを指定しない場合に使用 |
-API key と base URL の両方が空の場合、サーバーサイド LLM 生成は無効になり、呼び出し側はローカルのフォールバックロジックを使います。
+このレイヤーを使う機能は 2 つあり、どちらも設定した endpoint にチャットの内容を送信します。
+
+- **会話タイトルの自動生成** — 新しいチャットセッションでユーザーが最初に送ったメッセージを、そのまま送信します。添付ファイルは含まれません。
+- **フォローアップ質問**(エージェントの返信の下に表示されるボタン) — 会話の末尾を送信します。最大 6 メッセージで、対象の返信は 3000 文字、それより古いメッセージは各 800 文字が上限です。
+
+API key と base URL の両方が空の場合、このレイヤーは無効になり、上流へのリクエストを一切行いません。上記 2 つの機能はどちらも何も送信しなくなります。このレイヤーからチャットの内容をデプロイ外へ出せないポリシーでは、これがサポートされた構成です。セッションはクライアントが最初のメッセージから生成したタイトルをそのまま使い、フォローアップ質問のボタンは表示されず、他の機能への影響はありません。
+
+<Callout type="info">
+これは補助生成レイヤーのみに関する説明です。エージェントの実行は別のデータ経路です。エージェントがチャットに応答するとき、デーモンはそのエージェントの AI コーディングツールをツール自身の資格情報で実行し、上記の `MULTICA_LLM_*` 設定をツールへ渡すことはありません。(エージェント自身が必要とするタスク単位の Multica 接続用変数は、デーモンが別途注入します。)上記の変数を空にしてもこの経路には影響しないため、エージェントのランタイム設定側で制御してください。
+</Callout>
## デーモン設定
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index befe83c1d0..4ccd48fff6 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -187,7 +187,16 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야
| `MULTICA_LLM_BASE_URL` | 비어 있음 | OpenAI 호환 endpoint |
| `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | 요청에 모델이 지정되지 않았을 때 사용 |
-API key와 base URL이 모두 비어 있으면 서버 측 LLM 생성이 꺼지고 호출자가 로컬 fallback 로직을 사용합니다.
+이 레이어를 사용하는 기능은 두 가지이며, 둘 다 설정한 endpoint로 채팅 내용을 전송합니다.
+
+- **대화 제목 자동 생성** — 새 채팅 세션에서 사용자가 보낸 첫 메시지를 그대로 전송합니다. 첨부 파일은 포함되지 않습니다.
+- **후속 질문**(에이전트 답변 아래의 버튼) — 대화의 마지막 부분을 전송합니다. 최대 6개 메시지이며, 대상 답변은 3000자, 그보다 오래된 메시지는 각각 800자로 제한됩니다.
+
+API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스트림 요청을 전혀 보내지 않습니다. 위 두 기능 모두 아무것도 전송하지 않습니다. 이 레이어가 채팅 내용을 배포 환경 밖으로 보내면 안 되는 정책이라면 이것이 지원되는 구성입니다. 세션은 클라이언트가 첫 메시지에서 만든 제목을 그대로 사용하고, 후속 질문 버튼은 표시되지 않으며, 나머지 기능은 영향을 받지 않습니다.
+
+<Callout type="info">
+이는 보조 생성 레이어에만 해당합니다. 에이전트 실행은 별도의 데이터 경로입니다. 에이전트가 채팅에 답변할 때 데몬은 해당 에이전트의 AI 코딩 도구를 그 도구 자체의 자격 증명으로 실행하며, 위의 `MULTICA_LLM_*` 설정을 도구에 전달하지 않습니다. (에이전트 자체에 필요한 태스크 범위의 Multica 연결 변수는 데몬이 별도로 주입합니다.) 위 변수를 비워 두어도 이 경로에는 영향이 없으므로, 에이전트의 런타임 설정에서 관리하세요.
+</Callout>
## 데몬 설정
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 61195a6c26..19b9a3bf97 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -187,7 +187,16 @@ This group configures server-side assist generation, such as conversation titles
| `MULTICA_LLM_BASE_URL` | empty | OpenAI-compatible endpoint |
| `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | Used when a request does not specify a model |
-When both the API key and base URL are empty, server-side LLM generation is off and callers use local fallback logic.
+Two features use this layer, and each one sends chat content to the endpoint you configure:
+
+- **Chat auto-titling** — the first user message of a new chat session, sent verbatim. Attachments are never included.
+- **Follow-up questions** (the suggestion buttons under an agent reply) — the tail of the conversation: up to 6 messages, with the reply being answered capped at 3000 characters and each older message at 800.
+
+When both the API key and the base URL are empty, this layer is disabled and makes no upstream request at all — neither feature above sends anything. That is the supported configuration when your policy does not allow this layer to send chat content off the deployment: chat sessions keep the title the client derives from the first message, the follow-up question buttons do not appear, and everything else is unaffected.
+
+<Callout type="info">
+This covers the assist layer only. Running an agent is a separate data path: when an agent answers a chat, your daemon executes that agent's AI coding tool using the tool's own credentials, and does not forward the `MULTICA_LLM_*` settings above to it. (The task-scoped Multica connection variables the agent needs are injected by the daemon separately.) Emptying the variables above does not affect that path — govern it through the agent's runtime configuration.
+</Callout>
## Daemon configuration
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index c8ed4ccfff..dfdab68dd2 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -187,7 +187,16 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com
| `MULTICA_LLM_BASE_URL` | 空 | OpenAI 兼容 endpoint |
| `MULTICA_LLM_DEFAULT_MODEL` | `gpt-5.6-luna` | 请求未指定模型时使用 |
-API key 与 base URL 都为空时,服务端 LLM 生成关闭,调用方会使用本地回退逻辑。
+有两个功能会使用这一层,它们都会把聊天内容发送到你配置的 endpoint:
+
+- **对话标题自动生成** —— 发送新对话中用户的第一条消息,原文发送。附件不会包含在内。
+- **后续提问建议**(智能体回复下方的按钮)—— 发送对话末尾的内容:最多 6 条消息,其中被追问的那条回复上限 3000 字符,更早的每条上限 800 字符。
+
+API key 与 base URL 都为空时,这一层关闭,不会发出任何上游请求——上面两个功能都不再发送内容。如果你的政策不允许这一层把聊天内容发到部署之外,这就是受支持的配置方式:对话继续使用客户端根据第一条消息生成的标题,后续提问按钮不再出现,其余功能不受影响。
+
+<Callout type="info">
+这只覆盖辅助生成这一层。智能体执行是另一条数据路径:智能体回复对话时,由你的守护进程调用该智能体的 AI 编程工具,用的是那个工具自己的凭据,守护进程不会把上面的 `MULTICA_LLM_*` 配置传给它。(智能体自身需要的任务级 Multica 连接变量由守护进程单独注入。)把上面的变量留空不影响这条路径——它由智能体的运行时配置决定。
+</Callout>
## 守护进程配置
diff --git a/server/pkg/llm/client.go b/server/pkg/llm/client.go
index 655f959706..1f38b9cf92 100644
--- a/server/pkg/llm/client.go
+++ b/server/pkg/llm/client.go
@@ -1,8 +1,59 @@
// Package llm is a thin, reusable wrapper around the official OpenAI Go SDK
// (github.com/openai/openai-go). It exists so the rest of the server has a
// single, well-typed entry point for "just call an LLM" needs that do NOT
-// require the full agent runtime — e.g. generating a chat title or drafting a
-// quick-create issue (MUL-4238).
+// require the full agent runtime — currently chat auto-titling and chat
+// follow-up questions (MUL-4238).
+//
+// # Scope: the assist layer, not every model call in the product
+//
+// This package covers the LLM calls the API process makes on its own behalf.
+// Running an agent is a different data path entirely: the daemon executes an
+// AI coding tool as a subprocess under that tool's own credentials, and does
+// not forward this layer's MULTICA_LLM_* settings to it. (It does inject the
+// task-scoped Multica connection variables the agent itself needs — see
+// mergeEnv in pkg/agent, which drops the daemon's inherited MULTICA_* and then
+// appends the values assembled for that task.) Nothing here governs that path,
+// and operator-facing copy about this layer must not imply otherwise — an
+// admin who reads "empty means nothing is sent" as covering the whole product
+// has been misled about where their chat content goes.
+//
+// # The single-entry-point rule
+//
+// Every LLM call the server process makes on its own behalf goes through this
+// package, and nothing outside it imports the OpenAI SDK directly. That is a
+// constraint to keep, not a coincidence: it is what makes "what does this
+// deployment's assist layer send to a third party?" answerable by reading one
+// package instead of auditing the tree. A new feature that wants a model calls
+// this package. Two tests hold the halves of that rule:
+// TestOpenAISDKIsImportedOnlyByThisPackage (nothing else reaches the SDK) and
+// TestDocumentedConsumersAreTheOnlyCallers (nothing else reaches this client).
+//
+// # Consumers, and what they send upstream
+//
+// Keep this list current when a consumer is added, removed, or changes what it
+// sends — it is the source the operator-facing copy is written from
+// (.env.example and apps/docs/content/docs/environment-variables*.mdx), and
+// TestDocumentedConsumersAreTheOnlyCallers fails until a new call site is
+// reflected here.
+//
+// - Chat auto-titling — server/internal/handler/chat_title.go. Sends the
+// first user message of a new chat session, verbatim and uncapped.
+// Attachments are never included.
+// - Chat follow-up questions, a.k.a. quick actions —
+// server/internal/service/chat_quick_actions_generate.go.
+// Sends the tail of the conversation: up to 6 messages, the reply being
+// answered capped at 3000 runes (2000 head + 1000 tail) and each older
+// message at 800.
+//
+// Both consumers send private chat content, which is why an unconfigured
+// deployment making zero upstream requests is a contract rather than a side
+// effect: New with no API key and no base URL returns a disabled client whose
+// every call fails with ErrNotConfigured before an HTTP request is ever built,
+// and both consumers check Enabled() before doing any work
+// (TestUnconfiguredClientMakesZeroUpstreamRequests). An operator who must not
+// let THIS layer send chat content leaves MULTICA_LLM_API_KEY and
+// MULTICA_LLM_BASE_URL empty; the product stays whole (client-derived chat
+// titles, no follow-up question buttons).
//
// The wrapper is intentionally small:
//
diff --git a/server/pkg/llm/outbound_contract_test.go b/server/pkg/llm/outbound_contract_test.go
new file mode 100644
index 0000000000..a1795b358d
--- /dev/null
+++ b/server/pkg/llm/outbound_contract_test.go
@@ -0,0 +1,286 @@
+package llm
+
+import (
+ "context"
+ "errors"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "io/fs"
+ "net/http"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ openai "github.com/openai/openai-go/v3"
+)
+
+// countingHTTPClient is an option.HTTPClient that records every request the SDK
+// hands it and refuses to perform any of them. It exists to assert an absence:
+// a test that only checks the returned error cannot tell "returned
+// ErrNotConfigured without dialing" apart from "dialed, failed, and mapped the
+// failure to ErrNotConfigured".
+type countingHTTPClient struct {
+ requests atomic.Int64
+ urls []string
+}
+
+func (c *countingHTTPClient) Do(req *http.Request) (*http.Response, error) {
+ c.requests.Add(1)
+ c.urls = append(c.urls, req.URL.String())
+ return nil, errors.New("upstream must not be contacted by a disabled client")
+}
+
+// TestUnconfiguredClientMakesZeroUpstreamRequests pins the contract a
+// deployment relies on when it leaves MULTICA_LLM_API_KEY and
+// MULTICA_LLM_BASE_URL empty: this layer sends nothing, to anyone. (Only this
+// layer — agent runs reach a model by their own path, which no variable here
+// governs. See the package doc.)
+//
+// Both consumers of this package send private chat content upstream — the
+// first message of a chat session (auto-titling) and the tail of a conversation
+// (follow-up questions). "Leave the LLM variables empty" is the documented
+// answer for an operator whose policy forbids that (.env.example, the docs
+// environment-variables pages, and GitHub issue #7162), so the behaviour has to
+// be a tested guarantee rather than something that happens to be true today.
+//
+// Every exported call path is exercised, because each one is a place a future
+// refactor could start building a request before consulting Enabled().
+func TestUnconfiguredClientMakesZeroUpstreamRequests(t *testing.T) {
+ // A deployment that set only the model — the shape most likely to be
+ // mistaken for "configured" — must be just as inert as an empty config.
+ for _, cfg := range []Config{{}, {DefaultModel: "gpt-5.6-luna"}} {
+ transport := &countingHTTPClient{}
+ cfg.HTTPClient = transport
+ c := New(cfg)
+
+ if c.Enabled() {
+ t.Fatalf("client with no API key or base URL reports enabled: %+v", cfg)
+ }
+
+ ctx := context.Background()
+ userMessage := openai.ChatCompletionNewParams{
+ Messages: []openai.ChatCompletionMessageParamUnion{openai.UserMessage("private chat content")},
+ }
+ calls := []struct {
+ name string
+ run func() error
+ }{
+ {"Chat", func() error {
+ _, err := c.Chat(ctx, userMessage)
+ return err
+ }},
+ {"ChatStream", func() error {
+ _, err := c.ChatStream(ctx, userMessage)
+ return err
+ }},
+ {"GenerateText", func() error {
+ _, err := c.GenerateText(ctx, "", "system", "private chat content")
+ return err
+ }},
+ {"GenerateJSON", func() error {
+ _, err := c.GenerateJSON(ctx, "", "system JSON", "private chat content", 0.3, 2048)
+ return err
+ }},
+ }
+ for _, call := range calls {
+ if err := call.run(); !errors.Is(err, ErrNotConfigured) {
+ t.Errorf("%s on a disabled client: got %v, want ErrNotConfigured", call.name, err)
+ }
+ }
+
+ if n := transport.requests.Load(); n != 0 {
+ t.Errorf("disabled client (%+v) made %d upstream request(s): %v", cfg, n, transport.urls)
+ }
+ }
+
+ // Guard against a vacuous pass. Everything above asserts that a counter
+ // stayed at zero, which is also what a seam that stopped being wired would
+ // produce: drop option.WithHTTPClient from New and the assertions keep
+ // passing while the real client dials OpenAI. So prove the counter can move
+ // — a configured client must reach the same transport.
+ transport := &countingHTTPClient{}
+ configured := New(Config{APIKey: "test-key", BaseURL: "http://127.0.0.1:1", HTTPClient: transport, MaxRetries: -1})
+ if _, err := configured.GenerateText(context.Background(), "", "system", "hi"); err == nil {
+ t.Fatal("expected the refusing transport to fail a configured client's call")
+ }
+ if transport.requests.Load() == 0 {
+ t.Fatal("configured client sent nothing through the test transport: the HTTPClient seam is not wired, so the zero-request assertions above prove nothing")
+ }
+}
+
+// llmPackageDir is this package's path relative to the server module root. The
+// two source scans below exempt it: it is the layer they are guarding, not a
+// caller of it.
+const llmPackageDir = "pkg/llm"
+
+const openAISDKImportPrefix = "github.com/openai/openai-go"
+
+// documentedConsumers is the inventory this package's doc comment,
+// .env.example and the environment-variables docs pages all publish to
+// operators: these files, and only these, ask this layer to send something
+// upstream. The value is the summary each one is documented with.
+var documentedConsumers = map[string]string{
+ "internal/handler/chat_title.go": "chat auto-titling: the first user message of a new chat session",
+ "internal/service/chat_quick_actions_generate.go": "chat follow-up questions: the tail of the conversation",
+}
+
+// clientCallSurface is every method on Client that can produce an upstream
+// request. Enabled and DefaultModel are deliberately absent: asking whether the
+// layer is on sends nothing, and consumers are expected to call it.
+var clientCallSurface = map[string]bool{
+ "Chat": true,
+ "ChatStream": true,
+ "GenerateText": true,
+ "GenerateJSON": true,
+}
+
+// methodNameCollisions are call sites the scan below flags by name without
+// being consumers of this layer — some unrelated type that happens to have a
+// method called Chat or GenerateText. The scan matches on selector name alone,
+// which cannot tell the two apart.
+//
+// This is deliberately NOT part of documentedConsumers. That map is published
+// to operators as "what this deployment sends to a third party"; parking a
+// name collision there to quiet a test would corrupt a privacy disclosure to
+// save a line. Empty today — the repository has no collisions.
+var methodNameCollisions = map[string]bool{}
+
+// TestDocumentedConsumersAreTheOnlyCallers keeps the published consumer
+// inventory from going quietly stale.
+//
+// The operator-facing copy does not merely say this layer can be turned off; it
+// enumerates what is sent, feature by feature, so an admin can decide whether
+// to turn it on. That list is a promise about the whole server, and a third
+// feature calling GenerateText would break it silently: nothing in the build
+// notices, the docs keep naming two consumers, and the deployment starts
+// sending something no one disclosed.
+//
+// The import guard below cannot catch that case — a new consumer goes through
+// this package exactly as the existing two do, importing no SDK. So this test
+// scans production call sites instead and requires the set to match the
+// inventory in both directions: an undocumented caller fails, and so does a
+// documented one that stopped calling.
+func TestDocumentedConsumersAreTheOnlyCallers(t *testing.T) {
+ found := map[string][]string{}
+ scanServerModule(t, skipTestFiles, func(rel string, file *ast.File) {
+ ast.Inspect(file, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ if sel, ok := call.Fun.(*ast.SelectorExpr); ok && clientCallSurface[sel.Sel.Name] && !methodNameCollisions[rel] {
+ found[rel] = append(found[rel], sel.Sel.Name)
+ }
+ return true
+ })
+ })
+
+ for rel, methods := range found {
+ if _, documented := documentedConsumers[rel]; !documented {
+ t.Errorf("undocumented consumer of this layer: %s calls %v.\n"+
+ "If it sends content upstream, it must be disclosed before it ships: add it to "+
+ "documentedConsumers, to this package's doc comment, and to the operator copy in "+
+ ".env.example and apps/docs/content/docs/environment-variables*.mdx (all four locales).\n"+
+ "If it is an unrelated type that merely shares a method name, add it to "+
+ "methodNameCollisions — never to documentedConsumers, which operators read as the "+
+ "list of things that send their chat content somewhere.", rel, methods)
+ }
+ }
+ for rel, summary := range documentedConsumers {
+ if _, still := found[rel]; !still {
+ t.Errorf("%s no longer calls this layer, but is still published as a consumer (%q).\n"+
+ "Drop it from documentedConsumers, this package's doc comment, and the operator copy — "+
+ "an inventory that overstates what is sent is as misleading as one that understates it.",
+ rel, summary)
+ }
+ }
+}
+
+// TestOpenAISDKIsImportedOnlyByThisPackage enforces the import half of the
+// single-entry-point rule: nothing outside pkg/llm reaches the OpenAI SDK.
+//
+// This is narrower than it sounds, and deliberately paired with the inventory
+// test above. On its own it proves only that the SDK has one door; it says
+// nothing about how many callers walk through it. Together the two mean the
+// package doc's consumer list can be trusted: no one can bypass this layer, and
+// no one can join it unannounced.
+//
+// It asserts on source rather than behaviour because the regression is the
+// existence of a call site, and no runtime assertion can observe a request the
+// test never triggers.
+func TestOpenAISDKIsImportedOnlyByThisPackage(t *testing.T) {
+ var offenders []string
+ scanServerModule(t, includeTestFiles, func(rel string, file *ast.File) {
+ for _, imp := range file.Imports {
+ if strings.HasPrefix(strings.Trim(imp.Path.Value, `"`), openAISDKImportPrefix) {
+ offenders = append(offenders, rel)
+ return
+ }
+ }
+ })
+
+ if len(offenders) > 0 {
+ sort.Strings(offenders)
+ t.Fatalf("these files import the OpenAI SDK directly, bypassing pkg/llm:\n %s\n"+
+ "Call this package instead (add a helper here if it lacks what you need), so what this "+
+ "deployment's assist layer sends to a third party stays answerable by reading one package.",
+ strings.Join(offenders, "\n "))
+ }
+}
+
+const (
+ skipTestFiles = false
+ includeTestFiles = true
+)
+
+// scanServerModule parses every Go file in the server module except this
+// package's own, calling visit with the file's module-relative path. Test files
+// are included only when withTests is set: a stub in a _test.go is not a
+// product feature sending chat content anywhere.
+func scanServerModule(t *testing.T, withTests bool, visit func(rel string, file *ast.File)) {
+ t.Helper()
+
+ // Tests run in their package directory, so the server module root is two
+ // levels up from pkg/llm.
+ moduleRoot := filepath.Join("..", "..")
+ exempt := filepath.Join(moduleRoot, filepath.FromSlash(llmPackageDir))
+
+ err := filepath.WalkDir(moduleRoot, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ name := d.Name()
+ if path != moduleRoot && (strings.HasPrefix(name, ".") || name == "vendor" || name == "testdata") {
+ return fs.SkipDir
+ }
+ if path == exempt {
+ return fs.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(d.Name(), ".go") {
+ return nil
+ }
+ if !withTests && strings.HasSuffix(d.Name(), "_test.go") {
+ return nil
+ }
+
+ file, parseErr := parser.ParseFile(token.NewFileSet(), path, nil, parser.SkipObjectResolution)
+ if parseErr != nil {
+ return parseErr
+ }
+ rel, relErr := filepath.Rel(moduleRoot, path)
+ if relErr != nil {
+ return relErr
+ }
+ visit(filepath.ToSlash(rel), file)
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("scan server module: %v", err)
+ }
+}