autosnippet 3.3.4 → 3.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/README.md +174 -83
  2. package/config/constitution.yaml +2 -0
  3. package/dist/lib/cli/KnowledgeSyncService.d.ts +5 -1
  4. package/dist/lib/cli/KnowledgeSyncService.js +5 -2
  5. package/dist/lib/domain/knowledge/values/Stats.d.ts +1 -1
  6. package/dist/lib/domain/knowledge/values/Stats.js +2 -2
  7. package/dist/lib/external/mcp/handlers/consolidated.js +178 -0
  8. package/dist/lib/external/mcp/tools.js +2 -1
  9. package/dist/lib/injection/modules/InfraModule.js +4 -1
  10. package/dist/lib/injection/modules/KnowledgeModule.js +23 -0
  11. package/dist/lib/repository/evolution/ProposalRepository.d.ts +99 -0
  12. package/dist/lib/repository/evolution/ProposalRepository.js +255 -0
  13. package/dist/lib/service/bootstrap/UiStartupTasks.d.ts +17 -4
  14. package/dist/lib/service/bootstrap/UiStartupTasks.js +53 -5
  15. package/dist/lib/service/evolution/DecayDetector.d.ts +4 -3
  16. package/dist/lib/service/evolution/DecayDetector.js +97 -22
  17. package/dist/lib/service/evolution/KnowledgeMetabolism.d.ts +4 -2
  18. package/dist/lib/service/evolution/KnowledgeMetabolism.js +29 -2
  19. package/dist/lib/service/evolution/ProposalExecutor.d.ts +62 -0
  20. package/dist/lib/service/evolution/ProposalExecutor.js +360 -0
  21. package/dist/lib/service/evolution/StagingManager.js +5 -3
  22. package/dist/lib/service/guard/GuardCrossFileChecks.js +2 -0
  23. package/dist/lib/service/guard/ReverseGuard.d.ts +1 -1
  24. package/dist/lib/service/guard/ReverseGuard.js +32 -2
  25. package/dist/lib/service/knowledge/SourceRefReconciler.d.ts +2 -0
  26. package/dist/lib/service/knowledge/SourceRefReconciler.js +48 -0
  27. package/dist/lib/shared/schemas/mcp-tools.d.ts +1 -0
  28. package/dist/lib/shared/schemas/mcp-tools.js +4 -0
  29. package/package.json +1 -1
package/README.md CHANGED
@@ -2,181 +2,272 @@
2
2
 
3
3
  # AutoSnippet
4
4
 
5
- Extract code patterns from your codebase into a knowledge base, and serve them to AI coding assistants in your IDE — so generated code actually follows your team's conventions.
5
+ Extract patterns from your codebase into a knowledge base that AI coding assistants can query in your IDE — so generated code actually follows your team's conventions.
6
6
 
7
7
  [![npm version](https://img.shields.io/npm/v/autosnippet.svg?style=flat-square)](https://www.npmjs.com/package/autosnippet)
8
8
  [![License](https://img.shields.io/npm/l/autosnippet.svg?style=flat-square)](https://github.com/GxFn/AutoSnippet/blob/main/LICENSE)
9
- [![Node](https://img.shields.io/badge/node-%E2%89%A520-brightgreen?style=flat-square)](https://nodejs.org)
9
+ [![Node](https://img.shields.io/badge/node-%E2%89%A522-brightgreen?style=flat-square)](https://nodejs.org)
10
10
 
11
- [中文文档](README_CN.md)
11
+ [中文](README_CN.md)
12
12
 
13
13
  </div>
14
14
 
15
15
  ---
16
16
 
17
- - [Why](#why) · [Get Started](#get-started) · [Using in Your IDE](#using-in-your-ide) · [More Capabilities](#more-capabilities) · [Dashboard](#dashboard) · [IDE Support](#ide-support) · [Architecture](docs/architecture.en.md)
17
+ - [Why](#why) · [Getting Started](#getting-started) · [Using in IDE](#using-in-ide) · [Evolution Architecture](#evolution-architecture) · [Engineering Capabilities](#engineering-capabilities) · [IDE Support](#ide-support) · [Docs](#docs)
18
18
 
19
19
  ## Why
20
20
 
21
- Copilot and Cursor don't know how your team writes code. They'll generate something that works, but it won't look like yours — wrong naming, wrong patterns, wrong abstractions. You end up rewriting the AI's output or explaining the same conventions in every PR review.
21
+ Copilot and Cursor don't know how your team writes code. What they generate works, but doesn't look like yours — wrong naming, wrong patterns, wrong abstractions. You end up rewriting AI output or explaining the same conventions in every Code Review.
22
22
 
23
- AutoSnippet builds a **persistent local memory** for your project. It scans your codebase, extracts the patterns that matter (with your approval), and makes them available to any AI tool via [MCP](https://modelcontextprotocol.io/). This knowledge lives locally, doesn't consume your LLM context window, and is injected on demand when AI needs it the more knowledge accumulates, the more your AI writes code that actually follows your conventions.
23
+ AutoSnippet builds a layer of **localized project memory**. It scans your codebase, extracts valuable patterns (with your approval), and makes them searchable by all AI tools via [MCP](https://modelcontextprotocol.io/). Knowledge persists locally, never consuming the LLM context window it's injected on-demand when the AI needs it. The more knowledge accumulates, the more the generated code matches your conventions.
24
24
 
25
25
  ```
26
26
  Your code → AI extracts patterns → You review → Knowledge base
27
-
28
- Cursor / Copilot / VS Code / Xcode
29
-
30
- AI follows your patterns
27
+
28
+ Cursor / Copilot / VS Code / Xcode
29
+
30
+ AI generates your way
31
31
  ```
32
32
 
33
- ## Get Started
33
+ ## Getting Started
34
34
 
35
35
  ```bash
36
36
  npm install -g autosnippet
37
37
 
38
38
  cd your-project
39
- asd setup # workspace + DB + MCP configs (auto-detects Cursor / VS Code / Trae / Qoder)
40
- asd ui # start the background service (MCP Server + Dashboard) — IDE and MCP tools require this
39
+ asd setup # Initialize workspace + database + MCP config (auto-detects Cursor / VS Code / Trae / Qoder)
40
+ asd ui # Start background service (MCP Server + Dashboard) — IDE and MCP tools depend on this
41
41
  ```
42
42
 
43
43
  > **Trae / Qoder users:** After `asd setup`, run `asd mirror` to sync `.cursor/` config to `.trae/` / `.qoder/`.
44
44
 
45
- ## Using in Your IDE
45
+ ## Using in IDE
46
46
 
47
- `asd setup` takes care of everything. Open your IDE's **Agent Mode** (Cursor Composer / VS Code Copilot Chat / Trae) and start talking.
47
+ `asd setup` configures everything. Open your IDE's **Agent Mode** (Cursor Composer / VS Code Copilot Chat / Trae) and start chatting.
48
48
 
49
- > **First time:** Enable the `autosnippet` server in your IDE's MCP settings.
49
+ > **First time:** Manually enable the `autosnippet` service in your IDE's MCP settings.
50
50
 
51
- > **Tip:** The stronger your IDE Agent model, the better the results. Choose Claude Opus 4 / Sonnet 4, GPT-5, or Gemini 3 Pro in Cursor / Copilot for more accurate patterns and fewer false positives.
51
+ > **Tip:** Stronger models work better. We recommend Claude Opus 4 / Sonnet 4, GPT-5, or Gemini 3 Pro in Cursor / Copilot for more accurate patterns and fewer false positives.
52
52
 
53
- ### Cold Start: Build the project knowledge base
53
+ ### Cold Start: Build Your Knowledge Base
54
54
 
55
- > 💬 *"Run a cold start, build the project knowledge base"*
55
+ > 💬 *"Cold start build the project knowledge base"*
56
56
 
57
- The agent scans the entire project and extracts your team's coding patterns, architecture conventions, and call idioms, generating a project Wiki along the way. You only need to do this once, then it's daily use from here.
57
+ The Agent scans your entire project, extracting coding patterns, architecture conventions, and call habits, while generating a project Wiki. Cold start runs once; after that, it's daily use.
58
58
 
59
- ### Daily: just say what you need
59
+ ### Daily Use: Just Ask
60
60
 
61
61
  | You say | You get |
62
62
  |---------|---------|
63
- | ① *"How do we write API endpoints in this project?"* | Code that matches your project's style, not generic examples |
64
- | ② *"Write a user registration endpoint"* | Generated code automatically follows the API conventions you just looked up |
65
- | ③ *"Check if this file follows the project conventions"* | Pre-commit convention check — fewer round-trips in Code Review |
66
- | ④ *"Save this error handling as a project convention"* | One save, and everyone's AI writes it this way from now on |
63
+ | ① *"How do we write API endpoints in this project?"* | Code following your project's actual style, not generic examples |
64
+ | ② *"Write a user registration endpoint"* | Generated code automatically follows the API conventions just retrieved |
65
+ | ③ *"Check if this file follows our conventions"* | Pre-commit convention check — fewer back-and-forths in Code Review |
66
+ | ④ *"Save this error handling pattern as a project convention"* | One-time capture every team member's AI learns this pattern |
67
67
 
68
- After the Agent writes code, the Guard compliance engine automatically checks the diff — violations are self-repaired without you lifting a finger.
68
+ After the Agent finishes writing code, the Guard compliance engine auto-checks the diff — violations trigger self-repair, no manual intervention needed.
69
69
 
70
- ### It gets better over time
70
+ ### Gets Better Over Time
71
71
 
72
- Review candidates in Dashboard (`asd ui`) → approve as **Recipe** → AI follows your conventions → you spot a good new pattern save it → AI gets even better at writing code your team's way. Recipes are local Markdown files, tracked by git, never lost between conversations. AI queries them on demand without filling the context window your knowledge base can grow without slowing AI down.
72
+ Review and approve candidates in Dashboard (`asd ui`) → they become **Recipes** → AI references them when generating code → you spot new good patternskeep capturing → AI increasingly writes like a team member. Knowledge is local Markdown files, travels with git, never disappears with conversations, and doesn't consume context window no matter how large the knowledge base grows, it won't slow down AI.
73
73
 
74
- ## More Capabilities
74
+ ---
75
75
 
76
- ### Guard Compliance Engine
76
+ ## Evolution Architecture
77
77
 
78
- Beyond the Agent's automatic checks, Guard also plugs into your engineering workflow:
78
+ AutoSnippet isn't a static knowledge tool — it's a **knowledge organism**. Recipes are its cells — the IDE Agent is the external driving force, and each interaction triggers coordinated responses from different organs inside the organism.
79
79
 
80
- ```bash
81
- asd guard src/ # Check a directory
82
- asd guard:staged # Pre-commit: only staged files
83
- asd guard:ci --threshold 90 # CI quality gate
80
+ ```
81
+ IDE Agent (Cursor / Copilot / Trae)
82
+
83
+ Capture · Write · Search · Shift · Complete · Boundary
84
+
85
+ ═════════════════▼══════════════════════════════════════
86
+ ║ AutoSnippet Knowledge Organism ║
87
+ ║ ║
88
+ ║ ┌─ Panorama (Skeleton) ──── Project Structure ───┐ ║
89
+ ║ │ │ ║
90
+ ║ │ Signal (Nerves) ◄────► Governance (Digest) │ ║
91
+ ║ │ ↕ ↕ │ ║
92
+ ║ │ ┌──────────┐ │ ║
93
+ ║ │ │ Recipe │ │ ║
94
+ ║ │ │ Living │ │ ║
95
+ ║ │ │Knowledge │ │ ║
96
+ ║ │ └──────────┘ │ ║
97
+ ║ │ ↕ ↕ │ ║
98
+ ║ │ Guard (Immunity) ◄────► Tool Forge (Create) │ ║
99
+ ║ │ │ ║
100
+ ║ └────────────────────────────────────────────────┘ ║
101
+ ║ ║
102
+ ══════════════════════════════════════════════════════════
84
103
  ```
85
104
 
86
- Built-in multi-language compliance rules (regex + AST) checking naming, deprecated APIs, thread safety, and more — each violation comes with a fix example.
105
+ ### Agent Actions × Organism Responses
87
106
 
88
- ### Call Graph
107
+ Each IDE Agent action triggers coordinated responses from different organs:
89
108
 
90
- Want to know the blast radius before refactoring a function? Static call graph analysis across 8 languages — query any function's callers, callees, and impact radius via MCP tools `call_graph` and `call_context`.
109
+ | Agent Action | Organism Response | Organs Involved |
110
+ |-------------|------------------|-----------------|
111
+ | **Capture knowledge** — extract and submit patterns | Digestive system metabolizes internally: confidence routing → staging observation → evolves or decays. Developer retains full intervention rights | Digest → Nerves |
112
+ | **Write code** — start coding | Nervous system analyzes intent, auto-injects relevant Recipes with sourceRefs source evidence for higher trust | Nerves → Recipe |
113
+ | **Search knowledge** — active search | Precise retrieval based on current intent + file context, multi-path fusion ranking, dynamic weight adjustment per scenario | Nerves → Recipe |
114
+ | **Shift intent** — change direction | Nervous system records drift signals, senses problems; immune system reverse-checks whether Recipes are still valid | Nerves → Immunity |
115
+ | **Complete task** — finish writing code | Immune system triggers Guard Review, attaches relevant Recipes for Agent to fix violations | Immunity → Recipe |
116
+ | **Capability boundary** — hit an unsolvable problem | Creation system calls LLM to forge temporary tools, vm-sandboxed execution, auto-reclaimed on expiry | Create |
91
117
 
92
- ### Semantic Search
118
+ ### Five Organs
93
119
 
94
- Keyword search only finds literal matches. With an LLM API Key, search upgrades to vector + BM25 hybrid retrieval asking "how to manage memory" finds Recipes about garbage collection, semantically similar results rank first.
120
+ **SkeletonPanorama**
95
121
 
96
- ### Intent-Aware Search (Prime)
122
+ The organism's structural awareness. AST + call graphs infer module roles & layers (four-signal fusion, 13 role types), Tarjan SCC computes coupling, Kahn topological sort infers layering, DimensionAnalyzer generates 11-dimension health radar, outputting coverage heatmaps and gap reports. All organs share this project overview.
97
123
 
98
- At the start of every conversation, the Agent auto-triggers prime to intelligently inject knowledge based on the user query and current file. IntentExtractor extracts tech terms, infers language and module, performs cross-language (EN↔CJK) synonym expansion; PrimeSearchPipeline executes multi-query parallel search (raw query + term query + file context + focused synonyms), returning precise results after 3-layer quality filtering. Supports long natural-language sentences, short exact matches, and mixed-language queries.
124
+ **Digest Governance**
99
125
 
100
- ### Recipe Source Evidence (sourceRefs)
126
+ The metabolic engine for new knowledge entering the organism. ContradictionDetector finds conflicts, RedundancyAnalyzer flags duplication, DecayDetector scores decay (6 strategies + 4-dimension scoring), ConfidenceRouter numerically routes (≥ 0.85 auto-publishes, < 0.2 rejects). ProposalExecutor auto-executes evolution proposals on expiry (7 types, differentiated observation windows). Six-state lifecycle: `pending → staging → active → evolving/decaying → deprecated`.
101
127
 
102
- Recipes carry the project file paths analyzed during creation as evidence. The 📍 sourceRefs in search results point to real project files the Agent can trust and reference them without self-verification. Path validity is monitored automatically, with git rename auto-repair.
128
+ **NervesSignal + Intent**
103
129
 
104
- ### Knowledge Graph
130
+ Senses all Agent behavior. IntentExtractor extracts terms, infers language and module, cross-language synonym expansion, identifies 4 scenarios. SignalBus unifies 12 signal types (guard / search / usage / lifecycle / quality / exploration / panorama / decay / forge / intent / anomaly / guard_blind_spot), HitRecorder batches usage events. When the Agent shifts intent, nerves record drift signals and coordinate the immune system for reverse checking.
105
131
 
106
- Recipes have relationships. Query impact paths, dependency depth, and related Recipes for any module once you've accumulated enough knowledge, it helps you see the structure behind it.
132
+ **ImmunityGuard**
107
133
 
108
- ### Self-Cycling Signal Mechanism
134
+ Bidirectional immune system. Forward: four-layer detection (regex → code-level multi-line → tree-sitter AST → cross-file), built-in 8-language rules, three-state output (pass / violation / uncertain). Backward: ReverseGuard verifies Recipe-referenced API symbols still exist (5 drift types). Auto-triggers Review when Agent completes a task, handing violations along with relevant Recipes to the Agent for fixing. RuleLearner tracks P/R/F1 for auto-tuning.
109
135
 
110
- AutoSnippet quietly collects your coding habit signals in the background (Guard violations, conversation topics, Recipe usage, candidate backlog, operation logs, git diff), and AI mines patterns to recommend Skills. Don't like one? Delete it zero commitment. But if a recommendation happens to nail a team habit you never wrote down — that's a freebie. Your adopt/dismiss actions feed back into the algorithm, making recommendations more precise over time.
136
+ **CreateTool Forge**
111
137
 
112
- ### Lark Remote Programming
138
+ Creativity at capability boundaries. Three progressive modes — Reuse (0ms) → Compose (10ms, atomic tool assembly) → Generate (~5s, LLM writes code → vm sandbox validation: 5s timeout + 18 security rules). Temporary tools have 30min TTL, auto-reclaimed on expiry. LLM participates only during forging; execution is fully deterministic.
113
139
 
114
- Send a message on Lark (Feishu) from your phone — intent recognition auto-routes it to your local IDE, Copilot Agent Mode executes, results sent back to Lark. Refactor, screenshot, look up conventions — you don't need to be near your computer, as long as it's not asleep.
140
+ ### Design Philosophy
115
141
 
116
- ### Recipe Remote Repository
142
+ 1. **AI Compile-Time + Engineering Runtime** — LLM produces deterministic artifacts; runtime is pure engineering logic
143
+ 2. **Deterministic Marking + Probabilistic Resolution** — Each layer does its deterministic part; uncertainty escalates to AI
144
+ 3. **Orthogonal Composition > Specialized Subclasses** — Capability × Strategy × Policy replaces N subclasses
145
+ 4. **Signal-Driven > Time-Driven** — Trigger on signal saturation, not scheduled scans
146
+ 5. **Defense in Depth** — Constitution → Gateway → Permission → SafetyPolicy → PathGuard → ConfidenceRouter
117
147
 
118
- `asd remote <url>` converts your knowledge base directory into an independent git sub-repository. Share Recipes across projects with separate access control, unified management, and version tracking.
148
+ > Organ implementation details, engineering metrics, and defense chain breakdown in [Technical Reference](docs/technical-reference.en.md)
119
149
 
120
- > Semantic search, signal recommendations, Lark remote, and other AI-driven features require an LLM API Key. Set it up in the Dashboard's LLM Config panel, or add it to your `.env` — supports Google / OpenAI / Claude / DeepSeek / Ollama, with auto-fallback.
150
+ ---
121
151
 
122
- ## Dashboard
152
+ ## Engineering Capabilities
123
153
 
124
- Run `asd ui` to manage everything in one place:
154
+ The above is the organism itself. Below are the engineering integration capabilities it exposes.
125
155
 
126
- <div align="center">
127
- <img src="docs/images/dashboard-help-en.png" alt="Dashboard Help" width="800" />
128
- </div>
156
+ ### Guard CLI
129
157
 
130
- ## IDE Support
158
+ ```bash
159
+ asd guard src/ # Check directory
160
+ asd guard:staged # pre-commit: staged files only
161
+ asd guard:ci --min-score 90 # CI quality gate
162
+ ```
131
163
 
132
- | IDE | Integration | How it connects |
133
- |-----|-------------|----------------|
134
- | **VS Code** | Extension + MCP | `#asd` in Agent Mode; search, directives, CodeLens, Guard |
135
- | **Cursor** | MCP + Rules | `.cursor/mcp.json` + `.cursor/rules/` |
136
- | **Claude Code** | MCP + CLAUDE.md | `CLAUDE.md` + MCP tools; supports hooks |
137
- | **Trae / Qoder** | MCP | Auto-generated by `asd setup` |
138
- | **Xcode** | File watcher | `asd watch` + file directives + snippet sync |
139
- | **Lark (Feishu)** | Bot + WebSocket | Send commands from phone → IDE executes via Copilot Agent Mode |
164
+ ### Multi-Language AST
165
+
166
+ 11-language tree-sitter: Go · Python · Java · Kotlin · Swift · JS · TS · Rust · ObjC · Dart · C#. 5-stage CallGraph, incremental analysis, 8 project types auto-detected.
167
+
168
+ ### 6-Channel IDE Delivery
169
+
170
+ Knowledge changes auto-deliver to IDE-consumable formats:
171
+
172
+ | Channel | Path | Content |
173
+ |---------|------|---------|
174
+ | **A** | `.cursor/rules/autosnippet-project-rules.mdc` | alwaysApply one-liner rules |
175
+ | **B** | `.cursor/rules/autosnippet-patterns-{topic}.mdc` | When/Do/Don't themed rules |
176
+ | **C · D** | `.cursor/skills/` | Project Skills + development docs |
177
+ | **F** | `AGENTS.md` / `CLAUDE.md` / `.github/copilot-instructions.md` | Agent instructions |
178
+ | **Mirror** | `.qoder/` / `.trae/` | IDE mirrors |
140
179
 
141
- All configs generated by `asd setup`. Run `asd upgrade` to refresh after updates.
180
+ ### More
181
+
182
+ - **Bootstrap Cold Start** — 6-phase · 10-dimension analysis, one-time knowledge base build
183
+ - **Knowledge Graph** — 14 relationship types, query impact paths and dependency depth
184
+ - **Semantic Search** — HNSW vector index + field-weighted scoring hybrid, RRF fusion + 7-signal ranking
185
+ - **sourceRefs** — Recipes carry source evidence, Agent trusts without self-verification
186
+ - **Lark Remote** — Message from phone, intent routes to Bot or IDE
187
+ - **Remote Repository** — Recipe directory as git sub-repo, shared across projects
188
+
189
+ > AI-driven features require an LLM API Key. Supports Google / OpenAI / Claude / DeepSeek / Ollama with automatic fallback.
190
+
191
+ ---
142
192
 
143
193
  ## Project Structure
144
194
 
145
- After `asd setup`, your project gets:
195
+ After `asd setup`, your project gains these:
146
196
 
147
197
  ```
148
198
  your-project/
149
199
  ├── AutoSnippet/ # Knowledge data (git-tracked)
150
- │ ├── recipes/ # Approved patterns (Markdown)
200
+ │ ├── recipes/ # Reviewed patterns (Markdown)
151
201
  │ ├── candidates/ # Pending review
152
- └── skills/ # Project-specific agent instructions
202
+ ├── skills/ # Project-specific Agent instructions
203
+ │ └── wiki/ # Project Wiki
153
204
  ├── .autosnippet/ # Runtime cache (gitignored)
154
- │ ├── autosnippet.db # SQLite
155
- │ └── context/ # Vector index
156
- ├── .cursor/mcp.json # Cursor MCP config
157
- └── .vscode/mcp.json # VS Code MCP config
205
+ │ ├── autosnippet.db # SQLite (WAL mode)
206
+ │ └── context/ # Vector index (HNSW)
207
+ ├── .cursor/
208
+ │ ├── mcp.json # Cursor MCP config
209
+ │ ├── rules/ # Channel A + B rules
210
+ │ └── skills/ # Channel C + D Skills
211
+ ├── .vscode/mcp.json # VS Code MCP config
212
+ ├── .github/copilot-instructions.md
213
+ ├── AGENTS.md
214
+ └── CLAUDE.md
158
215
  ```
159
216
 
160
- Recipes are Markdown files. SQLite is a read cache. If the DB breaks, `asd sync` rebuilds it.
217
+ Recipes are Markdown files. SQLite is just a read cache. If the database breaks, `asd sync` rebuilds it.
218
+
219
+ ---
220
+
221
+ ## IDE Support
222
+
223
+ | IDE | Integration | Details |
224
+ |-----|------------|---------|
225
+ | **VS Code** | Extension + MCP | `#asd` tool references in Agent Mode; search, directives, CodeLens, Guard diagnostic squiggles, light-bulb fixes |
226
+ | **Cursor** | MCP + Rules | `.cursor/mcp.json` + `.cursor/rules/` + `.cursor/skills/` |
227
+ | **Claude Code** | MCP + CLAUDE.md | `CLAUDE.md` + MCP tools; supports hooks |
228
+ | **Trae / Qoder** | MCP | `asd setup` auto-generates, `asd mirror` syncs config |
229
+ | **Xcode** | File watching | `asd watch` + file directives + Snippet sync |
230
+ | **Lark** | Bot + WebSocket | Message from phone → intent recognition → Bot Agent or IDE Agent Mode execution |
161
231
 
162
- ## Configuration Details
232
+ ### VS Code Extension
163
233
 
164
- See [Configuration Guide](docs/configuration.en.md) for more LLM configuration options.
234
+ - **Comment Directives**: `// as:s <query>` search & insert, `// as:c` create candidate from selection, `// as:a` audit current file
235
+ - **CodeLens**: Clickable actions above directives
236
+ - **Guard Diagnostics**: Violations shown as squiggles + light-bulb quick fixes
237
+ - **Status Bar**: Live API Server connection status
165
238
 
166
- ## Architecture
239
+ All configuration auto-generated by `asd setup`. Run `asd upgrade` after updates.
167
240
 
168
- See [Architecture Documentation](docs/architecture.en.md) for the full system design.
241
+ ---
242
+
243
+ ## Docs
244
+
245
+ | Document | Content |
246
+ |----------|---------|
247
+ | [Technical Reference](docs/technical-reference.en.md) | Six subsystem implementation details, engineering metrics, defense chain |
248
+ | [Dashboard](docs/dashboard.en.md) | Dashboard views and tech stack |
249
+ | [CLI Reference](docs/cli-reference.en.md) | Full usage for all 20 commands |
250
+ | [MCP Tools Reference](docs/mcp-tools.en.md) | 16 MCP tools with parameters and usage |
251
+ | [Architecture](docs/architecture.en.md) | Overall architecture and module design |
252
+ | [Configuration](docs/configuration.en.md) | LLM and advanced configuration options |
253
+ | [Guard Guide](docs/guard.en.md) | Guard rules and customization |
254
+ | [IDE Integration](docs/ide-integration.en.md) | Detailed IDE setup guides |
255
+ | [Lark Integration](docs/lark-integration.en.md) | Lark Bot setup and usage |
256
+ | [Agent Architecture](docs/agent-architecture.en.md) | Agent Runtime and MCP protocol |
257
+ | [Development](docs/development.en.md) | Contributing and dev environment setup |
258
+
259
+ ---
169
260
 
170
261
  ## Requirements
171
262
 
172
263
  - Node.js ≥ 22
173
- - macOS recommended (Xcode features need it; everything else is cross-platform)
264
+ - macOS recommended (Xcode features require it; other features are cross-platform)
174
265
  - better-sqlite3 (bundled)
175
266
 
176
267
  ## Contributing
177
268
 
178
- 1. `npm test` before submitting
179
- 2. Follow existing patterns (ESM, domain-driven structure)
269
+ 1. Run `npm test` before submitting
270
+ 2. Follow existing code patterns (ESM, domain-driven structure)
180
271
 
181
272
  ## License
182
273
 
@@ -36,6 +36,7 @@ roles:
36
36
  - "candidate:update"
37
37
  - "knowledge:create"
38
38
  - "knowledge:update"
39
+ - "knowledge:evolve"
39
40
  - "submit:knowledge"
40
41
  - "read:audit_logs:self"
41
42
  - "knowledge:bootstrap"
@@ -46,6 +47,7 @@ roles:
46
47
  - "delete:skills"
47
48
  constraints:
48
49
  - "can submit knowledge entries (all go to pending)"
50
+ - "can create evolution proposals (merge/enhance/deprecate — system auto-executes)"
49
51
  - "cannot publish/deprecate knowledge — only developer can do that"
50
52
  - "can reactivate deprecated entries back to pending"
51
53
  - "cannot modify Guard rules"
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import Logger from '../infrastructure/logging/Logger.js';
17
17
  import type { ApplyReport, ReconcileReport, RepairReport } from '../service/knowledge/SourceRefReconciler.js';
18
+ import { SourceRefReconciler } from '../service/knowledge/SourceRefReconciler.js';
18
19
  export interface SyncAllReport {
19
20
  synced: number;
20
21
  created: number;
@@ -27,11 +28,14 @@ export interface SyncAllReport {
27
28
  applyReport?: ApplyReport;
28
29
  }
29
30
  export declare class KnowledgeSyncService {
31
+ #private;
30
32
  candidatesDir: string;
31
33
  logger: ReturnType<typeof Logger.getInstance>;
32
34
  projectRoot: string;
33
35
  recipesDir: string;
34
- constructor(projectRoot: string);
36
+ constructor(projectRoot: string, options?: {
37
+ sourceRefReconciler?: SourceRefReconciler;
38
+ });
35
39
  /**
36
40
  * 完整同步入口 — sync + reconcile + repair
37
41
  *
@@ -25,11 +25,13 @@ export class KnowledgeSyncService {
25
25
  logger;
26
26
  projectRoot;
27
27
  recipesDir;
28
- constructor(projectRoot) {
28
+ #sourceRefReconciler;
29
+ constructor(projectRoot, options) {
29
30
  this.projectRoot = projectRoot;
30
31
  this.recipesDir = path.join(projectRoot, RECIPES_DIR);
31
32
  this.candidatesDir = path.join(projectRoot, CANDIDATES_DIR);
32
33
  this.logger = Logger.getInstance();
34
+ this.#sourceRefReconciler = options?.sourceRefReconciler ?? null;
33
35
  }
34
36
  /**
35
37
  * 完整同步入口 — sync + reconcile + repair
@@ -46,7 +48,8 @@ export class KnowledgeSyncService {
46
48
  const report = { ...syncReport };
47
49
  // 2. 填充/验证 recipe_source_refs 桥接表
48
50
  try {
49
- const reconciler = new SourceRefReconciler(this.projectRoot, db);
51
+ const reconciler = this.#sourceRefReconciler ??
52
+ new SourceRefReconciler(this.projectRoot, db);
50
53
  report.reconcileReport = reconciler.reconcile({ force: opts.force });
51
54
  // 3. git rename 修复
52
55
  report.repairReport = await reconciler.repairRenames();
@@ -43,7 +43,7 @@ export declare class Stats {
43
43
  static from(input: unknown): Stats;
44
44
  /** 增加计数 */
45
45
  increment(counter: StatsCounter, delta?: number): Stats;
46
- /** 记录一次命中,同时更新时间戳 */
46
+ /** 记录一次命中,同时更新时间戳(Unix 秒) */
47
47
  recordHit(counter: StatsCounter, timestamp?: number): Stats;
48
48
  /** 转换为 JSON */
49
49
  toJSON(): {
@@ -60,8 +60,8 @@ export class Stats {
60
60
  this[counter] += delta;
61
61
  return this;
62
62
  }
63
- /** 记录一次命中,同时更新时间戳 */
64
- recordHit(counter, timestamp = Date.now()) {
63
+ /** 记录一次命中,同时更新时间戳(Unix 秒) */
64
+ recordHit(counter, timestamp = Math.floor(Date.now() / 1000)) {
65
65
  this[counter] += 1;
66
66
  this.lastHitAt = timestamp;
67
67
  if (counter === 'searchHits') {