diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 773ad9c0..5fdabf22 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -7,7 +7,11 @@ "Bash(dotnet ef migrations add AddStarsAndForksToWarehouse --project src/KoalaWiki --context KoalaWikiContext)", "Bash(dotnet ef migrations add AddStarsAndForksToWarehouse --project src/KoalaWiki --context IKoalaWikiContext)", "Bash(find OpenDeepWiki -type f -name \"*.cs\")", - "Bash(git add:*)" + "Bash(git add:*)", + "WebFetch(domain:docs.anthropic.com)", + "WebFetch(domain:learn.microsoft.com)", + "Bash(dotnet build:*)", + "Bash(npm run build:*)" ], "deny": [] } diff --git a/Directory.Packages.props b/Directory.Packages.props index b4d49c7a..10bf977c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -57,9 +57,9 @@ - - - + + + diff --git a/README.md b/README.md index 6602159e..0d6d3ddb 100644 --- a/README.md +++ b/README.md @@ -307,10 +307,10 @@ make build-frontend-amd # Frontend only AMD # Community -- Discord: [join us](https://discord.gg/8sxUNacv) -- WeChat Official Account QR Code: +- Discord: [join us](https://discord.gg/Y3fvpnGVwt) +- Feishu QR Code: -![WeChat QR](/img/wechat.jpg) +![Feishu](/img/feishu.png) --- diff --git a/README.zh-CN.md b/README.zh-CN.md index 751fadcc..04f3c963 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -307,10 +307,10 @@ make build-frontend-amd # 仅前端AMD # 交流社区 Community -- Discord: [join us](https://discord.gg/8sxUNacv) -- 微信公众号二维码: +- Discord: [join us](https://discord.gg/Y3fvpnGVwt) +- 飞书交流群二维码: -![WeChat QR](/img/wechat.jpg) +![飞书交流群](/img/feishu.png) --- diff --git a/docker-compose-mem0.yml b/docker-compose-mem0.yml index 08bbdc47..1c0481fd 100644 --- a/docker-compose-mem0.yml +++ b/docker-compose-mem0.yml @@ -71,6 +71,7 @@ koalawiki-web: image: crpi-j9ha7sxwhatgtvj4.cn-shenzhen.personal.cr.aliyuncs.com/koala-ai/koala-wiki-web + command: ["/app/start.sh"] networks: - koala_network environment: diff --git a/docker-compose-mysql.yml b/docker-compose-mysql.yml index 483b4420..3b5983f8 100644 --- a/docker-compose-mysql.yml +++ b/docker-compose-mysql.yml @@ -53,6 +53,7 @@ koalawiki-web: image: crpi-j9ha7sxwhatgtvj4.cn-shenzhen.personal.cr.aliyuncs.com/koala-ai/koala-wiki-web + command: ["/app/start.sh"] environment: - NEXT_PUBLIC_API_URL=http://koalawiki:8080 # 用于提供给server的地址 build: diff --git a/docker-compose.yml b/docker-compose.yml index 3fa59892..e6281758 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -31,6 +31,7 @@ koalawiki-web: image: crpi-j9ha7sxwhatgtvj4.cn-shenzhen.personal.cr.aliyuncs.com/koala-ai/koala-wiki-web + command: ["/app/start.sh"] environment: - NEXT_PUBLIC_API_URL=http://koalawiki:8080 # 用于提供给server的地址 build: diff --git a/img/feishu.png b/img/feishu.png new file mode 100644 index 00000000..693cc2d7 Binary files /dev/null and b/img/feishu.png differ diff --git a/src/KoalaWiki/BackendService/WarehouseTask.cs b/src/KoalaWiki/BackendService/WarehouseTask.cs index 685d4ac2..2d86e676 100644 --- a/src/KoalaWiki/BackendService/WarehouseTask.cs +++ b/src/KoalaWiki/BackendService/WarehouseTask.cs @@ -67,12 +67,24 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) activity?.SetTag("git.version", info.Version); activity?.SetTag("git.local_path", info.LocalPath); - await dbContext!.Warehouses.Where(x => x.Id == value.Id) - .ExecuteUpdateAsync(x => x.SetProperty(a => a.Name, info.RepositoryName) - .SetProperty(x => x.Branch, info.BranchName) - .SetProperty(x => x.Version, info.Version) - .SetProperty(x => x.Status, WarehouseStatus.Processing) - .SetProperty(x => x.OrganizationName, info.Organization), stoppingToken); + // 判断是否组织名称和项目名称为空 + if (string.IsNullOrEmpty(value.OrganizationName) && string.IsNullOrEmpty(value.Name)) + { + await dbContext!.Warehouses.Where(x => x.Id == value.Id) + .ExecuteUpdateAsync(x => + x.SetProperty(a => a.Name, info.RepositoryName) + .SetProperty(x => x.Branch, info.BranchName) + .SetProperty(x => x.Version, info.Version) + .SetProperty(x => x.Status, WarehouseStatus.Processing) + .SetProperty(x => x.OrganizationName, info.Organization), stoppingToken); + } + else + { + await dbContext!.Warehouses.Where(x => x.Id == value.Id) + .ExecuteUpdateAsync(x => + x.SetProperty(x => x.Version, info.Version) + .SetProperty(x => x.Status, WarehouseStatus.Processing), stoppingToken); + } logger.LogInformation("更新仓库信息到数据库完成,仓库ID:{Id}", value.Id); diff --git a/src/KoalaWiki/CodeMap/CodeMap.cs b/src/KoalaWiki/CodeMap/CodeMap.cs index 9a6698be..c17a478e 100644 --- a/src/KoalaWiki/CodeMap/CodeMap.cs +++ b/src/KoalaWiki/CodeMap/CodeMap.cs @@ -298,7 +298,7 @@ private DependencyTree BuildFileDependencyTree(string filePath, HashSet return tree; } - private DependencyTree BuildFunctionDependencyTree(string filePath, string functionName, HashSet visited, int level, int maxDepth = 10) + private DependencyTree BuildFunctionDependencyTree(string filePath, string functionName, HashSet visited, int level, int maxDepth = 2) { var fullFunctionId = $"{filePath}:{functionName}"; @@ -354,7 +354,6 @@ private DependencyTree BuildFunctionDependencyTree(string filePath, string funct private HashSet ResolveImportPaths(List imports, string currentFile, string basePath) { var result = new HashSet(); - var currentDir = Path.GetDirectoryName(currentFile); var parser = GetParserForFile(currentFile); foreach (var import in imports) @@ -417,7 +416,7 @@ private ILanguageParser GetParserForFile(string filePath) return extension switch { - // ".cs" => _parsers.FirstOrDefault(p => p is CSharpParser), + ".cs" => _parsers.FirstOrDefault(p => p is CSharpParser), ".js" => _parsers.FirstOrDefault(p => p is JavaScriptParser), ".py" => _parsers.FirstOrDefault(p => p is PythonParser), ".java" => _parsers.FirstOrDefault(p => p is JavaParser), diff --git a/src/KoalaWiki/Functions/AgentFunction.cs b/src/KoalaWiki/Functions/AgentFunction.cs index b1f26d41..448e3efd 100644 --- a/src/KoalaWiki/Functions/AgentFunction.cs +++ b/src/KoalaWiki/Functions/AgentFunction.cs @@ -1,342 +1,89 @@ -// using System.ComponentModel; -// using System.Text; -// using System.Text.Json; -// using KoalaWiki.Functions.Model; -// -// namespace KoalaWiki.Functions; -// -// public class AgentFunction -// { -// private List? _input; -// -// [KernelFunction, -// Description( -// """ -// Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user. -// It also helps the user understand the progress of the task and overall progress of their requests. -// -// ## When to Use This Tool -// Use this tool proactively in these scenarios: -// -// 1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions -// 2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations -// 3. User explicitly requests todo list - When the user directly asks you to use the todo list -// 4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated) -// 5. After receiving new instructions - Immediately capture user requirements as todos -// 6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time -// 7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation -// -// ## When NOT to Use This Tool -// -// Skip using this tool when: -// 1. There is only a single, straightforward task -// 2. The task is trivial and tracking it provides no organizational benefit -// 3. The task can be completed in less than 3 trivial steps -// 4. The task is purely conversational or informational -// -// NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly. -// -// ## Examples of When to Use the Todo List -// -// -// User: I want to add a dark mode toggle to the application settings. Make sure you run the tests and build when you're done! -// Assistant: I'll help add a dark mode toggle to your application settings. Let me create a todo list to track this implementation. -// *Creates todo list with the following items:* -// 1. Create dark mode toggle component in Settings page -// 2. Add dark mode state management (context/store) -// 3. Implement CSS-in-JS styles for dark theme -// 4. Update existing components to support theme switching -// 5. Run tests and build process, addressing any failures or errors that occur -// *Begins working on the first task* -// -// -// The assistant used the todo list because: -// 1. Adding dark mode is a multi-step feature requiring UI, state management, and styling changes -// 2. The user explicitly requested tests and build be run afterward -// 3. The assistant inferred that tests and build need to pass by adding \\\"Ensure tests and build succeed\\\" as the final task -// -// -// -// -// User: Help me rename the function getCwd to getCurrentWorkingDirectory across my project -// Assistant: Let me first search through your codebase to find all occurrences of 'getCwd'. -// *Uses grep or search tools to locate all instances of getCwd in the codebase* -// Assistant: I've found 15 instances of 'getCwd' across 8 different files. Let me create a todo list to track these changes. -// *Creates todo list with specific items for each file that needs updating* -// -// -// The assistant used the todo list because: -// 1. First, the assistant searched to understand the scope of the task -// 2. Upon finding multiple occurrences across different files, it determined this was a complex task with multiple steps -// 3. The todo list helps ensure every instance is tracked and updated systematically -// 4. This approach prevents missing any occurrences and maintains code consistency -// -// -// -// -// -// User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow. -// Assistant: I'll help implement these features. First, let's add all the features to the todo list. -// *Creates a todo list breaking down each feature into specific tasks based on the project architecture* -// Assistant: Let's start with user registration. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system. -// -// -// The assistant used the todo list because: -// 1. The user provided multiple complex features to implement in a comma separated list -// 2. The todo list helps organize these large features into manageable tasks -// 3. This approach allows for tracking progress across the entire implementation -// -// -// -// -// User: Can you help optimize my React application? It's rendering slowly and has performance issues. -// Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks. -// *Reviews component structure, render patterns, state management, and data fetching* -// Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts. -// *Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting* -// Let's start by implementing memoization for the expensive calculations in your ProductList component. -// -// -// The assistant used the todo list because: -// 1. First, the assistant examined the codebase to identify specific performance issues -// 2. Based on this analysis, it identified multiple optimization opportunities -// 3. Performance optimization is a non-trivial task requiring multiple steps -// 4. The todo list helps methodically track improvements across different components -// 5. This systematic approach ensures all performance bottlenecks are addressed -// -// -// -// ## Examples of When NOT to Use the Todo List -// -// -// User: How do I print 'Hello World' in Python? -// Assistant: In Python, you can print \\\"Hello World\\\" with this simple code: -// -// python -// print(\\\"Hello World\\\") -// -// This will output the text \\\"Hello World\\\" to the console when executed. -// -// -// The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request. -// -// -// -// -// User: What does the git status command do? -// Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits. -// -// -// The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks. -// -// -// -// -// User: Can you add a comment to the calculateTotal function to explain what it does? -// Assistant: Sure, let me add a comment to the calculateTotal function to explain what it does. -// * Uses the Edit tool to add a comment to the calculateTotal function * -// -// -// The assistant did not use the todo list because this is a single, straightforward task confined to one location in the code. Adding a comment doesn't require tracking multiple steps or systematic organization. -// -// -// -// -// User: Run npm install for me and tell me what happens. -// Assistant: I'll run the npm install command for you. -// -// *Executes: npm install* -// -// The command completed successfully. Here's the output: -// [Output of npm install command] -// -// All dependencies have been installed according to your package.json file. -// -// -// The assistant did not use the todo list because this is a single command execution with immediate results. There are no multiple steps to track or organize, making the todo list unnecessary for this straightforward task. -// -// -// -// ## Task States and Management -// -// 1. **Task States**: Use these states to track progress: -// - pending: Task not yet started -// - in_progress: Currently working on (limit to ONE task at a time) -// - completed: Task finished successfully -// -// 2. **Task Management**: -// - Update task status in real-time as you work -// - Mark tasks complete IMMEDIATELY after finishing (don't batch completions) -// - Only have ONE task in_progress at any time -// - Complete current tasks before starting new ones -// - Remove tasks that are no longer relevant from the list entirely -// -// 3. **Task Completion Requirements**: -// - ONLY mark a task as completed when you have FULLY accomplished it -// - If you encounter errors, blockers, or cannot finish, keep the task as in_progress -// - When blocked, create a new task describing what needs to be resolved -// - Never mark a task as completed if: -// - Tests are failing -// - Implementation is partial -// - You encountered unresolved errors -// - You couldn't find necessary files or dependencies -// -// 4. **Task Breakdown**: -// - Create specific, actionable items -// - Break complex tasks into smaller, manageable steps -// - Use clear, descriptive task names -// -// When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully. -// """)] -// public string TodoWrite( -// [Description("The updated todo list")] -// TodoInputItem[] todos) -// { -// if (_input == null) -// { -// // 初始化TODO列表 -// _input = new List(todos); -// // 设置控制台编码支持UTF-8 -// Console.OutputEncoding = System.Text.Encoding.UTF8; -// Console.WriteLine("□ Initializing TODO list..."); -// // 通过控制台打印一下TODO -// foreach (var item in todos) -// { -// // 根据item等级渲染不同颜色 -// if (item.Priority == Priority.High) -// { -// Console.ForegroundColor = ConsoleColor.Red; -// } -// else if (item.Priority == Priority.Medium) -// { -// Console.ForegroundColor = ConsoleColor.Yellow; -// } -// else -// { -// Console.ForegroundColor = ConsoleColor.Green; -// } -// -// Console.Write("□ "); -// Console.Write(item.Content); -// Console.WriteLine(); -// -// Console.ResetColor(); -// } -// -// return GenerateInitialTodoMessage(todos); -// } -// else -// { -// // 添加新的TODO项 -// var newItems = todos.Where(x => _input.All(existing => existing.Id != x.Id)).ToList(); -// _input.AddRange(newItems); -// -// // 更新现有TODO项的状态 -// foreach (var item in _input) -// { -// var updatedItem = todos.FirstOrDefault(x => x.Id == item.Id); -// if (updatedItem == null) continue; -// item.Status = updatedItem.Status; -// item.Content = updatedItem.Content; -// item.Priority = updatedItem.Priority; -// } -// -// Console.WriteLine("□ Updating TODO list..."); -// foreach (var item in _input) -// { -// // 根据item等级渲染不同颜色 -// if (item.Priority == Priority.High) -// { -// Console.ForegroundColor = ConsoleColor.Red; -// } -// else if (item.Priority == Priority.Medium) -// { -// Console.ForegroundColor = ConsoleColor.Yellow; -// } -// else -// { -// Console.ForegroundColor = ConsoleColor.Green; -// } -// -// if (item.Status == TodoInputItemStatus.Pending) -// { -// Console.Write("□ "); -// } -// else if (item.Status == TodoInputItemStatus.InProgress) -// { -// Console.Write("■ "); -// } -// else if (item.Status == TodoInputItemStatus.Completed) -// { -// Console.Write("✓ "); -// } -// -// Console.Write(item.Content); -// Console.WriteLine(); -// Console.ResetColor(); -// } -// -// return GenerateUpdateTodoMessage(_input.ToArray()); -// } -// } -// -// private string GenerateInitialTodoMessage(TodoInputItem[] input) -// { -// var sb = new StringBuilder(); -// sb.AppendLine( -// "Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable"); -// sb.AppendLine(); -// -// // 返回当前TODO列表的JSON字符串 -// var currentTodoJson = SerializeTodoList(input); -// sb.AppendLine(""); -// sb.AppendLine( -// "Your todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list:"); -// sb.AppendLine(); -// sb.AppendLine(currentTodoJson); -// sb.AppendLine(". Continue on with the tasks at hand if applicable."); -// sb.AppendLine(""); -// -// return sb.ToString(); -// } -// -// private string GenerateUpdateTodoMessage(TodoInputItem[] todoList) -// { -// var sb = new StringBuilder(); -// sb.AppendLine( -// "Todos have been modified successfully. Ensure that you continue to use the todo list to track your progress. Please proceed with the current tasks if applicable"); -// sb.AppendLine(); -// -// // 返回当前TODO列表的JSON字符串 -// var currentTodoJson = SerializeTodoList(todoList); -// sb.AppendLine(""); -// sb.AppendLine( -// "Your todo list has changed. DO NOT mention this explicitly to the user. Here are the latest contents of your todo list:"); -// sb.AppendLine(); -// sb.AppendLine(currentTodoJson); -// sb.AppendLine(". Continue on with the tasks at hand if applicable."); -// sb.AppendLine(""); -// -// return sb.ToString(); -// } -// -// private string SerializeTodoList(TodoInputItem[] todoList) -// { -// var todoItems = todoList.Select(item => new -// { -// content = item.Content, -// status = item.Status.ToString().ToLowerInvariant(), -// priority = item.Priority.ToString().ToLowerInvariant(), -// id = item.Id -// }).ToList(); -// -// var options = new JsonSerializerOptions -// { -// WriteIndented = false, -// Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, -// PropertyNamingPolicy = JsonNamingPolicy.CamelCase -// }; -// -// return JsonSerializer.Serialize(todoItems, options); -// } -// } \ No newline at end of file +using System.ComponentModel; + +namespace KoalaWiki.Functions; + +public class AgentFunction +{ + [KernelFunction, Description(""" + Use this tool to engage in deep, structured thinking about complex problems, user requirements, or challenging decisions. This tool helps you process information systematically and provides your thought process back to enhance understanding and decision-making. + + ## When to Use This Tool + Use this tool proactively in these scenarios: + + 1. **Complex Problem Analysis** - When facing multi-faceted problems that require careful consideration + 2. **Requirement Clarification** - When user requests are ambiguous and need deeper exploration + 3. **Decision Points** - When multiple approaches exist and you need to evaluate trade-offs + 4. **Architecture Planning** - When designing systems or making technical decisions + 5. **Risk Assessment** - When considering potential issues or complications + 6. **Learning from Context** - When analyzing existing code or systems to understand patterns + + ## Core Thinking Principles + + 1. **Question Assumptions** - Challenge initial interpretations and explore alternatives + 2. **Break Down Complexity** - Decompose complex problems into manageable components + 3. **Consider Multiple Perspectives** - Look at problems from different angles + 4. **Evaluate Trade-offs** - Weigh pros and cons of different approaches + 5. **Anticipate Consequences** - Think through potential implications and side effects + 6. **Build on Context** - Use existing knowledge and patterns to inform decisions + + ## Thinking Process Structure + + Your thought process should follow this pattern: + + 1. **Initial Understanding** - What is the core problem or requirement? + 2. **Context Analysis** - What relevant information do we have? + 3. **Assumption Identification** - What assumptions am I making? + 4. **Alternative Exploration** - What other approaches could work? + 5. **Trade-off Evaluation** - What are the pros and cons of each option? + 6. **Decision Rationale** - Why is this the best approach? + 7. **Implementation Considerations** - What practical factors matter? + 8. **Risk Assessment** - What could go wrong and how to mitigate? + + ## Examples of Deep Thinking Scenarios + + + User: "I want to add real-time notifications to my app" + Thought Process: + - Initial Understanding: User wants real-time notifications, but what type? Push notifications, in-app notifications, or both? + - Context Analysis: Need to examine existing tech stack, user base size, notification frequency + - Assumptions: Assuming they want both types, but should clarify the specific use cases + - Alternatives: WebSockets, Server-Sent Events, Push API, third-party services + - Trade-offs: WebSockets offer full duplex but require more infrastructure; SSE is simpler but one-way + - Decision: Recommend starting with requirements clarification, then suggest appropriate technology based on their specific needs + - Implementation: Consider scalability, reliability, user preferences + - Risks: Notification fatigue, performance impact, complexity overhead + + + + User: "This code is running slowly, can you help optimize it?" + Thought Process: + - Initial Understanding: Performance issue exists, but need to identify bottlenecks + - Context Analysis: Need to examine the code, understand data volumes, usage patterns + - Assumptions: Assuming it's algorithmic complexity, but could be I/O, memory, or network + - Alternatives: Algorithm optimization, caching, database indexing, parallel processing + - Trade-offs: Code complexity vs performance gains, memory usage vs speed + - Decision: Profile first to identify actual bottlenecks before optimizing + - Implementation: Measure performance, implement targeted optimizations + - Risks: Premature optimization, breaking existing functionality, over-engineering + + + ## Guidelines for Effective Thinking + + 1. **Be Thorough** - Don't rush to conclusions; explore the problem space fully + 2. **Stay Objective** - Consider evidence and logic over preferences + 3. **Embrace Uncertainty** - It's okay to acknowledge when you need more information + 4. **Think Practically** - Consider real-world constraints and limitations + 5. **Document Reasoning** - Clearly explain your thought process and rationale + 6. **Iterate and Refine** - Be prepared to revise your thinking as new information emerges + + The goal is to provide well-reasoned, thoughtful analysis that leads to better outcomes and helps others understand complex problems more clearly. + """)] + public string DeepThinking( + [Description( + "Your structured thought process about the problem, following the thinking framework provided in the tool description. This should be a detailed analysis that explores the problem from multiple angles.")] + string thought) + { + Console.WriteLine("深入思考:\n" + thought); + return thought; + } +} \ No newline at end of file diff --git a/src/KoalaWiki/Functions/FileFunction.cs b/src/KoalaWiki/Functions/FileFunction.cs index b92a7522..34afd609 100644 --- a/src/KoalaWiki/Functions/FileFunction.cs +++ b/src/KoalaWiki/Functions/FileFunction.cs @@ -4,13 +4,12 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; -using Microsoft.SemanticKernel; using OpenDeepWiki.CodeFoundation; using OpenDeepWiki.CodeFoundation.Utils; namespace KoalaWiki.Functions; -public class FileFunction(string gitPath) +public class FileFunction(string gitPath, List? files) { private readonly CodeCompressionService _codeCompressionService = new(); private int _count; @@ -47,11 +46,7 @@ public async Task ReadFileAsync( "⛔ STOP reading files immediately and complete analysis with existing da2000ta."; } - if (DocumentContext.DocumentStore?.Files != null) - { - DocumentContext.DocumentStore.Files.Add(filePath); - } - + files?.Add(filePath); filePath = Path.Combine(gitPath, filePath.TrimStart('/')); Console.WriteLine($"Reading file: {filePath}"); @@ -95,21 +90,22 @@ public async Task ReadFileAsync( /// /// /// - [KernelFunction(name: "Glob"), + [KernelFunction(name: "Glob"), Description( - """ - - Fast file pattern matching tool for targeted file searches in codebases - - Use specific patterns like \"*.js\", \"src/**/*.tsx\", \"components/**/*.css\" to find relevant files - - Avoid broad patterns like \"**/*\" or \"*\" which scan entire directories - - Focus on searching for files related to specific features, technologies, or file types - - Returns matching file paths sorted by modification time - - Best for finding files when you know the general location or file extension - - When you need open-ended exploration, use the Agent tool instead of broad scanning - - You have the capability to call multiple tools in a single response for targeted searches - - Examples: \"pages/**/*.tsx\" (React pages), \"*.config.js\" (config files), \"src/components/**/*.ts\" (TypeScript components) - """)] + """ + - Fast file pattern matching tool for targeted file searches in codebases + - Use specific patterns like \"*.js\", \"src/**/*.tsx\", \"components/**/*.css\" to find relevant files + - Avoid broad patterns like \"**/*\" or \"*\" which scan entire directories + - Focus on searching for files related to specific features, technologies, or file types + - Returns matching file paths sorted by modification time + - Best for finding files when you know the general location or file extension + - When you need open-ended exploration, use the Agent tool instead of broad scanning + - You have the capability to call multiple tools in a single response for targeted searches + - Examples: \"pages/**/*.tsx\" (React pages), \"*.config.js\" (config files), \"src/components/**/*.ts\" (TypeScript components) + """)] public string Glob( - [Description("Specific glob pattern for targeted file search (e.g., '*.tsx', 'src/**/*.ts', 'components/**/*.css'). Avoid broad patterns like '**/*' or '*'.")] + [Description( + "Specific glob pattern for targeted file search (e.g., '*.tsx', 'src/**/*.ts', 'components/**/*.css'). Avoid broad patterns like '**/*' or '*'.")] string pattern, [Description( """ @@ -122,9 +118,10 @@ public string Glob( { if (pattern == "**/*") { - return "Please use a more specific pattern instead of '**/*'. This pattern is too broad and may cause performance issues. Try using patterns like '*.js', 'src/**/*.tsx', or 'components/**/*.css' to narrow down your search."; + return + "Please use a more specific pattern instead of '**/*'. This pattern is too broad and may cause performance issues. Try using patterns like '*.js', 'src/**/*.tsx', or 'components/**/*.css' to narrow down your search."; } - + // 如果没有指定路径,使用根目录 if (string.IsNullOrEmpty(path)) { @@ -141,21 +138,33 @@ public string Glob( return $"Directory not found: {path.Replace(gitPath, "").TrimStart(Path.DirectorySeparatorChar)}"; } - // 获取忽略文件列表 +// 检查目录是否存在 + if (!Directory.Exists(path)) + { + return $"Directory not found: {path.Replace(gitPath, "").TrimStart(Path.DirectorySeparatorChar)}"; + } + +// 获取忽略文件列表 var ignoreFiles = DocumentsHelper.GetIgnoreFiles(gitPath); - // 获取匹配的文件 - var matchedFiles = GetMatchingFiles(path, pattern, ignoreFiles); +// 使用改进的文件搜索方法 + var matchedFiles = new List(); + SearchFiles(path, pattern, matchedFiles, gitPath); - // 按修改时间排序 +// 排除忽略文件 + matchedFiles = matchedFiles + .Where(f => !ignoreFiles.Any(ignore => IsIgnoredFile(f, ignoreFiles))) + .ToList(); + +// 按修改时间排序 var sortedFiles = matchedFiles - .Select(f => new FileInfo(f)) + .Select(f => new FileInfo(Path.Combine(gitPath, f.Replace('/', Path.DirectorySeparatorChar)))) .Where(fi => fi.Exists) .OrderByDescending(fi => fi.LastWriteTime) .Select(fi => fi.FullName) .ToList(); - // 处理路径,去掉gitPath前缀 +// 处理路径,去掉gitPath前缀 var relativePaths = sortedFiles .Select(f => f.Replace(gitPath, "").TrimStart(Path.DirectorySeparatorChar)) .Select(f => f.Replace(Path.DirectorySeparatorChar, '/')) // 统一使用正斜杠 @@ -414,6 +423,8 @@ public async Task ReadItem( { try { + files?.Add(filePath); + filePath = Path.Combine(gitPath, filePath.TrimStart('/')); Console.WriteLine( $"Reading file from line {offset}: {filePath} offset={offset}, limit={limit}"); @@ -435,11 +446,6 @@ public async Task ReadItem( limit = int.MaxValue; } - if (DocumentContext.DocumentStore?.Files != null) - { - DocumentContext.DocumentStore.Files.Add(filePath); - } - // 先读取整个文件内容 string fileContent = await File.ReadAllTextAsync(filePath); @@ -497,6 +503,112 @@ The current file contains empty text content. return $"Error reading file: {ex.Message}"; } } + + /// + /// 使用迭代方式搜索文件,避免递归调用栈溢出 + /// + private void SearchFiles(string directory, string pattern, List results, string baseDirectory = null) + { + // 如果没有指定基础目录,使用当前目录作为基础 + if (baseDirectory == null) + baseDirectory = directory; + + // 使用栈来实现迭代遍历,避免递归 + var directoriesToSearch = new Stack(); + directoriesToSearch.Push(directory); + + while (directoriesToSearch.Count > 0) + { + var currentDir = directoriesToSearch.Pop(); + + try + { + // 搜索当前目录中的文件 + var files = Directory.GetFiles(currentDir); + foreach (var file in files) + { + var fileName = Path.GetFileName(file); + var relativePath = GetRelativePath(baseDirectory, file).Replace('\\', '/'); + + if (IsMatch(fileName, relativePath, pattern)) + { + results.Add(relativePath); + } + } + + // 将子目录添加到栈中进行后续搜索 + var directories = Directory.GetDirectories(currentDir); + foreach (var subDir in directories) + { + // 跳过一些常见的不需要搜索的目录 + var dirName = Path.GetFileName(subDir); + if (dirName.StartsWith(".") || + dirName.Equals("bin", StringComparison.OrdinalIgnoreCase) || + dirName.Equals("obj", StringComparison.OrdinalIgnoreCase) || + dirName.Equals("node_modules", StringComparison.OrdinalIgnoreCase) || + dirName.Equals(".git", StringComparison.OrdinalIgnoreCase) || + dirName.Equals(".vs", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + directoriesToSearch.Push(subDir); + } + } + catch (UnauthorizedAccessException) + { + // 跳过无权限访问的目录 + } + catch (Exception) + { + // 跳过其他错误的目录 + } + } + } + + /// + /// 检查文件名或路径是否匹配给定的glob模式 + /// + private bool IsMatch(string fileName, string relativePath, string pattern) + { + try + { + // 如果是简单的文件名模式(如 *.js, *.ts) + if (pattern.StartsWith("*.") && !pattern.Contains("/") && !pattern.Contains("\\")) + { + var extension = pattern.Substring(1); // 去掉 * + return fileName.EndsWith(extension, StringComparison.OrdinalIgnoreCase); + } + + // 使用正则表达式匹配复杂的glob模式 + var regexPattern = ConvertGlobToRegex(pattern); + var regex = new Regex(regexPattern, RegexOptions.IgnoreCase); + + // 同时检查文件名和相对路径 + return regex.IsMatch(fileName) || regex.IsMatch(relativePath); + } + catch + { + // 如果匹配失败,返回false + return false; + } + } + + /// + /// 获取相对路径 + /// + private string GetRelativePath(string basePath, string fullPath) + { + try + { + return Path.GetRelativePath(basePath, fullPath); + } + catch + { + // 如果获取相对路径失败,返回文件名 + return Path.GetFileName(fullPath); + } + } } public class ReadFileItemInput diff --git a/src/KoalaWiki/Git/GitService.cs b/src/KoalaWiki/Git/GitService.cs index 38951fca..087483c5 100644 --- a/src/KoalaWiki/Git/GitService.cs +++ b/src/KoalaWiki/Git/GitService.cs @@ -8,15 +8,32 @@ public class GitService { public static (string localPath, string organization) GetRepositoryPath(string repositoryUrl) { - // 解析仓库地址 - var uri = new Uri(repositoryUrl); - // 得到组织名和仓库名称 - var segments = uri.Segments; - var organization = segments[1].Trim('/'); - var repositoryName = segments[2].Trim('/').Replace(".git", ""); - - // 拼接本地路径,默认使用"/repositories", - var repositoryPath = Path.Combine(Constant.GitPath, organization, repositoryName); + var uri = new Uri(repositoryUrl); + var segments = uri.Segments; + + if (segments.Length < 2) + { + throw new ArgumentException("仓库URL格式不正确,至少需要包含组织名和仓库名"); + } + + string organization; + string repositoryName; + + + // 对于 GitLab,最后一个段是仓库名,前面的都是组织/子组织 + repositoryName = segments[segments.Length - 1].Trim('/').Replace(".git", ""); + + // 组织名包含所有中间路径,用下划线连接以避免路径冲突 + var orgParts = new List(); + for (int i = 1; i < segments.Length - 1; i++) + { + orgParts.Add(segments[i].Trim('/')); + } + organization = string.Join("/", orgParts); + + + // 拼接本地路径 + var repositoryPath = Path.Combine(Constant.GitPath, organization, repositoryName); return (repositoryPath, organization); } diff --git a/src/KoalaWiki/Infrastructure/UserContext.cs b/src/KoalaWiki/Infrastructure/UserContext.cs index 34dc4510..1b05d9bc 100644 --- a/src/KoalaWiki/Infrastructure/UserContext.cs +++ b/src/KoalaWiki/Infrastructure/UserContext.cs @@ -47,5 +47,5 @@ public UserContext(IHttpContextAccessor httpContextAccessor) /// /// 判断用户是否是管理员 /// - public bool IsAdmin => CurrentUserRole == "admin"; + public bool IsAdmin => _httpContextAccessor.HttpContext?.User?.IsInRole("admin") ?? false; } \ No newline at end of file diff --git a/src/KoalaWiki/KernelFactory.cs b/src/KoalaWiki/KernelFactory.cs index d822e481..4a9519df 100644 --- a/src/KoalaWiki/KernelFactory.cs +++ b/src/KoalaWiki/KernelFactory.cs @@ -25,7 +25,8 @@ public static class KernelFactory public static Kernel GetKernel(string chatEndpoint, string apiKey, string gitPath, - string model, bool isCodeAnalysis = true) + string model, bool isCodeAnalysis = true, + List? files = null) { using var activity = Activity.Current?.Source.StartActivity(); activity?.SetTag("model", model); @@ -98,8 +99,9 @@ public static Kernel GetKernel(string chatEndpoint, } // 添加文件函数 - var fileFunction = new FileFunction(gitPath); + var fileFunction = new FileFunction(gitPath,files); kernelBuilder.Plugins.AddFromObject(fileFunction); + kernelBuilder.Plugins.AddFromType(); activity?.SetTag("plugins.file_function", "loaded"); if (DocumentOptions.EnableCodeDependencyAnalysis) diff --git a/src/KoalaWiki/KoalaWarehouse/DocumentContext.cs b/src/KoalaWiki/KoalaWarehouse/DocumentContext.cs index 21268e74..0fc1d277 100644 --- a/src/KoalaWiki/KoalaWarehouse/DocumentContext.cs +++ b/src/KoalaWiki/KoalaWarehouse/DocumentContext.cs @@ -24,7 +24,6 @@ private class DocumentHolder public class DocumentStore { - public List Files { get; set; } = new(); public List GitIssus { get; set; } = new(); } diff --git a/src/KoalaWiki/KoalaWarehouse/DocumentPending/DocumentPendingService.Prompt.cs b/src/KoalaWiki/KoalaWarehouse/DocumentPending/DocumentPendingService.Prompt.cs index 7aa11165..9e318871 100644 --- a/src/KoalaWiki/KoalaWarehouse/DocumentPending/DocumentPendingService.Prompt.cs +++ b/src/KoalaWiki/KoalaWarehouse/DocumentPending/DocumentPendingService.Prompt.cs @@ -20,6 +20,7 @@ public static async Task GetDocumentPendingPrompt(ClassifyType? classify ["git_repository"] = gitRepository.Replace(".git", ""), ["branch"] = branch, ["title"] = title, + ["language"] = Prompt.Language, ["projectType"] = projectType }, OpenAIOptions.ChatModel); } @@ -33,28 +34,28 @@ private static string GetProjectTypeDescription(ClassifyType? classifyType) Generate comprehensive enterprise application documentation that enables successful adoption, deployment, and maintenance through systematic coverage of user workflows, technical architecture, and operational procedures. - + **DOCUMENTATION GENERATION METHODOLOGY:** Create exhaustive application documentation through structured understanding-focused protocols: - + **Phase 1: Conceptual Foundation Documentation** - **Application Philosophy & Purpose**: Think step by step about the application's core mission, design philosophy, and value proposition - **Architectural Concepts**: Comprehensive explanation of system design principles, patterns, and architectural decisions - **User Experience Design**: Detailed analysis of user workflow concepts, interaction patterns, and usability considerations - **Technology Stack Rationale**: In-depth explanation of technology choices, trade-offs, and architectural implications - + **Phase 2: Implementation Understanding Documentation** - **System Architecture Analysis**: Detailed examination of component relationships, data flow patterns, and integration strategies - **Business Logic Exploration**: Comprehensive explanation of core business processes, rules, and decision-making workflows - **Data Management Philosophy**: Analysis of data modeling approaches, persistence strategies, and information architecture - **Security Architecture**: Thorough explanation of security concepts, authentication flows, and protection mechanisms - + **Phase 3: Operational Understanding Documentation** - **Deployment Strategy Analysis**: Conceptual explanation of deployment approaches, environment management, and scalability considerations - **Monitoring Philosophy**: Understanding of observability concepts, logging strategies, and performance measurement approaches - **Maintenance Methodology**: Analysis of operational procedures, troubleshooting approaches, and maintenance strategies - **Integration Ecosystem**: Comprehensive explanation of external dependencies, API design philosophy, and integration patterns - + **DOCUMENTATION QUALITY STANDARDS:** - **Concept-First Approach**: Begin every section with comprehensive conceptual explanation before any implementation details - **Understanding-Focused Content**: Prioritize explaining 'why' and 'how' systems work over showing what they do @@ -70,28 +71,28 @@ private static string GetProjectTypeDescription(ClassifyType? classifyType) Create comprehensive framework documentation that facilitates developer adoption, mastery, and ecosystem integration through systematic coverage of concepts, APIs, and practical implementation guidance. - + **FRAMEWORK DOCUMENTATION METHODOLOGY:** Generate complete framework documentation through structured development-focused protocols: - + **Phase 1: Framework Adoption Documentation** - **Quick Start Guide**: Complete installation procedures, environment setup, and first project creation workflows - **Core Concepts Explanation**: Framework philosophy, design principles, architectural patterns, and mental models - **Developer Onboarding**: Learning path documentation, skill prerequisites, and concept progression strategies - **Configuration Management**: Framework configuration options, environment setup, and customization capabilities - + **Phase 2: Comprehensive API Documentation** - **Complete API Reference**: Full method documentation, parameter specifications, return values, and usage examples - **Extension & Plugin System**: Plugin development guides, hook systems, and extensibility mechanisms - **Advanced Features**: Complex usage patterns, performance optimization, and advanced configuration options - **Integration Patterns**: Framework integration with popular tools, libraries, and development ecosystems - + **Phase 3: Practical Implementation Guidance** - **Tutorial & Example Collection**: Step-by-step implementation guides, real-world examples, and best practice demonstrations - **Migration & Upgrade Documentation**: Version migration guides, breaking change handling, and compatibility maintenance - **Performance & Optimization**: Performance tuning guides, resource optimization, and scaling considerations - **Community & Ecosystem**: Third-party integration guides, community resources, and contribution procedures - + **FRAMEWORK DOCUMENTATION STANDARDS:** - **Conceptual Mastery**: Focus on explaining framework philosophy, design patterns, and architectural principles - **Progressive Understanding**: Content must build conceptual understanding from basic principles to advanced patterns @@ -107,28 +108,28 @@ private static string GetProjectTypeDescription(ClassifyType? classifyType) Create comprehensive library documentation that enables seamless integration, effective usage, and optimal performance through systematic coverage of APIs, implementation patterns, and best practices. - + **LIBRARY DOCUMENTATION METHODOLOGY:** Generate complete library documentation through structured integration-focused protocols: - + **Phase 1: Library Integration Documentation** - **Installation & Setup Guide**: Package manager installation, dependency management, and environment configuration - **Quick Start Examples**: Immediate usage examples, basic implementation patterns, and key feature demonstrations - **API Overview**: Complete public interface documentation, method categories, and functionality mapping - **Type System Integration**: Type definitions, generic usage patterns, and TypeScript/typing support - + **Phase 2: Comprehensive Usage Documentation** - **Complete API Reference**: Full method signatures, parameter specifications, return types, and comprehensive usage examples - **Implementation Patterns**: Common usage scenarios, design pattern applications, and integration strategies - **Advanced Features**: Complex functionality, configuration options, and advanced usage techniques - **Error Handling**: Exception documentation, error recovery patterns, and debugging guidance - + **Phase 3: Optimization & Best Practices** - **Performance Documentation**: Performance characteristics, optimization techniques, and resource usage patterns - **Best Practices Guide**: Recommended implementation approaches, common pitfalls, and optimization strategies - **Compatibility & Migration**: Version compatibility, upgrade procedures, and breaking change documentation - **Integration Examples**: Real-world integration scenarios, framework compatibility, and ecosystem usage - + **LIBRARY DOCUMENTATION STANDARDS:** - **Conceptual API Understanding**: Explain the library's design philosophy, patterns, and intended usage concepts - **API Design Rationale**: Comprehensive explanation of API design decisions, parameter choices, and method organization @@ -144,28 +145,28 @@ private static string GetProjectTypeDescription(ClassifyType? classifyType) Create comprehensive development tool documentation that maximizes developer productivity through detailed setup procedures, feature exploration, and workflow integration guidance. - + **DEVELOPMENT TOOL DOCUMENTATION METHODOLOGY:** Generate complete tool documentation through structured productivity-focused protocols: - + **Phase 1: Tool Setup & Configuration Documentation** - **Installation Guide**: Complete installation procedures, system requirements, and dependency management - **Configuration Reference**: Comprehensive settings documentation, customization options, and preference management - **Environment Integration**: Development environment setup, IDE plugins, and toolchain integration procedures - **Initial Setup Workflows**: First-time configuration, account setup, and essential configuration procedures - + **Phase 2: Feature & Capability Documentation** - **Core Feature Guide**: Complete feature documentation, capability explanations, and functionality mapping - **Workflow Integration**: Development workflow optimization, productivity enhancement techniques, and automation capabilities - **Advanced Features**: Complex functionality, power-user features, and specialized use case documentation - **Automation & Scripting**: Automation capabilities, scripting interfaces, and batch operation procedures - + **Phase 3: Integration & Optimization Documentation** - **Development Environment Integration**: IDE support, editor plugins, and development workflow integration - **Build System Compatibility**: Build tool integration, CI/CD pipeline compatibility, and deployment workflow support - **Performance Optimization**: Tool performance tuning, resource management, and efficiency optimization - **Troubleshooting & Support**: Common issue resolution, debugging procedures, and performance problem diagnosis - + **TOOL DOCUMENTATION STANDARDS:** - **Step-by-Step Procedures**: All setup and usage procedures must include detailed, sequential instructions - **Real-World Examples**: Include practical examples that demonstrate actual development workflow scenarios @@ -181,28 +182,28 @@ private static string GetProjectTypeDescription(ClassifyType? classifyType) Create comprehensive command-line tool documentation that enables mastery through detailed command references, practical examples, and automation integration guidance. - + **CLI TOOL DOCUMENTATION METHODOLOGY:** Generate complete CLI documentation through structured command-line focused protocols: - + **Phase 1: Installation & Configuration Documentation** - **Installation Guide**: Multiple installation methods, system requirements, and platform-specific procedures - **Environment Setup**: Environment variable configuration, PATH setup, and shell integration procedures - **Configuration Management**: Config file formats, persistent settings, and preference customization - **Shell Integration**: Command completion, alias setup, and shell-specific optimization - + **Phase 2: Complete Command Reference Documentation** - **Command Hierarchy**: Complete command structure, subcommand organization, and option categorization - **Detailed Command Reference**: Every command with full option documentation, parameter specifications, and usage examples - **Input/Output Patterns**: Data input methods, output formatting options, and result processing techniques - **Interactive Features**: Interactive modes, prompt handling, and user input processing - + **Phase 3: Automation & Integration Documentation** - **Scripting Integration**: Automation examples, scripting patterns, and batch operation procedures - **Pipeline Integration**: Data pipeline usage, input/output chaining, and workflow automation - **CI/CD Integration**: Continuous integration usage, automated deployment, and build process integration - **Advanced Usage Patterns**: Complex workflows, advanced features, and power-user techniques - + **CLI DOCUMENTATION STANDARDS:** - **Executable Examples**: All command examples must be complete, runnable, and produce documented results - **Comprehensive Command Coverage**: Document every command, option, and usage pattern with examples @@ -218,28 +219,28 @@ private static string GetProjectTypeDescription(ClassifyType? classifyType) Create comprehensive infrastructure documentation that enables successful deployment, operation, and maintenance through detailed procedures, configuration guidance, and operational excellence practices. - + **DEVOPS DOCUMENTATION METHODOLOGY:** Generate complete infrastructure documentation through structured operational protocols: - + **Phase 1: Infrastructure Architecture Documentation** - **System Architecture Overview**: Complete infrastructure diagrams, component relationships, and deployment topology - **Environment Strategy**: Development, staging, and production environment documentation with configuration differences - **Service Dependencies**: Service interaction maps, dependency chains, and integration architecture documentation - **Resource Management**: Infrastructure resource allocation, scaling strategies, and capacity planning procedures - + **Phase 2: Deployment & Configuration Documentation** - **Deployment Procedures**: Step-by-step deployment guides, environment preparation, and configuration procedures - **Configuration Management**: Complete configuration reference, environment variables, and customization options - **Infrastructure as Code**: IaC implementation documentation, version control procedures, and deployment automation - **Environment Provisioning**: Infrastructure provisioning procedures, resource creation, and environment setup - + **Phase 3: Operations & Maintenance Documentation** - **Monitoring & Observability**: Complete monitoring setup, logging configuration, alerting procedures, and performance tracking - **Security & Compliance**: Security implementation procedures, access controls, compliance requirements, and audit processes - **Operational Procedures**: Maintenance workflows, backup procedures, disaster recovery, and incident response protocols - **Scaling & Optimization**: Scaling procedures, performance optimization, and resource efficiency improvement techniques - + **DEVOPS DOCUMENTATION STANDARDS:** - **Executable Procedures**: All deployment and operational procedures must include complete, step-by-step instructions - **Configuration Completeness**: Document every configuration option, environment variable, and customization capability @@ -255,28 +256,28 @@ private static string GetProjectTypeDescription(ClassifyType? classifyType) Create comprehensive meta-documentation that enables effective contribution, maintenance, and improvement of documentation projects through detailed processes, quality standards, and workflow guidance. - + **DOCUMENTATION PROJECT METHODOLOGY:** Generate complete documentation project documentation through structured knowledge management protocols: - + **Phase 1: Project Structure & Purpose Documentation** - **Project Overview**: Documentation objectives, scope definition, target audiences, and success metrics - **Content Architecture**: Information structure, navigation design, and content organization principles - **Audience Analysis**: User persona documentation, content consumption patterns, and accessibility requirements - **Content Strategy**: Content creation guidelines, maintenance procedures, and lifecycle management - + **Phase 2: Contribution & Quality Assurance Documentation** - **Contribution Guide**: Complete contributor onboarding, writing guidelines, and submission procedures - **Style & Standards**: Writing style guides, formatting standards, and consistency requirements - **Review Processes**: Content review workflows, approval procedures, and quality gates - **Quality Assurance**: Testing methodologies, accuracy validation, and content quality measurement - + **Phase 3: Tools & Workflow Documentation** - **Documentation Toolchain**: Complete tool documentation, build processes, and publication workflows - **Content Management**: Version control procedures, content organization, and asset management - **Automation & Integration**: Automated testing, content generation, and publication automation - **Maintenance Procedures**: Content update workflows, link validation, and accuracy maintenance procedures - + **DOCUMENTATION PROJECT STANDARDS:** - **Process Completeness**: Document every aspect of the documentation creation, review, and maintenance process - **Contributor Experience**: Focus on enabling easy contribution and effective collaboration @@ -290,28 +291,28 @@ private static string GetProjectTypeDescription(ClassifyType? classifyType) Create comprehensive software project documentation that enables understanding, adoption, and contribution through systematic coverage of project purpose, implementation guidance, and development procedures. - + **COMPREHENSIVE PROJECT DOCUMENTATION METHODOLOGY:** Generate complete project documentation through structured multi-purpose protocols: - + **Phase 1: Project Understanding & Adoption Documentation** - **Project Overview & Purpose**: Complete project description, value proposition, key features, and target use case documentation - **Getting Started Guide**: Comprehensive installation procedures, environment setup, and initial configuration workflows - **Quick Start Examples**: Immediate usage examples, basic implementation patterns, and core feature demonstrations - **Architecture Understanding**: System design overview, component relationships, and technical decision documentation - + **Phase 2: Implementation & Usage Documentation** - **Feature Documentation**: Complete feature explanations, configuration options, and implementation guidance - **API & Interface Reference**: Complete interface documentation, method specifications, and usage examples - **Configuration & Customization**: Comprehensive configuration options, environment setup, and customization capabilities - **Integration Patterns**: Integration examples, compatibility information, and ecosystem usage guidance - + **Phase 3: Development & Contribution Documentation** - **Development Environment Setup**: Complete development environment configuration, build procedures, and tool requirements - **Contributing Guidelines**: Contribution procedures, code standards, testing requirements, and submission workflows - **Architecture & Design**: Internal architecture documentation, design principles, and development guidelines - **Maintenance & Operations**: Deployment procedures, operational guidelines, and maintenance workflows - + **UNIVERSAL DOCUMENTATION STANDARDS:** - **Complete Implementation Examples**: All documentation must include complete, executable examples and configuration samples - **Step-by-Step Guidance**: Every procedure must be documented with detailed, sequential instructions diff --git a/src/KoalaWiki/KoalaWarehouse/DocumentPending/DocumentPendingService.cs b/src/KoalaWiki/KoalaWarehouse/DocumentPending/DocumentPendingService.cs index 1187bcc7..9bf4e9d6 100644 --- a/src/KoalaWiki/KoalaWarehouse/DocumentPending/DocumentPendingService.cs +++ b/src/KoalaWiki/KoalaWarehouse/DocumentPending/DocumentPendingService.cs @@ -2,15 +2,8 @@ using System.Text; using System.Text.RegularExpressions; using KoalaWiki.Core.Extensions; -using KoalaWiki.Domains; using KoalaWiki.Domains.DocumentFile; -using KoalaWiki.Domains.Warehouse; -using KoalaWiki.Entities; -using KoalaWiki.Functions; -using KoalaWiki.Options; using KoalaWiki.Prompts; -using Microsoft.EntityFrameworkCore; -using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; @@ -138,11 +131,13 @@ await dbContext.DocumentCatalogs.Where(x => x.Id == catalog.Id) RepairMermaid(fileItem); await dbContext.DocumentFileItems.AddAsync(fileItem); + await dbContext.DocumentFileItemSources.AddRangeAsync(files.Select(x => new DocumentFileItemSource() { Address = x, DocumentFileItemId = fileItem.Id, - Name = x, + Name = Path.GetFileName(x), + CreatedAt = DateTime.Now, Id = Guid.NewGuid().ToString("N"), })); @@ -247,7 +242,8 @@ private static async Task ProcessCatalogueItems(DocumentCatalo OpenAIOptions.ChatApiKey, path, OpenAIOptions.ChatModel, - false // 文档生成不需要代码分析功能 + false, // 文档生成不需要代码分析功能 + files ); var chat = documentKernel.Services.GetService(); @@ -261,9 +257,10 @@ private static async Task ProcessCatalogueItems(DocumentCatalo var contents = new ChatMessageContentItemCollection { - new TextContent(prompt) + new TextContent(prompt), + new TextContent(Prompt.Language) }; - + contents.AddDocsGenerateSystemReminder(); history.AddUserMessage(contents); @@ -275,6 +272,10 @@ private static async Task ProcessCatalogueItems(DocumentCatalo MaxTokens = DocumentsHelper.GetMaxTokens(OpenAIOptions.ChatModel), }; + int count = 1; + + reset: + await foreach (var i in chat.GetStreamingChatMessageContentsAsync(history, settings, documentKernel)) { if (!string.IsNullOrEmpty(i.Content)) @@ -283,9 +284,16 @@ private static async Task ProcessCatalogueItems(DocumentCatalo } } + // 保存原始内容,防止精炼失败时丢失 var originalContent = sr.ToString(); + if (string.IsNullOrEmpty(originalContent) && count < 3) + { + count++; + goto reset; + } + // 先进行基础质量验证,避免对质量过差的内容进行精炼 var (isInitialValid, initialMessage, initialMetrics) = ValidateDocumentQuality(originalContent, catalog.Name); @@ -357,7 +365,8 @@ 7. ENSURE all enhancements are based on the code files analyzed in the original Your goal is to take the good foundation that exists and make it BETTER, MORE DETAILED, and MORE COMPREHENSIVE while preserving its core structure and insights. - """) + """), + new TextContent(Prompt.Language) }; history.AddUserMessage(refineContents); @@ -440,8 +449,6 @@ 7. ENSURE all enhancements are based on the code files analyzed in the original Title = catalog.Name, }; - files.AddRange(DocumentContext.DocumentStore.Files); - return fileItem; } diff --git a/src/KoalaWiki/KoalaWarehouse/Extensions/ServiceCollectionExtensions.cs b/src/KoalaWiki/KoalaWarehouse/Extensions/ServiceCollectionExtensions.cs index 0f6744c9..7e55ac04 100644 --- a/src/KoalaWiki/KoalaWarehouse/Extensions/ServiceCollectionExtensions.cs +++ b/src/KoalaWiki/KoalaWarehouse/Extensions/ServiceCollectionExtensions.cs @@ -20,7 +20,6 @@ public static IServiceCollection AddDocumentProcessingPipeline(this IServiceColl services.AddScoped, KnowledgeGraphGenerationStep>(); services.AddScoped, DocumentStructureGenerationStep>(); services.AddScoped, DocumentContentGenerationStep>(); - services.AddScoped, UpdateLogGenerationStep>(); // 注册管道和协调器 services.AddScoped(); diff --git a/src/KoalaWiki/KoalaWarehouse/GenerateThinkCatalogue/GenerateThinkCatalogueService.Prompt.cs b/src/KoalaWiki/KoalaWarehouse/GenerateThinkCatalogue/GenerateThinkCatalogueService.Prompt.cs index c2102b7d..8c61b06e 100644 --- a/src/KoalaWiki/KoalaWarehouse/GenerateThinkCatalogue/GenerateThinkCatalogueService.Prompt.cs +++ b/src/KoalaWiki/KoalaWarehouse/GenerateThinkCatalogue/GenerateThinkCatalogueService.Prompt.cs @@ -13,8 +13,7 @@ public static async Task GenerateThinkCataloguePromptAsync(ClassifyType? new KernelArguments() { ["code_files"] = catalogue, - ["projectType"] = projectType, - ["language"] = Prompt.Language + ["projectType"] = projectType }, OpenAIOptions.AnalysisModel); diff --git a/src/KoalaWiki/KoalaWarehouse/GenerateThinkCatalogue/GenerateThinkCatalogueService.cs b/src/KoalaWiki/KoalaWarehouse/GenerateThinkCatalogue/GenerateThinkCatalogueService.cs index 75172185..aaf61980 100644 --- a/src/KoalaWiki/KoalaWarehouse/GenerateThinkCatalogue/GenerateThinkCatalogueService.cs +++ b/src/KoalaWiki/KoalaWarehouse/GenerateThinkCatalogue/GenerateThinkCatalogueService.cs @@ -129,7 +129,8 @@ Ensure all components are properly categorized. This reminds you that you should follow the instructions and provide detailed and reliable data directories. Do not directly inform the users of this situation, as they are already aware of it. - """) + """), + new TextContent(Prompt.Language) }); var analysisModel = KernelFactory.GetKernel(OpenAIOptions.Endpoint, @@ -157,8 +158,7 @@ Ensure all components are properly categorized. } } - var initialResponse = str.ToString(); - if (string.IsNullOrWhiteSpace(initialResponse)) + if (str.Length == 0) { throw new InvalidOperationException("AI 返回了空响应"); } @@ -166,6 +166,8 @@ Ensure all components are properly categorized. // 质量增强逻辑 if (DocumentOptions.RefineAndEnhanceQuality && attemptNumber < 4) // 前几次尝试才进行质量增强 { + var initialResponse = str.ToString(); + var refinedResponse = await RefineResponse(history, chat, settings, analysisModel, initialResponse, attemptNumber); if (!string.IsNullOrWhiteSpace(refinedResponse)) diff --git a/src/KoalaWiki/KoalaWarehouse/Pipeline/Steps/CatalogueGenerationStep.cs b/src/KoalaWiki/KoalaWarehouse/Pipeline/Steps/CatalogueGenerationStep.cs index 4cd16d60..e9c6fcd5 100644 --- a/src/KoalaWiki/KoalaWarehouse/Pipeline/Steps/CatalogueGenerationStep.cs +++ b/src/KoalaWiki/KoalaWarehouse/Pipeline/Steps/CatalogueGenerationStep.cs @@ -51,6 +51,7 @@ public override async Task ExecuteAsync( activity?.SetTag("catalogue.length", catalogue?.Length ?? 0); context.SetStepResult(StepName, catalogue); + context.Catalogue = catalogue; Logger.LogInformation("完成 {StepName} 步骤,目录结构长度: {Length}", StepName, catalogue?.Length ?? 0); diff --git a/src/KoalaWiki/KoalaWarehouse/Pipeline/Steps/UpdateLogGenerationStep.cs b/src/KoalaWiki/KoalaWarehouse/Pipeline/Steps/UpdateLogGenerationStep.cs deleted file mode 100644 index 8c604aef..00000000 --- a/src/KoalaWiki/KoalaWarehouse/Pipeline/Steps/UpdateLogGenerationStep.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System.Diagnostics; -using KoalaWiki.Entities; -using KoalaWiki.Options; - -namespace KoalaWiki.KoalaWarehouse.Pipeline.Steps; - -public class UpdateLogGenerationStep : DocumentProcessingStepBase -{ - public UpdateLogGenerationStep(ILogger logger) : base(logger) { } - - public override string StepName => "生成更新日志"; - - public override StepExecutionConfig Configuration => new() - { - ExecutionStrategy = StepExecutionStrategy.Optional, // 更新日志是可选功能 - RetryStrategy = StepRetryStrategy.Smart, - MaxRetryAttempts = 2, - RetryDelay = TimeSpan.FromSeconds(5), - StepTimeout = TimeSpan.FromMinutes(8), - ContinueOnFailure = true, - RetriableExceptions = new List - { - typeof(HttpRequestException), - typeof(TaskCanceledException), - typeof(InvalidOperationException), - typeof(TimeoutException) - }, - NonRetriableExceptions = new List - { - typeof(UnauthorizedAccessException), - typeof(DirectoryNotFoundException) - } - }; - - public override async Task CanExecuteAsync(DocumentProcessingContext input) - { - return input.Warehouse.Type.Equals("git", StringComparison.CurrentCultureIgnoreCase); - } - - public override async Task ExecuteAsync( - DocumentProcessingContext context, - CancellationToken cancellationToken = default) - { - using var activity = ActivitySource.StartActivity(StepName); - SetActivityTags(activity, context); - - Logger.LogInformation("开始执行 {StepName} 步骤", StepName); - - try - { - // 确保有内核实例 - context.KernelInstance ??= KernelFactory.GetKernel( - OpenAIOptions.Endpoint, - OpenAIOptions.ChatApiKey, - context.Document.GitPath, - OpenAIOptions.ChatModel); - - // 删除现有的更新日志记录 - await context.DbContext.DocumentCommitRecords.Where(x => x.WarehouseId == context.Warehouse.Id) - .ExecuteDeleteAsync(cancellationToken: cancellationToken); - - // 生成更新日志 - var committer = await DocumentsService.GenerateUpdateLogAsync( - context.Document.GitPath, - context.Readme ?? string.Empty, - context.Warehouse.Address, - context.Warehouse.Branch, - context.KernelInstance); - - var records = committer.Select(x => new DocumentCommitRecord() - { - WarehouseId = context.Warehouse.Id, - CreatedAt = DateTime.Now, - Author = string.Empty, - Id = Guid.NewGuid().ToString("N"), - CommitMessage = x.description, - Title = x.title, - LastUpdate = x.date, - }); - - await context.DbContext.DocumentCommitRecords.AddRangeAsync(records, cancellationToken); - - activity?.SetTag("commit_records.count", records.Count()); - context.SetStepResult(StepName, records.Count()); - - Logger.LogInformation("完成 {StepName} 步骤,生成更新记录数量: {Count}", - StepName, records.Count()); - } - catch (Exception ex) - { - Logger.LogError(ex, "执行 {StepName} 步骤时发生错误", StepName); - activity?.SetTag("error", ex.Message); - throw; - } - - return context; - } - - public override async Task HandleErrorAsync( - DocumentProcessingContext input, - Exception exception, - int attemptCount) - { - Logger.LogWarning("更新日志生成失败,跳过此步骤,异常: {Exception}", exception.Message); - - // 更新日志生成失败时,记录警告但不影响整体流程 - input.SetMetadata("UpdateLogAvailable", false); - input.SetMetadata("UpdateLogError", exception.Message); - - return input; - } - - public override async Task IsHealthyAsync(DocumentProcessingContext input) - { - try - { - // 检查是否是Git仓库 - if (!input.Warehouse.Type.Equals("git", StringComparison.CurrentCultureIgnoreCase)) - { - return true; // 非Git仓库,健康检查通过(会在CanExecute中跳过) - } - - // 检查Git路径是否存在 - if (!Directory.Exists(input.Document.GitPath)) - { - Logger.LogWarning("Git路径不存在: {Path}", input.Document.GitPath); - return false; - } - - // 检查是否是有效的Git仓库 - var gitDir = Path.Combine(input.Document.GitPath, ".git"); - if (!Directory.Exists(gitDir) && !File.Exists(gitDir)) - { - Logger.LogWarning("不是有效的Git仓库: {Path}", input.Document.GitPath); - return false; - } - - return true; - } - catch (Exception ex) - { - Logger.LogWarning(ex, "更新日志生成步骤健康检查失败"); - return false; - } - } - - public override async Task GetDependenciesAsync() - { - // 更新日志生成依赖README内容 - return new[] { "读取生成README" }; - } - - protected override void SetActivityTags(Activity? activity, DocumentProcessingContext input) - { - activity?.SetTag("warehouse.id", input.Warehouse.Id); - activity?.SetTag("warehouse.type", "git"); - activity?.SetTag("git.address", input.Warehouse.Address); - activity?.SetTag("git.branch", input.Warehouse.Branch); - } -} \ No newline at end of file diff --git a/src/KoalaWiki/KoalaWarehouse/Prompt.cs b/src/KoalaWiki/KoalaWarehouse/Prompt.cs index 1a26f19d..af766012 100644 --- a/src/KoalaWiki/KoalaWarehouse/Prompt.cs +++ b/src/KoalaWiki/KoalaWarehouse/Prompt.cs @@ -14,9 +14,11 @@ static Prompt() { _language = language; } + + Console.WriteLine("当前语言环境:" + _language); } - public static string Language => $"\nYou must communicate with me in {_language}.\n"; + public static string Language => $"\nNote: You must reply in {_language}.\n"; public static readonly string AnalyzeNewCatalogue = """ diff --git a/src/KoalaWiki/MCP/MCPExtensions.cs b/src/KoalaWiki/MCP/MCPExtensions.cs index ecfb2a37..4a252ed1 100644 --- a/src/KoalaWiki/MCP/MCPExtensions.cs +++ b/src/KoalaWiki/MCP/MCPExtensions.cs @@ -196,7 +196,7 @@ public static IServiceCollection AddKoalaMcp(this IServiceCollection service) .Where(x => x.WarehouseId == warehouse.Id) .FirstOrDefaultAsync(token); - var fileFunction = new FileFunction(document.GitPath); + var fileFunction = new FileFunction(document.GitPath, null); var sw = Stopwatch.StartNew(); @@ -235,7 +235,7 @@ public static IServiceCollection AddKoalaMcp(this IServiceCollection service) .Where(x => x.WarehouseId == warehouse.Id) .FirstOrDefaultAsync(token); - var fileFunction = new FileFunction(document.GitPath); + var fileFunction = new FileFunction(document.GitPath, null); var sw = Stopwatch.StartNew(); diff --git a/src/KoalaWiki/Prompts/PromptExtensions.cs b/src/KoalaWiki/Prompts/PromptExtensions.cs index c5206de7..bcdc99e8 100644 --- a/src/KoalaWiki/Prompts/PromptExtensions.cs +++ b/src/KoalaWiki/Prompts/PromptExtensions.cs @@ -49,7 +49,6 @@ public static ChatHistory AddSystemEnhance(this ChatHistory chatHistory) { chatHistory.AddSystemMessage( $""" - {Prompt.Language} You are an AI assistant specialized in software engineering and code analysis. You assist users with repository analysis, documentation generation, code understanding, debugging, feature development, and other software development tasks. Use the instructions below and the tools available to you to assist the user. IMPORTANT: Assist with defensive security tasks only. Refuse to create, modify, or improve code that may be used maliciously. Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation. diff --git a/src/KoalaWiki/Prompts/Warehouse/AnalyzeCatalogue.md b/src/KoalaWiki/Prompts/Warehouse/AnalyzeCatalogue.md index c06d7ad3..36181552 100644 --- a/src/KoalaWiki/Prompts/Warehouse/AnalyzeCatalogue.md +++ b/src/KoalaWiki/Prompts/Warehouse/AnalyzeCatalogue.md @@ -1,22 +1,12 @@ -# Repository Documentation Catalog Generator +# Engineering Blog Content Catalog Generator -You are a technical documentation specialist who creates practical, user-focused documentation structures. Your mission is to analyze repositories and generate documentation catalogs that help users understand, use, and contribute to software projects effectively. +You are a senior software engineer who creates compelling content structures for technical blog series about software projects. Analyze repositories like an experienced developer exploring a new codebase, then generate content catalogs that tell the engineering story through a series of interconnected blog posts - from initial discovery to deep technical insights. -## 🎯 Core Mission +## Core Mission -Analyze repository code files to create clear, actionable documentation structures that serve real user needs - from getting started quickly to understanding complex implementations and contributing to the project. +Transform repository code analysis into engaging blog content series that tell the complete engineering story. Create content architectures that guide readers through a developer's journey of understanding a project - from initial curiosity and first impressions to deep architectural insights and implementation wisdom that fellow engineers would find valuable and inspiring. -## 📋 Critical Requirements - -**ESSENTIAL PRINCIPLES:** - -1. **👥 USER-FIRST APPROACH**: Structure around user tasks and goals, not internal system architecture -2. **⚡ PRACTICAL FOCUS**: Balance business context with actionable technical content -3. **🔄 ADAPTIVE STRUCTURE**: Scale complexity to match project needs (simple tool vs complex platform) -4. **📖 CLEAR NAVIGATION**: Follow established documentation patterns that users expect -5. **🎯 MULTI-AUDIENCE**: Support different user types (end users, developers, operators) - -## 📥 Input Analysis +## Input Analysis **Repository Code Files:** @@ -29,533 +19,618 @@ Analyze repository code files to create clear, actionable documentation structur **Target Language:** {{$language}} -## 🔍 Mandatory Repository Analysis Protocol +**IMPORTANT: ALL generated content, titles, descriptions, and prompts must be written in {{$language}}.** -### Phase 1: Complete Codebase Analysis (REQUIRED) -**You MUST systematically analyze ALL code files provided to understand:** +## Engineering Blog Series Architecture Principles -1. **Project Architecture & Type**: Identify if this is a web application, API service, CLI tool, library, framework, or complex platform -2. **Core System Components**: Map all major modules, services, controllers, utilities, and their relationships -3. **Entry Points & Main Flows**: Identify application entry points, main execution paths, and user interaction flows -4. **Data Models & Business Logic**: Understand domain entities, business rules, and core algorithms -5. **Integration Points**: Catalog APIs, external dependencies, databases, and third-party integrations -6. **Configuration & Deployment**: Analyze config files, environment settings, build processes, and deployment scripts -7. **Technology Stack**: Document frameworks, libraries, databases, and architectural patterns used +### 1. Developer Learning Journey Architecture -**Analysis Requirements:** -- Read EVERY significant source file to understand its purpose and functionality -- Identify ALL major classes, interfaces, services, and modules with their roles -- Map dependencies and relationships between components -- Understand the complete technology stack and architectural decisions +- **Discovery to Mastery Flow**: Natural progression from "What is this?" to "How can I build something like this?" +- **Engineering Perspective Layers**: Surface-level overview to deep implementation analysis +- **Technical Storytelling**: Each piece builds on previous insights and sets up future revelations +- **Complexity Graduation**: Structure matches how experienced developers actually explore new codebases -### Phase 2: Core Functionality Identification -**Based on code analysis, identify and categorize system capabilities:** +### 2. Engineering Content Discoverability -**Primary Value Functions**: Main features that deliver core user value -- What are the key capabilities users rely on? -- What problems does this system solve? -- What would be broken if these were removed? +- **Problem-Solution Grouping**: Content organized around engineering challenges and solutions +- **Technical Interest Tagging**: Metadata that helps developers find content relevant to their interests +- **Knowledge Building Paths**: Clear progression from basic understanding to implementation expertise +- **Multiple Technical Perspectives**: Different entry points for different engineering backgrounds -**Supporting Technical Functions**: Infrastructure that enables primary functions -- Authentication, authorization, security systems -- Data processing, storage, and retrieval systems -- Communication, integration, and API systems +### 3. Engineering-Focused Content Structure -**Operational Functions**: Systems for deployment, monitoring, and maintenance -- Configuration and environment management -- Logging, monitoring, and error handling -- Testing, building, and deployment systems +- **Technical Complexity Scaling**: Content depth matches the sophistication of the implementation +- **Domain-Specific Engineering Patterns**: Tailored content for different types of software projects +- **Developer Workflow Alignment**: Structure matches how engineers actually learn and work with new technologies +- **Technical Insight Calibration**: Balance accessibility with engineering depth -**User Interface Functions**: How users interact with the system -- Web interfaces, APIs, CLI commands -- User workflows and interaction patterns -- Integration interfaces for developers +## Repository Analysis Protocol -### Phase 3: Documentation Structure Planning -**Organize around actual discovered functionality and user needs:** +### Step 1: Deep Codebase Analysis -1. **Map Core Functions to Documentation Needs**: Each identified core function should have comprehensive documentation coverage -2. **Plan Multi-Level Structure**: Create 3-4 levels of hierarchy to cover overview → detailed implementation -3. **Consider Multiple User Types**: Structure for end users, developers, operators, and contributors -4. **Ensure Complete Coverage**: Every significant component should be documented appropriately +Systematically analyze ALL provided code files to understand: -## 📋 Documentation Structure Framework - Google Diátaxis Standard +**Core Project Philosophy Mining:** -### Core Diátaxis Principles -The Diátaxis framework organizes documentation around four distinct user needs, creating a systematic relationship between different documentation types. Each quadrant serves a specific purpose and follows unique principles: +1. **Fundamental Problem Definition** - Core technical or business challenges the project solves, why this solution is needed +2. **Design Philosophy Identification** - Core design principles inferred from code organization, naming conventions, API design +3. **Technical Philosophy Embodiment** - Priority choices and trade-offs in simplicity, performance, scalability, usability +4. **Innovation Breakthrough Points** - Unique innovations or improvements in technical implementation, user experience, development efficiency +5. **Value Proposition Analysis** - Unique advantages and differentiating features compared to existing solutions -**The Four Quadrants Matrix:** -``` - Practical (Doing) | Theoretical (Thinking) - ----------------------------|----------------------------- -Study | 📚 TUTORIALS | 🧠 EXPLANATION -(Learning)| - Learning-oriented | - Understanding-oriented - | - Guided experience | - Conceptual clarity - | - Guaranteed success | - Context & reasoning - ----------------------------|----------------------------- -Work | 🛠️ HOW-TO GUIDES | 📖 REFERENCE -(Doing) | - Problem-oriented | - Information-oriented - | - Goal achievement | - Authoritative facts - | - Task completion | - Comprehensive coverage -``` +**Technical Architecture:** -#### 1. 📚 Tutorials (Learning-Oriented + Practical) -**Guided learning experiences that guarantee success** -- **Purpose**: Help beginners acquire skills through doing -- **Characteristics**: Teacher-led, concrete actions, visible results -- **Focus**: Student's learning experience, not information transfer -- **Language**: "We will..." - first person plural -- **Success Metric**: Learner completes with confidence and skill - -#### 2. 🛠️ How-to Guides (Work-Oriented + Practical) -**Goal-oriented solutions for specific problems** -- **Purpose**: Help competent users achieve specific tasks -- **Characteristics**: User-centered, action-oriented, adaptable -- **Focus**: Real-world problems and practical goals -- **Language**: Conditional imperatives, clear directions -- **Success Metric**: User accomplishes their specific goal - -#### 3. 📖 Reference (Work-Oriented + Theoretical) -**Authoritative technical specifications** -- **Purpose**: Provide factual information about system machinery -- **Characteristics**: Neutral, objective, comprehensive -- **Focus**: Describe what exists, not how to use it -- **Language**: Factual statements, technical precision -- **Success Metric**: User finds accurate information quickly - -#### 4. 🧠 Explanation (Learning-Oriented + Theoretical) -**Conceptual understanding and context** -- **Purpose**: Deepen understanding of why things work as they do -- **Characteristics**: Broader perspective, connections, context -- **Focus**: Background, alternatives, design decisions -- **Language**: Discursive, thoughtful, opinion-friendly -- **Success Metric**: User develops deeper understanding - -### Diátaxis-First Documentation Structure - -**CRITICAL REQUIREMENT**: All documentation must be organized by Diátaxis quadrant FIRST, then by functionality within each quadrant. This ensures proper separation of user contexts and documentation purposes. - -#### 📚 TUTORIALS QUADRANT (Learning + Practical) -**Create guided learning experiences with guaranteed outcomes** - -1. **Getting Started Tutorial** - - First successful interaction with the system - - Complete guided journey from setup to working result - - Focus: Building learner confidence through success - -2. **Core Workflow Tutorial** - - Step-by-step lesson for primary system workflow - - Hands-on practice with concrete, visible results - - Focus: Skill acquisition through guided doing - -3. **Feature Learning Tutorials** - - Individual lessons for each major feature - - Progressive skill building with safe practice - - Focus: Competence development in controlled environment - -#### 🛠️ HOW-TO GUIDES QUADRANT (Work + Practical) -**Provide goal-oriented solutions for real problems** - -4. **Installation & Deployment How-tos** - - Production deployment procedures - - Environment-specific setup instructions - - Focus: Achieving deployment goals in real environments - -5. **Feature Implementation How-tos** - - Solve specific implementation challenges - - Configure features for particular use cases - - Focus: Accomplishing user's specific objectives - -6. **Integration How-tos** - - Connect with external systems and services - - Implement custom extensions and plugins - - Focus: Achieving integration goals - -7. **Troubleshooting How-tos** - - Diagnose and resolve specific problems - - Performance optimization procedures - - Focus: Solving real operational issues - -#### 📖 REFERENCE QUADRANT (Work + Theoretical) -**Provide authoritative technical specifications** - -8. **API Reference** - - Complete endpoint specifications - - Parameter schemas and response formats - - Focus: Factual API machinery descriptions - -9. **Configuration Reference** - - All configuration options and parameters - - Environment variables and settings - - Focus: Comprehensive configuration facts - -10. **Component Reference** - - Technical specifications for all system components - - Interface definitions and data models - - Focus: Authoritative component descriptions - -11. **Command Reference** - - All available commands, options, and flags - - Syntax specifications and parameter lists - - Focus: Complete command machinery documentation - -#### 🧠 EXPLANATION QUADRANT (Learning + Theoretical) -**Provide understanding and context** - -12. **Architecture Explanation** - - Why the system is designed this way - - Component relationships and design principles - - Focus: Understanding system design decisions - -13. **Core Concepts Explanation** - - Domain concepts and terminology - - Business logic and workflow reasoning - - Focus: Conceptual understanding of system foundations - -14. **Technology Choices Explanation** - - Why specific technologies were selected - - Trade-offs and alternatives considered - - Focus: Understanding technical decision-making - -15. **Operational Theory Explanation** - - How different components work together - - Data flow and processing concepts - - Focus: Understanding system operation principles - -**Diátaxis Structure Guidelines:** -- **Simple Projects (8-12 sections)**: 2-3 tutorials, 3-4 how-tos, 2-3 references, 1-2 explanations -- **Medium Projects (12-18 sections)**: 3-4 tutorials, 5-6 how-tos, 4-5 references, 2-3 explanations -- **Complex Projects (18-25 sections)**: 4-5 tutorials, 7-8 how-tos, 6-7 references, 3-4 explanations -- **Enterprise Systems (25-30+ sections)**: 5-6 tutorials, 8-10 how-tos, 8-10 references, 4-5 explanations - -**Balance Requirements:** -- Each quadrant must be represented in every documentation structure -- How-to guides typically form the largest section (40-50% of content) -- Reference documentation should be comprehensive but focused -- Tutorials must guarantee learner success -- Explanations provide essential context and understanding - -## 📝 Diátaxis-Specific Content Templates - -### Template Selection Rules - -**CRITICAL**: Each documentation section MUST be created using the template that matches its Diátaxis quadrant. Mixing quadrant characteristics will result in confused, ineffective documentation. - -**Template Selection Guide:** -- Use **Tutorial Template** for learning-oriented, guided experiences -- Use **How-to Template** for problem-solving, goal-oriented instructions -- Use **Reference Template** for authoritative, factual specifications -- Use **Explanation Template** for understanding-oriented, conceptual content - -### 📚 Tutorial Template (Learning + Practical) +1. **Project Classification** - Web app, API, CLI tool, library, framework, or platform +2. **Architectural Patterns** - Microservices, monolith, serverless, component-based +3. **Technology Ecosystem** - Primary stack, dependencies, integration points +4. **Code Organization** - Module structure, separation of concerns, design patterns +5. **Entry Points & Flows** - Application lifecycle, critical user journeys +6. **Configuration Complexity** - Setup requirements, environment management -``` -Create a guided learning experience for [specific functionality] that takes beginners through a complete, successful journey from start to finish. - -**Learning Objective:** -Define what skill or capability the learner will acquire by completing this tutorial. Focus on the learning outcome, not the system feature [^1]. - -**Guided Journey Structure:** -1. **Setup for Success**: Ensure learner has everything needed for guaranteed success -2. **Step-by-Step Actions**: Provide concrete, specific actions with expected results -3. **Visible Progress**: Show clear signs of progress and success at each step -4. **Successful Completion**: End with a meaningful, confidence-building result - -**Tutorial Requirements:** -- Use "We will..." language to guide the learner -- Provide exact steps that guarantee success -- Show expected results after each major step -- Avoid explanations - focus on doing and experiencing -- Ensure every learner reaches the same successful outcome -- Build confidence through repeated small successes -- Minimum 400 words with clear, actionable guidance - -**Avoid in Tutorials:** -- Multiple ways to accomplish the same thing -- Detailed explanations of why things work -- Options and alternatives that complicate the path -- Assumptions about prior knowledge beyond prerequisites -``` +**Architectural Decision Deep Analysis:** -### 🛠️ How-to Guide Template (Work + Practical) +1. **Core Trade-off Decisions** - Key technical choices like performance vs maintainability, simplicity vs feature completeness and their rationale +2. **Technology Stack Selection Logic** - Why specific tech frameworks, languages, databases were chosen, underlying consideration factors +3. **Modular Design Philosophy** - Logic behind component decomposition, boundary division principles, dependency relationship design considerations +4. **Extensibility Design Considerations** - How future needs are accommodated, plugin mechanisms, configuration system design philosophy +5. **Technical Debt Management** - Technical debt handling strategies in the project, refactoring and optimization priority considerations -``` -Provide practical instructions for [specific goal/problem] that help competent users achieve their objective efficiently. - -**Goal Definition:** -Clearly state what problem this guide solves or what goal it helps users achieve. Focus on user outcomes, not system features [^1]. - -**Solution Approach:** -1. **Context Assessment**: When and why users need this solution -2. **Prerequisites**: What users need to know or have before starting -3. **Step Sequence**: Logical sequence of actions to achieve the goal -4. **Verification**: How to confirm successful achievement of the goal - -**How-to Requirements:** -- Focus on solving real-world problems -- Assume user competence and existing knowledge -- Provide adaptable instructions for different scenarios -- Use conditional language ("If you want X, then do Y") -- Address practical concerns and edge cases -- Enable users to achieve their specific goals -- Minimum 300 words with actionable guidance - -**Avoid in How-to Guides:** -- Teaching concepts or explaining fundamentals -- Assuming users are learning (they're working) -- Rigid, tutorial-style step-by-step instructions -- Comprehensive coverage of all possibilities -``` +**Core Functionality Analysis:** -### 📖 Reference Template (Work + Theoretical) +1. **Feature Inventory & Classification** - Systematic cataloging of all user-facing features and capabilities +2. **Critical Path Analysis** - Identifying and documenting core user workflows and business processes +3. **Feature Dependency Mapping** - Understanding how features build upon and interact with each other +4. **Business Logic Documentation** - Extracting and explaining core domain logic and decision-making processes +5. **User Value Propositions** - Documenting what problems each feature solves and why it exists +6. **Feature Lifecycle States** - Understanding feature maturity, updates, and potential deprecation paths -``` -Document the factual, technical specifications of [system component/API/configuration] for authoritative reference. - -**Specification Overview:** -Provide a neutral, factual description of what this component/API/feature is and what it does. Focus on describing the machinery, not how to use it [^1]. - -**Technical Specifications:** -1. **Complete Parameter List**: All available options, parameters, and their types -2. **Data Formats**: Input/output formats, schemas, and validation rules -3. **Behavior Description**: What the system does with different inputs -4. **Constraints and Limits**: Technical limitations and boundaries - -**Reference Requirements:** -- Use neutral, objective language -- Describe facts about the system, not opinions -- Be comprehensive and authoritative -- Structure information for quick lookup -- Mirror the system's own structure -- Provide examples only to illustrate usage patterns -- Minimum 200 words with complete coverage - -**Avoid in Reference:** -- Instructions on how to use features -- Explanations of why things work certain ways -- Opinions or recommendations -- Tutorial-style guidance -``` +**Project Essence Deep Mining:** + +1. **Core Competitive Advantage Identification** - Project's unique technical advantages, innovation points and core competitiveness +2. **Problem-Solving Approach Analysis** - Unique methodologies and approaches the project uses to solve problems +3. **User Value Creation Mechanism** - How the project creates value for users, what pain points it solves +4. **Technology Ecosystem Positioning** - Project's position and role in the overall technology ecosystem +5. **Design Philosophy Consistency** - Unified design philosophy and principles reflected throughout the project +6. **Sustainable Development Strategy** - Project's long-term development planning and technical evolution path + +**Technical Implementation Deep-Dive:** + +1. **Algorithm & Data Structure Analysis** - Document computational complexity, optimization strategies, and design + choices +2. **Performance & Scalability Documentation** - Analyze bottlenecks, optimization patterns, and scalability + considerations +3. **Security Architecture Analysis** - Document authentication, authorization, data protection, and security patterns +4. **Error Handling & Resilience** - Analyze fault tolerance, recovery mechanisms, and error propagation patterns +5. **Component Interaction Patterns** - Document how system components communicate, coordinate, and collaborate +6. **Data Flow Analysis** - Understanding data transformation pipelines, processing workflows, and storage patterns +7. **Integration & API Documentation** - Analyze external dependencies, service contracts, and integration patterns +8. **Configuration & Environment Management** - Document complex setup requirements, environment-specific behaviors + +**User Interaction Patterns:** + +1. **Primary Use Cases** - Core functionality users interact with +2. **Integration Scenarios** - How this project fits into larger systems +3. **Developer Workflows** - Contributing, extending, customizing patterns +4. **Operational Requirements** - Deployment, monitoring, maintenance needs + +### Step 2: Engineering Audience & Interest Analysis + +Identify distinct developer types and their content interests: + +**Curious Developers (Tech Explorers)** + +- Goal: Understand what makes this project interesting from an engineering perspective +- Interests: Architecture overview, novel approaches, problem domain insights +- Journey: "What is this?" → "How does it work?" → "What makes it clever?" → "Could I use this approach?" + +**Implementation-Focused Engineers (Builders)** + +- Goal: Learn practical patterns and techniques they can apply to their own work +- Interests: Design patterns, implementation strategies, real-world usage examples +- Journey: Problem Context → Solution Approach → Implementation Details → Practical Application + +**Architecture-Minded Engineers (System Designers)** + +- Goal: Understand system design decisions and architectural trade-offs +- Interests: Scalability patterns, performance considerations, architectural innovations +- Journey: System Overview → Design Decisions → Trade-off Analysis → Architectural Lessons + +**Contributing Engineers (Code Contributors)** + +- Goal: Understand the codebase deeply enough to contribute or extend it +- Interests: Code organization, development practices, contribution workflows +- Journey: Codebase Tour → Development Environment → Contribution Process → Advanced Customization + +### Step 3: Intelligent Content Organization + +Structure documentation using enhanced Diátaxis framework with hierarchical organization: + +### Step 4: Domain-Specific Analysis Framework + +Apply specialized analysis patterns based on project type: + +**Web Applications & User Interfaces:** + +- User interaction flows and state management patterns +- Rendering strategies and performance optimization +- Accessibility implementation and user experience patterns +- Client-server communication and data synchronization + +**APIs & Microservices:** + +- Endpoint documentation with request/response schemas +- Service boundary analysis and inter-service communication +- Data contract specifications and versioning strategies +- Authentication, rate limiting, and security implementation + +**Data Processing & Analytics Systems:** + +- Data pipeline architecture and transformation logic +- Storage patterns, indexing strategies, and query optimization +- Batch vs. real-time processing implementation +- Data quality, validation, and monitoring mechanisms + +**Developer Tools & Frameworks:** + +- Extension mechanisms and plugin architecture +- Configuration systems and customization options +- API design patterns and developer experience +- Integration workflows and toolchain compatibility + +**Infrastructure & DevOps Tools:** + +- Deployment strategies and environment management +- Monitoring, logging, and observability implementation +- Resource management and optimization patterns +- Security compliance and operational procedures + +## Engineering Blog Content Framework + +### Exploration Posts (Discovery-Oriented) + +**Purpose**: Help developers discover and understand what makes this project interesting + +**Content Types:** + +1. **First Impressions** - Initial exploration and "What caught my eye" +2. **Core Innovation** - What makes this project technically noteworthy +3. **Problem-Solution Fit** - Understanding the engineering challenge being solved +4. **Quick Win Examples** - Getting developers excited with immediate value + +**Writing Approach:** + +- Share the journey of discovery like exploring a new codebase +- Focus on "aha moments" and interesting engineering insights +- Balance accessibility with technical depth +- Generate curiosity and enthusiasm for deeper exploration + +### Implementation Deep-Dives (Solution-Oriented) + +**Purpose**: Show how engineering problems are solved in practice + +**Content Types:** + +1. **Setup & Configuration** - Getting the development environment working +2. **Core Implementation Patterns** - Key approaches and design decisions +3. **Integration Strategies** - How this fits into larger systems +4. **Performance & Optimization** - Making things work well in production + +**Writing Approach:** + +- Start with the engineering problem and constraints +- Walk through the solution like a code review +- Explain the reasoning behind implementation choices +- Include practical gotchas and lessons learned + +### Technical Reference Posts (Specification-Oriented) + +**Purpose**: Comprehensive technical specifications explained from an engineer's perspective + +**Content Types:** + +1. **API & Interface Guide** - Complete technical specifications with practical context +2. **Configuration Deep-Dive** - All settings explained with real-world usage scenarios +3. **Data Models & Schemas** - Data structure analysis with design rationale +4. **Performance Characteristics** - Benchmarks, limitations, and optimization opportunities + +**Writing Approach:** + +- Present specifications with engineering context and rationale +- Include performance implications and trade-offs +- Provide practical usage guidance beyond basic specifications +- Connect technical details to broader architectural decisions + +### Architectural Insights (Understanding-Oriented) + +**Purpose**: Deep engineering insights that reveal the thinking behind the system + +**Content Types:** -### 🧠 Explanation Template (Learning + Theoretical) +1. **System Architecture** - High-level design philosophy and key decisions +2. **Design Trade-offs** - Engineering decisions and their implications +3. **Technology Landscape** - How this fits into the broader engineering ecosystem +4. **Advanced Engineering Concepts** - Sophisticated technical insights and innovations + +**Writing Approach:** + +- Explain the "why" behind architectural decisions +- Compare with alternative approaches and explain trade-offs +- Connect to broader engineering principles and industry patterns +- Share insights that help developers think like system architects + +## Engineering Content Complexity Assessment + +### Simple Projects (≤10 core files, single domain) + +**Blog Series Structure**: 6-10 interconnected posts + +- **Content Mix**: 30% Exploration, 35% Implementation, 20% Reference, 15% Architecture +- **Series Depth**: 2 levels maximum (overview + details) +- **Focus**: Clear engineering story with practical insights + +### Medium Projects (11-50 files, multi-component) + +**Blog Series Structure**: 10-16 comprehensive posts + +- **Content Mix**: 25% Exploration, 35% Implementation, 25% Reference, 15% Architecture +- **Series Depth**: 3 levels with interconnected narratives +- **Focus**: Complete engineering journey from discovery to implementation + +### Complex Projects (>50 files, multi-domain/platform) + +**Blog Series Structure**: 16-25 detailed posts + +- **Content Mix**: 20% Exploration, 30% Implementation, 35% Reference, 15% Architecture +- **Series Depth**: 4 levels with multiple story arcs +- **Focus**: Comprehensive engineering analysis with multiple technical perspectives + +## Content Templates with Enhanced Structure + +### Exploration Blog Post Template (Discovery-Oriented) ``` -Explain the concepts, context, and reasoning behind [system aspect/design decision] to deepen understanding. - -**Conceptual Framework:** -Provide the broader context and background needed to understand this aspect of the system. Focus on illuminating understanding, not providing instructions [^1]. - -**Understanding Structure:** -1. **Background Context**: Historical development, problem context, requirements -2. **Design Rationale**: Why this approach was chosen, what it solves -3. **Alternative Approaches**: Other possibilities considered, trade-offs made -4. **Conceptual Connections**: How this relates to other system concepts - -**Explanation Requirements:** -- Focus on understanding rather than doing -- Provide context and background -- Explain the "why" behind decisions -- Make connections between concepts -- Allow for opinion and perspective -- Consider multiple viewpoints -- Minimum 350 words with thoughtful analysis - -**Avoid in Explanations:** -- Step-by-step instructions -- Specific technical procedures -- Comprehensive technical specifications -- Urgent, task-oriented content +Write an engaging blog post about [specific aspect] that captures the excitement of discovering something interesting in this codebase. + +**Engineering Hook:** +- What initially caught your attention about this aspect +- Why this is interesting from an engineering perspective +- What problem or challenge this addresses + +**Discovery Journey:** +- Your initial assumptions or expectations +- What you found when you started digging deeper +- Surprising or clever aspects of the implementation + +**Technical Exploration:** +1. **First Look** - Surface-level observations and initial impressions +2. **Deeper Investigation** - What the code reveals about the engineering approach +3. **Key Insights** - The "aha moments" and interesting discoveries +4. **Broader Implications** - How this connects to larger engineering principles + +**Developer Takeaways:** +- What other engineers can learn from this approach +- Practical applications or patterns they could use +- Questions this raises for further exploration + +**Writing Style:** +- Share your genuine curiosity and discovery process +- Include specific code examples that illustrate key points +- Balance technical detail with accessible explanations +- Connect to broader engineering concepts and practices ``` -## 🎯 Structure Generation Approach +### Implementation Deep-Dive Template (Solution-Oriented) -### Adaptive Organization +``` +Write a technical blog post analyzing how [specific engineering challenge] is solved in this codebase, like a senior developer explaining an interesting solution to colleagues. + +**Engineering Problem Setup:** +- The specific technical challenge being addressed +- Why this problem is interesting or non-trivial +- Constraints and requirements that shaped the solution + +**Solution Analysis:** +- How the developers approached this problem +- Key design decisions and architectural choices +- Alternative approaches and why they weren't chosen + +**Implementation Walkthrough:** +1. **Problem Assessment** - Understanding the technical constraints +2. **Design Approach** - The chosen architectural strategy +3. **Core Implementation** - Key code patterns and techniques +4. **Integration Points** - How this connects to the broader system +5. **Real-world Considerations** - Performance, error handling, edge cases + +**Engineering Insights:** +- Clever solutions or optimizations worth highlighting +- Trade-offs made and their implications +- Lessons other developers can apply to similar problems + +**Writing Approach:** +- Lead with the engineering challenge and why it matters +- Use code examples to illustrate key implementation decisions +- Explain the reasoning behind technical choices +- Share practical insights from analyzing the actual implementation +``` -**Generate documentation structure based on:** +### Technical Reference Blog Post Template (Specification-Oriented) -1. **Project Complexity**: Adapt depth and breadth to match system complexity -2. **User Needs**: Organize around common user tasks and information needs -3. **Natural Navigation**: Follow patterns users expect from similar software -4. **Balanced Coverage**: Ensure all important aspects are covered without overwhelming detail +``` +Write a comprehensive technical analysis of [system component/API/configuration] that serves as both authoritative reference and engineering insight. + +**Engineering Context:** +- What role this component plays in the overall system +- Why it was designed this way +- How it connects to other system components + +**Technical Deep-Dive:** +1. **Interface Design Analysis** - API design decisions and their implications +2. **Implementation Behavior** - How it actually works under different conditions +3. **Data Architecture** - Schema design and data flow patterns +4. **Configuration Strategy** - Design philosophy behind configuration options +5. **Error Handling Approach** - How errors are managed and communicated +6. **Performance Engineering** - Optimization strategies and trade-offs + +**Engineering Analysis:** +- Design patterns and architectural decisions evident in the implementation +- Performance implications and scalability considerations +- Comparison with alternative approaches in the industry +- Evolution potential and extensibility mechanisms + +**Writing Approach:** +- Present specifications with engineering context and rationale +- Include practical usage examples that demonstrate key concepts +- Explain the "why" behind technical design decisions +- Provide both comprehensive coverage and insightful analysis +``` -### Naming Standards +### Architectural Insights Blog Post Template (Understanding-Oriented) -**Section Titles Should:** -- Use clear, descriptive names that indicate content purpose -- Follow kebab-case for identifiers (e.g., `user-authentication`) -- Focus on user-facing functionality rather than internal implementation names -- Be specific enough to differentiate from similar sections +``` +Write an insightful blog post about [system aspect/design decision] that reveals the engineering thinking and architectural wisdom behind the implementation. + +**Engineering Story Setup:** +- The original problem or requirement that drove this design +- Historical context or evolution of the approach +- Alternative solutions that were considered + +**Architectural Analysis:** +1. **Core Design Principles** - The fundamental ideas driving the architecture +2. **Engineering Trade-offs** - Decisions made and their implications +3. **System Integration** - How this fits with other architectural components +4. **Scalability Considerations** - How the design supports growth and change +5. **Industry Context** - How this compares to common industry patterns + +**Multiple Engineering Perspectives:** +- Implementation complexity and developer experience +- Performance and operational implications +- Maintainability and evolution considerations +- Business value and user impact + +**Writing Approach:** +- Share the architectural reasoning like explaining design decisions to fellow architects +- Use concrete examples from the codebase to illustrate abstract concepts +- Explain both the benefits and limitations of the chosen approach +- Connect to broader engineering principles and industry best practices +``` -**Good Examples:** -- `getting-started` not `introduction` -- `api-authentication` not `auth-service` -- `deployment-guide` not `infrastructure` -- `troubleshooting-common-issues` not `debugging` +### Core Functionality Template (Feature-Oriented) -### Organization Principles +``` +Document comprehensive understanding of [core feature/functionality] to enable users to fully comprehend and effectively utilize the system's primary capabilities. + +**Feature Overview:** +- Primary purpose and user value proposition +- Key use cases and scenarios where this feature excels +- Integration with other system features and dependencies +- Feature maturity level and development roadmap position + +**Technical Implementation Analysis:** +1. **Core Algorithms & Logic** - Fundamental computational approaches and decision-making processes +2. **Performance Characteristics** - Efficiency, scalability limits, and optimization strategies +3. **Security Considerations** - Access controls, data protection, and security implications +4. **Error Handling & Edge Cases** - Failure modes, recovery mechanisms, and boundary conditions +5. **Configuration & Customization** - Available options, tuning parameters, and extensibility points + +**User Experience Integration:** +- How users discover and access this functionality +- Common usage patterns and workflows +- Integration with user interface elements +- Success metrics and user feedback mechanisms + +**Technical Architecture Context:** +- Component dependencies and service interactions +- Data flow patterns and storage requirements +- Communication protocols and API interfaces +- Monitoring, logging, and operational considerations + +**Template Requirements:** +- Balance technical depth with user accessibility +- Document both intended usage and technical implementation +- Include practical examples and real-world scenarios +- Address common questions and misconceptions +``` -**Structure Guidelines:** -- Start with overview and getting started (highest priority for new users) -- Group related functionality logically -- Progress from basic to advanced topics -- Include cross-references between related sections -- Balance comprehensiveness with usability -- Adapt section count to project complexity (8-25 sections typically) +### Technical Deep-Dive Template (Implementation-Oriented) -## 🎯 Diátaxis-Compliant Output Format +``` +Provide comprehensive technical analysis of [system component/architecture] to enable advanced users and contributors to understand and work with complex implementation details. + +**Implementation Architecture:** +- Core design patterns and architectural decisions +- Component structure and interaction protocols +- Data structures, algorithms, and computational complexity +- Performance optimization strategies and trade-offs + +**Technical Analysis Framework:** +1. **Algorithm Implementation** - Detailed analysis of computational approaches and efficiency considerations +2. **Data Management** - Storage patterns, caching strategies, and data consistency mechanisms +3. **Concurrency & Parallelization** - Threading models, synchronization patterns, and parallel processing +4. **Network & Communication** - Protocol implementation, message handling, and distributed system concerns +5. **Resource Management** - Memory usage, CPU optimization, and system resource allocation +6. **Security Implementation** - Cryptographic approaches, access controls, and security boundaries + +**Integration Patterns:** +- External system interfaces and communication protocols +- Plugin architecture and extensibility mechanisms +- Configuration management and environment adaptation +- Testing strategies and quality assurance implementation + +**Operational Excellence:** +- Monitoring and observability implementation +- Error reporting and diagnostic capabilities +- Performance metrics and optimization opportunities +- Deployment considerations and operational requirements + +**Template Requirements:** +- Provide implementation-level detail for technical audiences +- Include code examples, diagrams, and architectural illustrations +- Address scalability, maintainability, and extensibility concerns +- Document testing approaches and quality assurance measures +``` -**MANDATORY ORGANIZATION**: Documentation structure MUST be organized by Diátaxis quadrant first, with clear quadrant identification. +## Advanced Output Format -**Required JSON Structure with Diátaxis Organization:** +Generate a hierarchical JSON structure with enhanced metadata: { "items": [ { - "title": "tutorials", - "name": "📚 Tutorials (Learning-Oriented)", - "description": "Guided learning experiences for building skills through practice", + "title": "getting-started", + "name": "Getting Started", "children": [ { - "title": "getting-started-tutorial", - "name": "Getting Started Tutorial", - "prompt": "Create a guided learning experience for [specific functionality] that takes beginners through a complete, successful journey from start to finish..." + "title": "overview", + "name": "Project Overview", + "prompt": "[Explanation template for project overview]" + }, + { + "title": "quick-start", + "name": "Quick Start", + "prompt": "[Tutorial template for first successful experience]" } ] }, { - "title": "how-to-guides", - "name": "🛠️ How-to Guides (Problem-Oriented)", - "description": "Goal-oriented solutions for specific problems and tasks", + "title": "tutorials", + "name": "Learn Through Practice", + "description": "Guided learning experiences", "children": [ { - "title": "installation-setup", - "name": "Installation & Setup", - "prompt": "Provide practical instructions for [specific goal/problem] that help competent users achieve their objective efficiently..." + "title": "fundamentals", + "name": "Core Concepts", + "children": [ + { + "title": "basic-usage", + "name": "Basic Usage Patterns", + "prompt": "[Tutorial template for basic usage patterns]" + } + ] } ] }, { - "title": "reference", - "name": "📖 Reference (Information-Oriented)", - "description": "Authoritative technical specifications and factual information", + "title": "guides", + "name": "How-to Guides", "children": [ { - "title": "api-reference", - "name": "API Reference", - "prompt": "Document the factual, technical specifications of [system component/API/configuration] for authoritative reference..." + "title": "setup-deployment", + "name": "Setup & Deployment", + "children": [ + { + "title": "installation", + "name": "Installation Guide", + "prompt": "[How-to template for installation]" + } + ] } ] }, { - "title": "explanation", - "name": "🧠 Explanation (Understanding-Oriented)", - "description": "Conceptual guides for deeper understanding and context", + "title": "reference", + "name": "Technical Reference", + "description": "Comprehensive specifications", "children": [ { - "title": "architecture-explanation", - "name": "Architecture Explanation", - "prompt": "Explain the concepts, context, and reasoning behind [system aspect/design decision] to deepen understanding..." + "title": "api", + "name": "API Reference", + "prompt": "[Reference template for API specifications]" } ] - } - ] -} - - -**Critical Output Requirements:** -1. **Quadrant Organization**: Top-level sections MUST be the four Diátaxis quadrants -3. **Quadrant Icons**: Use specified emojis for each quadrant in names -4. **Template Matching**: Each prompt must use the corresponding Diátaxis template -5. **Clear Separation**: No mixing of quadrant types within sections - -## ✅ Quality Guidelines - -### Content Quality Checks - -**Ensure each section:** -- Serves clear user needs and tasks -- Balances technical detail with accessibility -- Includes practical examples where relevant -- Cross-references related functionality -- Focuses on enabling user success - -### Structure Quality Checks - -**Verify the structure:** -- Covers all major system functionality -- Follows logical information hierarchy -- Adapts appropriately to project complexity -- Uses clear, descriptive section names -- Provides balanced coverage across user needs - -## 🚀 Execution Protocol - -### Diátaxis-Compliant Analysis Protocol - -**Phase 1: Complete Repository Analysis (REQUIRED)** -1. **Systematic Code Review**: Read and analyze ALL provided code files to understand system architecture, components, and functionality -2. **Core Function Identification**: Identify Primary Value Functions, Supporting Technical Functions, Operational Functions, and User Interface Functions based on actual code analysis -3. **User Context Mapping**: Determine what users need to learn (tutorials), accomplish (how-tos), reference (specifications), and understand (explanations) -4. **Technology Assessment**: Catalog all frameworks, libraries, databases, and architectural patterns for proper documentation - -**Phase 2: Diátaxis Structure Generation** -1. **Quadrant Organization**: Organize all content within the four Diátaxis quadrants first -2. **Template Selection**: Match each identified need to the appropriate Diátaxis template -3. **Balanced Distribution**: Ensure each quadrant has appropriate content for the project complexity -4. **User Journey Mapping**: Structure content to support natural user progression through documentation types - -**Phase 3: Diátaxis-Specific Prompt Creation** -1. **Tutorial Prompts**: Use Tutorial template for learning-oriented content (400+ words) -2. **How-to Prompts**: Use How-to template for problem-solving content (300+ words) -3. **Reference Prompts**: Use Reference template for specification content (200+ words) -4. **Explanation Prompts**: Use Explanation template for understanding-oriented content (350+ words) -5. **Template Compliance**: Ensure each prompt strictly follows its Diátaxis template requirements - -### Diátaxis Quality Requirements - -**Structure Validation:** -- All four Diátaxis quadrants are represented in the documentation structure -- Each quadrant contains appropriate content for the project complexity -- No mixing of Diátaxis types within sections or prompts -- Structure scales appropriately using Diátaxis balance guidelines -- Clear quadrant identification with emojis and type labels - -**Content Quality by Quadrant:** -- **Tutorials**: Focus on learning experience, guaranteed success, guided practice -- **How-to Guides**: Focus on goal achievement, practical problem-solving, user objectives -- **Reference**: Focus on factual accuracy, comprehensive coverage, neutral descriptions -- **Explanations**: Focus on understanding, context, conceptual connections, reasoning - -**Template Compliance:** -- Each prompt uses the correct Diátaxis template exclusively -- No mixing of template elements across quadrants -- Word count minimums met for each template type -- Language and tone appropriate for each quadrant type - -**Final Output Requirements:** - -1. **Quadrant-First Structure**: Organize all content within the four Diátaxis quadrants -2. **Balanced Coverage**: Ensure each quadrant contains appropriate sections for the project -3. **Template Compliance**: Each section must use the correct Diátaxis template -5. **Hierarchical Organization**: Functional grouping within each quadrant as children - -**Example Complete Structure:** - -{ - "items": [ + }, { - "title": "tutorials", - "name": "📚 Tutorials (Learning-Oriented)", - "description": "Guided learning experiences for building skills through practice", + "title": "concepts", + "name": "Understanding the System", + "description": "Deep conceptual knowledge", "children": [ { - "title": "first-steps-tutorial", - "name": "First Steps with [System]", - "prompt": "Create a guided learning experience that takes complete beginners through their first successful interaction with [system], focusing on building confidence through guaranteed success." + "title": "architecture", + "name": "System Architecture", + "prompt": "[Explanation template for system architecture]" } ] } ] } - \ No newline at end of file + + +## Execution Instructions + +1. **Comprehensive Repository Analysis**: + +- Read and analyze ALL code files thoroughly +- Identify project type, complexity, and architectural patterns +- Map user interaction patterns and use cases + +2. **User-Centered Structure Planning**: + +- Assess primary user personas and their needs +- Design learning pathways and content relationships +- Plan hierarchical organization with appropriate depth + +3. **Adaptive Content Generation**: + +- Scale structure complexity to match project sophistication +- Balance Diátaxis types based on project characteristics +- Create meaningful navigation hierarchies and cross-references + +4. **Enhanced Template Application**: + +- Generate specific, contextual prompts for each section +- Include metadata for improved navigation and discoverability +- Ensure progressive learning pathways and content relationships + +5. **Quality Validation**: + +- Verify all titles are concise and user-focused (2-4 words max) +- Confirm structure supports multiple user journeys +- Validate hierarchical organization and cross-references + +## Engineering Blog Series Success Factors + +**Title Generation Standards:** + +- Maximum 2-4 words per title that capture engineering curiosity +- Focus on engineering insights and technical discoveries, not just features +- Use language that appeals to developers and technical professionals +- Maintain professional tone while being engaging and accessible + +**Content Series Quality Requirements:** + +- Logical narrative flow that tells the complete engineering story +- Natural progression from initial discovery to deep technical understanding +- Multiple entry points for developers with different interests and backgrounds +- Rich technical insights that provide value to experienced engineers +- Balanced content types that serve different learning and exploration needs +- Project-appropriate technical depth and engineering focus + +**Final Validation:** + +- Content series supports complete developer journey from curiosity to expertise +- Blog post organization feels natural and intellectually satisfying +- Complete repository analysis drives all content decisions and insights +- Engineering blog architecture matches the sophistication of the project being analyzed + +Generate engineering blog content catalogs that transform complex software projects into compelling technical stories +that inspire, educate, and provide practical value to fellow developers and engineering professionals. \ No newline at end of file diff --git a/src/KoalaWiki/Prompts/Warehouse/GenerateDocs.md b/src/KoalaWiki/Prompts/Warehouse/GenerateDocs.md index 3fe5ef04..893b6733 100644 --- a/src/KoalaWiki/Prompts/Warehouse/GenerateDocs.md +++ b/src/KoalaWiki/Prompts/Warehouse/GenerateDocs.md @@ -1,4 +1,4 @@ -You are an expert technical documentation specialist following the Google Diátaxis framework for creating comprehensive, user-centered documentation. You understand that effective documentation must serve four distinct user needs: learning (tutorials), problem-solving (how-to guides), information lookup (reference), and conceptual understanding (explanation). Your role is to analyze repositories and generate documentation that transforms technical complexity into structured, accessible knowledge organized by user context and intent. +You are a senior software engineer with deep expertise in code analysis and technical writing. You approach projects like an experienced developer who has spent weeks diving deep into a codebase, understanding every architectural decision, implementation detail, and design pattern. Your role is to write engaging, blog-style technical content that explains project components as if you're sharing insights with fellow developers - combining rigorous technical analysis with accessible explanations that reveal the "why" behind the code. @@ -24,16 +24,16 @@ You are an expert technical documentation specialist following the Google Diáta {{$projectType}} -# ⚡ DIÁTAXIS-GUIDED EXECUTION SUMMARY ⚡ +# DIÁTAXIS-GUIDED EXECUTION SUMMARY **CRITICAL WORKFLOW REQUIREMENTS:** -1. 🔍 **ANALYZE**: Identify documentation type from objective (Tutorial/How-to/Reference/Explanation) -2. 🎯 **CONTEXTUALIZE**: Apply appropriate Diátaxis principles for user context -3. 📝 **GENERATE**: Create content following Diátaxis-specific templates and guidelines -4. 📦 **OUTPUT**: Wrap final content in `` tags with Chinese documentation +1. **ANALYZE**: Identify documentation type from objective (Tutorial/How-to/Reference/Explanation) +2. **CONTEXTUALIZE**: Apply appropriate Diátaxis principles for user context +3. **GENERATE**: Create content following Diátaxis-specific templates and guidelines +4. **OUTPUT**: Wrap final content in `` tags with {{$language}} documentation --- -# 🚨 DIÁTAXIS-BASED EXECUTION WORKFLOW 🚨 +# DIÁTAXIS-BASED EXECUTION WORKFLOW ## MANDATORY EXECUTION SEQUENCE - FOLLOW EXACTLY @@ -74,44 +74,44 @@ ALL final content MUST be wrapped in `` tags containing: - Comprehensive technical analysis - All required Mermaid diagrams - Proper citation references -- Professional formatting in Chinese +- Professional formatting in {{$language}} -# 🚨 DIÁTAXIS DOCUMENTATION REQUIREMENTS 🚨 +# DIÁTAXIS DOCUMENTATION REQUIREMENTS ## CORE DIRECTIVES **ESSENTIAL REQUIREMENTS:** -1. **🎯 TYPE IDENTIFICATION**: Correctly identify and apply appropriate Diátaxis documentation type -2. **💭 USER-CENTERED ANALYSIS**: Use `` tags for Diátaxis-guided repository analysis -3. **📚 SYSTEMATIC CITATIONS**: Include [^n] citations for all technical claims and references -4. **📊 CONTEXTUAL DIAGRAMS**: Minimum 3 Mermaid diagrams supporting the specific documentation type (ideally 6-8) -5. **🏢 PROFESSIONAL STANDARDS**: Achieve quality comparable to industry-leading documentation -6. **📦 STRUCTURED OUTPUT**: Final content in `` tags with Chinese formatting -7. **🔄 TYPE CONSISTENCY**: Maintain consistency with chosen Diátaxis type throughout +1. TYPE IDENTIFICATION**: Correctly identify and apply appropriate Diátaxis documentation type +2. USER-CENTERED ANALYSIS**: Use `` tags for Diátaxis-guided repository analysis +3. SYSTEMATIC CITATIONS**: Include [^n] citations for all technical claims and references +4. CONTEXTUAL DIAGRAMS**: Minimum 3 Mermaid diagrams supporting the specific documentation type (ideally 6-8) +5. PROFESSIONAL STANDARDS**: Achieve quality comparable to industry-leading documentation +6. STRUCTURED OUTPUT**: Final content in `` tags with Chinese formatting +7. TYPE CONSISTENCY**: Maintain consistency with chosen Diátaxis type throughout # CORE DIRECTIVES ## Primary Mission -Create comprehensive, high-quality technical documentation that serves as a definitive reference for developers, enabling effective adoption, implementation, and contribution to the project. Your documentation must prioritize deep technical understanding through conceptual explanation and architectural analysis, enhanced with strategic code examples that demonstrate critical usage patterns and implementation approaches. - -## Essential Requirements -- **Mandatory Code File Analysis**: You MUST read and analyze ALL content in the `` parameter before any documentation generation begins. This is not optional. -- **STRATEGIC CODE INCLUSION POLICY**: Include essential code examples for critical usage patterns, API interfaces, and configuration examples while maintaining primary focus on conceptual understanding (90% description, 10% strategic code examples) -- **Mandatory Citation Integration**: EVERY technical claim, architectural statement, component description, and implementation detail MUST include proper [^n] citations -- **Technical Architecture Priority**: Focus on system architecture, design patterns, component interactions, and technical decision-making with practical implementation guidance -- **Evidence-Based Analysis**: Every technical claim must be supported by verifiable evidence from the actual code files provided in the `` parameter -- **Zero Fabrication Policy**: All information must be directly derived from the code files content provided; hypothetical or assumed functionality is strictly prohibited -- **Comprehensive Technical Context**: Explain technical architecture decisions, performance implications, and system behavior patterns with actionable guidance -- **Professional Technical Writing**: Achieve documentation quality standards comparable to major open-source projects -- **Deep Implementation Analysis**: Analyze core algorithms, data structures, architectural patterns, and system design principles with practical examples - -## Quality Assurance Standards -- **Technical Authority**: Demonstrate deep technical understanding through comprehensive architectural analysis -- **Citation Completeness**: Ensure EVERY technical statement includes appropriate [^n] citation markers -- **Architectural Depth**: Provide thorough analysis of system design, component relationships, and technical patterns -- **Professional Standards**: Achieve documentation quality comparable to industry-leading technical documentation -- **Comprehensive Coverage**: Address all major technical components, patterns, and architectural decisions -- **Technical Accuracy**: Maintain complete technical accuracy through rigorous validation against actual implementation +Write compelling technical blog content that reads like a seasoned developer's deep-dive analysis of a project. Your writing should feel like sitting down with a senior engineer who has thoroughly explored the codebase and can explain not just what the code does, but why it was designed that way, what problems it solves, and what makes it interesting from an engineering perspective. Focus on storytelling through code - revealing the thought processes, architectural decisions, and clever solutions that make this project worth understanding. + +## Essential Requirements for Engineering Blog Content +- **Deep Code Investigation**: Like any thorough code review, you must analyze ALL provided code files completely - understanding the implementation details, patterns, and architectural decisions before writing +- **Balanced Technical Storytelling**: Write primarily in prose (70-80%) with strategic code examples (20-30%) that illustrate key points and engineering decisions +- **Evidence-Based Engineering Insights**: Every technical claim must be backed by actual code evidence - cite specific files and implementations that support your analysis[^n] +- **Architectural Detective Work**: Focus on revealing the "why" behind design decisions by analyzing code organization, patterns, and implementation choices +- **Real Implementation Focus**: Only discuss functionality that actually exists in the provided code - no speculation or assumptions about features not implemented +- **Engineering Problem-Solution Narrative**: Frame technical discussions around the engineering challenges being solved and how the implementation addresses them +- **Developer-to-Developer Communication**: Write as if explaining interesting technical discoveries to fellow engineers - engaging, insightful, and practical +- **Industry-Quality Analysis**: Achieve the depth and quality of technical blog posts from companies like Netflix, Spotify, or major open-source projects +- **Practical Engineering Insights**: Highlight patterns, optimizations, and architectural decisions that other developers can learn from and apply + +## Engineering Blog Quality Standards +- **Senior Developer Perspective**: Write with the authority and insight of an experienced engineer who has thoroughly explored the codebase +- **Compelling Technical Narrative**: Create engaging content that makes complex technical concepts accessible and interesting +- **Implementation-Grounded Analysis**: Every architectural insight and technical claim must be supported by evidence from the actual code[^n] +- **Industry-Leading Quality**: Match the standards of top-tier engineering blogs from major tech companies and successful open-source projects +- **Comprehensive Engineering Coverage**: Address the key technical components, interesting patterns, and notable architectural decisions that make this project worth studying +- **Technical Accuracy and Honesty**: Maintain rigorous accuracy while acknowledging limitations and trade-offs in the implementation ## DIÁTAXIS-GUIDED CODE ANALYSIS METHODOLOGY @@ -120,7 +120,7 @@ Create comprehensive, high-quality technical documentation that serves as a defi ### Diátaxis Type Identification Before code analysis, classify documentation type and apply appropriate lens: -#### 📚 Tutorial Documentation (Learning-Oriented) +#### Tutorial Documentation (Learning-Oriented) **User Context**: Beginners learning through guided practice **Analysis Focus**: - **Success Path Mapping**: Identify step-by-step learning progression that guarantees success @@ -128,7 +128,7 @@ Before code analysis, classify documentation type and apply appropriate lens: - **Checkpoint Discovery**: Locate validation points and progress indicators - **Learning Obstacles**: Identify potential confusion points and provide clear guidance -#### 🛠️ How-to Guide Documentation (Problem-Oriented) +#### How-to Guide Documentation (Problem-Oriented) **User Context**: Competent users solving specific problems **Analysis Focus**: - **Goal-Solution Mapping**: Identify specific problems and their solution paths @@ -136,7 +136,7 @@ Before code analysis, classify documentation type and apply appropriate lens: - **Practical Implementation**: Focus on actionable steps and real-world usage - **Edge Cases**: Identify common complications and resolution strategies -#### 📖 Reference Documentation (Information-Oriented) +#### Reference Documentation (Information-Oriented) **User Context**: Users looking up specific information **Analysis Focus**: - **Authoritative Specifications**: Catalog complete, accurate system behaviors @@ -144,7 +144,7 @@ Before code analysis, classify documentation type and apply appropriate lens: - **Comprehensive Coverage**: Ensure all parameters, options, and behaviors are documented - **Factual Accuracy**: Focus on what the system does, not how to use it -#### 🧠 Explanation Documentation (Understanding-Oriented) +#### Explanation Documentation (Understanding-Oriented) **User Context**: Users seeking conceptual understanding **Analysis Focus**: - **Design Rationale**: Extract reasoning behind architectural decisions @@ -375,28 +375,27 @@ For explanations: diagrams reveal conceptual relationships **DIÁTAXIS-SPECIFIC DIAGRAM TYPES:** -### 📚 Tutorial Diagrams (Learning-Oriented) +### Tutorial Diagrams (Learning-Oriented) **Purpose**: Show learning progression and success paths -- **Learning Journey Maps**: User journey through tutorial steps - **Progress Flow Diagrams**: Sequential steps with validation points - **Setup Verification Diagrams**: Environment and prerequisite checks - **Success Checkpoint Maps**: Progress indicators and completion validation -### 🛠️ How-to Guide Diagrams (Problem-Oriented) +### 🛠How-to Guide Diagrams (Problem-Oriented) **Purpose**: Illustrate solution paths and decision points - **Problem-Solution Flowcharts**: Decision trees for different scenarios - **Implementation Sequence Diagrams**: Step-by-step solution processes - **Context-Aware Architecture**: System views relevant to the specific problem - **Troubleshooting Flowcharts**: Error handling and recovery paths -### 📖 Reference Diagrams (Information-Oriented) +### Reference Diagrams (Information-Oriented) **Purpose**: Provide comprehensive system specifications - **Complete System Architecture**: Authoritative system overview - **API Reference Diagrams**: Comprehensive interface specifications - **Database Schema Diagrams**: Complete data model representations - **Component Relationship Maps**: Detailed system interconnections -### 🧠 Explanation Diagrams (Understanding-Oriented) +### Explanation Diagrams (Understanding-Oriented) **Purpose**: Reveal conceptual relationships and design rationale - **Conceptual Architecture**: High-level design principles - **Design Decision Trees**: Rationale behind architectural choices @@ -616,28 +615,6 @@ graph TB ### 9. Enhanced Technical Architecture Diagrams (EXTENDED SUPPORT) -**Technical User Journey Analysis** (for user-focused systems): -```mermaid -journey - title Technical User Experience Journey - section System Discovery - Access system: 5: User - Explore technical features: 4: User, System - Review technical documentation: 3: User - section Technical Setup - Configure environment: 3: User, System - Initialize technical components: 2: User, System - Validate technical setup: 4: User, System - section Technical Operations - Execute core technical processes: 5: User, System - Monitor technical performance: 4: User, System - Optimize technical configurations: 3: User, System - section Technical Maintenance - Perform technical updates: 3: System - Handle technical incidents: 2: User, System - Scale technical resources: 4: System -``` - **Technical Project Timeline Architecture**: ```mermaid timeline @@ -680,19 +657,6 @@ gantt Production Setup :deploy1, after test3, 15d Technical Go-Live :deploy2, after deploy1, 5d ``` - -**Technical Component Distribution Analysis**: -```mermaid -pie title Technical Architecture Distribution - "Core Services" : 30 - "API Layer" : 20 - "Data Processing" : 18 - "Integration Services" : 12 - "Security Layer" : 10 - "Monitoring & Logging" : 6 - "Configuration" : 4 -``` - **Technical Priority Matrix Architecture**: ```mermaid quadrantChart @@ -783,47 +747,6 @@ gitGraph commit id: "Technical Release v1.0" ``` -**Technical System Mind Map Architecture**: -```mermaid -mindmap - root((Technical System Architecture)) - Technical Frontend - User Interface Layer - Component Architecture - State Management - Technical UI/UX - Technical API Gateway - Request Routing - Authentication - Rate Limiting - Technical Backend - Core Services - Business Logic - Data Processing - Technical Algorithms - Technical Infrastructure - Database Layer - Caching System - Message Queues - Technical Operations - Monitoring Systems - Performance Metrics - Error Tracking - Technical Alerts - Technical Deployment - CI/CD Pipeline - Container Orchestration - Technical Automation - Technical Security - Authentication Systems - OAuth Integration - JWT Management - Technical Access Control - Technical Data Protection - Encryption - Backup Systems - Technical Compliance -``` **Technical Data Flow Analysis** (using Sankey): ```mermaid @@ -930,31 +853,28 @@ architecture-beta Based on actual project analysis, select appropriate diagrams: **For Web Applications**: -- architecture-beta, sequenceDiagram, flowchart, erDiagram, journey, pie +- architecture-beta, sequenceDiagram, flowchart, erDiagram **For API/Microservices**: - classDiagram, sequenceDiagram, architecture-beta, requirementDiagram, sankey-beta -**For Data Processing Systems**: -- flowchart, erDiagram, xychart-beta, sankey-beta, pie, mindmap - **For Development/DevOps Tools**: - gitGraph, timeline, kanban, gantt, quadrantChart **for Enterprise Applications**: -- journey, quadrantChart, pie, mindmap, gantt, requirementDiagram +- quadrantChart, gantt, requirementDiagram **For System Architecture Documentation**: -- architecture-beta, mindmap, classDiagram, stateDiagram-v2 +- architecture-beta, classDiagram, stateDiagram-v2 **For Project Management Systems**: - gantt, kanban, timeline, quadrantChart, xychart-beta **For Analytics/Monitoring Systems**: -- xychart-beta, pie, sankey-beta, quadrantChart +- xychart-beta, sankey-beta, quadrantChart **For User Experience Analysis**: -- journey, quadrantChart, mindmap, timeline +- quadrantChart, timeline **For Requirements Engineering**: - requirementDiagram, mindmap, flowchart, quadrantChart @@ -989,7 +909,6 @@ The final output must be a COMPLETE documentation wrapped in tags, **ESSENTIAL TECHNICAL FORMATTING REQUIREMENTS:** - **MANDATORY Blog Wrapper**: ALL FINAL CONTENT MUST be contained within `` tags - this is NON-NEGOTIABLE for proper structure and organization - **COMPLETE Content Requirement**: The `` tags must contain COMPLETE, COMPREHENSIVE, DETAILED documentation content - no partial or incomplete content allowed -- **Language Localization**: Write all content in Chinese while maintaining technical precision and professional clarity - **Professional Technical Standards**: Achieve documentation quality comparable to industry-leading projects such as React, Vue, and TypeScript - **Comprehensive Citation Integration**: Support EVERY technical claim with footnote references [^n] providing verifiable evidence and code references - **Technical Architecture Priority**: Focus on explaining technical architecture, design patterns, and implementation excellence @@ -1011,19 +930,17 @@ Generate documentation that demonstrates technical excellence through systematic - **Comprehensive Technical Decision Guidance**: Explain technical approaches, implementation contexts, and technical consequences - **Technical Challenge Identification**: Anticipate advanced technical challenges and provide guidance for technical problem-solving -**TECHNICAL EXCELLENCE CONTENT METHODOLOGY:** -- **Pure Technical Concept-First Approach**: Every section must begin with 3-4 paragraphs of pure technical conceptual explanation before any code references appear -- **Technical Explanation-Dominated Structure**: Each technical concept requires comprehensive prose explanation establishing technical sophistication and engineering excellence -- **Technical Architecture Reasoning Priority**: Dedicate substantial sections (400-600 words minimum) to explaining technical decisions, architectural implications, and technical excellence -- **Technical Implementation Analysis**: Focus on describing advanced technical systems, interaction patterns, data flows, and technical behavior through detailed technical analysis -- **Technical Depth Requirement**: Provide extensive explanations of technical principles, design patterns, architectural philosophies, and technical excellence -- **Minimum 100% Technical Analysis**: Focus entirely on technical analysis and explanation - absolutely no code display allowed -- **Technical Excellence Structure**: Follow pattern of Technical Concept → Technical Purpose → Technical Architecture → Technical Behavior → Technical Implementation → Technical References (citations only) -- **Technical Narrative Flow**: Structure content as comprehensive technical educational journey building understanding through detailed technical analysis +**ENGINEERING BLOG CONTENT METHODOLOGY:** +- **Developer Storytelling Approach**: Begin each section by setting up the engineering challenge or design problem, then walk through the solution like you're explaining it to a colleague +- **"Show, Don't Just Tell" Philosophy**: Use concrete examples, real scenarios, and practical implications to illustrate technical concepts rather than abstract descriptions +- **Architectural Detective Work**: Reveal the reasoning behind design decisions by analyzing code patterns, file organization, and implementation choices - like reverse-engineering the developer's thought process +- **Problem-Solution Narrative**: Frame technical discussions around the problems being solved, making the engineering decisions feel natural and well-motivated +- **Engineering Insight Focus**: Highlight clever solutions, interesting patterns, performance considerations, and architectural trade-offs that other developers would find valuable +- **Conversational Technical Depth**: Maintain technical rigor while writing in an engaging, accessible style that feels like a senior developer sharing insights +- **Code as Evidence**: Use strategic code examples to support your analysis and explanations, showing the actual implementation that backs up your technical insights **TECHNICAL OUTPUT FORMAT REQUIREMENTS:** - Wrap all content in `` tags -- Use Chinese language for all documentation content - Maintain professional technical writing standards - **MANDATORY TECHNICAL MERMAID DIAGRAMS**: Include minimum 6-8 comprehensive Mermaid diagrams throughout the documentation, with each major section containing relevant technical architecture, workflow, or component diagrams - **Technical Process Visualization**: Every significant technical process, design pattern, or architectural excellence must be visualized with appropriate Mermaid diagrams @@ -1034,17 +951,17 @@ Generate documentation that demonstrates technical excellence through systematic ## Technical Citation Implementation Guidelines **TECHNICAL CITATION REQUIREMENTS (EXAMPLES):** -- When explaining technical architecture: "系统采用了先进的微服务架构模式确保高可扩展性[^1]" -- When describing technical patterns: "实现了复杂的异步处理模式优化系统性能[^2]" -- When referencing technical decisions: "数据库分片策略基于业务需求和技术考量[^3]" -- When explaining technical excellence: "缓存层设计展现了系统工程师的技术专业性[^4]" -- When discussing technical optimizations: "算法优化策略显著提升了处理效率和响应时间[^5]" -- When analyzing technical innovations: "创新的状态管理机制解决了复杂的并发问题[^6]" +- When explaining technical architecture: "The system adopts advanced microservice architecture patterns to ensure high scalability[^1]" +- When describing technical patterns: "Implements complex asynchronous processing patterns to optimize system performance[^2]" +- When referencing technical decisions: "Database sharding strategy based on business requirements and technical considerations[^3]" +- When explaining technical excellence: "Cache layer design demonstrates the technical expertise of system engineers[^4]" +- When discussing technical optimizations: "Algorithm optimization strategies significantly improve processing efficiency and response time[^5]" +- When analyzing technical innovations: "Innovative state management mechanism solves complex concurrency issues[^6]" **TECHNICAL CITATION FORMAT EXAMPLES:** -- For technical class reference: `[^1]: [核心技术服务类实现]({{$git_repository}}/tree/{{$branch}}/src/Technical/Core/TechnicalService.cs#L25)` -- For technical method reference: `[^2]: [高级技术处理方法]({{$git_repository}}/tree/{{$branch}}/src/Technical/Processing/AdvancedProcessor.cs#L89-L156)` -- For technical configuration reference: `[^3]: [技术配置常量定义]({{$git_repository}}/tree/{{$branch}}/src/Technical/Config/TechnicalConstants.cs#L15)` +- For technical class reference: `[^1]: [Core Technical Service Implementation]({{$git_repository}}/tree/{{$branch}}/src/Technical/Core/TechnicalService.cs#L25)` +- For technical method reference: `[^2]: [Advanced Technical Processing Method]({{$git_repository}}/tree/{{$branch}}/src/Technical/Processing/AdvancedProcessor.cs#L89-L156)` +- For technical configuration reference: `[^3]: [Technical Configuration Constants Definition]({{$git_repository}}/tree/{{$branch}}/src/Technical/Config/TechnicalConstants.cs#L15)` **TECHNICAL CITATION PLACEMENT:** - Add `[^n]` immediately after the technical content, before punctuation @@ -1153,7 +1070,7 @@ The framework must ensure: **TYPE-SPECIFIC CONTENT STRATEGIES:** -### 📚 Tutorial Content Strategy (Learning + Practical) +### Tutorial Content Strategy (Learning + Practical) **Core Principle**: Guarantee learning success through guided experience **Content Requirements**: - **Sequential Learning Path**: Clear, linear progression with concrete outcomes @@ -1163,7 +1080,7 @@ The framework must ensure: - **Confidence Building**: Each step builds competence and confidence - **Scope Limitation**: Focus on one learning objective at a time -### 🛠️ How-to Guide Strategy (Work + Practical) +### How-to Guide Strategy (Work + Practical) **Core Principle**: Help competent users achieve specific goals **Content Requirements**: - **Goal-Oriented Structure**: Start with clear objective, end with achievement @@ -1173,7 +1090,7 @@ The framework must ensure: - **Efficiency Priority**: Shortest path to goal achievement - **Adaptability**: Instructions work in various contexts -### 📖 Reference Content Strategy (Work + Theoretical) +### Reference Content Strategy (Work + Theoretical) **Core Principle**: Provide authoritative, factual information **Content Requirements**: - **Comprehensive Coverage**: Complete and accurate technical specifications @@ -1183,7 +1100,7 @@ The framework must ensure: - **Findable Information**: Organized for efficient information retrieval - **Behavioral Description**: What the system does, not how to use it -### 🧠 Explanation Content Strategy (Learning + Theoretical) +### Explanation Content Strategy (Learning + Theoretical) **Core Principle**: Deepen understanding through context and reasoning **Content Requirements**: - **Conceptual Clarity**: Clear explanation of underlying principles @@ -1205,56 +1122,55 @@ The framework must ensure: ### Technical Section Structure Template (REQUIRED for every major technical topic): -**1. Technical Concept Introduction (comprehensive depth without artificial limits)** -- Define the technical component/system in clear, technically precise language based on actual implementation analysis -- Explain its fundamental technical purpose and role within the larger technical system architecture as evidenced by the codebase structure -- Establish why this technical component exists and what technical problems it solves, derived from actual usage patterns and implementation context -- Analyze the conceptual innovation and technical sophistication demonstrated in the actual approach taken -- Compare with alternative conceptual approaches where evidence exists in code comments, documentation, or implementation choices -- Discuss the technical philosophy and design principles evident from the actual implementation patterns -- NO CODE REFERENCES allowed in this subsection - ALL ANALYSIS MUST BE BASED ON ACTUAL REPOSITORY CONTENT - -**2. Technical Architectural Context (extensive architectural analysis)** -- Describe how this technical component fits within the overall technical system architecture based on actual file organization and dependency analysis -- Explain its technical relationships and dependencies with other technical system components as evidenced by imports, interfaces, and actual usage -- Analyze technical design decisions and their technical architectural implications derived from actual implementation patterns -- Detail the component's position in technical data flow and system technical behavior based on observable patterns in the codebase -- Examine architectural patterns employed as evidenced by actual code structure and organization -- Analyze the component's role in maintaining system integrity, consistency, and reliability based on error handling and validation patterns found in code -- Discuss how the architectural design supports extensibility and maintainability as evidenced by actual extension points and plugin systems -- Compare the architectural approach with patterns observable in the codebase and configuration files -- NO CODE REFERENCES allowed in this subsection - ALL ANALYSIS MUST BE DERIVED FROM ACTUAL REPOSITORY EVIDENCE - -**3. Technical Behavioral Analysis (comprehensive behavioral examination)** -- Describe how the technical component behaves under different technical conditions based on actual error handling, validation logic, and conditional processing found in the code -- Explain its operational technical characteristics and performance technical implications derived from actual optimization patterns, caching strategies, and resource management code -- Analyze technical interaction patterns with other technical system components based on actual API calls, event handling, and communication patterns in the codebase -- Detail technical state management, lifecycle, and runtime technical characteristics based on actual state management code, initialization sequences, and cleanup procedures -- Examine error handling behavior and recovery mechanisms actually implemented in the codebase -- Analyze performance characteristics based on actual optimization techniques, algorithmic choices, and resource management patterns found in the code -- Discuss concurrency behavior and thread safety based on actual synchronization mechanisms and parallel processing implementations -- Evaluate monitoring and observability capabilities actually built into the component based on logging, metrics, and instrumentation code -- Assess security behavior and access control mechanisms based on actual security implementations found in the codebase -- Compare behavioral characteristics with patterns observable in similar components within the same repository -- NO CODE REFERENCES allowed in this subsection - ALL ANALYSIS MUST BE BASED ON ACTUAL IMPLEMENTATION EVIDENCE - -**4. Technical Implementation Strategy (thorough implementation analysis)** -- Explain the chosen technical implementation approach and its technical rationale based on actual design patterns and architectural choices evident in the codebase -- Describe key technical implementation patterns and technical design decisions derived from actual code organization, naming conventions, and structural patterns -- Analyze technical trade-offs evident from actual implementation choices, commented alternatives, and architectural decisions visible in the code -- Detail technical considerations that influenced the technical implementation based on configuration options, environment handling, and deployment patterns -- Examine the implementation methodology and engineering practices evident from code quality, testing patterns, and documentation found in the repository -- Analyze how the implementation strategy addresses maintainability based on actual modularization, abstraction layers, and separation of concerns -- Discuss testing strategies and quality assurance approaches based on actual test files, testing utilities, and validation mechanisms in the codebase -- Evaluate the implementation's alignment with standards based on coding conventions, dependency choices, and architectural patterns actually used -- Assess technical risk mitigation strategies based on actual error handling, fallback mechanisms, and defensive programming patterns -- Analyze operational support based on actual configuration management, deployment scripts, and monitoring implementations -- ALL ANALYSIS MUST BE GROUNDED IN ACTUAL REPOSITORY CONTENT - NO SPECULATION OR FABRICATED INFORMATION - -**5. Technical Implementation Reference (NO CODE DISPLAY)** -- Reference specific technical implementations using only citation markers [^n] pointing to actual file locations -- Focus on describing technical interface contracts, method behaviors, and technical configuration patterns through detailed technical prose based on actual implementations -- Each technical implementation reference must be accompanied by comprehensive technical logic analysis derived exclusively from actual code analysis (aim for maximum depth and insight) +**1. Engineering Context and Problem Statement** +- Start by explaining what engineering challenge this component addresses - what problem were the developers trying to solve? +- Describe the real-world scenarios and use cases that drove the need for this particular solution +- Analyze the constraints and requirements that shaped the technical approach, based on evidence from the implementation +- Explain how this component fits into the larger system architecture and why it was designed this way +- Discuss the trade-offs and design decisions that are evident from examining the codebase structure +- Set up the technical narrative by explaining what makes this implementation interesting or noteworthy from an engineering perspective +- Ground all analysis in actual code evidence - what the implementation reveals about the developers' thinking + +**2. Architectural Deep Dive and Design Patterns** +- Walk through the architectural decisions like a code reviewer, explaining what the developers built and why it makes sense +- Analyze the component's relationships and dependencies by examining how it connects to other parts of the system +- Explain the design patterns and architectural principles at play, using the actual implementation as evidence +- Discuss how the code structure reveals the developers' approach to separation of concerns, modularity, and maintainability +- Examine the data flow and control flow patterns, explaining how information moves through the system +- Analyze error handling strategies and reliability patterns that demonstrate thoughtful engineering +- Explore extensibility mechanisms and how the architecture supports future changes and enhancements +- Include strategic code examples that illustrate key architectural concepts and design decisions[^n] + +**3. Implementation Analysis and Engineering Insights** +- Examine the actual implementation like a senior developer reviewing code, highlighting interesting technical choices +- Analyze runtime behavior and performance characteristics based on the algorithms and data structures used +- Explain state management and lifecycle patterns, showing how the component handles different operational scenarios +- Discuss error handling and edge case management, revealing the robustness of the implementation +- Explore concurrency and threading patterns, explaining how the code handles parallel operations and resource contention +- Analyze optimization techniques and performance considerations evident in the implementation +- Examine security and validation mechanisms, showing how the code protects against common vulnerabilities +- Include concrete code examples that demonstrate key implementation patterns and technical decisions[^n] +- Discuss monitoring, logging, and debugging features that show operational maturity + +**4. Developer Experience and Practical Usage** +- Analyze the implementation from a user's perspective - how easy is it to understand, use, and extend? +- Examine the API design and developer interface, highlighting thoughtful design choices +- Discuss configuration and customization options, showing how the system adapts to different use cases +- Explore testing strategies and quality assurance patterns that ensure reliability +- Analyze deployment and operational considerations that affect real-world usage +- Show practical examples of how developers would interact with this component in typical scenarios[^n] +- Discuss common gotchas, edge cases, and troubleshooting approaches based on the implementation +- Examine documentation patterns and developer guidance built into the code +- Analyze maintainability aspects - how the code is organized for long-term evolution and team collaboration + +**5. Key Code Examples and Technical Insights** +- Present the most important and illustrative code snippets that reveal the engineering approach[^n] +- Explain each code example in detail, walking through the logic and design decisions +- Highlight clever implementations, performance optimizations, or elegant solutions +- Show how different pieces of code work together to solve the overall problem +- Include configuration examples and usage patterns that demonstrate practical application[^n] +- Discuss code quality aspects - readability, maintainability, and adherence to best practices +- Point out any innovative or unusual approaches that other developers might find interesting **6. Performance and Optimization Analysis (comprehensive performance examination)** - Analyze actual performance characteristics and optimization strategies implemented in the codebase[^n] @@ -1288,13 +1204,13 @@ The framework must ensure: - Assess technical advancement based on actual technology choices, implementation techniques, and architectural innovations[^n] - ALL INNOVATION ANALYSIS MUST BE BASED ON ACTUAL IMPLEMENTATION EVIDENCE - NO SPECULATION -**CAREFULLY MANAGED TECHNICAL CONTENT PATTERNS:** -- **LIMITED CODE EXAMPLES**: Include only essential code examples for critical usage patterns, API interfaces, and key configuration examples -- **CONCEPTUAL FOUNDATION FIRST**: Always establish conceptual understanding before presenting implementation details -- **CONTEXTUAL CODE PRESENTATION**: Every code example must be accompanied by comprehensive explanation of its purpose, usage, and architectural significance -- **STRATEGIC CODE SELECTION**: Focus on code examples that demonstrate key usage patterns rather than implementation details -- **BALANCED PRESENTATION**: Maintain 90% descriptive analysis, 10% strategic code examples ratio -- **ESSENTIAL CONFIGURATION EXAMPLES**: Include critical configuration patterns that users need for successful implementation +**ENGINEERING BLOG CONTENT PATTERNS:** +- **Strategic Code Illustration**: Include code examples that best illustrate engineering decisions, interesting patterns, and key architectural concepts +- **Story-Driven Technical Exploration**: Lead with the engineering narrative and problem context before diving into implementation details +- **Meaningful Code Context**: Every code snippet should advance the technical story and reveal insights about the engineering approach +- **Developer-Focused Examples**: Choose code examples that demonstrate practical usage, clever solutions, or architectural patterns that other developers can learn from +- **Balanced Technical Communication**: Maintain engaging prose (70-80%) with well-chosen code examples (20-30%) that support the technical narrative +- **Practical Application Focus**: Include configuration examples and usage patterns that show how the technology works in real scenarios ## Technical Final Output Validation @@ -1308,38 +1224,38 @@ Final validation must confirm: **TECHNICAL PRE-DELIVERY CHECKLIST:** -1. **🔍 Repository Analysis Completion**: Verify thorough repository analysis was conducted using tags based on documentation_objective requirements -2. **📋 Complete Content Generation**: Confirm ALL documentation sections are COMPLETE and COMPREHENSIVE with required word counts -3. **📦 Blog Format Compliance**: Verify ALL final content is properly wrapped in tags with complete, detailed documentation -4. **📝 Strategic Code Balance Verification**: Confirm appropriate balance of 90% conceptual analysis and 10% essential code examples for critical usage patterns -5. **📚 Citation and Code Integration**: Verify all technical references use proper [^n] citations with strategically selected code examples properly contextualized -6. **🏗️ Technical Logic Analysis Depth**: Confirm comprehensive analysis of core technical processes, decision-making logic, and technical excellence -7. **📊 Technical Problem-Solution Mapping**: Verify clear explanation of what technical problems are solved and how technically -8. **💼 Technical Excellence Documentation**: Ensure thorough documentation of practical technical impact and real-world technical value delivery -9. **🔍 Technical Implementation Reasoning Analysis**: Confirm detailed explanation of WHY certain technical approaches were chosen and their technical implications -10. **📈 Technical Process Coverage**: Verify all major technical workflows and decision points are analyzed and explained -11. **🎯 Core Technical Logic Focus**: Ensure focus on actual technical implementation logic rather than peripheral technical details -12. **📝 Technical Citation Accuracy**: Validate all footnote references point to correct files and line numbers within the provided code files -13. **🔗 Technical Citation Completeness**: Ensure every technical logic claim and implementation description includes appropriate [^n] citations -14. **📋 Technical Mermaid Diagrams**: Confirm minimum 6-8 comprehensive Mermaid diagrams focusing on technical processes and technical excellence -15. **✅ Technical Understanding Assessment**: Confirm documentation enables informed technical and implementation decisions based on actual technical code analysis -16. **🎯 Documentation Objective Alignment**: Verify all content directly addresses and fulfills the specified documentation_objective requirements +1. Repository Analysis Completion**: Verify thorough repository analysis was conducted using tags based on documentation_objective requirements +2. Complete Content Generation**: Confirm ALL documentation sections are COMPLETE and COMPREHENSIVE with required word counts +3. Blog Format Compliance**: Verify ALL final content is properly wrapped in tags with complete, detailed documentation +4. Strategic Code Balance Verification**: Confirm appropriate balance of 90% conceptual analysis and 10% essential code examples for critical usage patterns +5. Citation and Code Integration**: Verify all technical references use proper [^n] citations with strategically selected code examples properly contextualized +6. ️ Technical Logic Analysis Depth**: Confirm comprehensive analysis of core technical processes, decision-making logic, and technical excellence +7. Technical Problem-Solution Mapping**: Verify clear explanation of what technical problems are solved and how technically +8. Technical Excellence Documentation**: Ensure thorough documentation of practical technical impact and real-world technical value delivery +9. Technical Implementation Reasoning Analysis**: Confirm detailed explanation of WHY certain technical approaches were chosen and their technical implications +10. Technical Process Coverage**: Verify all major technical workflows and decision points are analyzed and explained +11. Core Technical Logic Focus**: Ensure focus on actual technical implementation logic rather than peripheral technical details +12. Technical Citation Accuracy**: Validate all footnote references point to correct files and line numbers within the provided code files +13. Technical Citation Completeness**: Ensure every technical logic claim and implementation description includes appropriate [^n] citations +14. Technical Mermaid Diagrams**: Confirm minimum 6-8 comprehensive Mermaid diagrams focusing on technical processes and technical excellence +15. Technical Understanding Assessment**: Confirm documentation enables informed technical and implementation decisions based on actual technical code analysis +16. Documentation Objective Alignment**: Verify all content directly addresses and fulfills the specified documentation_objective requirements ## Professional Technical Documentation Standards -**TECHNICAL AUTHORITY REQUIREMENTS:** -Create technical documentation that demonstrates comprehensive technical understanding through: -- Extensive technical production experience and practical technical implementation knowledge -- Thorough understanding of technical edge cases and potential technical implementation challenges -- Complete mastery of the technical technology stack and its practical technical applications -- Expert technical judgment regarding appropriate technical usage patterns and implementation strategies +**ENGINEERING BLOG AUTHORITY REQUIREMENTS:** +Write technical content that demonstrates the perspective of a senior engineer who has thoroughly investigated the codebase: +- Deep practical understanding of the implementation patterns and architectural decisions evident in the code +- Insight into the engineering challenges and how the implementation addresses them +- Comprehensive knowledge of the technology stack and its practical applications as used in this project +- Expert analysis of the trade-offs, optimizations, and design patterns that make this implementation noteworthy -**TECHNICAL-CENTERED DOCUMENTATION PRINCIPLES:** -- **Proactive Technical Information Delivery**: Anticipate common technical questions and provide comprehensive technical answers within the documentation flow -- **Technical Risk Assessment Integration**: Identify potential technical implementation challenges and provide appropriate technical guidance and warnings -- **Technical Complexity Management**: Present complex technical concepts through structured, progressive technical explanation that builds technical understanding systematically -- **Technical Validation**: Include thorough explanations of technical implementation rationale and technical decision-making processes -- **Technical Error Prevention and Recovery**: Provide comprehensive technical guidance for avoiding common technical issues and resolving technical implementation challenges +**ENGINEERING BLOG WRITING PRINCIPLES:** +- **Developer-Centric Insights**: Anticipate what fellow developers would find interesting and valuable about this implementation +- **Engineering Challenges and Solutions**: Highlight the technical problems being solved and explain how the implementation addresses them elegantly +- **Accessible Technical Depth**: Present complex engineering concepts through engaging storytelling that builds understanding naturally +- **Implementation Wisdom**: Explain the reasoning behind architectural decisions and design patterns, revealing the engineering thought process +- **Practical Engineering Guidance**: Share insights about best practices, potential pitfalls, and lessons that other developers can apply to their own work **TECHNICAL DOCUMENTATION EXCELLENCE MANDATE**: @@ -1348,40 +1264,39 @@ Create technical documentation that demonstrates comprehensive technical underst 2. **STEP 2**: Generate COMPLETE, COMPREHENSIVE documentation covering all technical aspects 3. **STEP 3**: Wrap ALL final content in `` tags with detailed, complete documentation -Generate documentation that serves as a comprehensive, authoritative technical resource enabling effective technical technology adoption and implementation. Create educational technical content that facilitates complete technical understanding and supports successful technical project development. Maintain focus on technical logic analysis, practical technical utility, and comprehensive technical coverage throughout all documentation content. +Generate compelling engineering blog content that reads like an experienced developer's deep exploration of an interesting codebase. Create technical storytelling that reveals the engineering insights, architectural decisions, and implementation wisdom that other developers would find valuable and inspiring. Focus on the human story behind the code - the problems being solved, the clever solutions employed, and the engineering craftsmanship that makes this project worth understanding and learning from. -**FINAL OUTPUT REQUIREMENT**: The final result MUST be COMPLETE documentation content wrapped in `` tags, written in Chinese, following the identified Diátaxis type, with minimum 3 contextual Mermaid diagrams, proper citations, and professional formatting. +**FINAL OUTPUT REQUIREMENT**: The final result MUST be COMPLETE documentation content wrapped in `` tags, written in {{$language}}, following the identified Diátaxis type, with minimum 3 contextual Mermaid diagrams, proper citations, and professional formatting. **CRITICAL OUTPUT FORMAT**: - ALL final content MUST be wrapped in `` tags - NO content should appear outside these tags in the final response - The `` opening tag should be on its own line - The `` closing tag should be on its own line -- Content inside should be properly formatted Chinese documentation +- Content inside should be properly formatted {{$language}} documentation - `` tags and their content will be automatically removed from final output - Use `` tags only for analysis and planning, never for content meant to be visible --- -# 🎯 DIÁTAXIS QUALITY ASSURANCE SUMMARY +# DIÁTAXIS QUALITY ASSURANCE SUMMARY ## Final Validation Checklist **Essential Diátaxis Compliance:** -1. ✅ **Correct Type Application**: Content follows the identified Diátaxis type (Tutorial/How-to/Reference/Explanation) -2. 👥 **User Context Consistency**: All content serves the specific user needs of the chosen type -3. 📋 **Template Adherence**: Structure and language match Diátaxis type requirements -4. 🎯 **Type Purity**: No mixing of different documentation types within content +1. **Correct Type Application**: Content follows the identified Diátaxis type (Tutorial/How-to/Reference/Explanation) +2. **User Context Consistency**: All content serves the specific user needs of the chosen type +4. **Type Purity**: No mixing of different documentation types within content **Content Quality Standards:** -5. 📊 **Contextual Diagrams**: Minimum 3 Mermaid diagrams appropriate for documentation type -6. 📚 **Systematic Citations**: [^n] references for all technical claims -7. 🔍 **Repository Grounding**: Content based on actual code analysis -8. 📦 **Proper Formatting**: Chinese content wrapped in `` tags +5. **Contextual Diagrams**: Minimum 3 Mermaid diagrams appropriate for documentation type +6. **Systematic Citations**: [^n] references for all technical claims +7. **Repository Grounding**: Content based on actual code analysis +8. **Proper Formatting**: {{$language}} content wrapped in `` tags This Diátaxis-optimized approach ensures documentation truly serves user intent and provides maximum value within the specific user context. -## 🎯 ENHANCED TECHNICAL SUCCESS METRICS +## ENHANCED TECHNICAL SUCCESS METRICS **Your technical documentation will be evaluated on:** **PRIMARY QUALITY INDICATORS (CRITICAL):** diff --git a/src/KoalaWiki/Services/AuthService.cs b/src/KoalaWiki/Services/AuthService.cs index 0d468582..055c301f 100644 --- a/src/KoalaWiki/Services/AuthService.cs +++ b/src/KoalaWiki/Services/AuthService.cs @@ -843,12 +843,17 @@ public async Task GetAuthDebugInfoAsync() /// cookie选项 private CookieOptions CreateCookieOptions(int expireMinutes) { + var isHttps = httpContextAccessor.HttpContext?.Request.IsHttps ?? false; + var isDevelopment = configuration.GetValue("ASPNETCORE_ENVIRONMENT") == "Development"; + return new CookieOptions { HttpOnly = true, - Secure = false, // 开发环境或HTTP时不要求HTTPS - SameSite = SameSiteMode.Lax, // 开发环境使用更宽松的策略 - Expires = DateTime.UtcNow.AddMinutes(expireMinutes) + Secure = isHttps, // 在HTTPS环境下设置为true + SameSite = isDevelopment ? SameSiteMode.Lax : SameSiteMode.Strict, + Expires = DateTime.UtcNow.AddMinutes(expireMinutes), + Path = "/", // 确保cookie在整个站点有效 + Domain = null // 让浏览器自动设置域名 }; } } diff --git a/src/KoalaWiki/Services/DocumentCatalogService.cs b/src/KoalaWiki/Services/DocumentCatalogService.cs index 179620e8..cb93d310 100644 --- a/src/KoalaWiki/Services/DocumentCatalogService.cs +++ b/src/KoalaWiki/Services/DocumentCatalogService.cs @@ -97,14 +97,14 @@ public async Task GetDocumentByIdAsync(string owner, string name, string? branch string path, string? languageCode, HttpContext httpContext) { // 先根据仓库名称和组织名称找到仓库 - var query = await dbAccess.Warehouses + var warehouse = await dbAccess.Warehouses .AsNoTracking() .Where(x => x.Name == name && x.OrganizationName == owner && (string.IsNullOrEmpty(branch) || x.Branch == branch) && (x.Status == WarehouseStatus.Completed || x.Status == WarehouseStatus.Processing)) .FirstOrDefaultAsync(); - if (query == null) + if (warehouse == null) { throw new NotFoundException($"仓库不存在,请检查仓库名称和组织名称:{owner} {name}"); } @@ -112,10 +112,15 @@ public async Task GetDocumentByIdAsync(string owner, string name, string? branch // 找到catalog var id = await dbAccess.DocumentCatalogs .AsNoTracking() - .Where(x => x.WarehouseId == query.Id && x.Url == path && x.IsDeleted == false) + .Where(x => x.WarehouseId == warehouse.Id && x.Url == path && x.IsDeleted == false) .Select(x => x.Id) .FirstOrDefaultAsync(); + var document = await dbAccess.Documents + .AsNoTracking() + .Where(x => x.WarehouseId.ToLower() == warehouse.Id.ToLower()) + .FirstOrDefaultAsync(); + var item = await dbAccess.DocumentFileItems .AsNoTracking() .Where(x => x.DocumentCatalogId == id) @@ -136,21 +141,50 @@ public async Task GetDocumentByIdAsync(string owner, string name, string? branch var localizedContent = GetLocalizedContent(item, languageCode); var localizedDescription = GetLocalizedFileDescription(item, languageCode); + // 处理fileSource中地址可能是绝对路径 + foreach (var source in fileSource) + { + source.Name = source.Name.Replace(document?.GitPath, string.Empty); + source.Address = source.Address.Replace(document?.GitPath, string.Empty); + } + //md await httpContext.Response.WriteAsJsonAsync(new { content = localizedContent, title = localizedTitle, description = localizedDescription, - fileSource, - address = query?.Address.Replace(".git", string.Empty), - query?.Branch, + fileSource = fileSource.Select(x => ToFileSource(x, warehouse)), + address = warehouse?.Address.Replace(".git", string.Empty), + warehouse?.Branch, lastUpdate = item.CreatedAt, documentCatalogId = id, currentLanguage = languageCode ?? "zh-CN" }); } + private object ToFileSource(DocumentFileItemSource fileItemSource, Warehouse? warehouse) + { + var url = string.Empty; + + if (warehouse.Address.StartsWith("https://github.com/") || warehouse.Address.StartsWith("https://gitee.com/")) + { + url = warehouse.Address.TrimEnd('/') + $"/tree/{warehouse.Branch}/" + fileItemSource.Address; + } + + var name = Path.GetFileName(fileItemSource.Address); + + return new + { + name = name.TrimStart('/').TrimStart('\\'), + Address = fileItemSource.Address.TrimStart('/').TrimStart('\\'), + fileItemSource.CreatedAt, + url, + fileItemSource.Id, + fileItemSource.DocumentFileItemId, + }; + } + /// /// 更新目录信息 /// diff --git a/src/KoalaWiki/Services/WarehouseService.cs b/src/KoalaWiki/Services/WarehouseService.cs index 22961bdd..31181e84 100644 --- a/src/KoalaWiki/Services/WarehouseService.cs +++ b/src/KoalaWiki/Services/WarehouseService.cs @@ -1,22 +1,16 @@ using System.IO.Compression; using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; using System.Web; using FastService; -using KoalaWiki.Domains; +using KoalaWiki.Core; using KoalaWiki.Domains.DocumentFile; -using KoalaWiki.Domains.Warehouse; using KoalaWiki.Dto; using KoalaWiki.Functions; using LibGit2Sharp; using MapsterMapper; -using Microsoft.EntityFrameworkCore; -using System.Text.Json; -using KoalaWiki.Core.DataAccess; -using KoalaWiki.Git; -using KoalaWiki.Infrastructure; using Microsoft.AspNetCore.Authorization; -using System.Security.Claims; -using KoalaWiki.Core; namespace KoalaWiki.Services; @@ -558,11 +552,15 @@ public async Task SubmitWarehouseAsync(WarehouseInput input, HttpContext context { var branch = await koala.Warehouses .AsNoTracking() - .Where(x => x.Branch == input.Branch && x.OrganizationName == decodedOrganization && - x.Name == decodedRepositoryName) + .Where(x => x.Branch.ToLower() == input.Branch.ToLower() && + x.OrganizationName.ToLower() == decodedOrganization.ToLower() && + x.Name.ToLower() == decodedRepositoryName.ToLower()) .FirstOrDefaultAsync(); - if (branch is { Status: WarehouseStatus.Completed or WarehouseStatus.Processing }) + if (branch is + { + Status: WarehouseStatus.Completed or WarehouseStatus.Processing or WarehouseStatus.Pending + }) { throw new Exception("该分支已经存在"); } @@ -702,64 +700,6 @@ await context.Response.WriteAsJsonAsync(new } } - /// - /// 获取仓库概述 - /// - [EndpointSummary("获取仓库概述")] - public async Task GetWarehouseOverviewAsync(string owner, string name, string? branch, HttpContext context) - { - owner = owner.Trim().ToLower(); - name = name.Trim().ToLower(); - - var warehouse = await koala.Warehouses - .AsNoTracking() - .Where(x => x.Name.ToLower() == name && x.OrganizationName.ToLower() == owner && - (string.IsNullOrEmpty(branch) || x.Branch == branch) && - (x.Status == WarehouseStatus.Completed || x.Status == WarehouseStatus.Processing)) - .FirstOrDefaultAsync(); - - // 如果没有找到仓库,返回空列表 - if (warehouse == null) - { - throw new NotFoundException($"仓库不存在,请检查仓库名称和组织名称:{owner} {name} {branch}"); - } - - // 检查用户权限 - if (!await CheckWarehouseAccessAsync(warehouse.Id)) - { - context.Response.StatusCode = 403; - await context.Response.WriteAsJsonAsync(new - { - code = 403, - message = "您没有权限访问此仓库" - }); - return; - } - - var document = await koala.Documents - .AsNoTracking() - .Where(x => x.WarehouseId == warehouse.Id) - .FirstOrDefaultAsync(); - - if (document == null) - { - throw new NotFoundException("没有找到文档, 可能在生成中或者已经出现错误"); - } - - var overview = await koala.DocumentOverviews.FirstOrDefaultAsync(x => x.DocumentId == document.Id); - - if (overview == null) - { - throw new NotFoundException("没有找到概述"); - } - - await context.Response.WriteAsJsonAsync(new - { - content = overview.Content, - title = overview.Title - }); - } - /// /// 获取知识图谱 @@ -801,7 +741,8 @@ public async Task> GetMiniMapAsync( { address += "/tree/" + warehouse.Branch + "/"; } - else if (address.Contains("gitlab.com") || System.Text.RegularExpressions.Regex.IsMatch(address, @"^gitlab\.[\w-]+\.(com|cn|net|org)", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) + else if (address.Contains("gitlab.com") || Regex.IsMatch(address, + @"^gitlab\.[\w-]+\.(com|cn|net|org)", RegexOptions.IgnoreCase)) { address += "/-/tree/" + warehouse.Branch + "/"; } @@ -960,7 +901,7 @@ public async Task> GetWarehouseListAsync(int page, int pag foreach (var warehouseEntity in list) { var repository = dto.First(x => x.Id == warehouseEntity.Id); - + // Check if we have stored fork/star counts (non-zero values indicate we have data) if (warehouseEntity.Stars > 0 || warehouseEntity.Forks > 0) { @@ -1048,7 +989,7 @@ public async Task> GetFileContent(string warehouseId, string p throw new NotFoundException("文件不存在"); } - var fileFunction = new FileFunction(query.GitPath); + var fileFunction = new FileFunction(query.GitPath, null); var result = await fileFunction.ReadFileAsync(path); @@ -1108,17 +1049,6 @@ await context.Response.WriteAsJsonAsync(new using var memoryStream = new MemoryStream(); using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { - // 添加仓库概述文件 - var overview = await koala.DocumentOverviews - .FirstOrDefaultAsync(x => x.DocumentId == documents.Id); - - if (overview != null) - { - var readmeEntry = archive.CreateEntry("README.md"); - await using var writer = new StreamWriter(readmeEntry.Open()); - await writer.WriteAsync($"# 概述\n\n{overview.Content}"); - } - // 构建目录树结构 var catalogDict = documentCatalogs.ToDictionary(x => x.Id); var rootCatalogs = documentCatalogs.Where(x => string.IsNullOrEmpty(x.ParentId)).ToList(); @@ -1149,8 +1079,8 @@ async Task ProcessCatalogs(ZipArchive archive, List catalogs, // 创建并写入文档内容 var entry = archive.CreateEntry(entryPath.Replace('\\', '/')); - using var writer = new StreamWriter(entry.Open()); - writer.Write($"# {catalog.Name}\n\n{item.Content}"); + await using var writer = new StreamWriter(entry.Open()); + await writer.WriteAsync($"# {catalog.Name}\n\n{item.Content}"); await writer.DisposeAsync(); @@ -1210,7 +1140,7 @@ public async Task> GetFileContentLineAsync(string organization throw new Exception("Document not found"); } - var fileFunction = new FileFunction(document.GitPath); + var fileFunction = new FileFunction(document.GitPath, null); var value = await fileFunction.ReadFileAsync(filePath); diff --git a/web/.env.local b/web/.env.local deleted file mode 100644 index e438ceb8..00000000 --- a/web/.env.local +++ /dev/null @@ -1,10 +0,0 @@ -# React 开发工具编辑器集成配置 -REACT_EDITOR=code - -# 其他编辑器选项(根据需要取消注释): -# REACT_EDITOR=code-insiders -# REACT_EDITOR=cursor -# REACT_EDITOR=webstorm -# REACT_EDITOR=subl -# REACT_EDITOR=atom -# REACT_EDITOR=vim diff --git a/web/app/[owner]/[name]/[path]/FileDependencies.tsx b/web/app/[owner]/[name]/[path]/FileDependencies.tsx index 8e4485d7..e988a89a 100644 --- a/web/app/[owner]/[name]/[path]/FileDependencies.tsx +++ b/web/app/[owner]/[name]/[path]/FileDependencies.tsx @@ -1,10 +1,20 @@ 'use client'; import { useState } from 'react'; +import Link from 'next/link'; +import { Github, ChevronDown } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; +import { Badge } from '@/components/ui/badge'; +import { useTheme } from 'next-themes'; +import { ThemeProvider } from '@lobehub/ui'; interface FileSource { id: string; name: string; + url: string; + address: string; } interface FileDependenciesProps { @@ -12,55 +22,48 @@ interface FileDependenciesProps { } export default function FileDependencies({ files }: FileDependenciesProps) { - const [isExpanded, setIsExpanded] = useState(false); + const [isOpen, setIsOpen] = useState(true); + const { resolvedTheme } = useTheme(); return ( -
- - - {isExpanded && ( -
-
-
+ + + + +
+ + 文档依赖文件 + + {files.length} + +
+
+
+ + +
{files.map((file) => ( -
- {file.name} -
+ +
+ + {file.address} +
+ ))}
-
-
- )} -
+ + + + ); -} \ No newline at end of file +} \ No newline at end of file diff --git a/web/app/[owner]/[name]/[path]/page.tsx b/web/app/[owner]/[name]/[path]/page.tsx index 6d45c4d4..447a2472 100644 --- a/web/app/[owner]/[name]/[path]/page.tsx +++ b/web/app/[owner]/[name]/[path]/page.tsx @@ -247,7 +247,6 @@ export default async function DocumentPage({ try { const response = await documentById(owner, name, path, branch, lang); - console.log('response', response.data); if (response.isSuccess && response.data) { document = response.data as DocumentData; diff --git a/web/app/[owner]/[name]/[path]/types.ts b/web/app/[owner]/[name]/[path]/types.ts index fc41183d..56a37af6 100644 --- a/web/app/[owner]/[name]/[path]/types.ts +++ b/web/app/[owner]/[name]/[path]/types.ts @@ -4,7 +4,7 @@ export interface DocumentData { title: string; content: string; description?: string; - fileSource?: SourceFile[]; + fileSource?: any[]; branch: string; address: string; createdAt?: string; @@ -12,16 +12,6 @@ export interface DocumentData { lastUpdate?: any; } -// 文件源类型 - 匹配SourceFiles组件的接口 -export interface SourceFile { - documentFileItemId: string; - address: string; - name: string; - documentFileItem: any; - id: string; - createdAt: string; -} - // 标题类型 export interface Heading { key: string; diff --git a/web/app/admin/layout.tsx b/web/app/admin/layout.tsx index 788f8c8a..eaf07f3f 100644 --- a/web/app/admin/layout.tsx +++ b/web/app/admin/layout.tsx @@ -139,12 +139,10 @@ export default function AdminLayout({ if (userRole === 'admin') { return allItems; } else { - // 普通用户显示:数据统计、仓库管理、数据微调、系统设置 + // 普通用户显示:仓库管理、数据微调 return [ - allItems[0], // 数据统计 allItems[2], // 仓库管理 allItems[3], // 数据微调 - allItems[5], // 系统设置 ]; } }; @@ -187,9 +185,19 @@ export default function AdminLayout({ try { const userInfo = JSON.parse(userInfoStr); if (userInfo.role) { - setUserRole(userInfo.role); + // 检查是否包含 admin 角色(支持多角色,如 "admin,user") + const roles = userInfo.role.split(',').map((r: string) => r.trim()); + if (roles.includes('admin')) { + setUserRole('admin'); + } else { + setUserRole('user'); + // 普通用户重定向逻辑 + redirectUserIfNeeded('user'); + } } else { setUserRole('user'); + // 普通用户重定向逻辑 + redirectUserIfNeeded('user'); } } catch (error) { console.error('解析用户信息失败:', error); @@ -205,9 +213,15 @@ export default function AdminLayout({ checkLoginStatus(); }, [router, pathname]); + // 监听用户角色变化,进行权限检查 + useEffect(() => { + if (!isLoading && isLoggedIn && userRole) { + redirectUserIfNeeded(userRole); + } + }, [userRole, pathname, isLoading, isLoggedIn]); + // 处理登出 const handleLogout = () => { - console.log('用户退出登录'); localStorage.removeItem('userToken'); localStorage.removeItem('userName'); localStorage.removeItem('userInfo'); @@ -220,6 +234,30 @@ export default function AdminLayout({ router.push('/login'); }; + // 检查普通用户是否需要重定向 + const redirectUserIfNeeded = (role: string) => { + if (role === 'user') { + // 普通用户无权访问的页面列表 + const restrictedPaths = [ + '/admin', // 数据统计 + '/admin/users', // 用户管理 + '/admin/roles', // 角色管理 + '/admin/permissions', // 权限管理 + '/admin/settings' // 系统设置 + ]; + + // 检查当前路径是否是受限制的 + const isRestrictedPath = restrictedPaths.some(path => + pathname === path || pathname.startsWith(path + '/') + ); + + if (isRestrictedPath) { + // 重定向到仓库管理页面 + router.push('/admin/repositories'); + } + } + }; + // 处理菜单点击 const handleMenuClick = (url: string) => { router.push(url); diff --git a/web/app/admin/permissions/roles/page.tsx b/web/app/admin/permissions/roles/page.tsx index cbf9a69c..9f752b3e 100644 --- a/web/app/admin/permissions/roles/page.tsx +++ b/web/app/admin/permissions/roles/page.tsx @@ -20,6 +20,7 @@ import { Checkbox } from '@/components/ui/checkbox'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; import { useToast } from '@/components/ui/use-toast'; +import { Input } from '@/components/ui/input'; import { Database, Folder, @@ -27,6 +28,7 @@ import { RefreshCw, ChevronRight, ChevronDown, + Search, } from 'lucide-react'; import { roleService, Role } from '../../../services/roleService'; import { @@ -55,16 +57,26 @@ interface NodePermissions { }; } +// 虚拟滚动相关常量 +const ITEM_HEIGHT = 40; // 每个节点的高度 +const CONTAINER_HEIGHT = 500; // 容器高度 +const VISIBLE_ITEMS = Math.ceil(CONTAINER_HEIGHT / ITEM_HEIGHT) + 2; // 可见项目数 + 缓冲 + const RolePermissionsPage: React.FC = () => { const { toast } = useToast(); const [roles, setRoles] = useState([]); const [selectedRoleId, setSelectedRoleId] = useState(''); const [permissionTree, setPermissionTree] = useState([]); + const [filteredTree, setFilteredTree] = useState([]); + const [flattenedNodes, setFlattenedNodes] = useState<(PermissionNode & { level: number })[]>([]); const [checkedKeys, setCheckedKeys] = useState([]); const [nodePermissions, setNodePermissions] = useState({}); const [expandedKeys, setExpandedKeys] = useState([]); const [loading, setLoading] = useState(false); const [saving, setSaving] = useState(false); + const [searchValue, setSearchValue] = useState(''); + const [scrollTop, setScrollTop] = useState(0); + const [useVirtualScrolling, setUseVirtualScrolling] = useState(false); // 加载角色列表 const loadRoles = async () => { @@ -85,8 +97,21 @@ const RolePermissionsPage: React.FC = () => { const treeData = convertToTreeData(tree); setPermissionTree(treeData); - // 设置已选中的节点 - const selected = tree.filter(node => isNodeSelected(node)).map(node => node.id); + // 递归收集所有已选中的节点 + const collectSelectedNodes = (nodes: WarehousePermissionTree[]): string[] => { + const selected: string[] = []; + nodes.forEach(node => { + if (node.isSelected) { + selected.push(node.id); + } + if (node.children && node.children.length > 0) { + selected.push(...collectSelectedNodes(node.children)); + } + }); + return selected; + }; + + const selected = collectSelectedNodes(tree); setCheckedKeys(selected); // 设置节点权限 @@ -121,10 +146,71 @@ const RolePermissionsPage: React.FC = () => { } }; - // 递归检查节点是否被选中 - const isNodeSelected = (node: WarehousePermissionTree): boolean => { - if (node.isSelected) return true; - return node.children.some(child => isNodeSelected(child)); + // 将树结构展开为平面列表(用于虚拟滚动) + const flattenTree = (nodes: PermissionNode[], level: number = 0): (PermissionNode & { level: number })[] => { + const flattened: (PermissionNode & { level: number })[] = []; + + nodes.forEach(node => { + flattened.push({ ...node, level }); + + if (node.children && expandedKeys.includes(node.key)) { + flattened.push(...flattenTree(node.children, level + 1)); + } + }); + + return flattened; + }; + + // 搜索过滤树节点 + const filterTree = (nodes: PermissionNode[], searchText: string): PermissionNode[] => { + if (!searchText.trim()) return nodes; + + const filtered: PermissionNode[] = []; + + const searchInNode = (node: PermissionNode): PermissionNode | null => { + const matchesSearch = node.title.toLowerCase().includes(searchText.toLowerCase()); + const filteredChildren = node.children ? node.children.map(child => searchInNode(child)).filter(Boolean) as PermissionNode[] : []; + + if (matchesSearch || filteredChildren.length > 0) { + return { + ...node, + children: filteredChildren, + }; + } + + return null; + }; + + nodes.forEach(node => { + const result = searchInNode(node); + if (result) { + filtered.push(result); + } + }); + + return filtered; + }; + + // 处理搜索输入 + const handleSearch = (value: string) => { + setSearchValue(value); + const filtered = filterTree(permissionTree, value); + setFilteredTree(filtered); + + // 搜索时自动展开所有匹配的节点 + if (value.trim()) { + const expandedKeys = new Set(); + const collectExpandedKeys = (nodes: PermissionNode[]) => { + nodes.forEach(node => { + if (node.children && node.children.length > 0) { + expandedKeys.add(node.key); + collectExpandedKeys(node.children); + } + }); + }; + collectExpandedKeys(filtered); + setExpandedKeys(Array.from(expandedKeys)); + } }; // 转换权限树数据格式 @@ -152,13 +238,33 @@ const RolePermissionsPage: React.FC = () => { // 切换节点选中状态 const toggleChecked = (nodeKey: string) => { setCheckedKeys(prev => { - const newCheckedKeys = prev.includes(nodeKey) - ? prev.filter(key => key !== nodeKey) - : [...prev, nodeKey]; - - // 为新选中的仓库节点设置默认权限 - if (!prev.includes(nodeKey)) { - const node = findNodeByKey(permissionTree, nodeKey); + const isCurrentlyChecked = prev.includes(nodeKey); + let newCheckedKeys: string[]; + + if (isCurrentlyChecked) { + // 取消选中:移除该节点及其所有子节点 + const nodeToRemove = findNodeByKey(filteredTree, nodeKey); + const nodesToRemove = new Set([nodeKey]); + + if (nodeToRemove) { + const collectChildKeys = (node: PermissionNode) => { + if (node.children) { + node.children.forEach(child => { + nodesToRemove.add(child.key); + collectChildKeys(child); + }); + } + }; + collectChildKeys(nodeToRemove); + } + + newCheckedKeys = prev.filter(key => !nodesToRemove.has(key)); + } else { + // 选中:添加该节点 + newCheckedKeys = [...prev, nodeKey]; + + // 为新选中的仓库节点设置默认权限 + const node = findNodeByKey(filteredTree, nodeKey); if (node && node.type === 'warehouse' && !nodePermissions[nodeKey]) { setNodePermissions(prevPermissions => ({ ...prevPermissions, @@ -169,6 +275,35 @@ const RolePermissionsPage: React.FC = () => { } })); } + + // 如果是组织节点,自动选中所有子仓库 + if (node && node.type === 'organization' && node.children) { + const collectWarehouseKeys = (nodes: PermissionNode[]): string[] => { + const keys: string[] = []; + nodes.forEach(child => { + if (child.type === 'warehouse') { + keys.push(child.key); + // 为仓库设置默认权限 + if (!nodePermissions[child.key]) { + setNodePermissions(prevPermissions => ({ + ...prevPermissions, + [child.key]: { + isReadOnly: true, + isWrite: false, + isDelete: false, + } + })); + } + } else if (child.children) { + keys.push(...collectWarehouseKeys(child.children)); + } + }); + return keys; + }; + + const warehouseKeys = collectWarehouseKeys(node.children); + newCheckedKeys = [...newCheckedKeys, ...warehouseKeys]; + } } return newCheckedKeys; @@ -186,6 +321,11 @@ const RolePermissionsPage: React.FC = () => { })); }; + // 处理滚动事件 + const handleScroll = (e: React.UIEvent) => { + setScrollTop(e.currentTarget.scrollTop); + }; + // 渲染自定义树节点 const renderTreeNode = (node: PermissionNode, level: number = 0): React.ReactNode => { const isChecked = checkedKeys.includes(node.key); @@ -229,7 +369,7 @@ const RolePermissionsPage: React.FC = () => { {icon} {node.title} - {node.isSelected && 已授权} + {node.permission && node.isSelected && 已授权}
{node.type === 'warehouse' && isChecked && ( @@ -258,7 +398,7 @@ const RolePermissionsPage: React.FC = () => { )} - {node.type === 'warehouse' && !isChecked && node.permission && ( + {node.type === 'warehouse' && !isChecked && node.permission && node.isSelected && (
{node.permission.isReadOnly && } {node.permission.isWrite && } @@ -286,24 +426,39 @@ const RolePermissionsPage: React.FC = () => { - // 查找节点 + // 查找节点(优化版本,支持缓存) const findNodeByKey = (nodes: PermissionNode[], key: string): PermissionNode | null => { - for (const node of nodes) { - if (node.key === key) { - return node; - } - if (node.children) { - const found = findNodeByKey(node.children, key); - if (found) return found; + const search = (nodeList: PermissionNode[]): PermissionNode | null => { + for (const node of nodeList) { + if (node.key === key) { + return node; + } + if (node.children) { + const found = search(node.children); + if (found) return found; + } } - } - return null; + return null; + }; + + return search(nodes); }; // 保存权限配置 const handleSave = async () => { if (!selectedRoleId) { - toast({ description: '请先选择角色' }); + toast({ description: '请先选择角色', variant: 'destructive' }); + return; + } + + // 验证是否有选中的仓库 + const warehouseCount = checkedKeys.filter(key => { + const node = findNodeByKey(permissionTree, key); + return node && node.type === 'warehouse'; + }).length; + + if (warehouseCount === 0) { + toast({ description: '请至少选择一个仓库', variant: 'destructive' }); return; } @@ -321,6 +476,15 @@ const RolePermissionsPage: React.FC = () => { isDelete: false, }; + // 验证权限设置的合理性 + if (!permissions.isReadOnly && !permissions.isWrite && !permissions.isDelete) { + toast({ + description: `仓库 "${node.title}" 至少需要一个权限`, + variant: 'destructive' + }); + throw new Error('权限设置不合理'); + } + warehousePermissions.push({ warehouseId: node.key, isReadOnly: permissions.isReadOnly, @@ -342,11 +506,15 @@ const RolePermissionsPage: React.FC = () => { }; await permissionService.setRolePermissions(rolePermission); - toast({ description: '保存权限配置成功' }); + toast({ description: `保存成功,共配置了 ${warehousePermissions.length} 个仓库的权限` }); // 重新加载权限树以显示最新状态 - loadPermissionTree(selectedRoleId); + await loadPermissionTree(selectedRoleId); } catch (error) { + if (error instanceof Error && error.message === '权限设置不合理') { + // 已经显示了具体错误信息 + return; + } toast({ description: '保存权限配置失败', variant: 'destructive' }); console.error('保存权限配置失败:', error); } finally { @@ -369,7 +537,7 @@ const RolePermissionsPage: React.FC = () => { loadPermissionTree(); }, []); - // 当权限树数据加载完成后,设置默认展开的节点 + // 当权限树数据加载完成后,设置默认展开的节点和过滤树 useEffect(() => { if (permissionTree.length > 0) { // 默认展开所有组织节点 @@ -387,8 +555,25 @@ const RolePermissionsPage: React.FC = () => { }; setExpandedKeys(expandAllOrganizations(permissionTree)); + // 初始化过滤树 + setFilteredTree(permissionTree); + + // 检查是否需要启用虚拟滚动(超过100个节点) + const totalNodes = flattenTree(permissionTree).length; + setUseVirtualScrolling(totalNodes > 100); } }, [permissionTree]); + + // 当搜索值或展开状态变化时,更新过滤树和平面列表 + useEffect(() => { + const filtered = filterTree(permissionTree, searchValue); + setFilteredTree(filtered); + + if (useVirtualScrolling) { + const flattened = flattenTree(filtered); + setFlattenedNodes(flattened); + } + }, [permissionTree, searchValue, expandedKeys, useVirtualScrolling]); return (
@@ -398,33 +583,46 @@ const RolePermissionsPage: React.FC = () => { 角色权限配置 先选择角色,再配置其仓库权限 - -
- 选择角色: - -
+ +
+
+ 选择角色: + +
-
- - +
+ + +
+
+ + {/* 搜索框 */} +
+ + handleSearch(e.target.value)} + className="w-full" + />
@@ -444,15 +642,62 @@ const RolePermissionsPage: React.FC = () => {
) : ( <> -
- 说明 - - 选择组织将自动选择该组织下的所有仓库。选中仓库后,可以在右侧配置具体的读、写、删除权限。 - +
+
+ 说明 + + 选择组织将自动选择该组织下的所有仓库。选中仓库后,可以在右侧配置具体的读、写、删除权限。 + +
+ {useVirtualScrolling && ( +
+ 性能优化 + 检测到大量数据,已启用虚拟滚动优化加载性能。 +
+ )} + {checkedKeys.length > 0 && ( +
+ 统计 + 已选中 {checkedKeys.filter(key => { + const node = findNodeByKey(filteredTree, key); + return node && node.type === 'warehouse'; + }).length} 个仓库 +
+ )}
-
- {permissionTree.map(node => renderTreeNode(node))} +
+ {filteredTree.length > 0 ? ( + useVirtualScrolling && flattenedNodes.length > 100 ? ( + // 虚拟滚动模式 +
+
+ {flattenedNodes + .slice( + Math.max(0, Math.floor(scrollTop / ITEM_HEIGHT) - 1), + Math.min(flattenedNodes.length, Math.floor(scrollTop / ITEM_HEIGHT) + VISIBLE_ITEMS) + ) + .map((node, index) => ( +
+ {renderTreeNode(node, node.level)} +
+ ))} +
+
+ ) : ( + // 普通模式 + filteredTree.map(node => renderTreeNode(node)) + ) + ) : ( +
+ {searchValue.trim() ? '未找到匹配的仓库或组织' : '暂无数据'} +
+ )}
)} diff --git a/web/app/admin/users/page.tsx b/web/app/admin/users/page.tsx index 57bb99ae..c2470b25 100644 --- a/web/app/admin/users/page.tsx +++ b/web/app/admin/users/page.tsx @@ -183,7 +183,7 @@ export default function UsersPage() { // 处理表单提交(创建/更新用户) const handleFormSubmit = async () => { - // 简单的表单验证 + // 表单验证 if (!formData.name || !formData.email || (!currentUser && !formData.password)) { toast({ title: "错误", @@ -192,6 +192,51 @@ export default function UsersPage() { }); return; } + + // 验证角色是否选择 + if (!formData.role) { + toast({ + title: "错误", + description: "请选择用户角色", + variant: "destructive", + }); + return; + } + + // 验证邮箱格式 + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(formData.email)) { + toast({ + title: "错误", + description: "请输入正确的邮箱地址", + variant: "destructive", + }); + return; + } + + // 检查邮箱是否已存在(除了当前编辑的用户) + const existingUser = users.find(user => + user.email.toLowerCase() === formData.email.toLowerCase() && + (!currentUser || user.id !== currentUser.id) + ); + if (existingUser) { + toast({ + title: "错误", + description: "该邮箱地址已被使用", + variant: "destructive", + }); + return; + } + + // 验证密码强度(只在创建用户或修改密码时) + if ((!currentUser || formData.password) && formData.password.length < 6) { + toast({ + title: "错误", + description: "密码长度不能少于6位", + variant: "destructive", + }); + return; + } try { if (currentUser) { @@ -207,9 +252,9 @@ export default function UsersPage() { if (response.code === 200) { toast({ title: "成功", - description: "用户更新成功", + description: `用户 "${formData.name}" 更新成功`, }); - setIsModalOpen(false); + handleModalClose(false); loadUsers(); // 重新加载用户列表 } else { toast({ @@ -224,21 +269,21 @@ export default function UsersPage() { name: formData.name, email: formData.email, password: formData.password, - role: formData.role, + role: formData.role || undefined, // 确保空值传递undefined }; - const { data } = await createUser(createData) as any; - if (data.code === 200) { + const response = await createUser(createData); + if (response.code === 200) { toast({ title: "成功", - description: "用户创建成功", + description: `用户 "${formData.name}" 创建成功,角色为 "${formData.role}"`, }); - setIsModalOpen(false); + handleModalClose(false); loadUsers(); // 重新加载用户列表 } else { toast({ title: "错误", - description: data.message || '创建用户失败', + description: response.message || '创建用户失败', variant: "destructive", }); } @@ -264,6 +309,20 @@ export default function UsersPage() { }); setIsModalOpen(true); }; + + // 关闭对话框时清空表单 + const handleModalClose = (open: boolean) => { + setIsModalOpen(open); + if (!open) { + setCurrentUser(null); + setFormData({ + name: '', + email: '', + password: '', + role: '', + }); + } + }; // 根据角色获取标签颜色和样式 const getRoleTagProps = (role: string) => { @@ -325,7 +384,7 @@ export default function UsersPage() { > 搜索 - + -
diff --git a/web/app/chat/index.tsx b/web/app/chat/index.tsx index 34ee65c5..d9f4d2cb 100644 --- a/web/app/chat/index.tsx +++ b/web/app/chat/index.tsx @@ -52,8 +52,8 @@ interface ReferenceFile { // Tailwind CSS 类名常量 const styles = { - floatingButton: "fixed bottom-6 right-6 w-12 h-12 rounded-full flex items-center justify-center shadow-lg z-[1000] transition-all duration-300 hover:scale-105 hover:shadow-xl", - chatContainer: "fixed bottom-6 right-6 w-[550px] h-[700px] bg-card rounded-lg shadow-xl z-[1001] flex flex-col overflow-hidden transition-all duration-300 border", + floatingButton: "fixed bottom-6 right-6 w-12 h-12 rounded-full flex items-center justify-center shadow-lg z-[10] transition-all duration-300 hover:scale-105 hover:shadow-xl", + chatContainer: "fixed bottom-6 right-6 w-[550px] h-[700px] bg-card rounded-lg shadow-xl z-[10] flex flex-col overflow-hidden transition-all duration-300 border", chatContainerMinimized: "h-[60px]", chatContainerMaximized: "w-[580px] h-full bottom-0 right-0", chatContainerEmbedded: "relative !bottom-auto !right-auto !w-full !h-full !rounded-none !shadow-none !border-none", diff --git a/web/app/chat/workspace/message/assistant/index.tsx b/web/app/chat/workspace/message/assistant/index.tsx index f3614e9f..42f9cfb0 100644 --- a/web/app/chat/workspace/message/assistant/index.tsx +++ b/web/app/chat/workspace/message/assistant/index.tsx @@ -5,7 +5,7 @@ import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; -import { CollapsibleCard, Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible'; +import { Collapsible, CollapsibleTrigger, CollapsibleContent, CollapsibleCard } from '@/components/ui/collapsible'; import { toast } from "sonner"; import { Markdown } from "@lobehub/ui"; import { Copy, MoreHorizontal, Trash2, FileText, Brain, Settings, ChevronDown, ChevronRight, Maximize2, ExternalLink, Calendar, User, Loader2 } from "lucide-react"; diff --git a/web/app/components/HeadingAnchors.tsx b/web/app/components/HeadingAnchors.tsx index fca91356..b1f8c2c3 100644 --- a/web/app/components/HeadingAnchors.tsx +++ b/web/app/components/HeadingAnchors.tsx @@ -13,14 +13,11 @@ export default function HeadingAnchors() { document.querySelector('article'); if (!markdownBody) { - console.log('No markdown body found'); return; } // 查找所有h1-h6标签 const headings = markdownBody.querySelectorAll('h1, h2, h3, h4, h5, h6'); - console.log('Found headings:', headings.length); - const existingSlugs = new Set(); headings.forEach(function(heading) { diff --git a/web/app/components/HomeClient.tsx b/web/app/components/HomeClient.tsx index 158a7bb9..e407fbb2 100644 --- a/web/app/components/HomeClient.tsx +++ b/web/app/components/HomeClient.tsx @@ -9,6 +9,7 @@ import { Badge } from '@/components/ui/badge'; import { Card, CardContent } from '@/components/ui/card'; import { Separator } from '@/components/ui/separator'; import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from '@/components/ui/pagination'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'; import { Toaster } from '@/components/ui/sonner'; import { toast } from 'sonner'; @@ -18,7 +19,7 @@ import LastRepoModal from './LastRepoModal'; import LanguageSwitcher from './LanguageSwitcher'; import UserAvatar from './UserAvatar'; import { Repository, RepositoryFormValues } from '../types'; -import { submitWarehouse } from '../services/warehouseService'; +import { submitWarehouse, Customsubmitwarehouse, UploadAndSubmitWarehouse } from '../services/warehouseService'; import { HomeStats } from '../services/statsService'; import { homepage } from '../const/urlconst'; import { useTranslation } from '../i18n/client'; @@ -85,6 +86,7 @@ export default function HomeClient({ const repositories = initialRepositories; const [formVisible, setFormVisible] = useState(false); const [lastRepoModalVisible, setLastRepoModalVisible] = useState(false); + const [qrCodeModalVisible, setQrCodeModalVisible] = useState(false); const [searchValue, setSearchValue] = useState(initialSearchValue); const [currentPage, setCurrentPage] = useState(initialPage); const [pageSize, setPageSize] = useState(initialPageSize); @@ -106,12 +108,45 @@ export default function HomeClient({ const handleAddRepository = async (values: RepositoryFormValues) => { try { - const response = await submitWarehouse(values); - if (response.success) { - toast.success(t('home.messages.repo_add_success')); - window.location.reload(); + let response: any; + + if (values.submitType === 'git') { + // Git仓库提交 + response = await submitWarehouse(values); + if (response.data?.code === 200) { + toast.success(t('home.messages.repo_add_success')); + window.location.reload(); + } else { + toast.error(response.data?.message || t('home.messages.repo_add_failed', { error: response.error || t('home.messages.unknown_error') })); + } + } else if (values.submitType === 'custom') { + // 自定义仓库提交 + response = await Customsubmitwarehouse(values); + if (response.data?.code === 200) { + toast.success(t('home.messages.repo_add_success')); + window.location.reload(); + } else { + toast.error(response.data?.message || t('home.messages.repo_add_failed', { error: response.error || t('home.messages.unknown_error') })); + } } else { - toast.error(t('home.messages.repo_add_failed', { error: response.error || t('home.messages.unknown_error') })); + // 压缩包上传 + const formData = new FormData(); + formData.append('organization', values.organization!); + formData.append('repositoryName', values.repositoryName!); + + if (values.uploadMethod === 'file' && values.file) { + formData.append('file', values.file); + } else if (values.uploadMethod === 'url' && values.fileUrl) { + formData.append('fileUrl', values.fileUrl); + } + + response = await UploadAndSubmitWarehouse(formData); + if (response.data?.code === 200) { + toast.success(t('home.messages.repo_add_success')); + window.location.reload(); + } else { + toast.error(response.data?.message || t('home.messages.repo_add_failed', { error: response.error || t('home.messages.unknown_error') })); + } } } catch (error) { console.error('添加仓库出错:', error); @@ -228,7 +263,7 @@ export default function HomeClient({ {searchValue ? t('home.repo_list.not_found', { keyword: searchValue }) : t('home.repo_list.empty')}

- {searchValue ? '尝试调整搜索关键词' : '开始添加您的第一个代码仓库'} + {searchValue ? t('home.repo_list.try_adjust_keywords') : t('home.repo_list.get_started')}

+ + {/* Metadata Row */} +
+ {repository.branch && ( +
+ + {repository.branch} +
+ )} +
+ + {formatDate(repository.createdAt)} +
+
diff --git a/web/app/components/RepositoryCardRedesigned.tsx b/web/app/components/RepositoryCardRedesigned.tsx new file mode 100644 index 00000000..5b7d27b0 --- /dev/null +++ b/web/app/components/RepositoryCardRedesigned.tsx @@ -0,0 +1,196 @@ +'use client' + +import React, { useMemo } from 'react'; +import { Repository } from '../types'; +import { Card, CardContent } from '@/components/ui/card'; +import { Badge } from '@/components/ui/badge'; +import { Button } from '@/components/ui/button'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { useTranslation } from '../i18n/client'; +import { formatRelativeTime } from '../utils/timeFormat'; +import { + Github, + GitFork, + Star, + ExternalLink, + FileText, + GitBranch, + Clock +} from 'lucide-react'; + +interface RepositoryCardProps { + repository: Repository; +} + +const RepositoryCard: React.FC = ({ repository }) => { + const { t, i18n } = useTranslation(); + const currentLocale = i18n.language; + + // 获取头像URL + const getAvatarUrl = () => { + if (repository?.avatarUrl) return repository.avatarUrl; + + const platformMap: Record = { + 'github.com': 'https://github.com/', + 'gitee.com': 'https://gitee.com/', + 'gitlab.com': 'https://gitlab.com/', + 'gitea.com': 'https://gitea.com/' + }; + + const platform = Object.keys(platformMap).find(p => repository.address?.includes(p)); + if (platform && repository.organizationName) { + return `${platformMap[platform]}/${repository.organizationName}.png`; + } + + return null; + }; + + const avatarUrl = useMemo(() => getAvatarUrl(), [repository.address, repository.organizationName]); + + // 获取状态配置 - 简化版本 + const getStatusConfig = (status: string | number) => { + const statusNumber = typeof status === 'number' ? status : parseInt(status, 10) || 0; + + const configs = { + 0: { variant: 'secondary' as const, text: t('repository.status.pending', '待处理') }, + 1: { variant: 'default' as const, text: t('repository.status.processing', '处理中') }, + 2: { variant: 'outline' as const, text: t('repository.status.completed', '已完成') }, + 3: { variant: 'secondary' as const, text: t('repository.status.cancelled', '已取消') }, + 4: { variant: 'secondary' as const, text: t('repository.status.unauthorized', '未授权') }, + 99: { variant: 'destructive' as const, text: t('repository.status.failed', '已失败') } + }; + + return configs[statusNumber as keyof typeof configs] || { + variant: 'outline' as const, + text: t('repository.status.unknown', '未知状态') + }; + }; + + // 获取平台图标 + const getPlatformIcon = () => { + if (repository.address?.includes('github.com')) { + return ; + } else if (repository.address?.includes('gitee.com')) { + return
+ G +
; + } + return ; + }; + + const statusConfig = getStatusConfig(repository.status); + const formattedDate = formatRelativeTime(repository.createdAt, currentLocale); + + const handleCardClick = () => { + window.location.href = `/${repository.organizationName}/${repository.name}`; + }; + + const handleExternalClick = (e: React.MouseEvent) => { + e.stopPropagation(); + window.open(repository.address, '_blank'); + }; + + return ( + + + {/* Header区域 - 头像、基本信息、状态 */} +
+
+ + + + {repository.organizationName?.slice(0, 2)?.toUpperCase() || 'UN'} + + + +
+ {/* 仓库名称 - 主要信息 */} +

+ {repository.name || t('repository.unknown_name', '未知仓库名称')} +

+ + {/* 组织名称和平台 */} +
+ {getPlatformIcon()} + {repository.organizationName} +
+
+ + {/* 状态标签 - 右上角 */} + + {statusConfig.text} + +
+
+ + {/* 内容区域 - 描述 */} +
+ {repository.description ? ( +

+ {repository.description} +

+ ) : ( +

+ {t('repository.no_description', '暂无描述')} +

+ )} +
+ + {/* Footer区域 - 统计信息和操作 */} +
+
+ {/* 左侧:统计信息 */} +
+ {/* Stars */} +
+ + {repository.stars?.toLocaleString() || 0} +
+ + {/* Forks */} +
+ + {repository.forks?.toLocaleString() || 0} +
+ + {/* 分支信息(如果存在) */} + {repository.branch && ( +
+ + {repository.branch} +
+ )} +
+ + {/* 右侧:操作按钮和时间 */} +
+ {/* 时间信息 */} +
+ + {formattedDate} +
+ + {/* 外部链接 */} + +
+
+
+
+
+ ); +}; + +export default RepositoryCard; \ No newline at end of file diff --git a/web/app/components/RepositoryForm.tsx b/web/app/components/RepositoryForm.tsx index 1a227733..8d10fd01 100644 --- a/web/app/components/RepositoryForm.tsx +++ b/web/app/components/RepositoryForm.tsx @@ -2,7 +2,7 @@ import React, { useState, } from 'react'; import { RepositoryFormValues } from '../types'; -import { submitWarehouse, UploadAndSubmitWarehouse, getBranchList, Customsubmitwarehouse } from '../services'; +import { getBranchList } from '../services'; import { useTranslation } from '../i18n/client'; import { toast } from 'sonner'; @@ -78,82 +78,40 @@ const RepositoryForm: React.FC = ({ toast.error(t('repository.form.branch_required', '请选择分支')); return; } - - const response = await submitWarehouse(formData) as any; - if (response.data.code === 200) { - toast.success(t('repository.form.success_message', '仓库添加成功')); - onSubmit(formData); - resetForm(); - } else { - toast.error(response.data.message || t('repository.form.error_message', '添加失败,请重试')); - } } else if (formData.submitType === 'custom') { // 自定义仓库提交 if (!formData.organization || !formData.repositoryName || !formData.address) { - toast.error('请填写完整的仓库信息'); + toast.error(t('repository.form.complete_repo_info', '请填写完整的仓库信息')); return; } - - const response = await Customsubmitwarehouse(formData) as any; - if (response.data.code === 200) { - toast.success(t('repository.form.success_message', '仓库添加成功')); - onSubmit(formData); - resetForm(); - } else { - toast.error(response.data.message || t('repository.form.error_message', '添加失败,请重试')); - } } else { // 压缩包上传 if (!formData.organization || !formData.repositoryName) { - toast.error('请填写完整的仓库信息'); + toast.error(t('repository.form.complete_repo_info', '请填写完整的仓库信息')); return; } if (formData.uploadMethod === 'file') { // 文件上传方式 if (!formData.file) { - toast.error('请选择要上传的压缩包文件'); + toast.error(t('repository.form.select_zip_file', '请选择要上传的压缩包文件')); return; } - - const formDataObj = new FormData(); - formDataObj.append('file', formData.file); - formDataObj.append('organization', formData.organization); - formDataObj.append('repositoryName', formData.repositoryName); - - const { data } = await UploadAndSubmitWarehouse(formDataObj) as any; - if (data && data.code === 200) { - toast.success('文件上传成功'); - onSubmit(formData); - resetForm(); - } else { - toast.error(data?.message || '文件上传失败,请重试'); - } } else { // URL下载方式 if (!formData.fileUrl) { - toast.error('请输入压缩包URL地址'); + toast.error(t('repository.form.enter_zip_url', '请输入压缩包URL地址')); return; } - - const formDataObj = new FormData(); - formDataObj.append('fileUrl', formData.fileUrl); - formDataObj.append('organization', formData.organization); - formDataObj.append('repositoryName', formData.repositoryName); - - const { data } = await UploadAndSubmitWarehouse(formDataObj) as any; - if (data && data.code === 200) { - toast.success(t('repository.form.url_download_success', '从URL下载压缩包成功')); - onSubmit(formData); - resetForm(); - } else { - toast.error(data?.message || t('repository.form.url_download_failed', '从URL下载失败,请重试')); - } } } + + // 只进行表单验证,然后调用 onSubmit 回调,让父组件处理实际的提交 + onSubmit(formData); + resetForm(); } catch (error) { - console.error('Form submission failed:', error); - toast.error('提交失败,请重试'); + console.error('Form validation failed:', error); + toast.error(t('repository.form.submit_failed_retry', '提交失败,请重试')); } finally { setLoading(false); } @@ -209,11 +167,11 @@ const RepositoryForm: React.FC = ({ toast.success(`已加载 ${response.data.length} 个分支`); } else { setBranches([]); - toast.warning('未能获取分支信息,可以手动输入分支名'); + toast.warning(t('repository.form.branch_fetch_no_info', '未能获取分支信息,可以手动输入分支名')); } } catch (error) { console.error('Failed to fetch branches:', error); - toast.error('获取分支失败'); + toast.error(t('repository.form.branch_fetch_failed', '获取分支失败')); setBranches([]); } finally { setLoadingBranches(false); @@ -428,32 +386,32 @@ const RepositoryForm: React.FC = ({ - 请填写自定义仓库的详细信息,包括组织名、仓库名、Git地址等。 + {t('repository.form.custom_repo_description', '请填写自定义仓库的详细信息,包括组织名、仓库名、Git地址等。')}
- + setFormData(prev => ({ ...prev, organization: e.target.value }))} />
- + setFormData(prev => ({ ...prev, repositoryName: e.target.value }))} />
- +
= ({
- +
@@ -486,7 +444,7 @@ const RepositoryForm: React.FC = ({ onValueChange={(value) => setFormData(prev => ({ ...prev, branch: value }))} > - + {branches.map(branch => ( @@ -501,7 +459,7 @@ const RepositoryForm: React.FC = ({ setFormData(prev => ({ ...prev, branch: e.target.value }))} className="pl-10" @@ -514,34 +472,34 @@ const RepositoryForm: React.FC = ({
- +
setFormData(prev => ({ ...prev, gitUserName: e.target.value }))} className="pl-10" />
-

私有仓库需要提供用户名

+

{t('repository.form.private_repo_username_tip', '私有仓库需要提供用户名')}

- +
setFormData(prev => ({ ...prev, gitPassword: e.target.value }))} className="pl-10" />
-

私有仓库需要提供密码或访问令牌

+

{t('repository.form.private_repo_password_tip', '私有仓库需要提供密码或访问令牌')}

@@ -579,7 +537,7 @@ const RepositoryForm: React.FC = ({ {/* 上传方式选择 */}
- +
@@ -605,7 +563,7 @@ const RepositoryForm: React.FC = ({ {/* 文件上传 */} {formData.uploadMethod === 'file' && (
- + = ({ className="cursor-pointer" />

- 支持的文件格式:zip、gz、tar、br、7z、rar,最大100MB + {t('repository.form.supported_formats_tip', '支持的文件格式:zip、gz、tar、br、7z、rar,最大100MB')}

)} diff --git a/web/app/components/document/SourceFiles.tsx b/web/app/components/document/SourceFiles.tsx index c624223f..69e174d8 100644 --- a/web/app/components/document/SourceFiles.tsx +++ b/web/app/components/document/SourceFiles.tsx @@ -51,4 +51,4 @@ const SourceFiles: React.FC = ({ ); }; -export default SourceFiles; \ No newline at end of file +export default SourceFiles; \ No newline at end of file diff --git a/web/app/components/renderMarkdown.tsx b/web/app/components/renderMarkdown.tsx index 16b61c67..ef3cde5d 100644 --- a/web/app/components/renderMarkdown.tsx +++ b/web/app/components/renderMarkdown.tsx @@ -1,25 +1,24 @@ import { TOCItemType } from "fumadocs-core/server"; -import ThemedMarkdown from './ThemedMarkdown'; - +import ThemedMarkdown from "./ThemedMarkdown"; +import { ensureUniqueSlug, generateSlug } from "../utils/slug"; interface RenderMarkdownResult { body: any; - toc: TOCItemType[] + toc: TOCItemType[]; } // 手动解析markdown,提取标题作为TOC function extractTOC(markdown: string): TOCItemType[] { const toc: TOCItemType[] = []; const headingRegex = /^(#{1,6})\s+(.+)$/gm; + const existingSlugs = new Set(); let match; while ((match = headingRegex.exec(markdown)) !== null) { const level = match[1].length; const text = match[2].trim(); - const slug = text - .toLowerCase() - .replace(/[^\w\s-]/g, '') - .replace(/\s+/g, '-'); + const baseSlug = generateSlug(text); + const slug = ensureUniqueSlug(baseSlug, existingSlugs); toc.push({ title: text, @@ -31,15 +30,15 @@ function extractTOC(markdown: string): TOCItemType[] { return toc; } -export default function RenderMarkdown(props: { markdown: string }): RenderMarkdownResult { +export default function RenderMarkdown(props: { + markdown: string; +}): RenderMarkdownResult { if (!props.markdown) return { body: <>, toc: [] }; try { const toc = extractTOC(props.markdown); return { - body: - {props.markdown} - , + body: {props.markdown}, toc: toc }; } catch (error) { @@ -50,4 +49,5 @@ export default function RenderMarkdown(props: { markdown: string }): RenderMarkd toc: [] }; } -} \ No newline at end of file +} + diff --git a/web/app/page.tsx b/web/app/page.tsx index b40a21bf..71f73e82 100644 --- a/web/app/page.tsx +++ b/web/app/page.tsx @@ -5,6 +5,7 @@ import { getBasicHomeStats } from './services/statsService'; import HomeClient from './components/HomeClient'; import { Suspense } from 'react'; import { Skeleton } from '@/components/ui/skeleton'; +import { cookies } from 'next/headers'; export default async function Home({ searchParams @@ -19,10 +20,21 @@ export default async function Home({ const pageSize = Number(resolvedSearchParams?.pageSize) || 20; const keyword = (resolvedSearchParams?.keyword as string) || ''; + // 获取cookie用于服务端API认证 + const cookieStore = await cookies(); + const token = cookieStore.get('token')?.value; + const refreshToken = cookieStore.get('refreshToken')?.value; + + // 构造完整的cookie字符串 + const cookieString = [ + token ? `token=${token}` : '', + refreshToken ? `refreshToken=${refreshToken}` : '' + ].filter(Boolean).join('; '); + // 并行获取初始数据和统计数据 const [response, statsData] = await Promise.all([ - getWarehouse(page, pageSize, keyword), - getBasicHomeStats() + getWarehouse(page, pageSize, keyword, cookieString), + getBasicHomeStats(cookieString) ]); const initialRepositories = response.success ? response.data.items : []; diff --git a/web/app/register/page.tsx b/web/app/register/page.tsx index 101a626c..47218bbd 100644 --- a/web/app/register/page.tsx +++ b/web/app/register/page.tsx @@ -91,7 +91,6 @@ export default function RegisterPage() { // 调用注册API const {data} = await register(username, email, password) - console.log('注册响应:', data) if (data.success) { // 登录成功 toast.success('注册成功') diff --git a/web/app/services/api.ts b/web/app/services/api.ts index 0d17a5d0..2347ded8 100644 --- a/web/app/services/api.ts +++ b/web/app/services/api.ts @@ -203,5 +203,7 @@ async function* fetchSSE(url: string, data: any): AsyncIterableIterator { } const API_URL = process.env.NEXT_PUBLIC_API_URL || process.env.API_URL || ''; +console.log("API_URL", API_URL); + export { fetchApi, serverFetchApi, clientFetchApi, API_URL, fetchSSE }; export type { ApiResponse }; \ No newline at end of file diff --git a/web/app/services/documentI18nService.ts b/web/app/services/documentI18nService.ts index 0f7e9ed3..7bccdf9d 100644 --- a/web/app/services/documentI18nService.ts +++ b/web/app/services/documentI18nService.ts @@ -2,6 +2,9 @@ import { fetchApi, ApiResponse } from './api'; const API_URL = process.env.NEXT_PUBLIC_API_URL || ''; +console.log("API_URL", API_URL); + + // 文档目录多语言数据 interface DocumentCatalogI18n { id: string; diff --git a/web/app/services/statsService.ts b/web/app/services/statsService.ts index 513c1f05..302bf84c 100644 --- a/web/app/services/statsService.ts +++ b/web/app/services/statsService.ts @@ -97,12 +97,13 @@ export async function getHomeStats(): Promise { /** * 获取简化的统计数据(仅包含基本信息,用于快速加载) + * @param cookieString 可选的cookie字符串,用于服务端请求 * @returns Promise> */ -export async function getBasicHomeStats(): Promise> { +export async function getBasicHomeStats(cookieString?: string): Promise> { try { const [repositoriesResponse, openDeepWikiInfo] = await Promise.all([ - getWarehouse(1, 100), // 获取基本仓库信息 + getWarehouse(1, 100, '', cookieString), // 获取基本仓库信息 getGitHubRepoInfo('AIDotNet', 'OpenDeepWiki') ]); diff --git a/web/app/services/warehouseService.ts b/web/app/services/warehouseService.ts index ceed4a50..44a73be5 100644 --- a/web/app/services/warehouseService.ts +++ b/web/app/services/warehouseService.ts @@ -313,18 +313,24 @@ export async function getBranchList( * Get warehouse list * 此函数可在服务器组件中使用 */ -export async function getWarehouse(page: number, pageSize: number, keyword?: string): Promise> { +export async function getWarehouse(page: number, pageSize: number, keyword?: string, cookieString?: string): Promise> { // keyword == undefined 时,置空 if (keyword === undefined || keyword === 'undefined') { keyword = ''; } + const headers: HeadersInit = {}; + if (cookieString) { + headers['Cookie'] = cookieString; + } + // @ts-ignore return fetchApi(API_URL + '/api/Warehouse/WarehouseList?page=' + page + '&pageSize=' + pageSize + '&keyword=' + keyword, { method: 'GET', // 添加缓存控制使其适用于服务器组件 - cache: 'no-store' + cache: 'no-store', + headers }); } diff --git a/web/bun.lock b/web/bun.lock index 18a00612..155ffdf6 100644 --- a/web/bun.lock +++ b/web/bun.lock @@ -9,11 +9,12 @@ "@radix-ui/react-alert-dialog": "^1.1.14", "@radix-ui/react-avatar": "^1.1.10", "@radix-ui/react-checkbox": "^1.3.2", - "@radix-ui/react-collapsible": "^1.1.11", + "@radix-ui/react-collapsible": "^1.1.12", "@radix-ui/react-context-menu": "^2.2.15", "@radix-ui/react-dialog": "^1.1.14", "@radix-ui/react-dropdown-menu": "^2.1.15", "@radix-ui/react-label": "^2.1.7", + "@radix-ui/react-progress": "^1.1.7", "@radix-ui/react-radio-group": "^1.3.7", "@radix-ui/react-select": "^2.2.5", "@radix-ui/react-separator": "^1.1.7", @@ -469,7 +470,7 @@ "@radix-ui/react-checkbox": ["@radix-ui/react-checkbox@1.3.2", "https://registry.npmmirror.com/@radix-ui/react-checkbox/-/react-checkbox-1.3.2.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.2", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-presence": "1.1.4", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-yd+dI56KZqawxKZrJ31eENUwqc1QSqg4OZ15rybGjF2ZNwMO+wCyHzAVLRp9qoYJf7kYy0YpZ2b0JCzJ42HZpA=="], - "@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.1.11", "https://registry.npmmirror.com/@radix-ui/react-collapsible/-/react-collapsible-1.1.11.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.2", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-presence": "1.1.4", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-2qrRsVGSCYasSz1RFOorXwl0H7g7J1frQtgpQgYrt+MOidtPAINHn9CPovQXb83r8ahapdx3Tu0fa/pdFFSdPg=="], + "@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.1.12", "https://registry.npmmirror.com/@radix-ui/react-collapsible/-/react-collapsible-1.1.12.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-presence": "1.1.5", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA=="], "@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-collection/-/react-collection-1.1.7.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="], @@ -509,6 +510,8 @@ "@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "https://registry.npmmirror.com/@radix-ui/react-primitive/-/react-primitive-2.1.3.tgz", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="], + "@radix-ui/react-progress": ["@radix-ui/react-progress@1.1.7", "https://registry.npmmirror.com/@radix-ui/react-progress/-/react-progress-1.1.7.tgz", { "dependencies": { "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-vPdg/tF6YC/ynuBIJlk1mm7Le0VgW6ub6J2UWnTQ7/D23KXcPI1qy+0vBkgKgd38RCMJavBXpB83HPNFMTb0Fg=="], + "@radix-ui/react-radio-group": ["@radix-ui/react-radio-group@1.3.7", "https://registry.npmmirror.com/@radix-ui/react-radio-group/-/react-radio-group-1.3.7.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.2", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-presence": "1.1.4", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-roving-focus": "1.1.10", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-use-size": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9w5XhD0KPOrm92OTTE0SysH3sYzHsSTHNvZgUBo/VZ80VdYyB5RneDbc0dKpURS24IxkoFRu/hI0i4XyfFwY6g=="], "@radix-ui/react-roving-focus": ["@radix-ui/react-roving-focus@1.1.10", "https://registry.npmmirror.com/@radix-ui/react-roving-focus/-/react-roving-focus-1.1.10.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.2", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-dT9aOXUen9JSsxnMPv/0VqySQf5eDQ6LCk5Sw28kamz8wSOW2bJdlX2Bg5VUIIcV+6XlHpWTIuTPCf/UNIyq8Q=="], @@ -1963,6 +1966,12 @@ "@lobehub/ui/react-markdown": ["react-markdown@10.1.0", "https://registry.npmmirror.com/react-markdown/-/react-markdown-10.1.0.tgz", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "hast-util-to-jsx-runtime": "^2.0.0", "html-url-attributes": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "remark-parse": "^11.0.0", "remark-rehype": "^11.0.0", "unified": "^11.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" }, "peerDependencies": { "@types/react": ">=18", "react": ">=18" } }, "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ=="], + "@radix-ui/react-accordion/@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.1.11", "https://registry.npmmirror.com/@radix-ui/react-collapsible/-/react-collapsible-1.1.11.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.2", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-presence": "1.1.4", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-2qrRsVGSCYasSz1RFOorXwl0H7g7J1frQtgpQgYrt+MOidtPAINHn9CPovQXb83r8ahapdx3Tu0fa/pdFFSdPg=="], + + "@radix-ui/react-collapsible/@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "https://registry.npmmirror.com/@radix-ui/primitive/-/primitive-1.1.3.tgz", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="], + + "@radix-ui/react-collapsible/@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.5", "https://registry.npmmirror.com/@radix-ui/react-presence/-/react-presence-1.1.5.tgz", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ=="], + "@shikijs/rehype/@shikijs/types": ["@shikijs/types@3.7.0", "https://registry.npmmirror.com/@shikijs/types/-/types-3.7.0.tgz", { "dependencies": { "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-MGaLeaRlSWpnP0XSAum3kP3a8vtcTsITqoEPYdt3lQG3YCdQH4DnEhodkYcNMcU0uW0RffhoD1O3e0vG5eSBBg=="], "@shikijs/rehype/shiki": ["shiki@3.7.0", "https://registry.npmmirror.com/shiki/-/shiki-3.7.0.tgz", { "dependencies": { "@shikijs/core": "3.7.0", "@shikijs/engine-javascript": "3.7.0", "@shikijs/engine-oniguruma": "3.7.0", "@shikijs/langs": "3.7.0", "@shikijs/themes": "3.7.0", "@shikijs/types": "3.7.0", "@shikijs/vscode-textmate": "^10.0.2", "@types/hast": "^3.0.4" } }, "sha512-ZcI4UT9n6N2pDuM2n3Jbk0sR4Swzq43nLPgS/4h0E3B/NrFn2HKElrDtceSf8Zx/OWYOo7G1SAtBLypCp+YXqg=="], @@ -2021,6 +2030,8 @@ "fumadocs-mdx/zod": ["zod@3.25.74", "https://registry.npmmirror.com/zod/-/zod-3.25.74.tgz", {}, "sha512-J8poo92VuhKjNknViHRAIuuN6li/EwFbAC8OedzI8uxpEPGiXHGQu9wemIAioIpqgfB4SySaJhdk0mH5Y4ICBg=="], + "fumadocs-ui/@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.1.11", "https://registry.npmmirror.com/@radix-ui/react-collapsible/-/react-collapsible-1.1.11.tgz", { "dependencies": { "@radix-ui/primitive": "1.1.2", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-presence": "1.1.4", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-2qrRsVGSCYasSz1RFOorXwl0H7g7J1frQtgpQgYrt+MOidtPAINHn9CPovQXb83r8ahapdx3Tu0fa/pdFFSdPg=="], + "gray-matter/js-yaml": ["js-yaml@3.14.1", "https://registry.npmmirror.com/js-yaml/-/js-yaml-3.14.1.tgz", { "dependencies": { "argparse": "^1.0.7", "esprima": "^4.0.0" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g=="], "hast-util-from-dom/hastscript": ["hastscript@9.0.1", "https://registry.npmmirror.com/hastscript/-/hastscript-9.0.1.tgz", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "hast-util-parse-selector": "^4.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0" } }, "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w=="], diff --git a/web/components/ui/collapsible.tsx b/web/components/ui/collapsible.tsx index b3c6e66b..1e4cb413 100644 --- a/web/components/ui/collapsible.tsx +++ b/web/components/ui/collapsible.tsx @@ -1,103 +1,82 @@ import * as React from "react" import * as CollapsiblePrimitive from "@radix-ui/react-collapsible" +import { Card, CardContent, CardHeader } from "@/components/ui/card" import { ChevronDown } from "lucide-react" -import { cva, type VariantProps } from "class-variance-authority" - import { cn } from "@/lib/utils" -const Collapsible = CollapsiblePrimitive.Root - -const CollapsibleTrigger = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef & { - showIcon?: boolean - } ->(({ className, children, showIcon = true, ...props }, ref) => ( - svg]:rotate-180", - className - )} - {...props} - > - {children} - {showIcon && ( - - )} - -)) -CollapsibleTrigger.displayName = CollapsiblePrimitive.CollapsibleTrigger.displayName +function Collapsible({ + ...props +}: React.ComponentProps) { + return +} -const CollapsibleContent = React.forwardRef< - React.ElementRef, - React.ComponentPropsWithoutRef ->(({ className, children, ...props }, ref) => ( - -
{children}
-
-)) -CollapsibleContent.displayName = CollapsiblePrimitive.CollapsibleContent.displayName +function CollapsibleTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ) +} -// Card-like collapsible variant -const collapsibleCardVariants = cva( - "rounded-lg border bg-card text-card-foreground shadow-sm", - { - variants: { - variant: { - default: "border-border", - accent: "border-accent bg-accent/5", - muted: "border-muted bg-muted/30", - }, - }, - defaultVariants: { - variant: "default", - }, - } -) +function CollapsibleContent({ + ...props +}: React.ComponentProps) { + return ( + + ) +} -interface CollapsibleCardProps - extends React.ComponentPropsWithoutRef, - VariantProps { - title: any +interface CollapsibleCardProps { + title: React.ReactNode + children: React.ReactNode defaultOpen?: boolean - showIcon?: boolean + variant?: "default" | "accent" + className?: string } -const CollapsibleCard = React.forwardRef< - React.ElementRef, - CollapsibleCardProps ->(({ className, variant, title, children, defaultOpen, showIcon = true, ...props }, ref) => ( - - - {title} - - - {children} - - -)) -CollapsibleCard.displayName = "CollapsibleCard" +function CollapsibleCard({ + title, + children, + defaultOpen = false, + variant = "default", + className, + ...props +}: CollapsibleCardProps) { + const [isOpen, setIsOpen] = React.useState(defaultOpen) -export { - Collapsible, - CollapsibleTrigger, - CollapsibleContent, - CollapsibleCard, - collapsibleCardVariants, + return ( + + + + +
+
{title}
+ +
+
+
+ + + {children} + + +
+
+ ) } + +export { Collapsible, CollapsibleTrigger, CollapsibleContent, CollapsibleCard } diff --git a/web/layout.tsx b/web/layout.tsx index 034f35aa..b091d0cc 100644 --- a/web/layout.tsx +++ b/web/layout.tsx @@ -80,7 +80,6 @@ export default function AdminLayout({ config={{ proxy: 'custom', customCdnFn: (e: { pkg: string, version: string, path: string }) => { - console.log(e); return `/${e.pkg}/${e.version}/${e.path}`; } }} diff --git a/web/next.config.js b/web/next.config.js index a9b09944..f43b7f18 100644 --- a/web/next.config.js +++ b/web/next.config.js @@ -1,15 +1,15 @@ -import { createMDX } from 'fumadocs-mdx/next'; +import { createMDX } from "fumadocs-mdx/next"; const withMDX = createMDX(); /** @type {import('next').NextConfig} */ const nextConfig = { - output: 'standalone', + output: "standalone", reactStrictMode: true, - transpilePackages: ['fumadocs-ui'], + transpilePackages: ["fumadocs-ui"], // CSS配置 experimental: { - cssChunking: 'strict', + cssChunking: "strict", }, // 禁用CSS Modules的纯选择器校验 webpack: (config, { dev, isServer }) => { @@ -19,10 +19,10 @@ const nextConfig = { rule.oneOf.forEach((loader) => { if (loader.use && Array.isArray(loader.use)) { loader.use.forEach((use) => { - if (use.loader && use.loader.includes('css-loader')) { + if (use.loader && use.loader.includes("css-loader")) { if (use.options && use.options.modules) { // 禁用纯选择器模式 - use.options.modules.mode = 'local'; + use.options.modules.mode = "local"; use.options.modules.pure = false; } } @@ -35,25 +35,19 @@ const nextConfig = { return config; }, async rewrites() { - const apiUrl = 'http://localhost:5085/' - // 如果NEXT_PUBLIC_API_URL环境变量有值则使用 if (process.env?.NEXT_PUBLIC_API_URL) { return [ { - source: '/api/:path*', - destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*` + source: "/api/:path*", + destination: `${process.env.NEXT_PUBLIC_API_URL}/api/:path*`, }, ]; + } else { + console.log("NEXT_PUBLIC_API_URL 是空的,请在环境变量中配置"); + return []; } - - return [ - { - source: '/api/:path*', - destination: `${apiUrl}/api/:path*` - }, - ]; }, }; -export default withMDX(nextConfig); \ No newline at end of file +export default withMDX(nextConfig); diff --git a/web/package-lock.json b/web/package-lock.json index 941b11a9..f9434354 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -16,6 +16,7 @@ "@radix-ui/react-dialog": "^1.1.14", "@radix-ui/react-dropdown-menu": "^2.1.15", "@radix-ui/react-label": "^2.1.7", + "@radix-ui/react-progress": "^1.1.7", "@radix-ui/react-radio-group": "^1.3.7", "@radix-ui/react-select": "^2.2.5", "@radix-ui/react-separator": "^1.1.7", @@ -3660,6 +3661,30 @@ } } }, + "node_modules/@radix-ui/react-progress": { + "version": "1.1.7", + "resolved": "https://registry.npmmirror.com/@radix-ui/react-progress/-/react-progress-1.1.7.tgz", + "integrity": "sha512-vPdg/tF6YC/ynuBIJlk1mm7Le0VgW6ub6J2UWnTQ7/D23KXcPI1qy+0vBkgKgd38RCMJavBXpB83HPNFMTb0Fg==", + "license": "MIT", + "dependencies": { + "@radix-ui/react-context": "1.1.2", + "@radix-ui/react-primitive": "2.1.3" + }, + "peerDependencies": { + "@types/react": "*", + "@types/react-dom": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "@types/react-dom": { + "optional": true + } + } + }, "node_modules/@radix-ui/react-radio-group": { "version": "1.3.7", "resolved": "https://registry.npmmirror.com/@radix-ui/react-radio-group/-/react-radio-group-1.3.7.tgz", diff --git a/web/package.json b/web/package.json index 928495f0..01db7e15 100644 --- a/web/package.json +++ b/web/package.json @@ -16,11 +16,12 @@ "@radix-ui/react-alert-dialog": "^1.1.14", "@radix-ui/react-avatar": "^1.1.10", "@radix-ui/react-checkbox": "^1.3.2", - "@radix-ui/react-collapsible": "^1.1.11", + "@radix-ui/react-collapsible": "^1.1.12", "@radix-ui/react-context-menu": "^2.2.15", "@radix-ui/react-dialog": "^1.1.14", "@radix-ui/react-dropdown-menu": "^2.1.15", "@radix-ui/react-label": "^2.1.7", + "@radix-ui/react-progress": "^1.1.7", "@radix-ui/react-radio-group": "^1.3.7", "@radix-ui/react-select": "^2.2.5", "@radix-ui/react-separator": "^1.1.7", diff --git a/web/public/feishu.jpg b/web/public/feishu.jpg new file mode 100644 index 00000000..710abed0 Binary files /dev/null and b/web/public/feishu.jpg differ diff --git a/web/public/locales/en-US/common.json b/web/public/locales/en-US/common.json index 938ffdbb..db296b47 100644 --- a/web/public/locales/en-US/common.json +++ b/web/public/locales/en-US/common.json @@ -39,6 +39,15 @@ "processing_repositories": "Processing", "github_stars": "GitHub Stars" }, + "community": { + "title": "Join Our Community", + "join_group": "Scan to Join Feishu Group", + "description": "Connect with developers, discuss and get latest updates", + "qr_alt": "Feishu Community QR Code", + "click_to_enlarge": "Click to enlarge", + "qr_preview_title": "Feishu Community QR Code", + "scan_tip": "Use Feishu to scan this QR code and join our community" + }, "sponsors": { "title": "Thanks to Our Sponsors", "antsk": { @@ -61,7 +70,9 @@ "add_button": "Add Repository", "empty": "No repositories found", "not_found": "No repositories matching \"{{keyword}}\" found", - "add_now": "Add Now" + "add_now": "Add Now", + "get_started": "Start adding your first code repository", + "try_adjust_keywords": "Try adjusting search keywords" }, "pagination": { "total": "Total {{total}} repositories" @@ -137,7 +148,36 @@ "manual_input": "Manual Input", "use_select": "Use Selector", "default_branch_loaded": "Repository default branch auto-selected: {{branch}}", - "no_default_branch": "No default branch found, selected first branch" + "no_default_branch": "No default branch found, selected first branch", + "complete_info_required": "Please fill in complete repository information", + "select_file_required": "Please select a zip file to upload", + "file_upload_success": "File uploaded successfully", + "file_upload_failed": "File upload failed, please try again", + "zip_url_required": "Please enter zip file URL", + "submit_failed": "Submission failed, please try again", + "branches_loaded": "Loaded {{count}} branches", + "branches_load_warning": "Unable to fetch branch information, you can enter branch name manually", + "branches_load_failed": "Failed to load branches", + "custom_repo_info": "Please fill in custom repository details, including organization name, repository name, Git address, etc.", + "organization_name": "Organization Name", + "organization_name_placeholder": "Enter organization name", + "repository_name": "Repository Name", + "repository_name_placeholder": "Enter repository name", + "git_username_optional": "Git Username (Optional)", + "private_repo_username_tip": "Private repositories require username", + "git_password_optional": "Git Password/Token (Optional)", + "git_password_or_token": "Git password or access token", + "private_repo_password_tip": "Private repositories require password or access token", + "upload_method": "Upload Method", + "select_file": "Select File", + "download_from_url": "Download from URL", + "select_zip_file": "Select Zip File", + "supported_formats": "Supported formats: zip, gz, tar, br, 7z, rar, max 100MB", + "zip_url": "Zip URL", + "zip_url_placeholder": "https://github.com/user/repo/archive/refs/heads/main.zip", + "url_tip": "Supported archive formats: zip, gz, tar, br", + "url_download_success": "Successfully downloaded zip from URL", + "url_download_failed": "Failed to download from URL, please try again" }, "last_repo": { "title": "Query Repository", diff --git a/web/public/locales/zh-CN/common.json b/web/public/locales/zh-CN/common.json index 20c3ddf0..be2e520c 100644 --- a/web/public/locales/zh-CN/common.json +++ b/web/public/locales/zh-CN/common.json @@ -39,6 +39,15 @@ "processing_repositories": "处理中", "github_stars": "GitHub Stars" }, + "community": { + "title": "加入社区交流群", + "join_group": "扫码加入飞书群", + "description": "与开发者交流讨论,获取最新资讯", + "qr_alt": "飞书交流群二维码", + "click_to_enlarge": "点击查看大图", + "qr_preview_title": "飞书交流群二维码", + "scan_tip": "使用飞书扫描此二维码加入交流群" + }, "sponsors": { "title": "感谢赞助商支持", "antsk": { @@ -61,7 +70,9 @@ "add_button": "添加仓库", "empty": "暂无仓库数据", "not_found": "没有找到与\"{{keyword}}\"相关的仓库", - "add_now": "立即添加" + "add_now": "立即添加", + "get_started": "开始添加您的第一个代码仓库", + "try_adjust_keywords": "尝试调整搜索关键词" }, "pagination": { "total": "共 {{total}} 个仓库" @@ -101,7 +112,7 @@ "git_password": "Git密码/访问令牌", "git_password_placeholder": "请输入Git密码或访问令牌", "git_token_tip": "对于GitHub,推荐使用Personal Access Token", - "upload_info": "压缩包上传说明", + "upload_info": "支持上传压缩包或从URL下载。", "upload_formats": "支持的格式:zip、gz、tar、br", "org_name": "组织名称", "org_name_placeholder": "请输入组织名称", @@ -137,7 +148,34 @@ "manual_input": "手动输入", "use_select": "使用选择器", "default_branch_loaded": "已自动选择仓库默认分支: {{branch}}", - "no_default_branch": "未找到默认分支,已选择第一个分支" + "no_default_branch": "未找到默认分支,已选择第一个分支", + "complete_repo_info": "请填写完整的仓库信息", + "select_zip_file": "请选择要上传的压缩包文件", + "file_upload_success": "文件上传成功", + "file_upload_failed": "文件上传失败,请重试", + "enter_zip_url": "请输入压缩包URL地址", + "branch_fetch_failed": "获取分支失败", + "branch_fetch_no_info": "未能获取分支信息,可以手动输入分支名", + "custom_repo_description": "请填写自定义仓库的详细信息,包括组织名、仓库名、Git地址等。", + "org_name_cn": "组织名称", + "org_name_placeholder_cn": "请输入组织名称", + "repo_name_cn": "仓库名称", + "repo_name_placeholder_cn": "请输入仓库名称", + "repo_address_cn": "仓库地址", + "git_username_optional": "Git用户名(可选)", + "git_username_placeholder_cn": "Git用户名", + "private_repo_username_tip": "私有仓库需要提供用户名", + "git_password_optional": "Git密码/令牌(可选)", + "git_password_placeholder_cn": "Git密码或访问令牌", + "private_repo_password_tip": "私有仓库需要提供密码或访问令牌", + "upload_method": "上传方式", + "select_file": "选择文件", + "download_from_url": "从URL下载", + "select_zip_file_cn": "选择压缩包文件", + "supported_formats_tip": "支持的文件格式:zip、gz、tar、br、7z、rar,最大100MB", + "load_branches_cn": "加载分支", + "branch_placeholder_cn": "请输入分支名称", + "submit_failed_retry": "提交失败,请重试" }, "last_repo": { "title": "查询仓库",