Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix: correcting broken links + translating additional docs in English

openJiuwen-bot00d3ed193397
diff --git a/README.md b/README.md
index bfb97c72b2..d20c8f8faf 100644
--- a/README.md
+++ b/README.md
@@ -100,19 +100,19 @@ Set up heartbeat tasks with your to-do items, and JiuwenClaw will wake up on sch
| Document | Description |
| :--------------------------------------------------- | :------------------------------------------------------- |
-| [📖 Quick Start](docs/Quickstart.md) | Get up and running with JiuwenClaw in 5 minutes |
-| [⚙️ Configuration & Workspace](docs/配置信息.md) | Environment setup and workspace management |
-| [📁 Workspace Structure](docs/智能体.md) | workspace directory layout, presets, and dynamic content |
-| [🛠️ Skill System](docs/技能.md) | Guide to developing custom skills |
-| [📱 Channel Configuration](docs/频道.md) | Integrating Feishu, Xiaoyi, and other channels |
-| [⌨️ CLI Commands](docs/命令行指令.md) | Command-line tool usage guide |
-| [⏰ Scheduled Tasks](docs/定时任务.md) | Scheduled task management |
-| [🧠 Memory](docs/记忆.md) | Intelligent memory and learning capabilities |
-| [🌐 Browser Automation](docs/浏览器.md) | Web browsing and automation features |
-| [📋 Task Planning](docs/任务规划.md) | Chat behavior and task flow |
-| [🔄 Skill Self-Evolution](docs/Skill自演进.md) | Mechanism for automatic skill evolution |
-| [📦 Context Compression](docs/上下文压缩卸载.md) | Context compression and unloading |
-| [🚀 Development Practices](docs/开发实践/) | Development practices and experience sharing |
+| [📖 Quick Start](docs/en/Quickstart.md) | Get up and running with JiuwenClaw in 5 minutes |
+| [⚙️ Configuration & Workspace](docs/en/Configuration.md) | Environment setup and workspace management |
+| [📁 Workspace Structure](docs/en/Agent.md) | workspace directory layout, presets, and dynamic content |
+| [🛠️ Skill System](docs/en/Skills.md) | Guide to developing custom skills |
+| [📱 Channel Configuration](docs/en/Channels.md) | Integrating Feishu, Xiaoyi, and other channels |
+| [⌨️ CLI Commands](docs/en/CLI.md) | Command-line tool usage guide |
+| [⏰ Scheduled Tasks](docs/en/ScheduledTasks.md) | Scheduled task management |
+| [🧠 Memory](docs/en/Memory.md) | Intelligent memory and learning capabilities |
+| [🌐 Browser Automation](docs/en/Browser.md) | Web browsing and automation features |
+| [📋 Task Planning](docs/en/TaskPlanning.md) | Chat behavior and task flow |
+| [🔄 Skill Self-Evolution](docs/en/SkillSelfEvolution.md) | Mechanism for automatic skill evolution |
+| [📦 Context Compression](docs/en/ContextCompression.md) | Context compression and unloading |
+| [🚀 Development Practices](docs/en/development-practices/README.md) | Development practices and experience sharing |
## 🤝 Contributing
diff --git a/README_CN.md b/README_CN.md
index 4773562c2c..0a6332fff5 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -90,19 +90,19 @@ jiuwenclaw-start
| 文档 | 核心内容 |
|:------------------------------------|:-------------------------|
-| [📖 快速开始](docs/Quickstart.md) | 5分钟上手JiuwenClaw |
-| [⚙️ 配置与工作空间](docs/配置信息.md) | 环境配置与工作区管理 |
-| [📁 工作区结构](docs/智能体.md) | workspace 目录说明,预置与动态生成内容 |
-| [🛠️ 技能系统](docs/技能.md) | 自定义技能开发指南 |
-| [📱 频道配置](docs/频道.md) | 飞书、小艺等频道接入 |
-| [⌨️ 命令行指令](docs/命令行指令.md) | 命令行工具使用指南 |
-| [⏰ 定时任务](docs/定时任务.md) | 定时任务管理 |
-| [🧠 记忆功能](docs/记忆.md) | 智能记忆与学习 |
-| [🌐 浏览器相关](docs/浏览器.md) | 自动化浏览功能 |
-| [📋 任务规划](docs/任务规划.md) | 任务规划与待办事项 |
-| [🔄 Skill自演进](docs/Skill自演进.md) | Skill自演进机制 |
-| [📦 上下文压缩](docs/上下文压缩卸载.md) | 上下文压缩与卸载 |
-| [🚀 开发实践](docs/开发实践/) | 开发实践与经验分享 |
+| [📖 快速开始](docs/zh/Quickstart.md) | 5分钟上手JiuwenClaw |
+| [⚙️ 配置与工作空间](docs/zh/配置信息.md) | 环境配置与工作区管理 |
+| [📁 工作区结构](docs/zh/智能体.md) | workspace 目录说明,预置与动态生成内容 |
+| [🛠️ 技能系统](docs/zh/技能.md) | 自定义技能开发指南 |
+| [📱 频道配置](docs/zh/频道.md) | 飞书、小艺等频道接入 |
+| [⌨️ 命令行指令](docs/zh/命令行指令.md) | 命令行工具使用指南 |
+| [⏰ 定时任务](docs/zh/定时任务.md) | 定时任务管理 |
+| [🧠 记忆功能](docs/zh/记忆.md) | 智能记忆与学习 |
+| [🌐 浏览器相关](docs/zh/浏览器.md) | 自动化浏览功能 |
+| [📋 任务规划](docs/zh/任务规划.md) | 任务规划与待办事项 |
+| [🔄 Skill自演进](docs/zh/Skill自演进.md) | Skill自演进机制 |
+| [📦 上下文压缩](docs/zh/上下文压缩卸载.md) | 上下文压缩与卸载 |
+| [🚀 开发实践](docs/zh/开发实践/) | 开发实践与经验分享 |
## 🤝 参与贡献
diff --git a/docs/en/Channels.md b/docs/en/Channels.md
index 2eac8d9a6d..c9cca20dc6 100644
--- a/docs/en/Channels.md
+++ b/docs/en/Channels.md
@@ -407,6 +407,8 @@ channels:
Discord is supported. Configure in **Channel management** or edit `config.yaml`.
+**Step-by-step guide** (Developer Portal, intents, install link, channel management): see [Discord.md](Discord.md).
+
- `bot_token`
- `application_id`
- `guild_id`
diff --git a/docs/discord_en.md b/docs/en/Discord.md
similarity index 92%
rename from docs/discord_en.md
rename to docs/en/Discord.md
index 839dc368de..5a923924d4 100644
--- a/docs/discord_en.md
+++ b/docs/en/Discord.md
@@ -21,7 +21,7 @@ The bot connects with your **Bot Token**, receives messages in configured guild
1. Open [https://discord.com/developers/applications](https://discord.com/developers/applications).
2. Click **New Application**, choose a name, and create it.
-![Create a new Discord application](assets/images/discord/1_create_new_app.png)
+![Create a new Discord application](../assets/images/discord/1_create_new_app.png)
You will use this application for both **OAuth2 / installation** and the **Bot** user.
@@ -33,7 +33,7 @@ You will use this application for both **OAuth2 / installation** and the **Bot**
2. Under **Token**, use **Reset Token** and confirm.
3. **Copy the token immediately** and store it somewhere safe. Discord shows it only once after a reset.
-![Reset and copy Bot Token](assets/images/discord/2_reset_bot_token.png)
+![Reset and copy Bot Token](../assets/images/discord/2_reset_bot_token.png)
**Security**
@@ -53,7 +53,7 @@ JiuwenClaw reads the text of messages your bot receives. Discord requires an exp
2. Under **Privileged Gateway Intents**, turn on **MESSAGE CONTENT INTENT**.
3. Save changes if the portal prompts you.
-![Enable Message Content Intent](assets/images/discord/3_set_required_intent.png)
+![Enable Message Content Intent](../assets/images/discord/3_set_required_intent.png)
Without this, the bot may connect but will not see normal message text content.
@@ -75,7 +75,7 @@ In the Developer Portal, use the installation / OAuth2 tools (e.g. **Installatio
- Bot permissions that match the list above.
- Screenshot attached below shows the recommended permissions, the mandatory ones are marked.
-![Guild install scopes and bot permissions](assets/images/discord/4_set_guild_install_scope_and_permissions.png)
+![Guild install scopes and bot permissions](../assets/images/discord/4_set_guild_install_scope_and_permissions.png)
Exact labels may move between **Installation**, **OAuth2**, and **Bot** sections as Discord updates the portal; align your choices with the screenshot and the capabilities above.
@@ -90,7 +90,7 @@ Choose how users or admins can add the app:
Copy the **generated URL** or **Install link** from the portal and open it in a browser to complete authorization.
-![Install methods and copy setup link](assets/images/discord/5_select_install_methods_and_copy_setup_link.png)
+![Install methods and copy setup link](../assets/images/discord/5_select_install_methods_and_copy_setup_link.png)
After installation:
@@ -183,4 +183,4 @@ Discord delivery is separate from model configuration. If you see HTTP errors fr
## Related
-- Short overview and field table: [频道.md](频道.md) (Discord section)
+- Short overview and field table: [Channels.md](Channels.md) (Discord section)
diff --git a/docs/en/OpenTelemetryObservability.md b/docs/en/OpenTelemetryObservability.md
new file mode 100644
index 0000000000..2ade478156
--- /dev/null
+++ b/docs/en/OpenTelemetryObservability.md
@@ -0,0 +1,367 @@
+# OpenTelemetry observability
+
+JiuWenClaw includes observability built on the OpenTelemetry protocol. It follows the [OpenTelemetry GenAI semantic conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) and supports exporting full call-chain traces and runtime metrics.
+
+## 1. Overview
+
+Through OpenTelemetry integration, you can observe the following call paths:
+
+| Type | Meaning | What is recorded |
+|------|---------|------------------|
+| ENTRY | Request entry | Who sent the message, which channel it came from |
+| AGENT | Agent invocation | Which agent is running, session ID |
+| LLM | Large model call | Model name, token usage (input/output/cache), system prompt, full input and output message content |
+| TOOL | Tool call | Tool name, arguments, return value, whether an error occurred |
+
+The following runtime metrics are also recorded:
+
+- End-to-end request latency, agent processing latency, LLM call latency, tool execution latency
+- Total requests, error count, LLM call count, tool call count, tool error count
+- Token usage (broken down by input/output/cache)
+
+## 2. Quick enable
+
+### 2.1 Via environment variables
+
+```bash
+# Enable telemetry with console output (development / debugging)
+OTEL_ENABLED=true OTEL_EXPORTER_TYPE=console jiuwenclaw-app
+
+# Enable telemetry with OTLP export to Jaeger, Tempo, etc.
+OTEL_ENABLED=true OTEL_EXPORTER_TYPE=otlp OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 jiuwenclaw-app
+```
+
+### 2.2 Via config.yaml
+
+Add or edit the `telemetry` section in `config.yaml`:
+
+```yaml
+telemetry:
+ enabled: true # Master switch
+ exporter: otlp # otlp / console / none
+ endpoint: http://localhost:4317 # OTLP endpoint
+ protocol: grpc # grpc / http
+ log_messages: true # Whether to record full message content
+ service_name: jiuwenclaw
+```
+
+> Environment variables take precedence over `config.yaml`.
+
+## 3. Configuration parameters
+
+| Environment variable | config.yaml field | Default | Description |
+|----------------------|-------------------|---------|-------------|
+| `OTEL_ENABLED` | `telemetry.enabled` | `false` | Master switch |
+| `OTEL_EXPORTER_TYPE` | `telemetry.exporter` | `otlp` | Exporter: otlp / console / none |
+| `OTEL_EXPORTER_OTLP_ENDPOINT` | `telemetry.endpoint` | `http://localhost:4317` | OTLP backend URL |
+| `OTEL_EXPORTER_OTLP_PROTOCOL` | `telemetry.protocol` | `grpc` | OTLP protocol: grpc / http |
+| `OTEL_LOG_MESSAGES` | `telemetry.log_messages` | `true` | Whether to record full message content in span events |
+| `OTEL_SERVICE_NAME` | `telemetry.service_name` | `jiuwenclaw` | Service name |
+
+## 4. Trace structure
+
+A full request trace looks like this:
+
+```
+[ENTRY] channel.request
+ └── [AGENT] jiuwenclaw.agent.invoke
+ ├── [LLM] gen_ai.chat ← ReAct round 1
+ │ ├── event: gen_ai.system.message ← system prompt
+ │ ├── event: gen_ai.user.message ← user input
+ │ ├── event: gen_ai.assistant.message ← model output
+ │ └── [TOOL] gen_ai.tool.execute: search_web
+ │ ├── event: tool.arguments
+ │ └── event: tool.result
+ └── [LLM] gen_ai.chat ← ReAct round 2
+ └── event: gen_ai.assistant.message ← final answer
+```
+
+### Span attributes (GenAI semantic conventions)
+
+**ENTRY span** (`gen_ai.span.type=workflow`):
+
+- `jiuwenclaw.channel.id` — Channel identifier (feishu / web / wecom, etc.)
+- `jiuwenclaw.session.id` — Session ID
+- `jiuwenclaw.request.id` — Request ID
+- `gen_ai.span.type` — `"workflow"`
+
+**AGENT span** (`gen_ai.span.type=agent`):
+
+- `jiuwenclaw.agent.name` — Agent name
+- `jiuwenclaw.session.id` — Session ID
+- `gen_ai.agent.name` — Agent name (GenAI standard namespace)
+- `gen_ai.conversation.id` — Conversation ID (GenAI standard namespace)
+- `gen_ai.span.type` — `"agent"`
+
+**LLM span** (`gen_ai.span.type=model`):
+
+- `gen_ai.system` — Model provider (openai, etc.)
+- `gen_ai.request.model` — Requested model name
+- `gen_ai.response.model` — Response model name
+- `gen_ai.operation.name` — Operation type (chat)
+- `gen_ai.request.temperature` — Temperature
+- `gen_ai.request.top_p` — top_p
+- `gen_ai.usage.input_tokens` — Input tokens
+- `gen_ai.usage.output_tokens` — Output tokens
+- `gen_ai.usage.total_tokens` — Total tokens
+- `gen_ai.usage.cache_read_tokens` — Cache read tokens (when caching is used)
+- `gen_ai.response.finish_reasons` — Finish reasons (array)
+- `gen_ai.response.finish_reason` — Finish reason (string)
+- `gen_ai.span.type` — `"model"`
+
+**TOOL span** (`gen_ai.span.type=tool`):
+
+- `gen_ai.tool.name` — Tool name
+- `gen_ai.tool.call.id` — Call ID
+- `gen_ai.span.type` — `"tool"`
+
+## 5. Metrics
+
+| Metric name | Type | Description |
+|-------------|------|-------------|
+| `jiuwenclaw.request.duration` | Histogram | End-to-end request latency (seconds) |
+| `jiuwenclaw.request.count` | Counter | Total requests |
+| `jiuwenclaw.request.error.count` | Counter | Request errors |
+| `jiuwenclaw.agent.duration` | Histogram | Agent processing latency (seconds) |
+| `gen_ai.client.operation.duration` | Histogram | LLM call latency (seconds) |
+| `gen_ai.client.token.usage` | Counter | Token usage (by `gen_ai.token.type`) |
+| `gen_ai.client.operation.count` | Counter | LLM call count |
+| `gen_ai.tool.duration` | Histogram | Tool execution latency (seconds) |
+| `gen_ai.tool.call.count` | Counter | Tool call count |
+| `gen_ai.tool.error.count` | Counter | Tool errors |
+
+## 6. Jaeger example
+
+```bash
+# Start Jaeger (OTLP gRPC supported)
+docker run -d --name jaeger \
+ -p 16686:16686 \
+ -p 4317:4317 \
+ jaegertracing/all-in-one:latest
+
+# Start JiuWenClaw
+OTEL_ENABLED=true OTEL_EXPORTER_TYPE=otlp jiuwenclaw-app
+```
+
+Open http://localhost:16686 to view full traces in the Jaeger UI.
+
+## 7. Notes
+
+- When `telemetry.enabled` is `false`, the telemetry module is not loaded at all; there is no performance impact.
+- With `log_messages` set to `true`, full system prompts, user input, and model output are recorded in span events, which can be large; you may disable this in production as needed.
+- W3C TraceContext propagation across WebSockets is supported, so traces stay complete when Gateway and AgentServer are deployed separately.
+
+## 8. Low-intrusion provider extension and third-party integration
+
+For third-party integration, JiuWenClaw exposes a low-intrusion extension on the default OpenTelemetry initialization path:
+
+- Send traces and metrics to different backends
+- Let users supply `service.name`, `protocol`, `endpoint`, and `headers` / tokens
+- Replace provider initialization entirely via an extension point when the default implementation is not enough
+
+### 8.1 Design goals
+
+This behavior follows these principles:
+
+- `OTEL_ENABLED` remains the single master switch for telemetry
+- There are no separate “collect trace / collect metrics” switches—only independent export configuration
+- Whether traces and metrics are actually exported is determined by each exporter being `none` or not
+- The default provider implementation remains available
+- Third parties can take over provider initialization completely via the provider factory extension
+
+### 8.2 Export semantics
+
+This design separates “collection” from “export”:
+
+- When `OTEL_ENABLED=true`, existing instrumentation continues to run
+- Whether traces are actually exported is controlled by `OTEL_TRACES_EXPORTER`
+- Whether metrics are actually exported is controlled by `OTEL_METRICS_EXPORTER`
+
+Example:
+
+```bash
+OTEL_ENABLED=true
+OTEL_TRACES_EXPORTER=otlp
+OTEL_METRICS_EXPORTER=none
+```
+
+Meaning:
+
+- Traces are still collected and exported
+- Metrics are still recorded but not exported to a backend
+
+This allows independent control of trace and metric export without refactoring instrumentation.
+
+### 8.3 Signal-specific configuration
+
+In addition to the shared settings in section 3, trace and metrics can be configured independently.
+
+Shared configuration:
+
+```bash
+OTEL_SERVICE_NAME
+OTEL_EXPORTER_TYPE
+OTEL_EXPORTER_OTLP_ENDPOINT
+OTEL_EXPORTER_OTLP_PROTOCOL
+OTEL_EXPORTER_OTLP_HEADERS
+```
+
+Trace-specific configuration:
+
+```bash
+OTEL_TRACES_EXPORTER
+OTEL_EXPORTER_OTLP_TRACES_ENDPOINT
+OTEL_EXPORTER_OTLP_TRACES_PROTOCOL
+OTEL_EXPORTER_OTLP_TRACES_HEADERS
+```
+
+Metrics-specific configuration:
+
+```bash
+OTEL_METRICS_EXPORTER
+OTEL_EXPORTER_OTLP_METRICS_ENDPOINT
+OTEL_EXPORTER_OTLP_METRICS_PROTOCOL
+OTEL_EXPORTER_OTLP_METRICS_HEADERS
+```
+
+Details:
+
+- `OTEL_EXPORTER_TYPE` still acts as the shared exporter fallback; values are `otlp` / `console` / `none`
+- `OTEL_EXPORTER_OTLP_HEADERS` uses the `k=v,k2=v2` string format
+
+Precedence:
+
+1. Signal-specific environment variables
+2. Shared environment variables
+3. Defaults from `config.yaml`
+
+Examples:
+
+- If `OTEL_TRACES_EXPORTER` is unset, it falls back to `OTEL_EXPORTER_TYPE`
+- If `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` is unset, it falls back to `OTEL_EXPORTER_OTLP_ENDPOINT`
+- If `OTEL_EXPORTER_OTLP_TRACES_HEADERS` is unset, it falls back to `OTEL_EXPORTER_OTLP_HEADERS`
+
+The same applies to metrics.
+
+### 8.4 Provider factory extension
+
+When the default provider logic is insufficient, you can take over initialization with:
+
+```bash
+OTEL_PROVIDER_FACTORY=package.module:function
+```
+
+The function signature is:
+
+```python
+def build_providers() -> ProviderBundle:
+ ...
+```
+
+The return value must include:
+
+```python
+ProviderBundle(
+ tracer_provider=...,
+ meter_provider=...,
+)
+```
+
+Framework behavior:
+
+- If `OTEL_PROVIDER_FACTORY` is unset, the built-in default provider initialization is used
+- If it is set, the framework loads that function dynamically
+- The third-party function reads environment variables and constructs the tracer and meter providers
+- The framework installs the providers and continues to apply instrumentors
+
+### 8.5 Third-party examples
+
+Default provider, traces and metrics to different backends:
+
+```bash
+export OTEL_ENABLED=true
+export OTEL_SERVICE_NAME=my-app
+
+export OTEL_TRACES_EXPORTER=otlp
+export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://trace.example.com
+export OTEL_EXPORTER_OTLP_TRACES_PROTOCOL=http
+export OTEL_EXPORTER_OTLP_TRACES_HEADERS='Authorization=Bearer trace-token'
+
+export OTEL_METRICS_EXPORTER=otlp
+export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://metrics.example.com
+export OTEL_EXPORTER_OTLP_METRICS_PROTOCOL=http
+export OTEL_EXPORTER_OTLP_METRICS_HEADERS='Authorization=Bearer metrics-token'
+```
+
+Export traces only, not metrics:
+
+```bash
+export OTEL_ENABLED=true
+export OTEL_TRACES_EXPORTER=otlp
+export OTEL_METRICS_EXPORTER=none
+```
+
+Custom provider factory:
+
+```bash
+export OTEL_ENABLED=true
+export OTEL_PROVIDER_FACTORY=mycompany.custom_otel:build_providers
+```
+
+Example implementation:
+
+```python
+import os
+
+from jiuwenclaw.telemetry.provider import ProviderBundle
+from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
+from opentelemetry.sdk.metrics import MeterProvider
+from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
+from opentelemetry.sdk.resources import SERVICE_NAME, Resource
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import BatchSpanProcessor
+
+
+def build_providers() -> ProviderBundle:
+ service_name = os.getenv("OTEL_SERVICE_NAME", "my-app")
+ trace_endpoint = os.getenv("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "")
+ metric_endpoint = os.getenv("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT", "")
+
+ trace_token = os.getenv("TRACE_BACKEND_TOKEN", "")
+ metric_token = os.getenv("METRIC_BACKEND_TOKEN", "")
+
+ resource = Resource.create({
+ SERVICE_NAME: service_name,
+ "service.version": os.getenv("APP_VERSION", "unknown"),
+ })
+
+ tracer_provider = TracerProvider(resource=resource)
+ if trace_endpoint:
+ tracer_provider.add_span_processor(
+ BatchSpanProcessor(
+ OTLPSpanExporter(
+ endpoint=f"{trace_endpoint}/v1/traces",
+ headers={"Authorization": f"Bearer {trace_token}"},
+ )
+ )
+ )
+
+ meter_provider = MeterProvider(
+ resource=resource,
+ metric_readers=[
+ PeriodicExportingMetricReader(
+ OTLPMetricExporter(
+ endpoint=f"{metric_endpoint}/v1/metrics",
+ headers={"Authorization": f"Bearer {metric_token}"},
+ ),
+ export_interval_millis=15000,
+ )
+ ],
+ )
+
+ return ProviderBundle(
+ tracer_provider=tracer_provider,
+ meter_provider=meter_provider,
+ )
+```
diff --git a/docs/en/Quickstart.md b/docs/en/Quickstart.md
index c5b4baf29c..64e9cd3488 100644
--- a/docs/en/Quickstart.md
+++ b/docs/en/Quickstart.md
@@ -92,6 +92,7 @@ Static frontend (production build):
```bash
npm run build
cd ../../
+ uv run jiuwenclaw-init
uv run jiuwenclaw-start
```
@@ -99,6 +100,7 @@ Dev mode (dynamic frontend):
```bash
cd ../../
+ uv run jiuwenclaw-init
uv run jiuwenclaw-start dev
```
diff --git a/docs/en/SUMMARY.md b/docs/en/SUMMARY.md
index 302db2f873..c48b0cab15 100644
--- a/docs/en/SUMMARY.md
+++ b/docs/en/SUMMARY.md
@@ -4,6 +4,7 @@
- [Configuration](Configuration.md)
- [User guide](README.md)
- [Channels](Channels.md)
+ - [Discord](Discord.md)
- [WhatsApp](WhatsApp.md)
- [CLI commands](CLI.md)
- [Heartbeat](Heartbeat.md)
diff --git a/docs/en/development-practices/JiuwenClaw-Code-Review-Assistant.md b/docs/en/development-practices/JiuwenClaw-Code-Review-Assistant.md
new file mode 100644
index 0000000000..01131d333b
--- /dev/null
+++ b/docs/en/development-practices/JiuwenClaw-Code-Review-Assistant.md
@@ -0,0 +1,1573 @@
+# Beyond Manual Code Review? Building an Automated Review Pipeline with JiuwenClaw
+
+## Introduction — When “code quality” becomes part of daily development
+
+In team development, code review is a key safeguard for quality. In practice, though:
+
+> After every push, reviewers spend a long time on syntax, style, and security, while the conversations that actually matter get buried.
+
+Code review tends to hit three pain points:
+
+1. **Too much repetition** — Syntax, formatting, and basic security checks are repeated by hand every time.
+2. **Fragmented tooling** — Linters, security scanners, and complexity tools each run in isolation; results are hard to combine.
+3. **No clear metrics** — It is unclear how good the code is; there is no shared score or actionable guidance.
+
+If code review is to improve quality, it needs three capabilities:
+
+1. **Multi-dimensional static analysis** (lint + security + complexity)
+2. **Intelligent scoring and suggestions** (quantified assessment + direction for improvement)
+3. **Multi-channel reporting** (e.g. Feishu notifications + local reports)
+
+This article walks through:
+
+- How to design a layered analysis stack (Ruff + Radon + Bandit)
+- How to implement a composite scoring engine (quality + security + complexity + style)
+- How to build flexible report generators (Markdown reports + Feishu cards)
+- How to support multiple code sources (local scan + Git clone)
+- End-to-end implementation and testing
+
+If you are asking:
+
+- How to move code review from “manual checking” to “intelligent analysis”
+- How to give code quality a quantifiable score
+- How to build an extensible analysis pipeline
+
+the following sections may offer a useful angle.
+
+---
+
+## Project environment
+
+> **This document reflects a real project.** Configuration and code match what was actually used, not placeholder examples.
+
+### Runtime environment
+
+| Item | Value |
+| --- | --- |
+| **Project path** | `D:\Download\jiuwenclaw` |
+| **OS** | Windows 10 |
+| **Python** | 3.10+ |
+| **Model service** | Zhipu AI (GLM-4.7) |
+
+### Analysis tools
+
+| Tool | Version | Purpose | Languages |
+| --- | --- | --- | --- |
+| **Ruff** | 0.4.0+ | Python linting (replaces Pylint/Flake8) | Python |
+| **Radon** | 6.0.0+ | Cyclomatic complexity | Python |
+| **Bandit** | 1.7.0+ | Security scanning | Python |
+| **ESLint** | 9.0+ | Code quality | JavaScript/TypeScript |
+| **Checkstyle** | 10.12+ | Style checks | Java |
+| **golangci-lint** | latest | General Go checks | Go |
+| **Clippy** | latest | Linting | Rust |
+
+### Key file layout
+
+```plain
+D:\Download\jiuwenclaw\
+├── .env # Environment variables
+├── workspace/
+│ └── agent/
+│ ├── reports/code-review/ # Review report output
+│ └── skills/code-review/ # Skill module
+│ ├── SKILL.md # Skill definition v2.0.1
+│ ├── config.py # Configuration
+│ ├── run_review.py # Entry script
+│ ├── models/ # Data models
+│ ├── collectors/ # Code collection
+│ ├── analyzers/ # Analysis engine
+│ └── generators/ # Report generation
+```
+
+## 1. Problem background
+
+### 1.1 Limits of traditional code review
+
+When people say “code review,” they often mean:
+
+> “Isn’t that just PR review — checking correctness and formatting?”
+
+For simple cases, manual review is enough.
+
+In real projects you quickly run into three issues:
+
+1. **Low efficiency**
+ Every review re-checks basics: unused imports, hard-coded secrets, oversized functions — work tools should automate.
+
+2. **Inconsistent standards**
+ Different reviewers care about different things; there is no shared, quantitative bar.
+
+3. **Easy to miss issues**
+ Vulnerabilities such as SQL injection or command injection usually need tooling; manual review misses them often.
+
+Example: fifteen functions, three with complexity over 20 (grade D), two with possible SQL injection — hard to catch everything in one pass.
+
+The **code review assistant** runs three complementary analyzers, feeds a scoring engine, and produces a report with issues and suggestions.
+
+### 1.2 Pain points for developers
+
+Typical quality workflows force you to **run many tools before each commit**: Flake8, Pylint, Bandit — each with its own output format to merge by hand.
+
+Another gap: **you do not know how good the code really is**. Fifty warnings appear — how serious are they? What is the overall quality?
+
+The worst misses are **security issues**: e.g. `os.system(user_input)` overlooked in review but exploitable in production.
+
+With the assistant, Ruff (lint), Radon (complexity), and Bandit (security) run automatically; the engine computes quality, security, complexity, and style scores and returns an overall grade with suggestions.
+
+### 1.3 Why JiuwenClaw’s skill system fits
+
+JiuwenClaw is an open Agent framework; its skill model fits code review tooling:
+
+| Capability | Description |
+| --- | --- |
+| **Modular skills** | Each skill can bundle multiple Python modules for clean layering |
+| **Tool integration** | `allowed_tools` grants access to system tools and external commands |
+| **File I/O** | Read/write files for scanning and report generation |
+| **Multi-channel delivery** | e.g. Feishu for review summaries |
+
+The main idea is **composability**: collection, static analysis, and reporting are separated with clear boundaries.
+
+## 2. Technical approach
+
+### 2.1 Layered architecture
+
+The code review skill lives in JiuwenClaw’s application layer and uses a classic three-tier layout:
+
+```
+┌─────────────────────────────────────────────────────────┐
+│ Application Layer │
+│ (code-review skill) │
+├─────────────────────────────────────────────────────────┤
+│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
+│ │ Collectors │→ │ Analyzers │→ │ Generators │ │
+│ │ Collection │ │ Analysis │ │ Reports │ │
+│ └─────────────┘ └─────────────┘ └─────────────┘ │
+│ │ │ │ │
+│ LocalCollector RuffAnalyzer ReportGenerator │
+│ AtomGitClient RadonAnalyzer FeishuPublisher │
+│ BanditAnalyzer │
+│ ScoreCalculator │
+└─────────────────────────────────────────────────────────┘
+```
+
+### 2.2 Data flow
+
+End-to-end review flow:
+
+```
+User / conversation triggers: review code
+ │
+ ▼
+┌──────────────────┐
+│ COLLECTORS │ Code collection
+│ LocalCollector │ Local directory scan
+│ AtomGitClient │ Git clone
+└────────┬─────────┘
+ │
+ ▼
+┌──────────────────┐
+│ ANALYZERS │ Multi-dimensional analysis
+│ RuffAnalyzer │ Lint → lint_issues
+│ RadonAnalyzer │ Complexity → complexity_issues
+│ BanditAnalyzer │ Security → security_issues
+│ ScoreCalculator │ Scoring → ReviewScore
+└────────┬─────────┘
+ │
+ ▼
+┌──────────────────┐
+│ GENERATORS │ Reporting
+│ ReportGenerator │ Markdown report
+│ FeishuPublisher │ Feishu card
+└────────┬─────────┘
+ │
+ ▼
+┌──────────────────┐
+│ OUTPUT │
+│ Local .md file │
+│ Feishu card │
+└──────────────────┘
+```
+
+### 2.3 Core components
+
+| Component | Type | Role | Module |
+| --- | --- | --- | --- |
+| **LocalCollector** | Collector | Local file collection | `collectors/local_collector.py` |
+| **AtomGitClient** | Collector | Git clone and file access | `collectors/atomgit_client.py` |
+| **RuffAnalyzer** | Analyzer | Lint | `analyzers/ruff_analyzer.py` |
+| **RadonAnalyzer** | Analyzer | Complexity | `analyzers/radon_analyzer.py` |
+| **BanditAnalyzer** | Analyzer | Security | `analyzers/bandit_analyzer.py` |
+| **ScoreCalculator** | Analyzer | Composite score | `analyzers/score_calculator.py` |
+| **ReportGenerator** | Generator | Markdown reports | `generators/report_generator.py` |
+| **FeishuPublisher** | Generator | Feishu delivery | `generators/feishu_publisher.py` |
+
+### 2.4 Scoring model
+
+Weighted multi-dimensional scoring:
+
+| Dimension | Weight | Basis |
+| --- | --- | --- |
+| **Code quality** | 35% | Lint issue count and severity |
+| **Security** | 30% | Security findings and severity |
+| **Complexity** | 20% | Cyclomatic complexity and high-complexity functions |
+| **Style** | 15% | Style issues |
+
+Overall score maps to grades:
+
+| Grade | Range | Meaning |
+| --- | --- | --- |
+| A | 90–100 | Excellent |
+| B | 80–89 | Good |
+| C | 70–79 | Acceptable |
+| D | 60–69 | Needs improvement |
+| F | Below 60 | Fail |
+
+## Chapter 3 — Engineering the Skills layout
+
+### 3.1 Directory structure
+
+```plain
+workspace/agent/skills/code-review/
+├── SKILL.md # Skill definition (required)
+├── config.py # Configuration
+├── run_review.py # Entry script
+│
+├── models/ # Data models
+│ ├── __init__.py
+│ ├── code_issue.py
+│ ├── code_metrics.py
+│ ├── review_result.py
+│ └── review_score.py
+│
+├── collectors/ # Collection layer
+│ ├── __init__.py
+│ ├── local_collector.py
+│ └── atomgit_client.py
+│
+├── analyzers/ # Analysis layer
+│ ├── __init__.py
+│ ├── ruff_analyzer.py
+│ ├── radon_analyzer.py
+│ ├── bandit_analyzer.py
+│ ├── ast_analyzer.py
+│ └── score_calculator.py
+│
+└── generators/ # Report layer
+ ├── __init__.py
+ ├── report_generator.py
+ └── feishu_publisher.py
+```
+
+### 3.2 SKILL.md definition (v2.0.1)
+
+```markdown
+---
+name: code-review
+version: 2.0.1
+description: Multi-language code review assistant for Python/JavaScript/Java/Go/Rust; quality, security, and complexity
+tags: [code, review, python, javascript, typescript, java, go, rust, quality, security]
+allowed_tools: [mcp_exec_command, read_file, write_file]
+---
+
+# Multi-language code review assistant
+
+Review code in arbitrary Git repositories across multiple languages; detect security, quality, and complexity issues.
+
+## Supported languages
+
+| Language | Lint | Security | Complexity |
+|----------|------|----------|------------|
+| **Python** | Ruff | Bandit | Radon |
+| **JavaScript/TypeScript** | ESLint | eslint-plugin-security | — |
+| **Java** | Checkstyle | — | — |
+| **Go** | golangci-lint | gosec | gocyclo |
+| **Rust** | Clippy | cargo-audit | — |
+
+## Usage
+
+### Review a remote Git repository
+
+```bash
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/code-review/run_review.py clone --url <repo-url>
+```
+
+### Review local code
+
+```bash
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/code-review/run_review.py local --path <path>
+```
+
+## Important limits
+
+**Do not read and return the full report file.**
+
+Large repositories can produce tens of thousands of lines, which can:
+
+- Exceed WebSocket message size (1MB limit)
+- Fail to send, so the user sees nothing
+
+**Correct approach:**
+
+1. Extract a summary from command output
+2. Return a short Feishu-friendly summary
+3. Tell the user the detailed report was saved
+
+## Feishu-friendly summary format
+
+```
+📊 Code review report
+
+━━━━━━━━━━━━━━━━━━━━━━
+📦 Repo: <name>
+📁 Files scanned: <count>
+⏰ Review time: <time>
+━━━━━━━━━━━━━━━━━━━━━━
+
+📋 Issue summary
+
+🔴 Errors: <count>
+🟡 Warnings: <count>
+🔵 Info: <count>
+
+💡 Suggestions
+
+1. <suggestion 1>
+2. <suggestion 2>
+
+━━━━━━━━━━━━━━━━━━━━━━
+📄 Full report saved
+```
+
+## Score grades
+
+| Grade | Score | Status | Icon |
+|-------|-------|--------|------|
+| A | 90-100 | Excellent | 🟢 |
+| B | 80-89 | Good | 🔵 |
+| C | 70-79 | Acceptable | 🟡 |
+| D | 60-69 | Needs work | 🟠 |
+| F | Below 60 | Fail | 🔴 |
+```
+
+### 3.3 Report template example
+
+```markdown
+# :white_check_mark: Code review report
+
+| Field | Value |
+|-------|-------|
+| Review type | clone |
+| Target | `owner/repo` |
+| Review time | 2026-03-08 10:30 |
+| Files scanned | 25 |
+
+## Scores
+
+| Dimension | Score |
+|-----------|-------|
+| **Overall** | **72.5** (C) |
+| Code quality | 65.0 |
+| Security | 80.0 |
+| Complexity | 85.0 |
+| Style | 70.0 |
+
+**Status**: Pass
+
+## Issue summary
+
+- Total: **45** issues
+- Errors: 3
+- Warnings: 28
+- Info: 14
+
+## Issue details
+
+### Security (5)
+
+- `app.py:42` [B608] Possible SQL injection vector
+ > SQL injection risk
+
+### Code quality (32)
+
+- `utils.py:15` [F401] `os` imported but unused
+ > Remove unused import
+
+### Complexity (8)
+
+- `service.py:120` [CD] Function 'process_data' complexity too high (23, grade D)
+ > Refactor strongly recommended: split into smaller functions
+
+## Suggestions
+
+1. Three high-severity security issues — prioritize fixes
+2. Five high-complexity functions — consider refactoring
+3. Fix three error-level issues
+
+---
+*Report generated at: 2026-03-08 10:30:15*
+```
+
+## Chapter 4 — Data models
+
+### 4.1 `CodeIssue` (`models/code_issue.py`)
+
+```python
+# models/code_issue.py
+# -*- coding: utf-8 -*-
+"""
+Code issue model
+
+Represents a single issue with location, severity, category, etc.
+"""
+
+from dataclasses import dataclass
+from typing import Optional
+
+
+@dataclass
+class CodeIssue:
+ """A single code issue."""
+
+ file: str # File path
+ line: int # Line number
+ severity: str # error / warning / info
+ category: str # lint / complexity / security / style
+ message: str # Description
+ rule: str # Rule id (e.g. E501, B101)
+ source: str # Tool (ruff / bandit / radon)
+ column: int = 0
+ suggestion: str = "" # Fix suggestion
+
+ def to_dict(self) -> dict:
+ return {
+ "file": self.file,
+ "line": self.line,
+ "column": self.column,
+ "severity": self.severity,
+ "category": self.category,
+ "message": self.message,
+ "rule": self.rule,
+ "source": self.source,
+ "suggestion": self.suggestion,
+ }
+
+ def __str__(self) -> str:
+ location = f"{self.file}:{self.line}"
+ return f"[{self.rule}] {location} - {self.message}"
+```
+
+### 4.2 `CodeMetrics` (`models/code_metrics.py`)
+
+```python
+# models/code_metrics.py
+# -*- coding: utf-8 -*-
+"""
+Code metrics model
+
+Line counts, function counts, complexity, etc.
+"""
+
+from dataclasses import dataclass
+
+
+@dataclass
+class CodeMetrics:
+ """Aggregated code metrics."""
+
+ total_lines: int = 0
+ code_lines: int = 0
+ comment_lines: int = 0
+ blank_lines: int = 0
+
+ avg_complexity: float = 0.0
+ max_complexity: int = 0
+ complexity_rank: str = "A"
+ high_complexity_count: int = 0
+
+ maintainability_index: float = 0.0
+ maintainability_rank: str = "A"
+
+ function_count: int = 0
+ class_count: int = 0
+ file_count: int = 0
+
+ def to_dict(self) -> dict:
+ return {
+ "total_lines": self.total_lines,
+ "code_lines": self.code_lines,
+ "comment_lines": self.comment_lines,
+ "avg_complexity": round(self.avg_complexity, 2),
+ "max_complexity": self.max_complexity,
+ "complexity_rank": self.complexity_rank,
+ "high_complexity_count": self.high_complexity_count,
+ "function_count": self.function_count,
+ "class_count": self.class_count,
+ "file_count": self.file_count,
+ }
+```
+
+### 4.3 `ReviewScore` (`models/review_score.py`)
+
+```python
+# models/review_score.py
+# -*- coding: utf-8 -*-
+"""
+Review score model
+
+Multi-dimensional scores and grade mapping.
+"""
+
+from dataclasses import dataclass
+
+
+@dataclass
+class ReviewScore:
+ """Scores for a review run."""
+
+ overall: float = 0.0 # Overall 0–100
+ quality_score: float = 0.0
+ security_score: float = 0.0
+ complexity_score: float = 0.0
+ style_score: float = 0.0
+
+ grade: str = "C" # A/B/C/D/F
+ passed: bool = False
+
+ @staticmethod
+ def score_to_grade(score: float) -> str:
+ if score >= 90:
+ return "A"
+ elif score >= 80:
+ return "B"
+ elif score >= 70:
+ return "C"
+ elif score >= 60:
+ return "D"
+ else:
+ return "F"
+
+ def to_dict(self) -> dict:
+ return {
+ "overall": round(self.overall, 1),
+ "quality_score": round(self.quality_score, 1),
+ "security_score": round(self.security_score, 1),
+ "complexity_score": round(self.complexity_score, 1),
+ "style_score": round(self.style_score, 1),
+ "grade": self.grade,
+ "passed": self.passed,
+ }
+```
+
+## Chapter 5 — Analysis engine
+
+### 5.1 Ruff analyzer
+
+```python
+# analyzers/ruff_analyzer.py
+# -*- coding: utf-8 -*-
+"""
+Ruff lint analyzer
+
+Uses Ruff for quality checks — typically 10–100× faster than Pylint/Flake8.
+"""
+
+import json
+import subprocess
+from pathlib import Path
+from typing import List, Optional
+
+try:
+ from ..models import CodeIssue
+except ImportError:
+ import sys
+ sys.path.insert(0, str(Path(__file__).parent.parent))
+ from models import CodeIssue
+
+
+class RuffAnalyzer:
+ """Ruff-based lint analyzer."""
+
+ def __init__(self, config: Optional[dict] = None):
+ self.config = config or {}
+
+ def analyze_code(self, code: str, filename: str = "temp.py") -> List[CodeIssue]:
+ """
+ Analyze a code string.
+
+ Uses stdin to avoid temp files. On Windows, pass bytes to avoid GBK issues.
+ """
+ try:
+ result = subprocess.run(
+ ["ruff", "check", "--output-format", "json",
+ "--stdin-filename", filename, "-"],
+ input=code.encode("utf-8"),
+ capture_output=True,
+ timeout=30,
+ )
+ return self._parse_output(
+ result.stdout.decode("utf-8", errors="replace"),
+ filename
+ )
+ except subprocess.TimeoutExpired:
+ return [CodeIssue(
+ file=filename, line=0, severity="error",
+ category="lint", message="Ruff analysis timed out",
+ rule="TIMEOUT", source="ruff"
+ )]
+ except FileNotFoundError:
+ return [CodeIssue(
+ file=filename, line=0, severity="warning",
+ category="lint", message="Ruff not installed; run: pip install ruff",
+ rule="MISSING", source="ruff"
+ )]
+
+ def analyze_directory(self, dirpath: str,
+ exclude_patterns: Optional[List[str]] = None) -> List[CodeIssue]:
+ """Analyze all Python files under a directory."""
+ path = Path(dirpath)
+ if not path.exists():
+ return []
+
+ exclude_args = []
+ if exclude_patterns:
+ for pattern in exclude_patterns:
+ exclude_args.extend(["--exclude", pattern])
+
+ cmd = ["ruff", "check", "--output-format", "json", str(path)]
+ cmd.extend(exclude_args)
+
+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
+ return self._parse_output(result.stdout, str(path))
+
+ def _parse_output(self, output: str, default_file: str = "") -> List[CodeIssue]:
+ issues = []
+ if not output.strip():
+ return issues
+
+ try:
+ data = json.loads(output)
+ except json.JSONDecodeError:
+ return issues
+
+ for item in data:
+ location = item.get("location", {})
+ issues.append(CodeIssue(
+ file=item.get("filename", default_file),
+ line=location.get("row", 0),
+ column=location.get("column", 0),
+ severity=self._map_severity(item.get("severity", "warning")),
+ category="lint",
+ message=item.get("message", ""),
+ rule=item.get("code", ""),
+ source="ruff",
+ suggestion=self._get_suggestion(item.get("code", ""), item.get("message", "")),
+ ))
+ return issues
+
+ def _map_severity(self, ruff_severity: str) -> str:
+ severity_map = {
+ "error": "error", "warning": "warning", "info": "info",
+ "fatal": "error", "convention": "info", "refactor": "info",
+ }
+ return severity_map.get(ruff_severity.lower(), "warning")
+
+ def _get_suggestion(self, rule: str, message: str) -> str:
+ suggestions = {
+ "E501": "Break long lines into multiple lines using parentheses or backslash",
+ "F401": "Remove unused imports",
+ "F841": "Remove unused variables",
+ "E711": "Use 'is None' instead of '== None'",
+ "E722": "Catch specific exceptions instead of bare except",
+ }
+ return suggestions.get(rule, "")
+```
+
+### 5.2 Radon complexity analyzer
+
+```python
+# analyzers/radon_analyzer.py
+# -*- coding: utf-8 -*-
+"""
+Radon complexity analyzer
+
+CC, raw metrics, maintainability index (MI).
+"""
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import List, Optional
+
+try:
+ from radon.complexity import cc_rank, cc_visit
+ from radon.metrics import mi_visit
+ from radon.raw import analyze as raw_analyze
+ RADON_AVAILABLE = True
+except ImportError:
+ RADON_AVAILABLE = False
+ cc_rank = cc_visit = mi_visit = raw_analyze = None
+
+try:
+ from ..models import CodeIssue, CodeMetrics
+except ImportError:
+ import sys
+ sys.path.insert(0, str(Path(__file__).parent.parent))
+ from models import CodeIssue, CodeMetrics
+
+
+@dataclass
+class ComplexityResult:
+ """Single complexity result."""
+ name: str
+ type: str # function / method / class
+ complexity: int
+ rank: str # A–F
+ line: int
+ file: str = ""
+ classname: str = ""
+
+
+class RadonAnalyzer:
+ """Radon-based complexity analyzer."""
+
+ COMPLEXITY_THRESHOLDS = {
+ "A": (1, 5),
+ "B": (6, 10),
+ "C": (11, 20),
+ "D": (21, 30),
+ "E": (31, 40),
+ "F": (41, 100),
+ }
+
+ def __init__(self, config: Optional[dict] = None):
+ self.config = config or {}
+ self.max_complexity = self.config.get("max_complexity", 10)
+
+ def analyze_complexity(self, code: str, filename: str = "") -> List[ComplexityResult]:
+ if not RADON_AVAILABLE:
+ return []
+
+ results = []
+ try:
+ cc_results = cc_visit(code)
+ for item in cc_results:
+ complexity = item.complexity
+ rank = cc_rank(complexity)
+ results.append(ComplexityResult(
+ name=item.name,
+ type="method" if item.is_method else "function",
+ complexity=complexity,
+ rank=rank,
+ line=item.lineno,
+ file=filename,
+ classname=item.classname or "",
+ ))
+ except Exception:
+ pass
+ return results
+
+ def analyze_metrics(self, code: str) -> CodeMetrics:
+ metrics = CodeMetrics()
+ if not RADON_AVAILABLE:
+ return metrics
+
+ try:
+ raw = raw_analyze(code)
+ metrics.total_lines = raw.loc
+ metrics.code_lines = raw.sloc
+ metrics.comment_lines = raw.comments
+ metrics.blank_lines = raw.blank
+
+ mi = mi_visit(code, True)
+ if isinstance(mi, (int, float)):
+ metrics.maintainability_index = mi
+ metrics.maintainability_rank = self._mi_to_rank(mi)
+ except Exception:
+ pass
+ return metrics
+
+ def get_high_complexity_issues(self, complexity_results: List[ComplexityResult]) -> List[CodeIssue]:
+ issues = []
+ for result in complexity_results:
+ if result.complexity > self.max_complexity:
+ severity = "error" if result.rank in ["D", "E", "F"] else "warning"
+ issues.append(CodeIssue(
+ file=result.file,
+ line=result.line,
+ severity=severity,
+ category="complexity",
+ message=f"Function '{result.name}' complexity too high ({result.complexity}, rank {result.rank})",
+ rule=f"C{result.rank}",
+ source="radon",
+ suggestion=self._get_complexity_suggestion(result),
+ ))
+ return issues
+
+ def _get_complexity_suggestion(self, result: ComplexityResult) -> str:
+ suggestions = {
+ "C": "Consider splitting the function to reduce branches",
+ "D": "Refactor strongly: split into smaller functions",
+ "E": "Must refactor — hard to maintain and test",
+ "F": "Must refactor immediately — nearly unmaintainable",
+ }
+ return suggestions.get(result.rank, "Consider reducing function complexity")
+```
+
+### 5.3 Bandit security analyzer
+
+```python
+# analyzers/bandit_analyzer.py
+# -*- coding: utf-8 -*-
+"""
+Bandit security analyzer
+
+Detects SQL injection, command injection, hard-coded secrets, weak crypto, etc.
+"""
+
+import json
+import os
+import subprocess
+import tempfile
+from pathlib import Path
+from typing import List, Optional
+
+try:
+ from ..models import CodeIssue
+except ImportError:
+ import sys
+ sys.path.insert(0, str(Path(__file__).parent.parent))
+ from models import CodeIssue
+
+
+class BanditAnalyzer:
+ """Bandit-based security analyzer."""
+
+ SECURITY_SUGGESTIONS = {
+ "B101": "assert may be stripped in optimized mode",
+ "B105": "Possible hard-coded password string",
+ "B110": "try/except catches all exceptions",
+ "B303": "Insecure hash (MD5/SHA1)",
+ "B311": "random not suitable for crypto",
+ "B324": "Certificate not verified",
+ "B404": "subprocess usage may be unsafe",
+ "B501": "requests without verifying certificate",
+ "B506": "Unsafe YAML load",
+ "B601": "subprocess command injection risk",
+ "B603": "subprocess command injection risk",
+ "B605": "os.system command injection risk",
+ "B606": "os.popen command injection risk",
+ "B608": "Possible SQL injection",
+ }
+
+ def __init__(self, config: Optional[dict] = None):
+ self.config = config or {}
+
+ def analyze_code(self, code: str, filename: str = "temp.py") -> List[CodeIssue]:
+ """Bandit has no stdin support — use a temp file."""
+ with tempfile.NamedTemporaryFile(
+ mode="w", suffix=".py", delete=False, encoding="utf-8"
+ ) as f:
+ f.write(code)
+ temp_path = f.name
+
+ try:
+ return self.analyze_file(temp_path, display_filename=filename)
+ finally:
+ try:
+ os.unlink(temp_path)
+ except OSError:
+ pass
+
+ def analyze_file(self, filepath: str, display_filename: Optional[str] = None) -> List[CodeIssue]:
+ path = Path(filepath)
+ if not path.exists():
+ return [CodeIssue(
+ file=filepath, line=0, severity="error",
+ category="security", message=f"File not found: {filepath}",
+ rule="NOT_FOUND", source="bandit"
+ )]
+
+ try:
+ result = subprocess.run(
+ ["bandit", "-f", "json", "-r", str(path)],
+ capture_output=True, text=True, timeout=60
+ )
+ return self._parse_output(result.stdout, display_filename or str(path))
+ except FileNotFoundError:
+ return [CodeIssue(
+ file=filepath, line=0, severity="warning",
+ category="security", message="Bandit not installed; run: pip install bandit",
+ rule="MISSING", source="bandit"
+ )]
+
+ def _parse_output(self, output: str, default_file: str = "") -> List[CodeIssue]:
+ issues = []
+ if not output.strip():
+ return issues
+
+ try:
+ data = json.loads(output)
+ except json.JSONDecodeError:
+ return issues
+
+ for item in data.get("results", []):
+ test_id = item.get("test_id", "")
+ issues.append(CodeIssue(
+ file=item.get("filename", default_file),
+ line=item.get("line_number", 0),
+ severity=self._map_severity(item.get("issue_severity", "MEDIUM")),
+ category="security",
+ message=item.get("issue_text", ""),
+ rule=test_id,
+ source="bandit",
+ suggestion=self.SECURITY_SUGGESTIONS.get(test_id, ""),
+ ))
+ return issues
+
+ def _map_severity(self, bandit_severity: str) -> str:
+ severity_map = {"HIGH": "error", "MEDIUM": "warning", "LOW": "info"}
+ return severity_map.get(bandit_severity.upper(), "warning")
+```
+
+### 5.4 Score calculator
+
+```python
+# analyzers/score_calculator.py
+# -*- coding: utf-8 -*-
+"""
+Composite score calculator
+
+Weighted multi-dimensional scoring from collected issues.
+"""
+
+from dataclasses import dataclass
+from typing import List, Optional
+
+try:
+ from ..models import CodeIssue, CodeMetrics, ReviewResult, ReviewScore
+except ImportError:
+ import sys
+ from pathlib import Path
+ sys.path.insert(0, str(Path(__file__).parent.parent))
+ from models import CodeIssue, CodeMetrics, ReviewResult, ReviewScore
+
+
+@dataclass
+class ScoringWeights:
+ quality: float = 0.35
+ security: float = 0.30
+ complexity: float = 0.20
+ style: float = 0.15
+
+
+class ScoreCalculator:
+ """Computes ReviewScore from a ReviewResult."""
+
+ DEFAULT_WEIGHTS = ScoringWeights()
+
+ SEVERITY_PENALTY = {
+ "error": 5.0,
+ "warning": 2.0,
+ "info": 0.5,
+ }
+
+ def __init__(self, config: Optional[dict] = None):
+ self.config = config or {}
+ self.pass_threshold = self.config.get("pass_threshold", 60.0)
+ self.max_complexity = self.config.get("max_complexity", 10)
+ self.weights = self.config.get("weights", self.DEFAULT_WEIGHTS)
+
+ def calculate(self, result: ReviewResult) -> ReviewScore:
+ score = ReviewScore()
+
+ score.quality_score = self._calc_quality_score(result.lint_issues)
+ score.security_score = self._calc_security_score(result.security_issues)
+ score.complexity_score = self._calc_complexity_score(result.metrics)
+ score.style_score = self._calc_style_score(result.style_issues)
+
+ score.overall = (
+ score.quality_score * self.weights.quality +
+ score.security_score * self.weights.security +
+ score.complexity_score * self.weights.complexity +
+ score.style_score * self.weights.style
+ )
+
+ score.grade = ReviewScore.score_to_grade(score.overall)
+ score.passed = score.overall >= self.pass_threshold
+
+ return score
+
+ def _calc_quality_score(self, issues: List[CodeIssue]) -> float:
+ score = 100.0
+ for issue in issues:
+ penalty = self.SEVERITY_PENALTY.get(issue.severity, 1.0)
+ score -= penalty
+ return max(0.0, min(100.0, score))
+
+ def _calc_security_score(self, issues: List[CodeIssue]) -> float:
+ score = 100.0
+ severity_multiplier = {"error": 15.0, "warning": 8.0, "info": 2.0}
+
+ for issue in issues:
+ base_penalty = self.SEVERITY_PENALTY.get(issue.severity, 1.0)
+ multiplier = severity_multiplier.get(issue.severity, 1.0)
+ score -= base_penalty * (multiplier / 5)
+
+ has_critical = any(i.severity == "error" for i in issues)
+ min_score = 20.0 if has_critical else 0.0
+ return max(min_score, min(100.0, score))
+
+ def _calc_complexity_score(self, metrics: CodeMetrics) -> float:
+ score = 100.0
+
+ if metrics.avg_complexity > 5:
+ score -= (metrics.avg_complexity - 5) * 5
+ if metrics.high_complexity_count > 0:
+ score -= metrics.high_complexity_count * 3
+
+ return max(0.0, min(100.0, score))
+
+ def _calc_style_score(self, issues: List[CodeIssue]) -> float:
+ score = 100.0
+ for issue in issues:
+ penalty = self.SEVERITY_PENALTY.get(issue.severity, 1.0)
+ score -= penalty * 0.5
+ return max(0.0, min(100.0, score))
+
+ def get_improvement_suggestions(self, result: ReviewResult) -> List[str]:
+ suggestions = []
+
+ if result.score.quality_score < 70:
+ suggestions.append("Code quality is low; fix lint errors and warnings first")
+
+ if result.score.security_score < 70:
+ critical = [i for i in result.security_issues if i.severity == "error"]
+ if critical:
+ suggestions.append(f"{len(critical)} high-severity security issues — prioritize fixes")
+
+ if result.score.complexity_score < 70:
+ if result.metrics.high_complexity_count > 0:
+ suggestions.append(
+ f"{result.metrics.high_complexity_count} high-complexity functions — consider splitting"
+ )
+
+ if result.errors > 0:
+ suggestions.append(f"Fix {result.errors} error-level issues")
+
+ if result.score.overall >= 90:
+ suggestions.append("Excellent code quality — keep it up")
+
+ return suggestions[:5]
+```
+
+## Chapter 6 — Collection and report generation
+
+### 6.1 Local collector
+
+```python
+# collectors/local_collector.py
+# -*- coding: utf-8 -*-
+"""
+Local code collector
+
+Scans a directory and collects Python files.
+"""
+
+import fnmatch
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import List, Optional
+
+
+@dataclass
+class FileInfo:
+ path: str
+ relative_path: str
+ size: int
+
+ def to_dict(self) -> dict:
+ return {
+ "path": self.path,
+ "relative_path": self.relative_path,
+ "size": self.size,
+ }
+
+
+@dataclass
+class ScanResult:
+ files: List[FileInfo] = field(default_factory=list)
+ total_files: int = 0
+ total_size: int = 0
+ errors: List[str] = field(default_factory=list)
+
+
+class LocalCollector:
+ """Collects Python files from a local tree."""
+
+ DEFAULT_EXCLUDES = [
+ "**/test_*.py",
+ "**/*_test.py",
+ "**/tests/**",
+ "**/venv/**",
+ "**/.venv/**",
+ "**/__pycache__/**",
+ "**/node_modules/**",
+ "**/.git/**",
+ ]
+
+ def __init__(
+ self,
+ path: str,
+ exclude_patterns: Optional[List[str]] = None,
+ max_file_size: int = 1024 * 1024,
+ ):
+ self.path = Path(path).resolve()
+ self.exclude_patterns = exclude_patterns or self.DEFAULT_EXCLUDES
+ self.max_file_size = max_file_size
+
+ def collect(self) -> ScanResult:
+ result = ScanResult()
+
+ if not self.path.exists():
+ result.errors.append(f"Path does not exist: {self.path}")
+ return result
+
+ for py_file in self.path.rglob("*.py"):
+ if self._should_exclude(py_file):
+ continue
+
+ size = py_file.stat().st_size
+ if size > self.max_file_size:
+ continue
+
+ result.files.append(FileInfo(
+ path=str(py_file),
+ relative_path=str(py_file.relative_to(self.path)),
+ size=size,
+ ))
+ result.total_size += size
+
+ result.total_files = len(result.files)
+ return result
+
+ def get_file_content(self, filepath: str) -> Optional[str]:
+ try:
+ return Path(filepath).read_text(encoding="utf-8")
+ except Exception:
+ return None
+
+ def _should_exclude(self, filepath: Path) -> bool:
+ for pattern in self.exclude_patterns:
+ if fnmatch.fnmatch(str(filepath), pattern):
+ return True
+ if fnmatch.fnmatch(filepath.name, pattern):
+ return True
+ return False
+```
+
+### 6.2 Git clone flow (`run_review.py`)
+
+```python
+def review_clone(repo_url: str, config: CodeReviewConfig, branch: str = "main") -> ReviewResult:
+ """
+ Clone a Git repository and run the review.
+
+ Works with any remote (AtomGit, GitHub, Gitee, etc.).
+ """
+ import shutil
+ import subprocess
+ import tempfile
+
+ parsed = parse_repo_url(repo_url)
+ repo_name = f"{parsed[0]}/{parsed[1]}" if parsed[0] and parsed[1] else repo_url
+
+ result = ReviewResult(review_type="clone", target=repo_name)
+
+ temp_dir = tempfile.mkdtemp(prefix="code_review_")
+
+ try:
+ clone_cmd = [
+ "git", "clone",
+ "--depth", "1",
+ "--branch", branch,
+ "--single-branch",
+ repo_url,
+ temp_dir
+ ]
+
+ proc = subprocess.run(clone_cmd, capture_output=True, text=True, timeout=300)
+
+ if proc.returncode != 0:
+ clone_cmd = ["git", "clone", "--depth", "1", repo_url, temp_dir]
+ proc = subprocess.run(clone_cmd, capture_output=True, text=True, timeout=300)
+
+ if proc.returncode != 0:
+ result.suggestions = [f"Clone failed: {proc.stderr}"]
+ return result
+
+ scan_result = review_local(temp_dir, config)
+ scan_result.review_type = "clone"
+ scan_result.target = repo_name
+ return scan_result
+
+ except subprocess.TimeoutExpired:
+ result.suggestions = ["Clone timed out — repository may be too large"]
+ return result
+ finally:
+ try:
+ shutil.rmtree(temp_dir)
+ except Exception:
+ pass
+```
+
+### 6.3 Report generator
+
+```python
+# generators/report_generator.py
+# -*- coding: utf-8 -*-
+"""
+Markdown report generator for code review results.
+"""
+
+from datetime import datetime
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from ..models import ReviewResult
+
+
+class ReportGenerator:
+ def __init__(self, output_dir: str = "workspace/agent/reports/code-review"):
+ self.output_dir = Path(output_dir)
+ self.output_dir.mkdir(parents=True, exist_ok=True)
+
+ def generate(self, result: "ReviewResult") -> str:
+ lines = []
+
+ icon = ":white_check_mark:" if result.score.passed else ":x:"
+ lines.append(f"# {icon} Code review report")
+ lines.append("")
+
+ lines.append("| Field | Value |")
+ lines.append("|------|-----|")
+ lines.append(f"| Review type | {result.review_type} |")
+ lines.append(f"| Target | `{result.target}` |")
+ lines.append(f"| Review time | {result.reviewed_at.strftime('%Y-%m-%d %H:%M')} |")
+ lines.append(f"| Files scanned | {result.files_scanned} |")
+ lines.append("")
+
+ lines.append("## Scores")
+ lines.append("")
+ lines.append("| Dimension | Score |")
+ lines.append("|------|------|")
+ lines.append(f"| **Overall** | **{result.score.overall:.1f}** ({result.score.grade}) |")
+ lines.append(f"| Code quality | {result.score.quality_score:.1f} |")
+ lines.append(f"| Security | {result.score.security_score:.1f} |")
+ lines.append(f"| Complexity | {result.score.complexity_score:.1f} |")
+ lines.append(f"| Style | {result.score.style_score:.1f} |")
+ lines.append("")
+ lines.append(f"**Status**: {'Pass' if result.score.passed else 'Fail'}")
+ lines.append("")
+
+ lines.append("## Issue summary")
+ lines.append("")
+ lines.append(f"- Total: **{result.total_issues}** issues")
+ lines.append(f"- Errors: {result.errors}")
+ lines.append(f"- Warnings: {result.warnings}")
+ lines.append(f"- Info: {result.infos}")
+ lines.append("")
+
+ lines.append("## Issue details")
+ lines.append("")
+
+ if result.total_issues == 0:
+ lines.append("No issues found.")
+ else:
+ if result.security_issues:
+ lines.append(f"### Security ({len(result.security_issues)})")
+ lines.append("")
+ for issue in result.security_issues[:10]:
+ lines.append(f"- `{issue.file}:{issue.line}` [{issue.rule}] {issue.message}")
+ if issue.suggestion:
+ lines.append(f" > {issue.suggestion}")
+ if len(result.security_issues) > 10:
+ lines.append(f"- ... and {len(result.security_issues) - 10} more")
+ lines.append("")
+
+ if result.lint_issues:
+ lines.append(f"### Code quality ({len(result.lint_issues)})")
+ lines.append("")
+ for issue in result.lint_issues[:10]:
+ lines.append(f"- `{issue.file}:{issue.line}` [{issue.rule}] {issue.message}")
+ if issue.suggestion:
+ lines.append(f" > {issue.suggestion}")
+ if len(result.lint_issues) > 10:
+ lines.append(f"- ... and {len(result.lint_issues) - 10} more")
+ lines.append("")
+
+ if result.complexity_issues:
+ lines.append(f"### Complexity ({len(result.complexity_issues)})")
+ lines.append("")
+ for issue in result.complexity_issues:
+ lines.append(f"- `{issue.file}:{issue.line}` [{issue.rule}] {issue.message}")
+ if issue.suggestion:
+ lines.append(f" > {issue.suggestion}")
+ lines.append("")
+
+ lines.append("## Code metrics")
+ lines.append("")
+ lines.append("| Metric | Value |")
+ lines.append("|------|-----|")
+ lines.append(f"| Total lines | {result.metrics.total_lines} |")
+ lines.append(f"| Code lines | {result.metrics.code_lines} |")
+ lines.append(f"| Comment lines | {result.metrics.comment_lines} |")
+ lines.append(f"| Functions | {result.metrics.function_count} |")
+ lines.append(f"| Classes | {result.metrics.class_count} |")
+ lines.append(f"| Avg complexity | {result.metrics.avg_complexity:.1f} |")
+ lines.append(f"| Max complexity | {result.metrics.max_complexity} |")
+ lines.append("")
+
+ lines.append("## Suggestions")
+ lines.append("")
+ for i, suggestion in enumerate(result.suggestions, 1):
+ lines.append(f"{i}. {suggestion}")
+ lines.append("")
+
+ lines.append("---")
+ lines.append(f"*Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*")
+
+ return "\n".join(lines)
+
+ def save_report(self, content: str, result: "ReviewResult") -> str:
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ target = result.target.replace("/", "_").replace("\\", "_").replace(":", "_")
+ filename = f"review_{result.review_type}_{target}_{timestamp}.md"
+ filepath = self.output_dir / filename
+
+ filepath.write_text(content, encoding="utf-8")
+ return str(filepath)
+```
+
+## Chapter 7 — Configuration and deployment
+
+### 7.1 Environment variables
+
+> **This project uses the project-directory layout**: config lives under the repo:
+> - Env file: `D:\Download\jiuwenclaw\.env`
+> - Skills: `D:\Download\jiuwenclaw\workspace\agent\skills\`
+>
+> That keeps everything version-controlled for PRs.
+
+Example `.env` at the project root:
+
+```env
+# Model (Zhipu GLM-4.7 via OpenAI-compatible client)
+MODEL_PROVIDER="OpenAI"
+MODEL_NAME="glm-4.7"
+API_BASE="https://open.bigmodel.cn/api/paas/v4"
+API_KEY="your-api-key"
+
+# Feishu (optional)
+FEISHU_APP_ID=cli_xxx
+FEISHU_APP_SECRET=xxx
+FEISHU_REVIEW_CHAT_ID=oc_xxx
+
+# AtomGit (no public API in this setup — use git clone)
+ATOMGIT_TOKEN=xxx
+```
+
+### 7.2 JiuwenClaw `config.yaml`
+
+> Config path: `D:\Download\jiuwenclaw\config\config.yaml`
+
+```yaml
+react:
+ agent_name: main_agent
+ max_iterations: 50
+ model_name: ${MODEL_NAME:-glm-4.7}
+ answer_chunk_size: 500
+ stream_chunk_threshold: 50
+ stream_character_threshold: 2000
+ model_client_config:
+ client_provider: OpenAI
+ api_base: https://open.bigmodel.cn/api/paas/v4
+ api_key: ${API_KEY}
+ verify_ssl: false
+ model_config_obj:
+ context_engine_config:
+ enable_reload: true
+ evolution:
+ enabled: true
+ auto_scan: false
+ skill_base_dir: "workspace/agent/skills"
+
+tools:
+ - todo
+ - skill
+
+channels:
+ feishu:
+ app_id: cli_xxx
+ app_secret: xxx
+ enabled: true
+```
+
+| Key | Meaning |
+|-----|---------|
+| `client_provider: OpenAI` | OpenAI-compatible client |
+| `api_base` | Zhipu API base URL |
+| `model_name` | Model id |
+| `channels.feishu.enabled` | Enable Feishu channel |
+
+### 7.3 Installing dependencies
+
+```bash
+pip install ruff radon bandit
+
+npm install -g eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
+
+go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
+go install github.com/securego/gosec/v2/cmd/gosec@latest
+
+rustup component add clippy
+cargo install cargo-audit
+
+mkdir -p tools
+curl -L "https://github.com/checkstyle/checkstyle/releases/download/checkstyle-10.12.5/checkstyle-10.12.5-all.jar" -o tools/checkstyle.jar
+
+pip install lark-oapi
+```
+
+### 7.4 Heartbeat
+
+In `HEARTBEAT.md`, schedule periodic scans:
+
+```markdown
+## Active tasks
+- Run code quality scan # daily
+```
+
+## Chapter 8 — Testing
+
+| Method | Notes |
+|--------|------|
+| Feishu chat | Send review requests to the bot in private chat |
+| Web UI | Send requests through the JiuwenClaw web app |
+
+### 8.1 Feishu
+
+Prerequisites: JiuwenClaw running, Feishu bot + WebSocket, `code-review` skill deployed.
+
+Example message:
+
+```
+https://atomgit.com/openJiuwen/deepsearch please review this repository
+```
+
+The agent loads the skill, clones, scans (Ruff + Radon + Bandit), generates a report, and replies on Feishu.
+
+### 8.2 Web UI
+
+Prerequisites: `python start_services.py web`, open the app (default `http://localhost:8000`), skill deployed.
+
+You get streaming thought traces and intermediate steps — useful for debugging.
+
+### 8.3 Sample report output
+
+```markdown
+# :x: Code review report
+
+| Field | Value |
+|------|-------|
+| Review type | local |
+| Target | `./jiuwenclaw` |
+| Review time | 2026-03-07 21:53 |
+| Files scanned | 110 |
+
+## Scores
+
+| Dimension | Score |
+|------|------|
+| **Overall** | **41.0** (F) |
+| Code quality | 0.0 |
+| Security | 20.0 |
+| Complexity | 100.0 |
+| Style | 100.0 |
+
+**Status**: Fail
+
+## Issue summary
+
+- Total: **245** issues
+- Errors: 5
+- Warnings: 184
+- Info: 56
+
+## Issue details
+
+### Security (72)
+
+- `app.py:130` [B105] Possible hardcoded password: 'EMAIL_TOKEN'
+ > Hard-coded password string
+- `database.py:654` [B608] Possible SQL injection vector
+ > SQL injection risk
+
+### Code quality (152)
+
+- `interface.py:10` [F401] `re` imported but unused
+ > Remove unused import
+
+### Complexity (21)
+
+- `app.py:720` [CD] Function '_run' complexity too high (23, grade D)
+ > Refactor strongly: split into smaller functions
+
+## Suggestions
+
+1. Code quality is low — fix lint errors and warnings first
+2. Two high-severity security issues — prioritize
+3. Fix five error-level issues
+```
+
+## Chapter 9 — Takeaways
+
+### 9.1 Key decisions
+
+| Topic | Choice | Reason |
+| --- | --- | --- |
+| Lint | Ruff | Much faster than Pylint/Flake8 |
+| Complexity | Radon | Native Python API |
+| Security | Bandit | Python-focused security rules |
+| Code fetch | `git clone` | No AtomGit REST API |
+| Reports | Markdown | Easy to share; Feishu renders it |
+
+### 9.2 Pitfalls we hit
+
+1. **Windows encoding** — Use `input=code.encode("utf-8")` instead of `text=True` for Ruff stdin.
+2. **Bandit and stdin** — Write a temp file, analyze, delete.
+3. **No AtomGit API** — Use `git clone`.
+4. **Project-directory mode** — Default user workspace `C:\Users\<user>\.jiuwenclaw\` is awkward for VCS; point config at the repo instead.
+5. **Skill paths** — With project mode, skills live under `...\workspace\agent\skills\code-review\`.
+6. **Max iterations** — Complex repos can hit `max_iterations` if the agent opens files one-by-one; follow the skill and use the right tools.
+7. **WebSocket size** — Huge reports exceed ~1MB; forbid returning the full file in `SKILL.md` and return summaries only.
+8. **Multi-language stacks** — Install ESLint, Checkstyle JAR, etc., for non-Python parts of the repo.
+
+### 9.3 Possible extensions
+
+1. More languages — ESLint, Checkstyle, golangci-lint, Clippy are already sketched in the skill.
+2. **Incremental scans** — Only `git diff` files.
+3. **PR integration** — When AtomGit exposes APIs, automate PR comments.
+4. **Trends** — Store scores over time and chart quality.
+
+---
+
+## Closing
+
+Building this review assistant clarified how to ship a practical analysis pipeline:
+
+1. **Combine tools** — Ruff, Bandit, Radon each cover different angles.
+2. **Make scoring meaningful** — Weight by severity, not raw counts.
+3. **Make reports actionable** — Say what to fix and how.
+4. **Keep architecture extensible** — New analyzers and formats plug in cleanly.
+
+**Paths**: `D:\Download\jiuwenclaw\workspace\agent\skills\code-review\` — `SKILL.md`, entry `run_review.py`.
diff --git a/docs/en/development-practices/JiuwenClaw-Daily-Report-Generator.md b/docs/en/development-practices/JiuwenClaw-Daily-Report-Generator.md
new file mode 100644
index 0000000000..695d2d4aaf
--- /dev/null
+++ b/docs/en/development-practices/JiuwenClaw-Daily-Report-Generator.md
@@ -0,0 +1,2568 @@
+# From Configuration to Architecture: Building the Advanced JiuwenClaw Daily Report Generator
+
+## Introduction — When “daily report automation” meets real office work
+
+Over the past year, AI agents have been discussed everywhere — from simple Q&A to complex workflows. Putting an agent into everyday office work surfaces a practical gap:
+
+> A conversational agent is not the same as an assistant that automates work.
+
+Office work is rarely “just chat.” It includes repetitive chores: end-of-day reports, weekly rollups, monthly summaries. They are not intellectually hard, but they consume time and attention.
+
+If an agent only chats, it stays a novelty.
+
+To be a **deliverable automation assistant**, it needs three things: (1) collect data from multiple sources, (2) analyze productivity intelligently, and (3) push results through the right channels proactively.
+
+This article covers:
+
+- Multi-source collection (Git commits + email stats + memory + todos)
+- A work-analysis engine (metrics, trends, keyword extraction)
+- Report generation (daily, weekly, monthly)
+- Scheduled tasks and push configuration
+- Implementation and validation
+
+If you are asking:
+
+- How to turn a demo agent into a productivity tool
+- How to make an agent push information instead of only reacting
+- How to build a reusable modular skill set
+
+the sections below may help.
+
+---
+
+## Project environment
+
+> **This document reflects a real project.** Configuration and code match what was actually used.
+
+### Runtime
+
+| Item | Value |
+| --- | --- |
+| **Project path** | `D:\Download\jiuwenclaw` |
+| **OS** | Windows 10 |
+| **Python** | 3.10+ |
+| **Model** | ModelScope (`Qwen/Qwen3-235B-A22B-Instruct-2507`) |
+
+### Data sources
+
+| Source | Value |
+| --- | --- |
+| **Git repo** | `D:\Download\jiuwenclaw` (this project) |
+| **Email** | `[email protected]` (NetEase 163 Email) |
+| **Delivery** | Feishu (`cli_a92035b1823a9cd2`) |
+| **Heartbeat window** | Daily 18:00–18:30 |
+
+### Key paths
+
+```plain
+D:\Download\jiuwenclaw\
+├── .env
+├── config/config.yaml # App config (heartbeat, Feishu)
+├── workspace/
+│ ├── HEARTBEAT.md # Heartbeat tasks
+│ └── agent/skills/daily-report/ # Skill module
+│ ├── SKILL.md # Skill definition v2.0.0
+│ ├── collectors/
+│ ├── analyzers/
+│ └── generators/
+```
+
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772822490912-87defae8-95ee-4c68-890b-d5082761d783.png)
+
+## 1. Problem background
+
+### 1.1 Limits of a “basic” daily report skill
+
+People often assume:
+
+> “Isn’t it just memory + todos + a template?”
+
+That works for toy demos.
+
+In production you hit three problems:
+
+1. **Single source** — Only memory and todos; no visibility into commits, email, or real output.
+2. **No analysis** — Lists tasks but does not compute metrics, trends, or advice.
+3. **Fixed report type** — Daily only; no weekly or monthly rollups.
+
+Example: “commit trend this week” or “productivity vs last week” needs Git history, time windows, and comparison logic — a basic skill cannot do that.
+
+The **advanced daily report** skill aggregates multiple sources, runs analysis, and produces metrics, trends, and suggestions.
+
+### 1.2 Office pain points
+
+**Writing the daily report takes too long** — 15–20 minutes at the end of the day to remember what shipped.
+
+**Formats drift** — Sometimes bullet lists, sometimes narrative, sometimes skipped; managers struggle to compare.
+
+**Important work gets forgotten** — A critical bug fix or feature may be omitted from the report. Auto-collecting Git commits reduces that gap.
+
+**Email work is invisible** — Volume, unread counts, and follow-ups rarely make it into a manual report.
+
+With the advanced skill, Git, email stats, memory, and todos feed an engine that computes metrics and trends.
+
+### 1.3 JiuwenClaw skills
+
+| Capability | Description |
+| --- | --- |
+| **Modular skills** | Multiple Python modules per skill |
+| **Tools** | `allowed_tools` for system integration |
+| **Heartbeat** | Periodic skill execution |
+| **Channels** | Feishu, Web, etc. |
+
+The payoff is **extensibility**: collection, analysis, and reporting stay separated.
+
+## 2. Technical approach
+
+### 2.1 Layering in JiuwenClaw
+
+The advanced daily report skill sits in the application layer (see diagram in the original article).
+
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772822901009-32c4955a-17b4-47f8-81f3-22283748f998.png)
+
+### 2.2 Three-layer data flow
+
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772861778248-67064c9c-4de8-41c7-850a-699ca4205cd1.png)
+
+### 2.3 Core components
+
+| Component | Type | Role | Module |
+| --- | --- | --- | --- |
+| **GitCollector** | Collector | Git commits | `collectors/git_collector.py` |
+| **EmailCollector** | Collector | NetEase mailbox stats | `collectors/email_collector.py` |
+| **MemoryCollector** | Collector | Memory files | `collectors/memory_collector.py` |
+| **TodoCollector** | Collector | Todo lists | `collectors/todo_collector.py` |
+| **DataAggregator** | Aggregator | Merge sources | `collectors/aggregator.py` |
+| **WorkAnalyzer** | Analyzer | Work analysis | `analyzers/work_analyzer.py` |
+| **ReportGenerator** | Generator | Reports | `generators/report_generator.py` |
+
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772861858079-e087425b-3bfd-40de-8567-92c874d0b396.png)
+
+### 2.4 Flow and design choices
+
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772861961611-4d5aae74-099e-4cc4-aec5-622b14fc515e.png)
+
+| Decision | Choice | Reason |
+| --- | --- | --- |
+| Git | `git log` | No extra deps |
+| Email | IMAP | Supported by NetEase |
+| Tokenization | jieba (optional) | Good for Chinese; can degrade gracefully |
+| Reports | Markdown | Portable; Feishu renders |
+| Trigger | Heartbeat + manual | Scheduled + on demand |
+
+## Chapter 3 — Skills system engineering
+
+### 3.1 Skills directory structure
+
+```plain
+workspace/agent/skills/daily-report/
+├── SKILL.md
+├── collectors/
+│ ├── __init__.py
+│ ├── git_collector.py
+│ ├── email_collector.py
+│ ├── memory_collector.py
+│ ├── todo_collector.py
+│ └── aggregator.py
+├── analyzers/
+│ ├── __init__.py
+│ └── work_analyzer.py
+├── generators/
+│ ├── __init__.py
+│ └── report_generator.py
+└── report_helper.py # Legacy compatibility
+```
+
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772862008911-7b9d807a-9175-4c62-a208-c3b6381169be.png)
+
+### 3.2 `advanced-daily-report` SKILL.md
+
+
+```markdown
+---
+name: advanced-daily-report
+version: 2.0.0
+description: Advanced version daily report generator, supports multi-data source collection, work analysis, trend comparison, and weekly and monthly report aggregation
+tags: [report, automation, productivity, daily, weekly, monthly, advanced]
+allowed_tools: [read_memory, write_memory, mcp_exec_command, read_file, write_file]
+---
+
+# Advanced version daily report generator
+
+Automatically collect multi-source data, intelligently analyze work efficiency, generate daily report/weekly report/monthly report and push them to Feishu.
+
+## Core capabilities
+
+### 1. Multi-data source collection
+
+| Data source | Collected content | Frequency |
+|--------|----------|------|
+| **Git repositories** | submission records, code change statistics | real time |
+| **Netease email** | sent/received email statistics, unread reminders | real time |
+| **memory system** | today’s work records, long-term memory | real time |
+| **to-do items** | task status, completion rate | real time |
+
+### 2. Intelligent work analysis
+
+- **Efficiency metric calculation**
+ - task completion rate = completed / total tasks
+ - productivity score (0-100)
+ - focus score (0-100)
+
+- **Trend comparison**
+ - compared with yesterday
+ - compared with the same period last week
+ - weekly trend chart
+
+- **Keyword extraction**
+ - automatically extract today’s work keywords
+ - work topic clustering
+
+### 3. Multiple report types
+
+| Type | Trigger method | Push time |
+|------|----------|----------|
+| **Daily report** | manual/timed | every day 18:00 |
+| **Weekly report** | timed | every Friday 18:00 |
+| **Monthly report** | timed | on the last day of every month 18:00 |
+
+## Directory structure
+```
+
+daily-report/
+├── SKILL.md # Skill definition (this file)
+├── collectors/
+│ ├── __init__.py
+│ ├── git_collector.py
+│ ├── email_collector.py
+│ ├── memory_collector.py
+│ ├── todo_collector.py
+│ └── aggregator.py
+├── analyzers/
+│ ├── __init__.py
+│ └── work_analyzer.py
+├── generators/
+│ ├── __init__.py
+│ └── report_generator.py
+└── report_helper.py # Legacy compatibility
+```
+
+## Usage
+
+### ⚠️ Important: how to run
+
+This skill collects data by running Python scripts (Git, mailbox, memory, todos).
+
+**You must use the `mcp_exec_command` tool to run the scripts** — do not reply to the user without executing them.
+
+**What the scripts collect automatically:**
+
+- **Git commits**: `git log` on repo `D:/Download/jiuwenclaw`
+- **Mailbox stats**: IMAP to `[email protected]` (requires mailbox authorization code)
+- **Memory**: daily files under `workspace/agent/memory/`
+- **Todos**: `todo.md` under `workspace/session/`
+
+### Manual trigger
+
+When the user asks for a daily / weekly / monthly report, **run:**
+
+```bash
+# Today’s daily report (Git + todos + memory)
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py daily --save
+
+# Daily report for a specific date
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py daily --date 2026-03-06 --save
+
+# Weekly report (aggregate one week)
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py weekly --save
+
+# Monthly report (aggregate one month, incl. per-day Git stats)
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py monthly --save
+
+# Monthly report for a given month
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py monthly --year 2026 --month 3 --save
+```
+
+### Execution steps
+
+1. User sends something like “generate daily / weekly / monthly report”.
+2. **Run the commands above with `mcp_exec_command`.**
+3. The script collects:
+ - **Git**: `git log` for commits and churn
+ - **Email**: IMAP stats (if mail is configured)
+ - **Memory**: work notes from memory files
+ - **Todos**: task state from `todo.md`
+4. Wait until the script finishes and read its output.
+5. Send the report content to the user.
+
+### Trigger phrases (examples)
+
+- **Daily**: generate today’s report, yesterday’s report, today’s work, today’s commits
+- **Weekly**: this week’s summary, weekly rollup, week in review
+- **Monthly**: this month’s summary, monthly review, summarize this month’s mail into a report, this month’s commit stats
+
+### Data sources
+
+| Source | How | Where to configure |
+|--------|-----|--------------------|
+| **Git** | `git log` | Repo path: `D:/Download/jiuwenclaw` |
+| **NetEase** | IMAP | `.env`: `EMAIL_ADDRESS`, `EMAIL_TOKEN` |
+| **Memory** | Read Markdown | `workspace/agent/memory/YYYY-MM-DD.md` |
+| **Todos** | Parse `todo.md` | `workspace/session/*/todo.md` |
+
+### Scheduled trigger
+
+Configure periodic runs in `HEARTBEAT.md`:
+
+```markdown
+## Active tasks
+- Generate today’s work report # daily
+- Generate weekly report # every Friday
+- Generate monthly report # month end
+```
+
+## Daily report template
+
+```markdown
+# 📋 Work daily — 2026-03-06
+
+## 📊 Overview
+
+| Metric | Value |
+|--------|-------|
+| Commits | 5 |
+| Tasks done | 3/8 |
+| Code churn | +350/-80 |
+| Email | in 12 / out 3 |
+| Productivity | 78.5 |
+
+## ✅ Done
+- Finished daily-report skill
+- Configured Feishu channel
+- Tested heartbeat
+
+## 🔄 In progress
+- Write documentation
+- Weekly aggregation
+
+## 💻 Commits
+
+| Time | Message | Churn |
+|------|---------|-------|
+| 09:30 | feat: daily report | +120/-30 |
+| 14:15 | fix: email collector | +45/-12 |
+
+## 📧 Email
+- Inbox today: 12
+- Sent today: 3
+- Unread: 2
+
+## 📈 Trends
+- Commits: ↑ 2 vs yesterday
+- Efficiency: ↑ 5.2 pts
+
+## 💡 Suggestions
+1. Focus seems low — reduce interruptions
+2. Task completion rate can improve
+
+## 🔜 Tomorrow
+- Polish daily template
+- Add weekly rollup
+```
+
+## Configuration
+
+### Git repo
+
+Monitored repository (read automatically by scripts):
+
+```
+Repo path: D:/Download/jiuwenclaw
+```
+
+The script uses `git log` to collect:
+
+- Commit hash, message, author, time
+- Per commit: files changed, insertions, deletions
+
+### Email
+
+Configure in `.env` (shape used in the project):
+
+```env
+EMAIL_TOKEN=<your-imap-auth-code>
+EMAIL_PROVIDER=163
+```
+
+**Note:** `EMAIL_TOKEN` is the mailbox **authorization code**, not the login password. In 163: Settings → POP3/SMTP/IMAP → enable IMAP → generate auth code.
+
+### Heartbeat
+
+```yaml
+heartbeat:
+ every: 3600
+ target: feishu
+ active_hours:
+ start: 18:00
+ end: 18:30
+```
+
+## API reference
+
+### Data aggregator
+
+```python
+from collectors import DataAggregator
+
+aggregator = DataAggregator(
+ workspace_dir="workspace",
+ git_repo="path/to/repo",
+ email_config={
+ "address": "[email protected]",
+ "auth_code": "xxx",
+ "provider": "163"
+ }
+)
+
+# Collect today
+data = aggregator.collect()
+
+# Collect one week
+week_data = aggregator.collect_week()
+```
+
+### Work analyzer
+
+```python
+from analyzers import WorkAnalyzer
+
+analyzer = WorkAnalyzer()
+result = analyzer.analyze(data.to_dict())
+
+print(f"Productivity: {result.metrics.productivity_score}")
+print(f"Keywords: {result.keywords}")
+print(f"Suggestions: {result.suggestions}")
+```
+
+### Report generator
+
+```python
+from generators import ReportGenerator
+
+generator = ReportGenerator(aggregator)
+
+daily = generator.generate_daily()
+weekly = generator.generate_weekly()
+monthly = generator.generate_monthly(2026, 3)
+```
+
+## Notes
+
+1. **Git**: ensure the repo path is correct and readable.
+2. **Mail**: use the authorization code, not the login password.
+3. **Heartbeat**: restart services after changes.
+4. **Storage**: reports are saved under `workspace/agent/reports/`.
+
+## Changelog
+
+- **v2.0.0** (2026-03-06): Advanced — multi-source, trends, weekly/monthly.
+- **v1.0.0** (2026-03-06): Initial basic daily report.
+```
+
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772862026601-dd7ed3ff-26da-4182-8f6f-c45c437feffc.png)
+
+### 3.3 Daily report template (minimal example)
+```markdown
+# 📋 Work daily — 2026-03-06
+
+## 📊 Overview
+
+| Metric | Value |
+|--------|-------|
+| Commits | 5 |
+| Tasks done | 3/8 |
+| Code churn | +350/-80 |
+| Email | in 12 / out 3 |
+| Productivity | 78.5 |
+
+## ✅ Done
+- Finished daily-report skill
+- Configured Feishu channel
+
+## 💻 Commits
+
+| Time | Message | Churn |
+|------|---------|-------|
+| 09:30 | feat: add daily report | +120/-30 |
+
+## 📧 Email
+- Inbox today: 12
+- Sent today: 3
+- Unread: 2
+
+## 📈 Trends
+- Commits: ↑ 2
+- Efficiency: ↑ 5.2 pts
+
+## 💡 Suggestions
+1. Focus seems low — reduce interruptions
+
+## 🔜 Tomorrow
+- Polish daily template
+```
+
+## Chapter 4 — Data collection layer (full implementation)
+
+### 4.1 Git collector
+
+```python
+# collectors/git_collector.py
+# -*- coding: utf-8 -*-
+"""
+Git 提交记录采集器
+
+功能:
+- 获取指定日期的 Git 提交记录
+- 统计提交次数、修改文件数、代码行数变化
+- 支持多个仓库
+"""
+
+import subprocess
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Optional
+
+
+@dataclass
+class GitCommit:
+ """Git 提交记录"""
+
+ hash: str # 提交哈希
+ message: str # 提交信息
+ author: str # 作者
+ date: datetime # 提交时间
+ files_changed: int = 0 # 修改文件数
+ insertions: int = 0 # 新增行数
+ deletions: int = 0 # 删除行数
+
+ def to_dict(self) -> dict:
+ return {
+ "hash": self.hash,
+ "message": self.message,
+ "author": self.author,
+ "date": self.date.isoformat(),
+ "files_changed": self.files_changed,
+ "insertions": self.insertions,
+ "deletions": self.deletions,
+ }
+
+
+@dataclass
+class GitStats:
+ """Git 统计数据"""
+
+ commits: list[GitCommit] = field(default_factory=list)
+ total_commits: int = 0
+ total_files_changed: int = 0
+ total_insertions: int = 0
+ total_deletions: int = 0
+
+ @property
+ def net_lines(self) -> int:
+ """净增行数"""
+ return self.total_insertions - self.total_deletions
+
+ def to_dict(self) -> dict:
+ return {
+ "total_commits": self.total_commits,
+ "total_files_changed": self.total_files_changed,
+ "total_insertions": self.total_insertions,
+ "total_deletions": self.total_deletions,
+ "net_lines": self.net_lines,
+ "commits": [c.to_dict() for c in self.commits],
+ }
+
+
+class GitCollector:
+ """Git 提交记录采集器"""
+
+ def __init__(self, repo_path: str | Path):
+ """
+ 初始化 Git 采集器
+
+ Args:
+ repo_path: Git 仓库路径
+ """
+ self.repo_path = Path(repo_path).resolve()
+
+ def _run_git_command(self, args: list[str], timeout: int = 30) -> str:
+ """执行 Git 命令"""
+ try:
+ result = subprocess.run(
+ ["git", "-C", str(self.repo_path)] + args,
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ encoding="utf-8",
+ errors="replace",
+ )
+ return result.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception as e:
+ return ""
+
+ def get_commits(self, date: Optional[str] = None, author: Optional[str] = None) -> GitStats:
+ """
+ 获取指定日期的提交记录
+
+ Args:
+ date: 日期字符串 (YYYY-MM-DD),默认今天
+ author: 作者名称过滤,默认不过滤
+
+ Returns:
+ GitStats: Git 统计数据
+ """
+ if date is None:
+ date = datetime.now().strftime("%Y-%m-%d")
+
+ stats = GitStats()
+
+ # 获取提交列表
+ log_format = "%H|%s|%an|%ai"
+ since = f"{date} 00:00:00"
+ until = f"{date} 23:59:59"
+
+ cmd_args = [
+ "log",
+ f"--since={since}",
+ f"--until={until}",
+ f"--format={log_format}",
+ ]
+
+ if author:
+ cmd_args.append(f"--author={author}")
+
+ log_output = self._run_git_command(cmd_args)
+
+ if not log_output:
+ return stats
+
+ # 解析提交记录
+ for line in log_output.split("\n"):
+ if not line.strip():
+ continue
+
+ parts = line.split("|", 3)
+ if len(parts) < 4:
+ continue
+
+ commit_hash, message, author_name, date_str = parts
+
+ try:
+ commit_date = datetime.fromisoformat(
+ date_str.replace(" ", "T").split("+")[0]
+ )
+ except ValueError:
+ commit_date = datetime.now()
+
+ # 获取每个提交的文件变更统计
+ numstat = self._run_git_command(
+ ["show", "--numstat", "--format=", commit_hash]
+ )
+
+ files_changed = 0
+ insertions = 0
+ deletions = 0
+
+ for stat_line in numstat.split("\n"):
+ if not stat_line.strip():
+ continue
+ stat_parts = stat_line.split("\t")
+ if len(stat_parts) >= 2:
+ try:
+ ins = int(stat_parts[0]) if stat_parts[0] != "-" else 0
+ dels = int(stat_parts[1]) if stat_parts[1] != "-" else 0
+ insertions += ins
+ deletions += dels
+ files_changed += 1
+ except ValueError:
+ continue
+
+ commit = GitCommit(
+ hash=commit_hash[:8],
+ message=message.strip(),
+ author=author_name,
+ date=commit_date,
+ files_changed=files_changed,
+ insertions=insertions,
+ deletions=deletions,
+ )
+
+ stats.commits.append(commit)
+ stats.total_commits += 1
+ stats.total_files_changed += files_changed
+ stats.total_insertions += insertions
+ stats.total_deletions += deletions
+
+ return stats
+```
+
+### 4.2 Email Statistics Collector
+
+> **Important Note**: The 163 email service’s IMAP has special restrictions. Using the `SELECT` command directly will return an `"Unsafe Login"` error.
+> Solution:
+> 1. Register the ID command in `imaplib`: `imaplib.Commands['ID'] = ('NONAUTH', 'AUTH', 'SELECTED')`
+> 2. After logging in, send the ID command to declare the client identity
+> 3. Use the `STATUS` command to obtain email statistics (bypassing the `SELECT` restriction)
+> 4. If you need to read email content, after the ID command is successfully sent, you can use `SELECT` normally
+
+```python
+# collectors/email_collector.py
+# -*- coding: utf-8 -*-
+"""
+Email Statistics Collector
+
+Supports:
+- NetEase Mail (163/126/yeah)
+- Reading emails via the IMAP protocol
+
+Features:
+- Count the number of emails in the inbox
+- Get the number of unread emails
+- Read email content previews
+
+Special handling for 163:
+- Must register the ID command and send it after logging in
+- Use the STATUS command to get statistics (bypass the Unsafe Login restriction)
+"""
+
+import email
+import re
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from email.header import decode_header
+from typing import Optional
+
+try:
+ import imaplib
+ IMAP_AVAILABLE = True
+ # 163 mailbox must: register ID command in imaplib
+ imaplib.Commands['ID'] = ('NONAUTH', 'AUTH', 'SELECTED')
+except ImportError:
+ IMAP_AVAILABLE = False
+ imaplib = None
+
+
+# NetEase IMAP server configuration
+NETEASE_IMAP_SERVERS = {
+ "163": "imap.163.com",
+ "126": "imap.126.com",
+ "yeah": "imap.yeah.net",
+}
+
+
+@dataclass
+class EmailInfo:
+ """Email information"""
+ subject: str = "" # Subject
+ sender: str = "" # Sender
+ date: str = "" # Date
+ body_preview: str = "" # Body preview
+
+ def to_dict(self) -> dict:
+ return {
+ "subject": self.subject,
+ "sender": self.sender,
+ "date": self.date,
+ "body_preview": self.body_preview[:200] if self.body_preview else "",
+ }
+
+
+@dataclass
+class EmailStats:
+ """Email statistics data"""
+ total_emails: int = 0 # Total number of emails in the mailbox
+ unread: int = 0 # Number of unread emails
+ recent_emails: list[EmailInfo] = field(default_factory=list) # Recent emails
+
+ def to_dict(self) -> dict:
+ return {
+ "total_emails": self.total_emails,
+ "unread": self.unread,
+ "recent_emails": [e.to_dict() for e in self.recent_emails],
+ }
+
+
+class EmailCollector:
+ """Email statistics collector"""
+
+ def __init__(
+ self,
+ email_address: str,
+ auth_code: str,
+ provider: str = "163",
+ ):
+ """
+ Initialize the email collector
+
+ Args:
+ email_address: Email address
+ auth_code: Authorization code (not the login password)
+ provider: Email provider (163/126/yeah)
+ """
+ if not IMAP_AVAILABLE:
+ raise ImportError("imaplib module is not available")
+
+ self.email_address = email_address
+ self.auth_code = auth_code
+ self.provider = provider.lower()
+
+ if self.provider not in NETEASE_IMAP_SERVERS:
+ raise ValueError(f"Unsupported email provider: {provider}")
+
+ self.imap_server = NETEASE_IMAP_SERVERS[self.provider]
+ self._connection = None
+
+ def _decode_str(self, s: str) -> str:
+ """Decode an email string"""
+ if s is None:
+ return ""
+ decoded_parts = decode_header(s)
+ result = []
+ for part, encoding in decoded_parts:
+ if isinstance(part, bytes):
+ try:
+ result.append(part.decode(encoding or "utf-8", errors="ignore"))
+ except Exception:
+ result.append(part.decode("utf-8", errors="ignore"))
+ else:
+ result.append(part)
+ return "".join(result)
+
+ def connect(self) -> bool:
+ """Connect to the IMAP server and send the ID command"""
+ try:
+ self._connection = imaplib.IMAP4_SSL(self.imap_server, 993)
+ self._connection.login(self.email_address, self.auth_code)
+
+ # 163 mailbox must: send ID immediately after login
+ args = '("name" "python" "version" "1.0" "vendor" "python-imap")'
+ self._connection._simple_command("ID", args)
+
+ return True
+ except Exception as e:
+ print(f"Failed to connect to mailbox: {e}")
+ return False
+
+ def disconnect(self):
+ """Disconnect"""
+ if self._connection:
+ try:
+ self._connection.logout()
+ except Exception:
+ pass
+ self._connection = None
+
+ def get_stats(self) -> EmailStats:
+ """
+ Get email statistics (use the STATUS command, bypass SELECT restrictions)
+
+ Returns:
+ EmailStats: Email statistics data
+ """
+ stats = EmailStats()
+
+ if not self._connection:
+ if not self.connect():
+ return stats
+
+ try:
+ # Use STATUS to get statistics (SELECT on 163 will return Unsafe Login)
+ status, data = self._connection.status("INBOX", "(MESSAGES UNSEEN)")
+ if status == "OK" and data:
+ # Parse response: b'"INBOX" (MESSAGES 39 UNSEEN 32)'
+ response = data[0].decode() if isinstance(data[0], bytes) else str(data[0])
+ messages_match = re.search(r'MESSAGES\s+(\d+)', response)
+ unseen_match = re.search(r'UNSEEN\s+(\d+)', response)
+ if messages_match:
+ stats.total_emails = int(messages_match.group(1))
+ if unseen_match:
+ stats.unread = int(unseen_match.group(1))
+ except Exception as e:
+ print(f"Failed to get email statistics: {e}")
+
+ return stats
+
+ def get_recent_emails(self, limit: int = 10, days: int = 30) -> list[EmailInfo]:
+ """
+ Read recent email content (after sending the ID command, SELECT works normally)
+
+ Args:
+ limit: Maximum number of emails to read
+ days: Only read emails within the last N days
+
+ Returns:
+ List of emails
+ """
+ if not self._connection:
+ if not self.connect():
+ return []
+
+ emails = []
+
+ try:
+ # ID command has been sent; now SELECT works normally
+ typ, dat = self._connection.select("INBOX")
+ if typ != "OK":
+ return []
+
+ # Search for emails within the last N days
+ since_date = (datetime.now() - timedelta(days=days)).strftime("%d-%b-%Y")
+ typ, msg_ids = self._connection.search(None, f'(SINCE {since_date})')
+
+ if typ != "OK" or not msg_ids[0]:
+ return []
+
+ ids = msg_ids[0].split()[-limit:] # Get the latest N emails
+
+ for msg_id in reversed(ids):
+ try:
+ typ, msg_data = self._connection.fetch(msg_id, "(RFC822)")
+ if typ != "OK":
+ continue
+
+ raw_email = msg_data[0][1]
+ msg = email.message_from_bytes(raw_email)
+
+ # Decode subject
+ subject = self._decode_str(msg["Subject"]) or "(No subject)"
+ from_addr = self._decode_str(msg.get("From", ""))
+ date_str = msg.get("Date", "")
+
+ # Extract body
+ body = ""
+ if msg.is_multipart():
+ for part in msg.walk():
+ content_type = part.get_content_type()
+ if content_type == "text/plain":
+ payload = part.get_payload(decode=True)
+ charset = part.get_content_charset() or "utf-8"
+ body = payload.decode(charset, errors="ignore")
+ break
+ elif content_type == "text/html" and not body:
+ payload = part.get_payload(decode=True)
+ charset = part.get_content_charset() or "utf-8"
+ html_body = payload.decode(charset, errors="ignore")
+ body = re.sub(r'<[^>]+>', ' ', html_body)
+ body = re.sub(r'\s+', ' ', body).strip()
+ else:
+ payload = msg.get_payload(decode=True)
+ charset = msg.get_content_charset() or "utf-8"
+ body = payload.decode(charset, errors="ignore") if payload else ""
+
+ emails.append(EmailInfo(
+ subject=subject[:100],
+ sender=from_addr[:80],
+ date=date_str,
+ body_preview=body[:500] if body else ""
+ ))
+ except Exception:
+ continue
+
+ except Exception as e:
+ print(f"Failed to read email content: {e}")
+
+ return emails
+
+ def __enter__(self):
+ self.connect()
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.disconnect()
+ return False
+```
+
+### 4.3 Memory Data Collector
+```python
+# collectors/memory_collector.py
+# -*- coding: utf-8 -*-
+"""
+Memory Data Collector
+
+Function:
+- Read today's memory file
+- Read long-term memory
+- Extract work summary
+"""
+
+import re
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Optional
+
+
+@dataclass
+class MemoryData:
+ """Memory data"""
+
+ today_content: str = "" # Today's memory content
+ long_term_content: str = "" # Long-term memory content
+ work_summaries: list[str] = field(default_factory=list) # List of work summaries
+ key_decisions: list[str] = field(default_factory=list) # Key decisions
+
+ def to_dict(self) -> dict:
+ return {
+ "today_content": self.today_content[:500] if self.today_content else "",
+ "work_summaries": self.work_summaries,
+ "key_decisions": self.key_decisions,
+ }
+
+
+class MemoryCollector:
+ """Memory Data Collector"""
+
+ def __init__(self, workspace_dir: str | Path):
+ """
+ Initialize memory collector
+
+ Args:
+ workspace_dir: workspace directory path
+ """
+ self.workspace_dir = Path(workspace_dir)
+ self.memory_dir = self.workspace_dir / "agent" / "memory"
+
+ def _read_file_safe(self, file_path: Path) -> str:
+ """Safely read file"""
+ if not file_path.exists():
+ return ""
+ try:
+ return file_path.read_text(encoding="utf-8")
+ except Exception:
+ return ""
+
+ def _extract_list_items(self, content: str) -> list[str]:
+ """Extract list items (lines starting with - or *)"""
+ items = []
+ for line in content.split("\n"):
+ stripped = line.strip()
+ if stripped.startswith("-") or stripped.startswith("*"):
+ item = stripped.lstrip("-* ").strip()
+ # Skip comments and empty items
+ if item and not item.startswith("<!--"):
+ items.append(item)
+ return items
+
+ def _extract_sections(self, content: str, section_title: str) -> list[str]:
+ """Extract content under a specified title"""
+ items = []
+ in_section = False
+
+ for line in content.split("\n"):
+ stripped = line.strip()
+
+ # Detect title
+ if stripped.startswith("##"):
+ if section_title.lower() in stripped.lower():
+ in_section = True
+ else:
+ in_section = False
+ continue
+
+ if in_section:
+ if stripped.startswith("-") or stripped.startswith("*"):
+ item = stripped.lstrip("-* ").strip()
+ if item and not item.startswith("<!--"):
+ items.append(item)
+
+ return items
+
+ def collect(self, date: Optional[str] = None) -> MemoryData:
+ """
+ Collect memory data
+
+ Args:
+ date: Date string (YYYY-MM-DD), default is today
+
+ Returns:
+ MemoryData: Memory data
+ """
+ if date is None:
+ date = datetime.now().strftime("%Y-%m-%d")
+
+ data = MemoryData()
+
+ # Read today's memory
+ today_file = self.memory_dir / f"{date}.md"
+ data.today_content = self._read_file_safe(today_file)
+
+ # Read long-term memory
+ memory_file = self.memory_dir / "MEMORY.md"
+ data.long_term_content = self._read_file_safe(memory_file)
+
+ # Extract work summaries
+ data.work_summaries = self._extract_list_items(data.today_content)
+
+ # Extract key decisions (from long-term memory)
+ data.key_decisions = self._extract_sections(
+ data.long_term_content, "decisions"
+ ) or self._extract_sections(data.long_term_content, "preferences")
+
+ return data
+
+ def get_week_memories(self, end_date: Optional[str] = None) -> dict[str, MemoryData]:
+ """Get memory data for a week"""
+ if end_date is None:
+ end_date = datetime.now()
+ else:
+ end_date = datetime.strptime(end_date, "%Y-%m-%d")
+
+ result = {}
+ for i in range(7):
+ date = (end_date - timedelta(days=i)).strftime("%Y-%m-%d")
+ result[date] = self.collect(date)
+
+ return result
+
+ def get_month_memories(self, year: int, month: int) -> dict[str, MemoryData]:
+ """Get memory data for a month"""
+ import calendar
+
+ _, days_in_month = calendar.monthrange(year, month)
+ result = {}
+
+ for day in range(1, days_in_month + 1):
+ date = f"{year:04d}-{month:02d}-{day:02d}"
+ result[date] = self.collect(date)
+
+ return result
+```
+
+### 4.4 To-Do Item Collector
+```python
+# collectors/todo_collector.py
+# -*- coding: utf-8 -*-
+"""
+To-Do Item Collector
+
+Function:
+- Read the todo.md file
+- Parse task status
+- Count completion status
+"""
+
+import re
+from dataclasses import dataclass, field
+from datetime import datetime
+from pathlib import Path
+from typing import Optional
+
+
+@dataclass
+class TodoTask:
+ """To-do task"""
+
+ id: str
+ content: str
+ status: str # completed, running, waiting, cancelled
+ created_at: Optional[datetime] = None
+ updated_at: Optional[datetime] = None
+
+ def to_dict(self) -> dict:
+ return {
+ "id": self.id,
+ "content": self.content,
+ "status": self.status,
+ "created_at": self.created_at.isoformat() if self.created_at else None,
+ "updated_at": self.updated_at.isoformat() if self.updated_at else None,
+ }
+
+
+@dataclass
+class TodoStats:
+ """To-do statistics"""
+
+ total: int = 0
+ completed: int = 0
+ running: int = 0
+ waiting: int = 0
+ cancelled: int = 0
+ tasks: list[TodoTask] = field(default_factory=list)
+
+ @property
+ def completion_rate(self) -> float:
+ """Completion rate"""
+ if self.total == 0:
+ return 0.0
+ return self.completed / self.total
+
+ def to_dict(self) -> dict:
+ return {
+ "total": self.total,
+ "completed": self.completed,
+ "running": self.running,
+ "waiting": self.waiting,
+ "cancelled": self.cancelled,
+ "completion_rate": round(self.completion_rate, 2),
+ "tasks": [t.to_dict() for t in self.tasks],
+ }
+
+
+class TodoCollector:
+ """To-Do Item Collector"""
+
+ def __init__(self, workspace_dir: str | Path):
+ """
+ Initialize the to-do collector
+
+ Args:
+ workspace_dir: workspace directory path
+ """
+ self.workspace_dir = Path(workspace_dir)
+ self.session_dir = self.workspace_dir / "session"
+
+ def _read_file_safe(self, file_path: Path) -> str:
+ """Safely read file"""
+ if not file_path.exists():
+ return ""
+ try:
+ return file_path.read_text(encoding="utf-8")
+ except Exception:
+ return ""
+
+ def _find_latest_todo_file(self) -> Optional[Path]:
+ """Find the latest todo.md file"""
+ if not self.session_dir.exists():
+ return None
+
+ todo_files = list(self.session_dir.rglob("todo.md"))
+
+ if not todo_files:
+ return None
+
+ # Sort by modification time and return the latest
+ todo_files.sort(key=lambda f: f.stat().st_mtime, reverse=True)
+ return todo_files[0]
+
+ def _parse_status(self, line: str) -> tuple[str, str]:
+ """
+ Parse the task line and extract ID and status
+
+ Supports format:
+ - [x] 1. Task content
+ - [ ] 1. Task content
+ - 1. [status:completed] Task content
+ - 1. ✅ Task content
+ """
+ # Markdown checkbox format
+ checkbox_match = re.match(r"\s*-\s*\[([xX ])\]\s*(.+)", line)
+ if checkbox_match:
+ checked = checkbox_match.group(1).lower() == "x"
+ content = checkbox_match.group(2).strip()
+ status = "completed" if checked else "waiting"
+ return "", status
+
+ # Format with status marker
+ status_match = re.match(r"\s*(\d+)\.\s*\[status:(\w+)\]\s*(.+)", line, re.IGNORECASE)
+ if status_match:
+ task_id = status_match.group(1)
+ status = status_match.group(2).lower()
+ content = status_match.group(3).strip()
+ return task_id, status
+
+ # Format with status marker (before square brackets)
+ bracket_match = re.match(r"\s*(\d+)\.\s*\[([xX✅🔄⏳❌])\]\s*(.+)", line)
+ if bracket_match:
+ task_id = bracket_match.group(1)
+ status_char = bracket_match.group(2)
+ content = bracket_match.group(3).strip()
+
+ status_map = {
+ "x": "completed", "X": "completed", "✅": "completed",
+ "🔄": "running", "⏳": "waiting", "❌": "cancelled",
+ }
+ status = status_map.get(status_char, "waiting")
+ return task_id, status
+
+ # Plain numbered format
+ number_match = re.match(r"\s*(\d+)\.\s+(.+)", line)
+ if number_match:
+ task_id = number_match.group(1)
+ content = number_match.group(2).strip()
+
+ # Detect status from content
+ if "✅" in content or "[completed]" in content:
+ status = "completed"
+ elif "🔄" in content or "[in progress]" in content:
+ status = "running"
+ elif "❌" in content or "[cancel]" in content:
+ status = "cancelled"
+ else:
+ status = "waiting"
+
+ return task_id, status
+
+ return "", ""
+
+ def collect(self) -> TodoStats:
+ """
+ Collect to-do data
+
+ Returns:
+ TodoStats: to-do statistics data
+ """
+ stats = TodoStats()
+
+ todo_file = self._find_latest_todo_file()
+ if not todo_file:
+ return stats
+
+ content = self._read_file_safe(todo_file)
+ if not content:
+ return stats
+
+ task_counter = 0
+
+ for line in content.split("\n"):
+ if not line.strip():
+ continue
+
+ task_id, status = self._parse_status(line)
+
+ if status:
+ task_counter += 1
+
+ # Extract task content (remove status marker)
+ content_clean = re.sub(r"\[status:\w+\]\s*", "", line)
+ content_clean = re.sub(r"\[[xX✅🔄⏳❌]\]\s*", "", content_clean)
+ content_clean = re.sub(r"^\s*-\s*\[[xX ]\]\s*", "", content_clean)
+ content_clean = re.sub(r"^\s*\d+\.\s*", "", content_clean)
+ content_clean = content_clean.strip()
+
+ if not task_id:
+ task_id = str(task_counter)
+
+ task = TodoTask(id=task_id, content=content_clean, status=status)
+
+ stats.tasks.append(task)
+ stats.total += 1
+
+ if status == "completed":
+ stats.completed += 1
+ elif status == "running":
+ stats.running += 1
+ elif status == "waiting":
+ stats.waiting += 1
+ elif status == "cancelled":
+ stats.cancelled += 1
+
+ return stats
+```
+
+### 4.5 Collection Module Initialization File
+
+```python
+# collectors/__init__.py
+# -*- coding: utf-8 -*-
+"""
+Advanced Daily Report Generator - Data Collection Module
+
+Includes:
+- GitCollector: Collects Git commit records
+- EmailCollector: Collects email statistics
+- MemoryCollector: Collects memory data
+- TodoCollector: Collects todo items
+- DataAggregator: Aggregates collected data
+"""
+
+from .git_collector import GitCollector, GitCommit
+from .email_collector import EmailCollector, EmailStats
+from .memory_collector import MemoryCollector
+from .todo_collector import TodoCollector
+from .aggregator import DataAggregator, CollectedData
+
+__all__ = [
+ "GitCollector", "GitCommit",
+ "EmailCollector", "EmailStats",
+ "MemoryCollector",
+ "TodoCollector",
+ "DataAggregator", "CollectedData",
+]
+```
+
+### 4.6 Data Aggregator
+```python
+# collectors/aggregator.py
+# -*- coding: utf-8 -*-
+"""
+Data Aggregator
+
+Function:
+- Integrate data from all collectors
+- Apply unified time window filtering
+- Provide a unified data access interface
+"""
+
+import json
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from pathlib import Path
+from typing import Any, Optional
+
+from .email_collector import EmailCollector, EmailStats
+from .git_collector import GitCollector, GitStats
+from .memory_collector import MemoryCollector, MemoryData
+from .todo_collector import TodoCollector, TodoStats
+
+
+@dataclass
+class CollectedData:
+ """Aggregated data"""
+
+ date: str # Date
+ collected_at: datetime # Collection time
+
+ # Git data
+ git: GitStats = field(default_factory=GitStats)
+
+ # Email data
+ email: EmailStats = field(default_factory=EmailStats)
+
+ # Memory data
+ memory: MemoryData = field(default_factory=MemoryData)
+
+ # Todo data
+ todo: TodoStats = field(default_factory=TodoStats)
+
+ # Historical comparison data
+ comparison: dict[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> dict:
+ return {
+ "date": self.date,
+ "collected_at": self.collected_at.isoformat(),
+ "git": self.git.to_dict(),
+ "email": self.email.to_dict(),
+ "memory": self.memory.to_dict(),
+ "todo": self.todo.to_dict(),
+ "comparison": self.comparison,
+ }
+
+
+class DataAggregator:
+ """Data Aggregator"""
+
+ def __init__(
+ self,
+ workspace_dir: str | Path,
+ git_repo: Optional[str | Path] = None,
+ email_config: Optional[dict] = None,
+ ):
+ """
+ Initialize the data aggregator
+
+ Args:
+ workspace_dir: workspace directory
+ git_repo: Git repository path
+ email_config: Email configuration
+ """
+ self.workspace_dir = Path(workspace_dir)
+
+ # Initialize each collector
+ self.memory_collector = MemoryCollector(self.workspace_dir)
+ self.todo_collector = TodoCollector(self.workspace_dir)
+
+ # Git collector (optional)
+ self.git_collector = None
+ if git_repo:
+ self.git_collector = GitCollector(git_repo)
+
+ # Email collector (optional)
+ self.email_collector = None
+ self.email_config = email_config
+
+ def collect(self, date: Optional[str] = None, include_comparison: bool = True) -> CollectedData:
+ """
+ Aggregate and collect data
+
+ Args:
+ date: Date string, default is today
+ include_comparison: Whether to include historical comparison
+
+ Returns:
+ CollectedData: Aggregated data
+ """
+ if date is None:
+ date = datetime.now().strftime("%Y-%m-%d")
+
+ data = CollectedData(
+ date=date,
+ collected_at=datetime.now(),
+ )
+
+ # Collect memory data
+ data.memory = self.memory_collector.collect(date)
+
+ # Collect todo data
+ data.todo = self.todo_collector.collect()
+
+ # Collect Git data
+ if self.git_collector:
+ data.git = self.git_collector.get_commits(date)
+
+ # Collect email data
+ if self.email_config and self.email_collector is None:
+ try:
+ self.email_collector = EmailCollector(
+ email_address=self.email_config["address"],
+ auth_code=self.email_config["auth_code"],
+ provider=self.email_config.get("provider", "163"),
+ )
+ except Exception as e:
+ print(f"Email collector initialization failed: {e}")
+
+ if self.email_collector:
+ try:
+ with self.email_collector:
+ data.email = self.email_collector.get_stats(date)
+ except Exception as e:
+ print(f"Email data collection failed: {e}")
+
+ # Historical comparison
+ if include_comparison:
+ data.comparison = self._generate_comparison(data, date)
+
+ return data
+
+ def _generate_comparison(self, current_data: CollectedData, date: str) -> dict:
+ """Generate historical comparison data"""
+ comparison = {}
+
+ try:
+ current_date = datetime.strptime(date, "%Y-%m-%d")
+
+ # Compare with yesterday
+ yesterday = (current_date - timedelta(days=1)).strftime("%Y-%m-%d")
+ yesterday_data = self._collect_light(yesterday)
+
+ comparison["yesterday"] = {
+ "git_commits": {
+ "current": current_data.git.total_commits,
+ "previous": yesterday_data.git.total_commits,
+ "change": current_data.git.total_commits - yesterday_data.git.total_commits,
+ },
+ "todo_completed": {
+ "current": current_data.todo.completed,
+ "previous": yesterday_data.todo.completed,
+ "change": current_data.todo.completed - yesterday_data.todo.completed,
+ },
+ }
+
+ except Exception:
+ pass
+
+ return comparison
+
+ def _collect_light(self, date: str) -> CollectedData:
+ """Lightweight collection (only Git and memory)"""
+ data = CollectedData(
+ date=date,
+ collected_at=datetime.now(),
+ )
+
+ if self.git_collector:
+ data.git = self.git_collector.get_commits(date)
+
+ data.memory = self.memory_collector.collect(date)
+
+ return data
+```
+
+---
+
+## Chapter 5 | Work Analysis and Report Generation Module
+
+This chapter integrates the complete implementation of the work analysis engine and the report generator, and is the core processing layer of the daily report generator.
+
+### 5.1 Data Source Collection Instructions
+**The script will automatically collect the following data**:
+
+| Data source | Collection method | Configuration location |
+| --- | --- | --- |
+| **Git repository** | `git log` command | Repository path: `D:/Download/jiuwenclaw` |
+| **NetEase email** | IMAP protocol | `.env`: `EMAIL_ADDRESS`, `EMAIL_TOKEN` |
+| **Memory system** | Read MD files | `workspace/agent/memory/YYYY-MM-DD.md` |
+| **To-do items** | Parse todo.md | `workspace/session/*/todo.md` |
+
+### 5.2 Execution Method
+**Important**: This skill collects data by executing a Python script, and must be executed using `mcp_exec_command`:
+
+```bash
+# Generate daily report
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py daily --save
+
+# Generate weekly report
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py weekly --save
+
+# Generate monthly report
+cd D:/Download/jiuwenclaw && python workspace/agent/skills/daily-report/run_report.py monthly --save
+```
+
+### 5.3 Efficiency Metrics Data Structure
+```python
+# analyzers/work_analyzer.py
+# -*- coding: utf-8 -*-
+"""
+Work analysis engine
+
+Functions:
+- Efficiency metrics calculation
+- Trend comparison analysis
+- Keyword extraction
+- Intelligent summary generation
+"""
+
+import re
+from collections import Counter
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta
+from typing import Any, Optional
+
+
+@dataclass
+class EfficiencyMetrics:
+ """Efficiency metrics"""
+
+ # Task metrics
+ task_completion_rate: float = 0.0 # Task completion rate
+ tasks_completed: int = 0 # Completed tasks count
+ tasks_total: int = 0 # Total tasks count
+
+ # Git metrics
+ commit_count: int = 0 # Number of commits
+ files_changed: int = 0 # Number of modified files
+ lines_added: int = 0 # Number of lines added
+ lines_deleted: int = 0 # Number of lines deleted
+ net_lines: int = 0 # Number of net added lines
+
+ # Communication metrics
+ emails_received: int = 0 # Emails received
+ emails_sent: int = 0 # Emails sent
+
+ # Comprehensive metrics
+ productivity_score: float = 0.0 # Productivity score (0-100)
+ focus_score: float = 0.0 # Focus score (0-100)
+
+ def to_dict(self) -> dict:
+ return {
+ "task_completion_rate": round(self.task_completion_rate, 2),
+ "tasks_completed": self.tasks_completed,
+ "tasks_total": self.tasks_total,
+ "commit_count": self.commit_count,
+ "files_changed": self.files_changed,
+ "lines_added": self.lines_added,
+ "lines_deleted": self.lines_deleted,
+ "net_lines": self.net_lines,
+ "emails_received": self.emails_received,
+ "emails_sent": self.emails_sent,
+ "productivity_score": round(self.productivity_score, 2),
+ "focus_score": round(self.focus_score, 2),
+ }
+```
+
+### 5.4 Productivity Score Calculation Logic
+```python
+class WorkAnalyzer:
+ """Work analysis engine"""
+
+ # Stop words list
+ STOPWORDS = {
+ "的", "了", "是", "在", "我", "有", "和", "就", "不", "人", "都", "一",
+ "上", "也", "很", "到", "说", "要", "去", "你", "会", "着", "没有", "看",
+ "自己", "这", "那", "什么", "这个", "那个", "可以", "然后", "还是", "但是",
+ "如果", "因为", "所以", "或者", "而且", "已经", "可能", "应该", "需要",
+ }
+
+ def _calculate_productivity_score(self, metrics: EfficiencyMetrics) -> float:
+ """
+ Calculate productivity score
+
+ Scoring rules:
+ 1. Task completion contribution (highest 40 points)
+ - Completion rate * 40
+
+ 2. Code contribution (highest 30 points)
+ - Number of commits: 5 points each time, up to 15 points
+ - Lines of code: 1 point for every 50 lines, up to 15 points
+
+ 3. Communication contribution (highest 20 points)
+ - Sent emails: 2 points per email, up to 10 points
+ - Received emails: 1 point per 5 emails, up to 10 points
+
+ 4. Activity contribution (highest 10 points)
+ - Any output gets 10 points
+ """
+ score = 0.0
+
+ # Task completion contribution (highest 40 points)
+ score += metrics.task_completion_rate * 40
+
+ # Code contribution (highest 30 points)
+ code_score = min(metrics.commit_count * 5, 15)
+ code_score += min(metrics.net_lines / 50, 15)
+ score += code_score
+
+ # Communication contribution (highest 20 points)
+ communication_score = min(metrics.emails_sent * 2, 10)
+ communication_score += min(metrics.emails_received / 5, 10)
+ score += communication_score
+
+ # Activity contribution (highest 10 points)
+ if metrics.commit_count > 0 or metrics.tasks_completed > 0:
+ score += 10
+
+ return min(score, 100.0)
+
+ def _calculate_focus_score(self, metrics: EfficiencyMetrics) -> float:
+ """
+ Calculate focus score
+
+ Scoring rules:
+ 1. Base score 100 points
+ 2. Uncompleted task deduction: deduct 5 points for each, maximum deduct 30 points
+ 3. Commit frequency bonus: reasonable commits (≤5 times) add 10 points
+ 4. Email interference deduction: more than 20 emails, deduct 0.5 points per email, maximum deduct 20 points
+ """
+ score = 100.0
+
+ # Deduction for unfinished tasks
+ pending_tasks = metrics.tasks_total - metrics.tasks_completed
+ score -= min(pending_tasks * 5, 30)
+
+ # Commit frequency (moderately optimal)
+ if metrics.commit_count > 0:
+ if metrics.commit_count <= 5:
+ score += 10
+ elif metrics.commit_count > 10:
+ score -= 5
+
+ # Email interference deduction
+ if metrics.emails_received > 20:
+ score -= min((metrics.emails_received - 20) * 0.5, 20)
+
+ return max(score, 0.0)
+```
+
+---
+
+### 5.5 Report Generator Core Code
+```python
+# generators/report_generator.py
+# -*- coding: utf-8 -*-
+"""
+Report Generator
+
+Supports:
+- Daily report generation
+- Weekly report generation (aggregates one week of data)
+- Monthly report generation (aggregates one month of data)
+"""
+
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from typing import Optional
+
+from ..analyzers.work_analyzer import AnalysisResult, WorkAnalyzer
+from ..collectors.aggregator import CollectedData, DataAggregator
+
+
+@dataclass
+class ReportConfig:
+ """Report configuration"""
+
+ report_type: str = "daily" # daily, weekly, monthly
+ date: str = ""
+ include_trends: bool = True
+ include_suggestions: bool = True
+ output_format: str = "markdown"
+
+
+class ReportGenerator:
+ """Report generator"""
+
+ def __init__(
+ self,
+ data_aggregator: DataAggregator,
+ work_analyzer: Optional[WorkAnalyzer] = None,
+ ):
+ self.data_aggregator = data_aggregator
+ self.work_analyzer = work_analyzer or WorkAnalyzer()
+
+ def generate_daily(self, date: Optional[str] = None) -> str:
+ """Generate daily report"""
+ if date is None:
+ date = datetime.now().strftime("%Y-%m-%d")
+
+ # Collect data
+ data = self.data_aggregator.collect(date, include_comparison=True)
+
+ # Analyze data
+ analysis = self.work_analyzer.analyze(data.to_dict())
+
+ # Generate report
+ return self._render_daily_report(data, analysis)
+
+ def generate_weekly(self, end_date: Optional[str] = None) -> str:
+ """Generate weekly report"""
+ if end_date is None:
+ end_date = datetime.now()
+ else:
+ end_date = datetime.strptime(end_date, "%Y-%m-%d")
+
+ start_date = end_date - timedelta(days=6)
+ start_str = start_date.strftime("%Y-%m-%d")
+ end_str = end_date.strftime("%Y-%m-%d")
+
+ # Collect one week of data
+ week_data = self.data_aggregator.collect_week(end_str)
+
+ # Aggregate week data
+ aggregated = self._aggregate_week_data(week_data)
+
+ return self._render_weekly_report(aggregated, start_str, end_str)
+
+ def _render_daily_report(self, data: CollectedData, analysis: AnalysisResult) -> str:
+ """Render daily report Markdown"""
+ lines = [
+ f"# 📋 Work Daily Report - {data.date}",
+ "",
+ "## 📊 Today’s Overview",
+ "",
+ "| Metric | Value |",
+ "|------|------|",
+ f"| Commit Count | {analysis.metrics.commit_count} |",
+ f"| Tasks Completed | {analysis.metrics.tasks_completed}/{analysis.metrics.tasks_total} |",
+ f"| Code Changes | +{analysis.metrics.lines_added}/-{analysis.metrics.lines_deleted} |",
+ f"| Productivity Score | {analysis.metrics.productivity_score:.1f} |",
+ "",
+ ]
+
+ # Completed tasks
+ completed_tasks = [t for t in data.todo.tasks if t.status == "completed"]
+ if completed_tasks:
+ lines.extend(["## ✅ Completed Tasks", ""])
+ for task in completed_tasks[:10]:
+ lines.append(f"- {task.content}")
+ lines.append("")
+
+ # Git commit records
+ if data.git.commits:
+ lines.extend([
+ "## 💻 Code Commits",
+ "",
+ "| Time | Commit Message | Change |",
+ "|------|----------|------|",
+ ])
+ for commit in data.git.commits[:10]:
+ time_str = commit.date.strftime("%H:%M") if commit.date else "-"
+ lines.append(
+ f"| {time_str} | {commit.message[:40]} | "
+ f"+{commit.insertions}/-{commit.deletions} |"
+ )
+ lines.append("")
+
+ # Trend comparison
+ if analysis.trends.vs_yesterday:
+ lines.extend(["## 📈 Trend Comparison", ""])
+ vs_y = analysis.trends.vs_yesterday
+ if "commits" in vs_y:
+ change = vs_y["commits"]["change"]
+ symbol = "↑" if change > 0 else "↓" if change < 0 else "→"
+ lines.append(f"- Commits: {symbol} {abs(change)} times")
+ lines.append("")
+
+ # Work suggestions
+ if analysis.suggestions:
+ lines.extend(["## 💡 Work Suggestions", ""])
+ for i, suggestion in enumerate(analysis.suggestions, 1):
+ lines.append(f"{i}. {suggestion}")
+ lines.append("")
+
+ return "\n".join(lines)
+```
+
+### 5.6 Analysis Module Initialization File
+```python
+# analyzers/__init__.py
+# -*- coding: utf-8 -*-
+"""
+Advanced Version Daily Report Generator - Analysis Module
+
+Contains:
+- WorkAnalyzer: work analysis engine
+- EfficiencyMetrics: efficiency metrics
+- TrendComparison: trend comparison
+- AnalysisResult: analysis result
+"""
+
+from .work_analyzer import (
+ WorkAnalyzer,
+ EfficiencyMetrics,
+ TrendComparison,
+ AnalysisResult,
+)
+
+__all__ = [
+ "WorkAnalyzer",
+ "EfficiencyMetrics",
+ "TrendComparison",
+ "AnalysisResult",
+]
+```
+
+### 5.7 Generation Module Initialization File
+```python
+# generators/__init__.py
+# -*- coding: utf-8 -*-
+"""
+Report generation module
+
+Supports:
+- Daily report generation
+- Weekly report generation
+- Monthly report generation
+"""
+
+from .report_generator import ReportGenerator, ReportConfig
+
+__all__ = ["ReportGenerator", "ReportConfig"]
+```
+
+### 5.8 Entry Script (run_report.py)
+```python
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+Daily/Weekly/Monthly Report Generation Entry Script (Independent Version)
+
+Usage:
+ python run_report.py daily [date] # Generate daily report
+ python run_report.py weekly [end_date] # Generate weekly report
+ python run_report.py monthly [year] [month] # Generate monthly report
+"""
+
+import argparse
+import io
+import os
+import sys
+import subprocess
+from datetime import datetime
+from pathlib import Path
+
+# Fix Windows encoding problems
+if sys.platform == "win32":
+ sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
+ sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
+
+# Get script directory
+SKILL_DIR = Path(__file__).parent
+PROJECT_ROOT = SKILL_DIR.parent.parent.parent.parent
+
+
+def collect_git_stats(date: str = None) -> dict:
+ """Collect Git submission statistics"""
+ if date is None:
+ date = datetime.now().strftime("%Y-%m-%d")
+
+ try:
+ result = subprocess.run(
+ ["git", "-C", str(PROJECT_ROOT), "log",
+ f"--since={date} 00:00:00",
+ f"--until={date} 23:59:59",
+ "--format=%H|%s|%an|%ai",
+ "--numstat"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ timeout=30
+ )
+
+ commits = []
+ total_insertions = 0
+ total_deletions = 0
+
+ if result.stdout:
+ current_commit = None
+ for line in result.stdout.strip().split("\n"):
+ if "|" in line and len(line.split("|")) >= 4:
+ parts = line.split("|")
+ if current_commit:
+ commits.append(current_commit)
+ current_commit = {
+ "hash": parts[0][:8],
+ "message": parts[1],
+ "author": parts[2],
+ "insertions": 0,
+ "deletions": 0
+ }
+ elif current_commit and "\t" in line:
+ stat_parts = line.split("\t")
+ if len(stat_parts) >= 2:
+ try:
+ ins = int(stat_parts[0]) if stat_parts[0] != "-" else 0
+ dels = int(stat_parts[1]) if stat_parts[1] != "-" else 0
+ current_commit["insertions"] += ins
+ current_commit["deletions"] += dels
+ total_insertions += ins
+ total_deletions += dels
+ except ValueError:
+ pass
+
+ if current_commit:
+ commits.append(current_commit)
+
+ return {
+ "total_commits": len(commits),
+ "total_insertions": total_insertions,
+ "total_deletions": total_deletions,
+ "commits": commits
+ }
+ except Exception as e:
+ return {"error": str(e)}
+
+
+def generate_daily_report(date: str = None) -> str:
+ """Generate daily report"""
+ if date is None:
+ date = datetime.now().strftime("%Y-%m-%d")
+
+ # Collect Git data
+ git_stats = collect_git_stats(date)
+
+ # Read memory file
+ memory_file = PROJECT_ROOT / "workspace" / "agent" / "memory" / f"{date}.md"
+ memory_content = ""
+ work_items = []
+
+ if memory_file.exists():
+ memory_content = memory_file.read_text(encoding="utf-8")
+ for line in memory_content.split("\n"):
+ stripped = line.strip()
+ if stripped.startswith("-") or stripped.startswith("*"):
+ item = stripped.lstrip("-* ").strip()
+ if item and not item.startswith("<!--"):
+ work_items.append(item)
+
+ # Find todo file
+ todo_file = None
+ session_dir = PROJECT_ROOT / "workspace" / "session"
+ if session_dir.exists():
+ todo_files = list(session_dir.rglob("todo.md"))
+ if todo_files:
+ todo_files.sort(key=lambda f: f.stat().st_mtime, reverse=True)
+ todo_file = todo_files[0]
+
+ # Parse todo
+ completed_tasks = []
+ pending_tasks = []
+
+ if todo_file and todo_file.exists():
+ todo_content = todo_file.read_text(encoding="utf-8")
+ import re
+ for line in todo_content.split("\n"):
+ stripped = line.strip()
+ # Checkbox format
+ match = re.match(r"-\s*\[([xX ])\]\s*(.+)", stripped)
+ if match:
+ checked = match.group(1).lower() == "x"
+ task = match.group(2).strip()
+ if checked:
+ completed_tasks.append(task)
+ else:
+ pending_tasks.append(task)
+
+ # Generate report
+ lines = [
+ f"# 📋 Work Daily Report - {date}",
+ "",
+ "## 📊 Today’s Overview",
+ "",
+ "| Metric | Value |",
+ "|------|------|",
+ f"| Code Commits | {git_stats.get('total_commits', 0)} times |",
+ f"| Code Changes | +{git_stats.get('total_insertions', 0)}/-{git_stats.get('total_deletions', 0)} |",
+ f"| Completed Tasks | {len(completed_tasks)} items |",
+ f"| In Progress | {len(pending_tasks)} items |",
+ "",
+ ]
+
+ # Completed tasks
+ if completed_tasks:
+ lines.extend(["## ✅ Completed Tasks", ""])
+ for task in completed_tasks[:10]:
+ lines.append(f"- {task}")
+ lines.append("")
+
+ # Code submissions
+ if git_stats.get("commits"):
+ lines.extend([
+ "## 💻 Code Submissions",
+ "",
+ "| Time | Submission Info | Changes |",
+ "|------|----------|------|",
+ ])
+ for commit in git_stats["commits"][:10]:
+ lines.append(
+ f"| {commit.get('hash', '-')} | {commit.get('message', '-')[:40]} | "
+ f"+{commit.get('insertions', 0)}/-{commit.get('deletions', 0)} |"
+ )
+ lines.append("")
+
+ # Work records
+ if work_items:
+ lines.extend(["## 📝 Today’s Work Records", ""])
+ for item in work_items[:10]:
+ lines.append(f"- {item}")
+ lines.append("")
+
+ # Tomorrow plan
+ lines.extend(["## 🔜 Tomorrow’s Plan", ""])
+ if pending_tasks:
+ for task in pending_tasks[:5]:
+ lines.append(f"- {task}")
+ else:
+ lines.append("- To be filled in")
+ lines.append("")
+
+ return "\n".join(lines)
+
+
+def generate_monthly_report(year: int = None, month: int = None) -> str:
+ """Generate monthly report"""
+ now = datetime.now()
+ if year is None:
+ year = now.year
+ if month is None:
+ month = now.month
+
+ import calendar
+ _, days_in_month = calendar.monthrange(year, month)
+
+ # Collect data for the whole month
+ total_commits = 0
+ total_insertions = 0
+ total_deletions = 0
+ active_days = 0
+
+ for day in range(1, days_in_month + 1):
+ date = f"{year:04d}-{month:02d}-{day:02d}"
+ stats = collect_git_stats(date)
+ commits = stats.get("total_commits", 0)
+ total_commits += commits
+ total_insertions += stats.get("total_insertions", 0)
+ total_deletions += stats.get("total_deletions", 0)
+ if commits > 0:
+ active_days += 1
+
+ # Generate report
+ lines = [
+ f"# 📋 Work Monthly Report - {year}年{month}月",
+ "",
+ "## 📊 This Month’s Overview",
+ "",
+ "| Metric | Value |",
+ "|------|------|",
+ f"| Active Days | {active_days}/{days_in_month} days |",
+ f"| Code Submissions | {total_commits} times |",
+ f"| Code Changes | +{total_insertions}/-{total_deletions} |",
+ "",
+ "## 📝 Work Summary",
+ "",
+ f"This month completed {total_commits} code submissions,",
+ f"Net added code {total_insertions - total_deletions} lines.",
+ "",
+ "## 🔜 Next Month’s Plan",
+ "",
+ "- Continue improving project features",
+ "",
+ ]
+
+ return "\n".join(lines)
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Daily/Weekly/Monthly Report Generator")
+ parser.add_argument(
+ "type",
+ choices=["daily", "weekly", "monthly"],
+ help="Report type: daily (daily report), weekly (weekly report), monthly (monthly report)"
+ )
+ parser.add_argument("--date", "-d", help="Date (YYYY-MM-DD)")
+ parser.add_argument("--year", "-y", type=int, help="Year")
+ parser.add_argument("--month", "-m", type=int, help="Month")
+ parser.add_argument("--save", "-s", action="store_true", help="Save to file")
+
+ args = parser.parse_args()
+
+ try:
+ if args.type == "daily":
+ date = args.date or datetime.now().strftime("%Y-%m-%d")
+ print(f"Generating daily report ({date})...", file=sys.stderr)
+ content = generate_daily_report(date)
+ date_str = date
+
+ elif args.type == "weekly":
+ date = args.date or datetime.now().strftime("%Y-%m-%d")
+ print(f"Generating weekly report (as of {date})...", file=sys.stderr)
+ # Weekly report temporarily use daily report instead
+ content = generate_daily_report(date)
+ date_str = date
+
+ elif args.type == "monthly":
+ now = datetime.now()
+ year = args.year or now.year
+ month = args.month or now.month
+ print(f"Generating monthly report ({year}年{month}月)...", file=sys.stderr)
+ content = generate_monthly_report(year, month)
+ date_str = f"{year:04d}-{month:02d}"
+
+ # Output result
+ print("\n" + "=" * 50)
+ print(content)
+ print("=" * 50)
+
+ # Save file
+ if args.save:
+ reports_dir = PROJECT_ROOT / "workspace" / "agent" / "reports"
+ reports_dir.mkdir(parents=True, exist_ok=True)
+ filepath = reports_dir / f"{args.type}-{date_str}.md"
+ filepath.write_text(content, encoding="utf-8")
+ print(f"\nReport saved to: {filepath}", file=sys.stderr)
+
+ except Exception as e:
+ print(f"Error: {e}", file=sys.stderr)
+ import traceback
+ traceback.print_exc()
+ sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
+```
+
+---
+
+## Chapter 6|Configuration and Deployment
+### 6.1 Environment Variable Configuration (.env)
+The `.env` configuration actually used by this project:
+
+```plain
+# Model configuration
+MODEL_PROVIDER="OpenAI"
+MODEL_NAME="Qwen/Qwen3-235B-A22B-Instruct-2507"
+API_BASE="https://api-inference.modelscope.cn/v1"
+API_KEY="ms***-bd3e-257a7eef7922"
+
+# Email configuration (NetEase 163 email)
+# Note: EMAIL_TOKEN uses the mailbox authorization code, not the login password
+# Get方式: log in to 163 email → Settings → POP3/SMTP/IMAP → enable IMAP service → get authorization code
+EMAIL_ADDRESS=zx***@163.com
+EMAIL_TOKEN=***
+EMAIL_PROVIDER=163
+
+# Embedding configuration (optional, used for memory system vectorization)
+EMBED_API_KEY=
+EMBED_API_BASE=
+EMBED_MODEL=
+
+# Other API configuration
+JINA_API_KEY=
+SERPER_API_KEY=
+PERPLEXITY_API_KEY=
+```
+
+**Email configuration description**:
+
++ `EMAIL_ADDRESS`:the complete email address
++ `EMAIL_TOKEN`:email authorization code (not login password); it needs to be obtained after enabling IMAP service in the mailbox settings
++ `EMAIL_PROVIDER`:email provider; currently supports three NetEase mailboxes: `163`、`126`、`yeah`
+
+### 6.2 Heartbeat Configuration (HEARTBEAT.md)
+```markdown
+# Heartbeat tasks
+
+In this file, configure tasks that JiuwenClaw needs to execute periodically.
+
+---
+
+## Active task items
+
+<!-- After this line, add tasks to be executed, one per line, starting with "- " -->
+
+- Generate today's work daily report
+
+<!-- Weekly report tasks (triggered every Friday) -->
+<!-- - Generate this week's work weekly report -->
+
+<!-- Monthly report tasks (triggered at the end of every month) -->
+<!-- - Generate this month's work monthly report -->
+
+---
+
+## Completed task items
+
+<!-- Move completed tasks to this section or delete -->
+
+---
+
+## Task description
+
+### Daily report task
+- **Trigger time**: Every day 18:00 - 18:30 (configured according to config.yaml)
+- **Push target**: Feishu
+- **Content**: Today's Git commits, task completion status, email statistics, work efficiency analysis
+
+### Weekly report task
+- **Trigger time**: Every Friday 18:00 - 18:30
+- **Push target**: Feishu
+- **Content**: This week's data aggregation, trend analysis, next week's plan
+
+### Monthly report task
+- **Trigger time**: The last day of every month 18:00 - 18:30
+- **Push target**: Feishu
+- **Content**: This month's data aggregation, achievements summary, next month's plan
+
+---
+
+## Configuration method
+
+Modify the `heartbeat` configuration in `config/config.yaml`:
+
+```yaml
+heartbeat:
+ every: 3600 # Heartbeat interval (seconds)
+ target: feishu # Push target
+ active_hours:
+ start: 18:00 # Effective start time
+ end: 18:30 # Effective end time
+```
+
+**After modification, restart the service for it to take effect.**
+
+```
+
+### 6.3 Git Repository Configuration
+The Git repositories monitored by this project (the script will automatically read):
+
+```plain
+Repository path: D:/Download/jiuwenclaw
+```
+
+**Collection method**:The script collects data through the `git log` command; no additional configuration is needed.
+
+**Collection content**:
+
++ Commit hash
++ Commit message
++ Commit author, commit time
++ Number of changed files, number of added lines, number of deleted lines
+
+**Execution command**:
+
+```bash
+# The git command executed internally by the script
+git -C D:/Download/jiuwenclaw log --since="2026-03-07 00:00:00" --until="2026-03-07 23:59:59" --format="%H|%s|%an|%ai" --numstat
+```
+
+**Multi-repository support**:If you need to monitor multiple repositories, expand `DataAggregator`:
+
+```python
+# Example of extending configuration (needs to be implemented by yourself)
+git_repos:
+ - path: "D:/Download/jiuwenclaw"
+ name: "jiuwenclaw"
+ - path: "D:/Projects/another-repo"
+ name: "another-project"
+```
+
+### 6.4 Feishu Channel Configuration (config.yaml)
+The Feishu configuration actually used by this project in `config.yaml`:
+
+```yaml
+heartbeat:
+ # Heartbeat interval (seconds), default 3600 (1 hour)
+ every: 3600
+ # The channel for returning heartbeat results
+ target: feishu
+ # Heartbeat effective time window (local time)
+ # Daily report generation will be triggered during 18:00-18:30
+ active_hours:
+ start: 18:00
+ end: 18:30
+
+channels:
+ feishu:
+ # Feishu application configuration
+ # Get方式: Feishu Open Platform → create an enterprise self-built application → get App ID and App Secret
+ app_id: cli_a92035b1823a9cd2
+ app_secret: *****
+ encrypt_key: # Encryption key (optional)
+ verification_token: # Verification token (optional)
+ allow_from: # IP whitelist (optional)
+ enabled: true
+```
+
+**Feishu application configuration steps**:
+
+1. Access [Feishu Open Platform](https://open.feishu.cn/)
+2. Create an enterprise self-built application to get `app_id` and `app_secret`
+3. Add “Bot” capability
+4. Configure event subscription: `im.message.receive_v1`
+5. Publish the app to all members
+
+---
+
+## Chapter 7|Test and Verification
+### 7.1 Test Data Collector
+```bash
+# Test Git collection (collect commit records for the specified date)
+cd D:\Download\jiuwenclaw
+python workspace/agent/skills/daily-report/run_report.py daily --date 2026-03-07
+
+# Test monthly report generation (collect data for the whole month)
+python workspace/agent/skills/daily-report/run_report.py monthly --year 2026 --month 3
+
+# Test saving to a file
+python workspace/agent/skills/daily-report/run_report.py daily --save
+```
+
+<!-- This is an image. The OCR content is: ASE)(JIUWENCLAW) PS D:\DOWNLOAD\JIUWE JIUWENCLAW> -MONTH 3 THLY--YEAR 2026 LOAD PYTHON WORKSPACE/AGENT/SKILLS/DAILY-REPORT/RUN REPORT.PY MONTHLY --Y 正在生成月报(2026年3月)... #自工作月报 2026年3月 本月概览 ## 指标数值 活跃天数|3/31天I 代码提交|6次| 代码变更 +73181/-616 工作总结 ## 本月共完成6次代码提交, 净增代码 72565行. 下月计划 ## 继续完善项目功能 -->
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772862327714-d3e2c75f-83bc-46fc-8c25-e95e723f9dee.png)
+
+### 7.2 Complete Test Procedure
+#### Step 1:Create a To-do List (test to-do data collection)
+Send in Feishu or the Web frontend:
+
+```plain
+Help me create a to-do list:
+1. Complete daily report generator skill development
+2. Implement the Git commit data collection module
+3. Implement the email statistics data collection module
+4. Configure Feishu channel push
+5. Test the heartbeat trigger function
+6. Write the development documentation
+```
+
+<!-- This is an image. The OCR content is: Help me create a to-do list: 1.Complete daily report generator skill development 2.Implement GIT commit data collection module 3.Implement email statistics data collection module 4.Configure Feishu channel push 5.Test heartbeat trigger function 6.Write development documentation JIUWENCLAW daily report sending It has successfully added 6 new tasks requested by the user to the to-do list, and recorded them in today's memory file. The current to-do list has been updated, including: 1.Complete daily report generator skill development 2.Implement GIT commit data collection module 3.Implement email statistics data collection module 4.Configure Feishu channel push 5.Test heartbeat trigger function 6.Write development documentation The previously completed tasks are kept at the bottom of the list as historical records. The new task list is ready and can be started. -->
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772862423989-5bdc4508-5cfe-4465-86c1-ba696f0246f8.png)
+
+#### Step 2:Simulate Work Records (test memory data collection)
+```plain
+Help me record today's work:
+- In the morning, completed the writing of the SKILL.md skill definition file
+- Created the Git commit collector git_collector.py
+- Created the email statistics collector email_collector.py
+- Created the memory data collector memory_collector.py
+- Created the to-do items collector todo_collector.py
+- In the afternoon, completed the work analysis engine work_analyzer.py
+- Implemented the report generator report_generator.py
+- Configured heartbeat and Feishu push
+- Conducted functional testing and debugging
+```
+
+<!-- This is an image. The OCR content is: Help me record today's work: In the morning, completed the writing of the SKILL.MD skill definition file Created the GIT commit collector GIT_COLLECTOR.PY Created the email statistics collector EMAIL_COLLECTOR.PY Created the memory data collector MEMORY_COLLECTOR.PY Created the to-do items collector TODO_COLLECTOR.PY In the afternoon, completed the work analysis engine WORK_ANALYZER.PY -Implemented the report generator REPORT_GENERATOR.PY Configured heartbeat and Feishu push Conducted functional testing and debugging JIUWENCLAW daily report sending It has successfully recorded today's work content to "MEMORY/2026-03-07.MD", including in the morning the completion of writing the SKILL.MD compiler and the creation of multiple collectors (GIT, COLLECTOR.PY, EMAIL_COLLECTOR.PY, MEMORY_COLLECTOR.PY, TODO_COLLECTOR.PY), as well as completing in the afternoon the work analysis engine and report generator development, and the configuration and functional testing. The record is completed. -->
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772862487637-8206f051-3e56-42b9-acc5-fa6a9d2ae819.png)
+
+<!-- This is an image. The OCR content is: 中口口口 终谈() 编码(日) 转到(G) 远泽(S) 文件() 运行() 直谷(M) 12026-03-07MD U X 发行说明:1.110.0 WORKSPACE>AGENL>MEMORY>因26-03-07MD>-07M 当施行办状态 两户请农创连设为适息,包容区项目标任务:1,充效白招生成员以期开发,2.配置飞手原油铁道, Q 上午完成了SKTLLIND滨与 创建了辅助原本 配出了心跳和飞书 .下午进行了功能测试开差执行 DAILY-REPORT 技能生成今日日报,2826-03-07 节#操作记录 用户请求创建新的消办清单,包含6项任务: REPORTS WORKSPACE ,实现GIT提交数据采集模块 实现邮箱统计数据采集模块 MEMORY 配置飞书频道推送 测试心既触发功能 2026-03-07MD 6.缩与开发文档新增任务 用户创建新的待办清单,包含以下6项任务: 完成日报生威器技能开发 MEMORY.OB SHM 实现GIT提交数据采集楼块 MEMORY.DB-WAL 实现由难统计数据采集模块 CA MEMORYMD 配置飞书须道推送 测试心跳触发功能 编写开发文档 当前待办状态 口 KILLS 插入新任务列表,原任务保留历史记录:工作日志 DAILY-REPORT 上午完成了 SKILL,MD 技能定义文件编与 ANALYZERS 创建了 GIT 提交采集器 GIT COLLECTOR.PY 理了邮件统计采货器EMAIL_COLLECTOR.PY 创建了记亿数据采集器 MENORY COLLECTOR.PY 创建了待办,事项采集器TODO COLLECTOR.PY REPERT_HELPER PY 下午完成了工作分析引引草WORK ANALYZER.PY RUN REPORT.PY 实现了报告生成器 REPORT.GENERATOR.PY SKILL.MD 配置了心跳和飞书推送 LINANCAL-DOCUMENI-PARSER 进行了功能测试和调试 INBNOAL PARSEC.OW SOULMD GIBGNORE BUILDPS1 >大男 行2.列10 空标2 UIF8 CRIF () MSTDOWN BFNITH >* GA MAIN' & ( 0 LICK TO UPDATE IS READY,CLICK TO REST 0乡 FINISH SETUP -->
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772862510145-a395e7f8-075a-4f4c-8757-10d4ba4074d9.png)
+
+#### Step 3:Submit Code (test Git data collection)
+```bash
+# Submit some code in the project to test Git collection
+git add .
+git commit -m "feat: Add complete daily report generator function
+
+- Implement multi-data source collection (Git/email/memory/todo)
+- Add work analysis engine
+- Support daily/weekly/monthly report generation
+- Configure Feishu push and heartbeat trigger"
+```
+
+<!-- This is an image. The OCR content is: JIUWENCLAW daily report sending JIUWENCLAW daily report sending Bot #Submit some code in the project to test GIT collection GIT ADD. GIT COMMIT -M "FEAT:Add complete daily report generator function Implement multi-data source collection (GIT/email/memory/todo) Add work analysis engine Support daily/weekly/monthly report generation Configure Feishu push and heartbeat trigger" JIUWENCLAW daily report sending It has successfully executed the GIT commit operation: 1. Disabled the prompt information for ignored files 2. Used the -F parameter to forcibly add files ignored by `GITIGNORE" 3. Successfully committed the code, the commit message is: 1 FEAT:Add complete daily report generator function 2 3 -Implement multi-data source collection (GIT/email/memory/todo) 4-Add work analysis engine 5 Support daily/weekly/monthly report generation 6-Configure Feishu push and heartbeat trigger The code submission is completed. -->
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772862545512-3cf0d5fd-ab1e-4d4a-bea2-520a843302f4.png)
+
+<!-- This is an image. The OCR content is: Historical records: Current project's GIT history Commit hash Date Commit message FEAT:Add complete daily report generator function 60ED98E 2026-03-07 FEAT:Optimize Feishu CHANNEL 8DBELCF 2026-03-06 FIX HEARTBEAT C1FE22D 2026-03-05 1D7CBDA 2026-03-05 SOME BUG FIX F21649A 2026-03-03 UPDATE:Update file README.MD 6C0F844 UPDATE:Update file README.MD 2026-03-03 INITIAL COMMIT 2026-03-03 C08E67E Total of 7 commits; the project started from March 3. Today's (March 7) latest commit is FEAT:Add complete daily report generator function. -->
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772862651273-81909a36-6233-46a6-b35f-2e21f783f7cc.png)
+
+#### Step 4:Generate the Daily Report
+```plain
+Generate today's daily report
+```
+
+<!-- This is an image. The OCR content is: JIUWENCLAW daily report sending JIUWENCLAW daily report sending Bot Heart Generate today's daily report JIUWENCLAW daily report sending Work daily report-2026-03-07 #and ### Values Metrics 1 time code submission +15/-0 code changes 7 items completed tasks 9 items in progress ## Completed tasks B.Execute DAILY-REPORT skill to generate today's daily report|COMPLETED Completed today's daily report has been regenerated, saved path: REPORTS/DAILY-2026-03-07.MD C.Execute DAILY-REPORT according to ability to generate today's daily report COMPLETED Completed today's daily report has been regenerated, saved path: REPORTS/DAILY-2026-03-07.MD J.Complete daily report generator skill development is completed K Configure Feishu channel push COMPLETED |Feishu channel push configuration completed 1.Record today's work log|COMPLETED|Has recorded today's work content to MEMORY/2026-03- 07.MD O.Execute DAILY-REPORT skill to generate today's daily report|COMPLETED Completed today's daily report has been regenerated, saved path: REPORTS/DAILY-2026-03-07.MD P.Execute DAILY-REPORT skill to generate today's daily report|COMPLETED|Generated a draft of today's daily report, saved path: REPORTS/DAILY-2026-03-06.MD Code submission change submission info time FEAT:Add daily report generator complete... +15/-0 60ED98EB ### Daily work record User requested to create a to-do list containing 6 tasks User submitted code to test GIT collection function Successfully executed DAILY-REPORT skill to generate today's daily report, saved path: REPORTS/DAILY-2026-07.MD Tomorrow's plan .Generate today's daily report|WAITING D.Complete daily report generator skill development | WAITING Implement GIT commit data collection module|WAITING +Implement email statistics data collection module|WAITING G Configure Feishu channel push | WAITING Send to JIUWENCLAW daily report sending -->
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772863455503-33da3fbd-859f-4ea0-8578-7a846c5438c4.png)
+
+#### Step 5:Generate the Monthly Report (test email data collection)
+```plain
+Read this month's content in the mailbox and organize it into a monthly report
+```
+
+<!-- This is an image. The OCR content is: JIUWENCLAW daily report sending Mechanic bot JIUWENCLAW daily report sending Read the month's content in the mailbox and organize it into a monthly report JIUWENCLAW daily report sending It has successfully generated the monthly report for March 2026 for you! Here is the full content: #Work monthly report- March 2026 井井 This month's overview Values Metrics Active days 4/31 days Code submissions 7 times Sender: Alibaba Cloud Time: FRI, 6 MAR 2026 14:42:14+0800 (CST) Content preview: A{COLOR:并1366EC;TEXT-DECORATION:NONE;] This email was sent by Alibaba Cloud, automatically sent by the system, please do not reply directly, thanks! Product solution documentation and community free trial pricing Cloud marketplace to learn more LET'S MAKE SURE THIS IS THE RIGHT EMAIL ADDRESS FOR YOU.PLEASE ENTER THIS VERIFICATION ###Spring recruitment good luck has arrived! Participate in activities to win prizes freely Sender: NetEase Mail Time: WED, 4 MAR 2026 12:45:12+0800 (CST) Content preview: @MEDIA SCREEN AND(MIN-WIDTH:750PX)AND(-WEBKIT-MIN-DEVICE-PIXEL-RATIO:1) [DIV.NTES-EDM-DESKTOP{DISPLAY:BLOCK!IMPORTANT]DIV.NTES-EDM MAHILOFDIENFARNANALIMNNNSTANFTLAMANIS ERREON SND (MIN.ININTH.7GANY) You can log in to Lingxia product market to use: HTTPS://WWW.IXWA... Otherwise, please immediately HREF-"HTTPS://HELP.STEAMPOWERED.COM//EN/WIZARD/HELPWITHLOGIN> your Steam password<... ###Your STEAM account recent changes Sender:'STEAM SUPPORT" Time:TUE,03 MAR 2026 05:16:00-0800 Content preview: QFRZG605, Hello! Time:TUE.03 MAR 2026 05:14:11 -0800 Content preview: GFRZG605, Hello! Below is the code required when changing your STEAM login credentials: Your account verification code is: PWJK8 If you did not try to change your STEAM login credentials on a computer located in TOKYO, Japan, please ignore this email. It may be another user entered incorrect login information. Have a nice day, STEAM Team This notice has been sent to the email address associated with your STEAM account. This email was automatically generated by the system, please... Sent to JIUWENCLAW daily report sending -->
+![](https://cdn.nlark.com/yuque/0/2026/png/27326384/1772866734099-2059a8b7-632a-4e42-978b-0bdc80f9c2b5.png)
+
+## Chapter 9|Expansion Directions
+### 9.1 More Data Sources
+| Data source | Collection method | Value |
+| --- | --- | --- |
+| WeCom/ DingTalk | API | Message communication statistics |
+| Schedules/Calendar | CalDAV/iCal | Meeting time analysis |
+| Jira/Feishu tasks | API | Project progress tracking |
+| Browser history | Local database | Tracing work content |
+
+### 9.2 Smarter Analysis
++ **Work mode recognition**:identify efficient time periods, inefficient time periods
++ **Fatigue level early warning**:based on continuous work duration
++ **Time allocation suggestions**:optimize task priority
+
+### 9.3 Richer Interaction
++ **Feishu button interaction**:edit, regenerate, push
++ **Daily report editing functionality**:save after online modification
++ **Approval process**:Leader review and confirmation
+
+---
+
+## To end with
+
+From the original simple idea—“Can AI help me write daily reports”—to this now complete multi-data source daily report generation system, this project has undergone multiple iterations and optimizations.
+
+The biggest challenge encountered during development was **IMAP protocol adaptation for the 163 email**. NetEase mail security restrictions caused the `SELECT` command to return the “Unsafe Login” error. After repeated debugging and consulting materials, the following solution was ultimately used:
+
+1. **Register ID command**:`imaplib.Commands['ID'] = ('NONAUTH', 'AUTH', 'SELECTED')`
+2. **Send identity declaration**:immediately send the `ID` command after logging in
+3. **Use STATUS command**:bypass the SELECT restriction to obtain email statistics
+
+This system can now:
+- Automatically collect Git commits, email statistics, memory records, and to-do items
+- Generate daily, weekly, and monthly reports
+- Push on a schedule through Feishu
+- Read email content and generate summaries
+
+If you are also trying to build similar AI Agent applications, I hope this article can provide you with some references.
+
+> **Let the AI Agent truly become an intelligent work assistant, starting with the advanced daily report generator.**
+>
+> — JiuwenClaw Advanced daily report generator development practice
+
+---
+
+**References**:
+- [163 email IMAP ID command solution](https://github.com/HKUDS/nanobot/issues/1123)
+- [NetEase email help center](https://help.mail.163.com/)
+- [Python imaplib documentation](https://docs.python.org/3/library/imaplib.html)
+
+
+
diff --git a/docs/en/development-practices/README.md b/docs/en/development-practices/README.md
index 219db1ba6d..05f5d44b52 100644
--- a/docs/en/development-practices/README.md
+++ b/docs/en/development-practices/README.md
@@ -1,8 +1,8 @@
# Development practices
-In-depth write-ups from building real skills on JiuwenClaw:
+Long-form notes on designing and shipping JiuwenClaw skills in real projects.
-- [Advanced daily report generator](JiuwenClaw-Daily-Report-Generator.md) — multi-source data, analysis, cron, Feishu
-- [Code review assistant](JiuwenClaw-Code-Review-Assistant.md) — Ruff, Radon, Bandit, scoring, Feishu reports
+- [JiuwenClaw Daily Report Generator](JiuwenClaw-Daily-Report-Generator.md) — Multi-source daily, weekly, and monthly reports with heartbeat and Feishu delivery.
+- [JiuwenClaw Code Review Assistant](JiuwenClaw-Code-Review-Assistant.md) — Layered static analysis, scoring, and Markdown / Feishu reporting.
Chinese originals: `docs/zh/开发实践/`.
diff --git a/docs/discord.md b/docs/zh/Discord.md
similarity index 93%
rename from docs/discord.md
rename to docs/zh/Discord.md
index 8f04a95bc9..d8a16aa40f 100644
--- a/docs/discord.md
+++ b/docs/zh/Discord.md
@@ -21,7 +21,7 @@ Bot 使用 **Bot Token** 登录,可在配置的服务器频道与/或私信(
1. 打开 [https://discord.com/developers/applications](https://discord.com/developers/applications)。
2. 点击 **New Application**,填写名称并创建。
-![创建 Discord 应用](assets/images/discord/1_create_new_app.png)
+![创建 Discord 应用](../assets/images/discord/1_create_new_app.png)
后续 **OAuth2 / 安装** 与 **Bot** 用户均在此应用下配置。
@@ -33,7 +33,7 @@ Bot 使用 **Bot Token** 登录,可在配置的服务器频道与/或私信(
2. 在 **Token** 区域点击 **Reset Token** 并确认。
3. **立即复制 Token** 并妥善保存;重置后 Discord 通常只完整展示一次。
-![重置并复制 Bot Token](assets/images/discord/2_reset_bot_token.png)
+![重置并复制 Bot Token](../assets/images/discord/2_reset_bot_token.png)
**安全提示**
@@ -53,7 +53,7 @@ JiuwenClaw 需要读取用户消息的**文本内容**。Discord 要求通过「
2. 在 **Privileged Gateway Intents** 中打开 **MESSAGE CONTENT INTENT**。
3. 若页面有保存提示,请保存。
-![开启 Message Content Intent](assets/images/discord/3_set_required_intent.png)
+![开启 Message Content Intent](../assets/images/discord/3_set_required_intent.png)
未开启时,Bot 可能在线但无法读取普通消息的文本内容。
@@ -75,7 +75,7 @@ JiuwenClaw 需要读取用户消息的**文本内容**。Discord 要求通过「
- 勾选与上表一致的 **Bot Permissions**。
- 下方截图中显示了推荐的权限配置,必选内容已标出。
-![服务器安装范围与 Bot 权限](assets/images/discord/4_set_guild_install_scope_and_permissions.png)
+![服务器安装范围与 Bot 权限](../assets/images/discord/4_set_guild_install_scope_and_permissions.png)
请以截图与上述能力为准;若菜单名称与截图略有差异,选择等效项即可。
@@ -90,7 +90,7 @@ JiuwenClaw 需要读取用户消息的**文本内容**。Discord 要求通过「
在门户中复制生成的 **URL** 或 **Install link**,在浏览器中打开完成授权。
-![选择安装方式并复制设置链接](assets/images/discord/5_select_install_methods_and_copy_setup_link.png)
+![选择安装方式并复制设置链接](../assets/images/discord/5_select_install_methods_and_copy_setup_link.png)
安装完成后:
diff --git "a/docs/OpenTelemetry\345\217\257\350\247\202\346\265\213\346\200\247.md" "b/docs/zh/OpenTelemetry\345\217\257\350\247\202\346\265\213\346\200\247.md"
similarity index 100%
rename from "docs/OpenTelemetry\345\217\257\350\247\202\346\265\213\346\200\247.md"
rename to "docs/zh/OpenTelemetry\345\217\257\350\247\202\346\265\213\346\200\247.md"
diff --git a/docs/zh/Quickstart.md b/docs/zh/Quickstart.md
index 1b18b50f73..51350b847f 100644
--- a/docs/zh/Quickstart.md
+++ b/docs/zh/Quickstart.md
@@ -92,6 +92,7 @@ jiuwenclaw-app
```bash
npm run build
cd ../../
+ uv run jiuwenclaw-init
uv run jiuwenclaw-start
```
@@ -99,6 +100,7 @@ jiuwenclaw-app
```bash
cd ../../
+ uv run jiuwenclaw-init
uv run jiuwenclaw-start dev
```
diff --git a/docs/zh/SUMMARY.md b/docs/zh/SUMMARY.md
index 173b9dc0c7..1ec7cce028 100644
--- a/docs/zh/SUMMARY.md
+++ b/docs/zh/SUMMARY.md
@@ -4,8 +4,9 @@
- [配置说明](配置信息.md)
- [使用指南](README.md)
- [频道](频道.md)
+ - [Discord](Discord.md)
- [WhatsApp(中文)](whatsapp.md)
- - [WhatsApp(English)](whatsapp_en.md)
+ - [WhatsApp(English)](../en/WhatsApp.md)
- [命令行指令](命令行指令.md)
- [心跳](心跳.md)
- [定时任务](定时任务.md)
diff --git "a/docs/zh/\351\242\221\351\201\223.md" "b/docs/zh/\351\242\221\351\201\223.md"
index e0b5e457ee..6efdc164c2 100644
--- "a/docs/zh/\351\242\221\351\201\223.md"
+++ "b/docs/zh/\351\242\221\351\201\223.md"
@@ -436,7 +436,7 @@ channels:
当前版本已经支持 Discord 频道接入。在「频道管理」中配置并启用 Discord Bot,也可以手动编辑 `config.yaml`。
-**分步图文(开发者后台创建 Bot、Intent、安装链接、频道管理)见 [discord.md](discord.md)。**
+**分步图文(开发者后台创建 Bot、Intent、安装链接、频道管理)见 [Discord.md](Discord.md)。**
- `bot_token`
- `application_id`