From 9e6ca4a01d2462491323dbe04cd14ec34303e503 Mon Sep 17 00:00:00 2001 From: Fen Date: Thu, 19 Nov 2026 15:26:21 +0800 Subject: [PATCH 1/3] docs: add repository and design guidelines (#1678) ## Proposed Changes - Add `AGENTS.md` with repository structure, development commands, coding conventions, testing guidance, and commit/PR expectations. - Add an English `DESIGN.md` following the design.md alpha specification, documenting React Bootstrap as the design foundation and the default primary color `#0033FF`. - Document existing theme overrides, dark mode, layout conventions, and component usage, with YAML design tokens and source references. ## Validation - Checked commands and conventions against repository configuration and source files. - Confirmed `DESIGN.md` contains no Chinese text. - `git diff --cached --check` passed before committing. - Documentation-only changes; no application tests run. --- AGENTS.md | 31 ++++++++++++++++++ DESIGN.md | 98 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 129 insertions(+) create mode 100644 AGENTS.md create mode 100644 DESIGN.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..c2f36934b --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,31 @@ +# Repository Guidelines + +## Project Structure & Module Organization + +Apache Answer combines a Go backend with a React/TypeScript frontend. `cmd/answer` is the executable entry point; `internal/` contains controllers, services, repositories, schemas, and migrations. Shared Go utilities live in `pkg/`, and extension interfaces live in `plugin/`. Frontend pages, components, stores, and API clients are under `ui/src/`; static assets are in `ui/public/`, and production output is embedded from `ui/build/`. Translations live in `i18n/`, configuration examples in `configs/`, and deployment resources in `charts/`. Go tests generally sit beside their implementation; repository integration tests live in `internal/repo/repo_test/`. + +## Build, Test, and Development Commands + +Use Go 1.25+, Node.js matching `ui/package.json` (`^20.19.0 || >=22.12.0`), and pnpm 9.7.0. `make lint` also requires Docker or Podman installed and running for the ASF header formatter. + +- `make generate`: install generators, regenerate Go code/API documentation, and tidy modules. +- `make ui`: install frontend dependencies and build the UI. +- `make build`: regenerate code and build the `answer` executable. +- `./answer init -C ./data` then `./answer run -C ./data`: initialize and run locally. +- Before `cd ui && pnpm start` (Vite, port 3000), set `REACT_APP_API_URL=http://localhost:8080/` in `ui/.env.development.local`, matching your backend address. This overrides the checked-in private proxy target; restart Vite after changes. +- `make test`: run repository integration tests. +- `go test ./...`: run the full Go test suite. +- `make lint`: regenerate code, check ASF headers, and run golangci-lint. +- `cd ui && pnpm lint`: run ESLint with automatic fixes; `pnpm prettier` formats frontend sources. + +## Coding Style & Naming Conventions + +Format Go with `gofmt`; use tabs and conventional exported `PascalCase` names. Follow existing snake_case Go filenames and package organization. Frontend code uses two spaces, single quotes, trailing commas, and an 80-column Prettier target. Use PascalCase component directories and follow neighboring files. Respect `.editorconfig`, ESLint, and ASF license headers. Regenerate generated files through tooling rather than editing them manually. + +## Testing Guidelines + +Use Go's `testing` package and existing Testify assertions. Name files `*_test.go` and functions `TestXxx`. Add regression coverage for changed behavior. Repository tests default to SQLite; MySQL/PostgreSQL variants use `TEST_DB_DRIVER` and Docker. No fixed coverage threshold or frontend test script is configured; verify UI changes with `pnpm build` and browser checks. + +## Commit & Pull Request Guidelines + +Follow history's conventional prefixes: `fix:`, `feat:`, `build:`, `test:`, or `chore:`, with optional scope, such as `fix(security): enforce visibility`. Keep commits focused. Follow the PR template: link the issue with `Fixes #...` and describe proposed changes. Include validation results and screenshots for visible UI changes. Review generated changes before committing; CI checks linting and unexpected generated diffs. diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 000000000..919236989 --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,98 @@ +--- +version: alpha +name: Apache Answer +description: A React Bootstrap interface for Q&A communities, branded through the primary color. +omitted: + - section: typography + reason: Inherits Bootstrap typography without separate brand typography tokens. + - section: spacing + reason: Uses Bootstrap spacing utilities and existing page layouts without a separate spacing scale. + - section: rounded + reason: Inherits default Bootstrap component radii. + - section: motion + reason: Inherits Bootstrap and React Bootstrap component transitions. +--- + +# Apache Answer Design System + +## Overview + +Apache Answer supports Q&A communities and knowledge sharing. Keep the interface clear and practical, prioritizing readable questions, answers, and actions. + +The foundation is **React Bootstrap 2.10.6 + Bootstrap 5.3.3** (currently locked versions). Brand customization changes only the primary color. Component structure, sizing, typography, radii, and interactions follow Bootstrap defaults. Reuse existing domain styles and layouts without expanding them into a separate component design system. + +Dependency sources: `@ui/package.json` and `@ui/pnpm-lock.yaml`. Global stylesheet entry point: `@ui/src/index.scss`. + +## Colors + +The default brand primary is **Answer Blue / `#0033FF`**, used for primary actions, links, selected states, and branded navigation. Success, warning, danger, secondary actions, and neutrals retain Bootstrap semantic colors. Do not turn every state blue. + +```yaml +colors: + primary: "#0033FF" +``` + +This token represents the default theme. The site setting `theme_config[theme].primary_color` can override the active primary color. Design previews should reflect the target site's configuration. + +At build time, `@ui/src/common/_variable.scss` sets the default primary through `$blue` before Bootstrap is imported. At runtime, `@ui/src/components/CustomizeTheme/index.tsx` synchronizes primary colors, links, buttons, pagination, selected items, and form focus states. Reuse this mechanism to derive hover, active, focus, and disabled states instead of introducing isolated color values. + +Light and dark modes use `data-bs-theme`. Bootstrap semantic variables and `@ui/src/common/color.scss` adapt surfaces, text, and borders. Dark mode links use lighter primary shades derived by the existing theme logic. Avoid hardcoded light backgrounds in components. + +## Typography + +Use Bootstrap's default system font stack, sizes, weights, and line heights. Establish hierarchy with semantic headings, body text, and existing utilities such as `small`. Keep the existing typography scale and system fonts. Project utilities such as `.small` and `.fs-12` follow their global stylesheet definitions. + +Long questions, answers, and code should wrap or scroll locally without overflowing the page. Preserve semantic headings, form labels, and body structure. + +## Layout + +Use Bootstrap responsive containers, grids, breakpoints, and spacing utilities. Reuse neighboring page layouts first. Pages typically combine navigation, main content, and an optional sidebar. Stack content naturally on narrow screens and keep primary actions accessible. + +The existing sidebar layout is defined in `@ui/src/common/sideNavLayout.scss`: `.main-mx-with` has a maximum width of `1072px`; `.page-right-side` has a desktop width of `300px` and becomes full width below `1199.9px`. Inherit these values when using that layout, rather than imposing them on every page. + +## Elevation & Depth + +Use Bootstrap borders, surface layers, and default overlay styles to distinguish regions. Preserve the existing navigation shadow. Keep ordinary content areas free of additional decorative shadows. Dropdowns, tooltips, and modals follow component defaults for stacking and positioning. + +## Shapes + +Buttons, inputs, cards, and modals retain Bootstrap default radii and borders. Domain elements such as avatars and tags reuse their existing component shapes. Do not apply a universal pill or square treatment. + +## Motion & Micro-interaction + +Use React Bootstrap's built-in collapse, fade, and component state feedback. Preserve default transition timing and honor `prefers-reduced-motion`. Avoid decorative looping animation. Asynchronous actions should communicate loading and prevent duplicate submission. + +## Voice & Content Strategy + +Write direct, friendly copy with clear action names and consistent Q&A terminology. Reuse existing translation keys in `i18n/`. Add new copy through the internationalization workflow rather than hardcoding a single language in components. + +Action labels describe outcomes, such as “Post question” and “Save changes.” Empty states explain what is missing and suggest a next step. Errors explain the failure and an actionable remedy. Dates, numbers, and capitalization follow the active locale and neighboring interfaces. + +## Components + +Prefer components exported by `react-bootstrap` and reuse existing domain wrappers in `ui/src/components/`. + +- **Buttons:** Use `Button variant="primary"` for primary actions. Use existing secondary, outline, or link variants for secondary actions. Preserve danger semantics for destructive actions. +- **Forms:** Use standard `Form`, `Form.Control`, and `Form.Select` components. Keep labels, help text, validation messages, and visible focus. Checked states and focus colors follow the theme. +- **Navigation and pagination:** Reuse Nav, Navbar, Dropdown, and Pagination. Selected states follow primary; sizing and keyboard behavior follow component defaults. +- **Content and feedback:** Reuse Card, ListGroup, Alert, Modal, and Tooltip. Question tags retain existing tag components and `.badge-tag` styling. +- **Icons:** Use the project's existing Bootstrap Icons. Give icon buttons accessible names. + +These tokens describe only the brand color mapping for default primary buttons. Bootstrap supplies other properties, and the existing theme implementation derives interaction states. + +```yaml +components: + button-primary: + backgroundColor: "{colors.primary}" + button-outline-primary: + textColor: "{colors.primary}" +``` + +## Do's and Don'ts + +- Prefer component props, Bootstrap utilities, and semantic CSS variables. +- Maintain primary at the theme entry points; avoid repeating hardcoded `#0033FF` in domain components. +- Preserve hover, focus, active, disabled, loading, and validation states. +- Check light mode, dark mode, narrow screens, and keyboard interaction. Keep text, icons, and focus indicators clearly visible. +- Keep the existing font, radius, shadow, spacing, and button systems. +- Preserve danger, success, and warning semantics. Communicate status through more than color alone. From 0ed4fecd5513c970d8dae7ad0ca5483b9fc640c0 Mon Sep 17 00:00:00 2001 From: Anurag Mishra Date: Sat, 21 Nov 2026 04:47:26 +0000 Subject: [PATCH 2/3] feat(mcp): expose semantic_search tool on the MCP server The semantic search tool, handler and availability check already existed but RegisterMCPRouter only registered the six basic tools, so external MCP clients could not use semantic search even with a VectorSearch plugin enabled. Register semantic_search next to the basic tools when a VectorSearch plugin is available, matching how the AI chat tool list hides the tool when it cannot succeed. The registration is split into addMCPTools so the conditional is covered by a test without a live plugin registry. --- internal/router/mcp_router.go | 24 ++++++--- internal/router/mcp_router_test.go | 81 ++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 6 deletions(-) create mode 100644 internal/router/mcp_router_test.go diff --git a/internal/router/mcp_router.go b/internal/router/mcp_router.go index 54f41971d..c07b8cc51 100644 --- a/internal/router/mcp_router.go +++ b/internal/router/mcp_router.go @@ -20,6 +20,7 @@ package router import ( + "github.com/apache/answer/internal/controller" "github.com/apache/answer/internal/schema/mcp_tools" "github.com/gin-gonic/gin" "github.com/mark3labs/mcp-go/server" @@ -28,12 +29,7 @@ import ( func (a *AnswerAPIRouter) RegisterMCPRouter(r *gin.RouterGroup) { s := server.NewMCPServer("Answer Enterprise MCP Server", "1.0.0") - s.AddTool(mcp_tools.NewQuestionsTool(), a.mcpController.MCPQuestionsHandler()) - s.AddTool(mcp_tools.NewAnswersTool(), a.mcpController.MCPAnswersHandler()) - s.AddTool(mcp_tools.NewCommentsTool(), a.mcpController.MCPCommentsHandler()) - s.AddTool(mcp_tools.NewTagsTool(), a.mcpController.MCPTagsHandler()) - s.AddTool(mcp_tools.NewTagDetailTool(), a.mcpController.MCPTagDetailsHandler()) - s.AddTool(mcp_tools.NewUserTool(), a.mcpController.MCPUserDetailsHandler()) + addMCPTools(s, a.mcpController, a.mcpController.SemanticSearchAvailable()) sseServer := server.NewSSEServer(s, server.WithSSEEndpoint("/answer/api/v1/mcp/see"), @@ -42,3 +38,19 @@ func (a *AnswerAPIRouter) RegisterMCPRouter(r *gin.RouterGroup) { r.GET("/mcp/sse", gin.WrapH(sseServer.SSEHandler())) r.POST("/mcp/message", gin.WrapH(sseServer.MessageHandler())) } + +// addMCPTools registers the tools the public MCP server exposes. semantic_search +// is registered only when a VectorSearch plugin is enabled, so an external client +// is never offered a capability that always fails, matching the tool list the AI +// chat builds. +func addMCPTools(s *server.MCPServer, c *controller.MCPController, semanticSearchAvailable bool) { + s.AddTool(mcp_tools.NewQuestionsTool(), c.MCPQuestionsHandler()) + s.AddTool(mcp_tools.NewAnswersTool(), c.MCPAnswersHandler()) + s.AddTool(mcp_tools.NewCommentsTool(), c.MCPCommentsHandler()) + s.AddTool(mcp_tools.NewTagsTool(), c.MCPTagsHandler()) + s.AddTool(mcp_tools.NewTagDetailTool(), c.MCPTagDetailsHandler()) + s.AddTool(mcp_tools.NewUserTool(), c.MCPUserDetailsHandler()) + if semanticSearchAvailable { + s.AddTool(mcp_tools.NewSemanticSearchTool(), c.MCPSemanticSearchHandler()) + } +} diff --git a/internal/router/mcp_router_test.go b/internal/router/mcp_router_test.go new file mode 100644 index 000000000..7051993d3 --- /dev/null +++ b/internal/router/mcp_router_test.go @@ -0,0 +1,81 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package router + +import ( + "sort" + "testing" + + "github.com/apache/answer/internal/controller" + "github.com/mark3labs/mcp-go/server" +) + +const semanticSearchToolName = "semantic_search" + +var basicMCPToolNames = []string{ + "get_questions", + "get_answers_by_question_id", + "get_comments", + "get_tags", + "get_tag_detail", + "get_user", +} + +func registeredMCPToolNames(tools map[string]*server.ServerTool) []string { + names := make([]string, 0, len(tools)) + for name := range tools { + names = append(names, name) + } + sort.Strings(names) + return names +} + +func TestAddMCPToolsRegistersSemanticSearchWhenAvailable(t *testing.T) { + s := server.NewMCPServer("test", "1.0.0") + addMCPTools(s, &controller.MCPController{}, true) + + tools := s.ListTools() + if _, ok := tools[semanticSearchToolName]; !ok { + t.Fatalf("semantic_search must be registered when a vector search plugin is available: %v", registeredMCPToolNames(tools)) + } + for _, name := range basicMCPToolNames { + if _, ok := tools[name]; !ok { + t.Fatalf("%s must stay registered: %v", name, registeredMCPToolNames(tools)) + } + } +} + +func TestAddMCPToolsOmitsSemanticSearchWhenUnavailable(t *testing.T) { + s := server.NewMCPServer("test", "1.0.0") + addMCPTools(s, &controller.MCPController{}, false) + + tools := s.ListTools() + if _, ok := tools[semanticSearchToolName]; ok { + t.Fatalf("semantic_search must not be registered without a vector search plugin: %v", registeredMCPToolNames(tools)) + } + if len(tools) != len(basicMCPToolNames) { + t.Fatalf("expect %d tools, got %d: %v", len(basicMCPToolNames), len(tools), registeredMCPToolNames(tools)) + } + for _, name := range basicMCPToolNames { + if _, ok := tools[name]; !ok { + t.Fatalf("%s must stay registered: %v", name, registeredMCPToolNames(tools)) + } + } +} From c9a474199408deba78462e75ac64152bf77edaef Mon Sep 17 00:00:00 2001 From: Anurag Mishra <97835032+shaktimaan00@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:57:44 +0000 Subject: [PATCH 3/3] fix(mcp): answer semantic_search only from public questions and answers The vector index keeps every synced record, so a question hidden or deleted after the sync was still returned by semantic_search, and answers/comments were read without a status check. Gate every result on the parent question with mcpQuestionIsPublic, the same check the other MCP handlers use, and skip answers and comments that are no longer available. --- internal/controller/mcp_controller.go | 54 +++++++++++++-------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/internal/controller/mcp_controller.go b/internal/controller/mcp_controller.go index 81e23e859..7fd7c9662 100644 --- a/internal/controller/mcp_controller.go +++ b/internal/controller/mcp_controller.go @@ -419,6 +419,17 @@ func (c *MCPController) MCPSemanticSearchHandler() func(ctx context.Context, req var meta plugin.VectorSearchMetadata _ = json.Unmarshal([]byte(r.Metadata), &meta) + // The vector index holds every synced record, so a question hidden or + // deleted after the sync is still in it. A result is only answered from + // what the other MCP handlers would show, never from the index alone. + question, qErr := c.questioncommon.Info(ctx, meta.QuestionID, "") + if qErr != nil { + log.Warnf("get question %s for semantic search failed: %v", meta.QuestionID, qErr) + } + if !mcpQuestionIsPublic(question) { + continue + } + item := &schema.MCPSemanticSearchResp{ ObjectID: r.ObjectID, ObjectType: r.ObjectType, @@ -434,18 +445,13 @@ func (c *MCPController) MCPSemanticSearchHandler() func(ctx context.Context, req // Query content from DB using IDs stored in metadata if r.ObjectType == "question" { - question, qErr := c.questioncommon.Info(ctx, meta.QuestionID, "") - if qErr != nil { - log.Warnf("get question %s for semantic search failed: %v", meta.QuestionID, qErr) - } else { - item.Title = question.Title - item.Content = question.Content - } + item.Title = question.Title + item.Content = question.Content // Fetch answers by ID from metadata for _, a := range meta.Answers { answerEntity, exist, aErr := c.answerRepo.GetAnswer(ctx, a.AnswerID) - if aErr != nil || !exist { + if aErr != nil || !exist || answerEntity.Status != entity.AnswerStatusAvailable { continue } answerItem := &schema.MCPSemanticSearchAnswer{ @@ -455,7 +461,7 @@ func (c *MCPController) MCPSemanticSearchHandler() func(ctx context.Context, req // Fetch comments on this answer from DB for _, ac := range a.Comments { cmt, cExist, cErr := c.commentRepo.GetComment(ctx, ac.CommentID) - if cErr == nil && cExist { + if cErr == nil && cExist && cmt.Status == entity.CommentStatusAvailable { answerItem.Comments = append(answerItem.Comments, &schema.MCPSemanticSearchComment{ CommentID: ac.CommentID, Content: cmt.OriginalText, @@ -468,7 +474,7 @@ func (c *MCPController) MCPSemanticSearchHandler() func(ctx context.Context, req // Fetch question comments from DB for _, qc := range meta.Comments { cmt, cExist, cErr := c.commentRepo.GetComment(ctx, qc.CommentID) - if cErr == nil && cExist { + if cErr == nil && cExist && cmt.Status == entity.CommentStatusAvailable { item.Comments = append(item.Comments, &schema.MCPSemanticSearchComment{ CommentID: qc.CommentID, Content: cmt.OriginalText, @@ -476,30 +482,24 @@ func (c *MCPController) MCPSemanticSearchHandler() func(ctx context.Context, req } } } else if r.ObjectType == "answer" { - // Fetch question title for context - question, qErr := c.questioncommon.Info(ctx, meta.QuestionID, "") - if qErr == nil { - item.Title = question.Title + // Fetch answer content from DB; the answer a result stands for must + // still be available, or there is nothing to show for this result. + answerID := meta.AnswerID + if answerID == "" && len(meta.Answers) > 0 { + answerID = meta.Answers[0].AnswerID } - - // Fetch answer content from DB - if meta.AnswerID != "" { - answerEntity, exist, aErr := c.answerRepo.GetAnswer(ctx, meta.AnswerID) - if aErr == nil && exist { - item.Content = answerEntity.OriginalText - } - } else if len(meta.Answers) > 0 { - answerEntity, exist, aErr := c.answerRepo.GetAnswer(ctx, meta.Answers[0].AnswerID) - if aErr == nil && exist { - item.Content = answerEntity.OriginalText - } + answerEntity, exist, aErr := c.answerRepo.GetAnswer(ctx, answerID) + if aErr != nil || !exist || answerEntity.Status != entity.AnswerStatusAvailable { + continue } + item.Title = question.Title + item.Content = answerEntity.OriginalText // Fetch answer comments from DB if len(meta.Answers) > 0 { for _, ac := range meta.Answers[0].Comments { cmt, cExist, cErr := c.commentRepo.GetComment(ctx, ac.CommentID) - if cErr == nil && cExist { + if cErr == nil && cExist && cmt.Status == entity.CommentStatusAvailable { item.Comments = append(item.Comments, &schema.MCPSemanticSearchComment{ CommentID: ac.CommentID, Content: cmt.OriginalText,