autosnippet 2.0.2 → 2.4.0

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 (47) hide show
  1. package/README.md +189 -113
  2. package/bin/api-server.js +1 -4
  3. package/bin/cli.js +1 -50
  4. package/config/constitution.yaml +33 -107
  5. package/dashboard/dist/assets/{icons-B4FfLfBA.js → icons-B5rs8uNb.js} +85 -80
  6. package/dashboard/dist/assets/index-0YzLw2ga.css +1 -0
  7. package/dashboard/dist/assets/index-B9py3ybr.js +154 -0
  8. package/dashboard/dist/index.html +3 -3
  9. package/lib/bootstrap.js +5 -31
  10. package/lib/cli/SetupService.js +16 -14
  11. package/lib/core/capability/CapabilityProbe.js +8 -6
  12. package/lib/core/constitution/Constitution.js +13 -4
  13. package/lib/core/constitution/ConstitutionValidator.js +106 -211
  14. package/lib/core/gateway/Gateway.js +34 -98
  15. package/lib/core/gateway/GatewayActionRegistry.js +12 -1
  16. package/lib/core/permission/PermissionManager.js +2 -2
  17. package/lib/external/mcp/McpServer.js +4 -7
  18. package/lib/external/mcp/handlers/bootstrap.js +13 -1
  19. package/lib/external/mcp/handlers/browse.js +0 -7
  20. package/lib/external/mcp/handlers/candidate.js +1 -1
  21. package/lib/external/mcp/handlers/guard.js +11 -0
  22. package/lib/external/mcp/handlers/skill.js +186 -18
  23. package/lib/external/mcp/tools.js +40 -1
  24. package/lib/http/middleware/roleResolver.js +1 -1
  25. package/lib/http/routes/auth.js +2 -2
  26. package/lib/http/routes/commands.js +58 -3
  27. package/lib/http/routes/monitoring.js +4 -4
  28. package/lib/http/routes/recipes.js +96 -4
  29. package/lib/http/routes/search.js +34 -35
  30. package/lib/injection/ServiceContainer.js +21 -40
  31. package/lib/service/candidate/CandidateService.js +12 -1
  32. package/lib/service/chat/ChatAgent.js +171 -30
  33. package/lib/service/chat/Memory.js +104 -0
  34. package/lib/service/chat/tools.js +244 -10
  35. package/lib/service/guard/GuardCheckEngine.js +9 -1
  36. package/lib/service/knowledge/KnowledgeGraphService.js +20 -9
  37. package/lib/service/recipe/RecipeService.js +8 -0
  38. package/lib/service/skills/SkillHooks.js +126 -0
  39. package/package.json +1 -1
  40. package/scripts/init-db.js +1 -2
  41. package/templates/constitution.yaml +29 -85
  42. package/dashboard/dist/assets/index-ChxJxX4B.js +0 -154
  43. package/dashboard/dist/assets/index-DwAp1mx5.css +0 -1
  44. package/lib/core/session/SessionManager.js +0 -232
  45. package/lib/infrastructure/logging/ReasoningLogger.js +0 -269
  46. package/lib/infrastructure/monitoring/RoleDriftMonitor.js +0 -259
  47. package/lib/infrastructure/quality/ComplianceEvaluator.js +0 -326
@@ -27,9 +27,12 @@ import path from 'node:path';
27
27
  import { fileURLToPath } from 'node:url';
28
28
  import Logger from '../../infrastructure/logging/Logger.js';
29
29
  import { TaskPipeline } from './TaskPipeline.js';
30
+ import { Memory } from './Memory.js';
30
31
 
31
32
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
32
- const SKILLS_DIR = path.resolve(__dirname, '../../../skills');
33
+ const PROJECT_ROOT = path.resolve(__dirname, '../../..');
34
+ const SKILLS_DIR = path.resolve(PROJECT_ROOT, 'skills');
35
+ const SOUL_PATH = path.resolve(PROJECT_ROOT, 'SOUL.md');
33
36
  const MAX_ITERATIONS = 6;
34
37
 
35
38
  export class ChatAgent {
@@ -39,6 +42,10 @@ export class ChatAgent {
39
42
  #logger;
40
43
  /** @type {Map<string, TaskPipeline>} */
41
44
  #pipelines = new Map();
45
+ /** @type {string} 缓存的项目概况(每次 execute 刷新一次) */
46
+ #projectBriefingCache = '';
47
+ /** @type {Memory|null} 跨对话轻量记忆 */
48
+ #memory = null;
42
49
 
43
50
  /**
44
51
  * @param {object} opts
@@ -55,6 +62,12 @@ export class ChatAgent {
55
62
  /** 是否有 AI Provider(只读) */
56
63
  this.hasAI = !!aiProvider;
57
64
 
65
+ // 初始化跨对话记忆
66
+ try {
67
+ const projectRoot = container?.singletons?._projectRoot || process.cwd();
68
+ this.#memory = new Memory(projectRoot);
69
+ } catch { /* Memory init failed, degrade silently */ }
70
+
58
71
  // 注册内置 DAG 管线
59
72
  this.#registerBuiltinPipelines();
60
73
  }
@@ -71,6 +84,9 @@ export class ChatAgent {
71
84
  * @returns {Promise<{reply: string, toolCalls: Array, hasContext: boolean}>}
72
85
  */
73
86
  async execute(prompt, { history = [] } = {}) {
87
+ // 每次对话刷新项目概况(不是每轮 ReAct)
88
+ this.#projectBriefingCache = await this.#buildProjectBriefing();
89
+
74
90
  const toolSchemas = this.#toolRegistry.getToolSchemas();
75
91
  const systemPrompt = this.#buildSystemPrompt(toolSchemas);
76
92
 
@@ -97,11 +113,9 @@ export class ChatAgent {
97
113
 
98
114
  if (!action) {
99
115
  // 没有 Action → 最终回答
100
- return {
101
- reply: this.#cleanFinalAnswer(response),
102
- toolCalls,
103
- hasContext: toolCalls.length > 0,
104
- };
116
+ const reply = this.#cleanFinalAnswer(response);
117
+ this.#extractMemory(prompt, reply);
118
+ return { reply, toolCalls, hasContext: toolCalls.length > 0 };
105
119
  }
106
120
 
107
121
  // 执行工具
@@ -141,8 +155,11 @@ export class ChatAgent {
141
155
  systemPrompt: '直接回答用户问题,不要再调用工具。',
142
156
  });
143
157
 
158
+ const finalReply = this.#cleanFinalAnswer(finalResponse);
159
+ this.#extractMemory(prompt, finalReply);
160
+
144
161
  return {
145
- reply: this.#cleanFinalAnswer(finalResponse),
162
+ reply: finalReply,
146
163
  toolCalls,
147
164
  hasContext: toolCalls.length > 0,
148
165
  };
@@ -286,11 +303,14 @@ ${highSim.map(s => `- ${s.title} (相似度: ${s.similarity})`).join('\n')}
286
303
  async #taskDiscoverAllRelations({ batchSize = 20 } = {}) {
287
304
  const ctx = this.#getToolContext();
288
305
  const recipeService = ctx.container.get('recipeService');
306
+ if (!recipeService) throw new Error('RecipeService 不可用');
307
+
308
+ if (!ctx.aiProvider) throw new Error('AI Provider 未配置,请先设置 API Key');
289
309
 
290
310
  // 获取所有 recipe
291
311
  const { items = [], data = [] } = await recipeService.listRecipes({}, { page: 1, pageSize: 500 });
292
312
  const recipes = items.length > 0 ? items : data;
293
- if (recipes.length < 2) return { discovered: 0, message: 'Need at least 2 recipes' };
313
+ if (recipes.length < 2) return { discovered: 0, totalPairs: 0, message: `只有 ${recipes.length} Recipe,至少需要 2 条` };
294
314
 
295
315
  // 按 batch 分组分析
296
316
  const pairs = [];
@@ -302,24 +322,41 @@ ${highSim.map(s => `- ${s.title} (相似度: ${s.similarity})`).join('\n')}
302
322
 
303
323
  let discovered = 0;
304
324
  const results = [];
325
+ let batchErrors = 0;
305
326
 
306
- // 分批处理
327
+ // 分批处理,单批失败不终止整体
307
328
  for (let b = 0; b < pairs.length; b += batchSize) {
308
329
  const batch = pairs.slice(b, b + batchSize);
309
- const result = await this.executeTool('discover_relations', {
310
- recipePairs: batch.map(([a, b]) => ({
311
- a: { id: a.id, title: a.title, category: a.category, language: a.language, code: (a.content || a.code || '').substring(0, 500) },
312
- b: { id: b.id, title: b.title, category: b.category, language: b.language, code: (b.content || b.code || '').substring(0, 500) },
313
- })),
314
- });
330
+ try {
331
+ const result = await this.executeTool('discover_relations', {
332
+ recipePairs: batch.map(([a, b]) => ({
333
+ a: { id: a.id, title: a.title, category: a.category, language: a.language, code: String(a.content || a.code || '').substring(0, 500) },
334
+ b: { id: b.id, title: b.title, category: b.category, language: b.language, code: String(b.content || b.code || '').substring(0, 500) },
335
+ })),
336
+ });
315
337
 
316
- if (result.relations) {
317
- discovered += result.relations.length;
318
- results.push(...result.relations);
338
+ if (result.error) {
339
+ batchErrors++;
340
+ this.#logger.warn(`[DiscoverRelations] Batch ${Math.floor(b / batchSize) + 1} error: ${result.error}`);
341
+ continue;
342
+ }
343
+ if (result.relations) {
344
+ discovered += result.relations.length;
345
+ results.push(...result.relations);
346
+ }
347
+ } catch (err) {
348
+ batchErrors++;
349
+ this.#logger.warn(`[DiscoverRelations] Batch ${Math.floor(b / batchSize) + 1} threw: ${err.message}`);
319
350
  }
320
351
  }
321
352
 
322
- return { discovered, totalPairs: pairs.length, relations: results };
353
+ return {
354
+ discovered,
355
+ totalPairs: pairs.length,
356
+ totalBatches: Math.ceil(pairs.length / batchSize),
357
+ batchErrors,
358
+ relations: results,
359
+ };
323
360
  }
324
361
 
325
362
  /**
@@ -554,9 +591,18 @@ ${code.substring(0, 3000)}
554
591
  ? `\n## 可用 Skills\n通过 load_skill 工具按需加载领域知识文档,获取操作指南和最佳实践参考。\n\n| Skill | 说明 |\n|---|---|\n${skillList.map(s => `| ${s.name} | ${s.summary || '-'} |`).join('\n')}\n\n**场景 → Skill 推荐**:\n- 冷启动、初始化 → autosnippet-coldstart\n- 深度项目分析 → autosnippet-analysis\n- 候选生成 → autosnippet-candidates + autosnippet-create\n- 代码规范审计 → autosnippet-guard\n- Snippet 概念解释 → autosnippet-concepts\n- 生命周期管理 → autosnippet-lifecycle\n- Swift/ObjC/JS·TS 语言参考 → autosnippet-reference-{swift,objc,jsts}\n- 项目结构分析 → autosnippet-structure\n- 不确定该用哪个 → autosnippet-intent\n`
555
592
  : '';
556
593
 
557
- return `你是 AutoSnippet 项目的统一 AI 中心。项目内所有 AI 推理和分析都通过你执行。
558
- 你拥有 ${toolSchemas.length} 个工具覆盖知识库管理全链路:搜索、提交、审核、质量评估、Guard 检查、知识图谱、冷启动等。
594
+ // SOUL AI 人格注入(如果 SOUL.md 存在)
595
+ let soulSection = '';
596
+ try {
597
+ if (fs.existsSync(SOUL_PATH)) {
598
+ soulSection = '\n' + fs.readFileSync(SOUL_PATH, 'utf-8').trim() + '\n';
599
+ }
600
+ } catch { /* SOUL.md not available */ }
559
601
 
602
+ return `${soulSection}
603
+ 你是 AutoSnippet 项目的统一 AI 中心。项目内所有 AI 推理和分析都通过你执行。
604
+ 你拥有 ${toolSchemas.length} 个工具覆盖知识库管理全链路:搜索、提交、审核、质量评估、Guard 检查、知识图谱、冷启动等。
605
+ ${this.#projectBriefingCache}${this.#memory?.toPromptSection() || ''}
560
606
  可用工具:
561
607
 
562
608
  ${toolDescriptions}
@@ -579,7 +625,9 @@ ${skillSection}
579
625
  - 候选创建/提交 → load_skill("autosnippet-candidates")
580
626
  - 代码规范/Guard → load_skill("autosnippet-guard")
581
627
  - 不确定做什么 → load_skill("autosnippet-intent")
582
- 8. 你可以组合多个工具完成复杂任务(如:查重 → 提交 → 质量评分 → 知识图谱关联)。`;
628
+ 8. 你可以组合多个工具完成复杂任务(如:查重 → 提交 → 质量评分 → 知识图谱关联)。
629
+ 9. 当工具返回 _meta.confidence = "none" 时,告知用户无匹配并建议下一步,不要凭空编造。当 _meta.confidence = "low" 时,明确标注结果不确定性。
630
+ 10. 优先使用组合工具(analyze_code, knowledge_overview, submit_with_check)减少调用轮次。`;
583
631
  }
584
632
 
585
633
  /**
@@ -640,24 +688,39 @@ ${skillSection}
640
688
 
641
689
  /**
642
690
  * 列出可用的 Skills 及其摘要(用于系统提示词)
691
+ * 加载顺序: 内置 skills/ → 项目级 .autosnippet/skills/(同名覆盖)
643
692
  * @returns {{ name: string, summary: string }[]}
644
693
  */
645
694
  #listAvailableSkills() {
695
+ const skillMap = new Map();
696
+
697
+ // 1. 内置 Skills
698
+ this.#loadSkillsFromDir(SKILLS_DIR, skillMap);
699
+
700
+ // 2. 项目级 Skills(覆盖同名内置 Skill)
701
+ const projectSkillsDir = path.resolve(PROJECT_ROOT, '.autosnippet', 'skills');
702
+ this.#loadSkillsFromDir(projectSkillsDir, skillMap);
703
+
704
+ return Array.from(skillMap.values());
705
+ }
706
+
707
+ /**
708
+ * 从目录加载 Skills 到 Map
709
+ */
710
+ #loadSkillsFromDir(dir, skillMap) {
646
711
  try {
647
- const dirs = fs.readdirSync(SKILLS_DIR, { withFileTypes: true })
712
+ const dirs = fs.readdirSync(dir, { withFileTypes: true })
648
713
  .filter(d => d.isDirectory())
649
714
  .map(d => d.name);
650
- return dirs.map(name => {
651
- const skillPath = path.join(SKILLS_DIR, name, 'SKILL.md');
715
+ for (const name of dirs) {
716
+ const skillPath = path.join(dir, name, 'SKILL.md');
652
717
  let summary = '';
653
718
  try {
654
719
  const raw = fs.readFileSync(skillPath, 'utf-8');
655
- // 从 frontmatter description 或首行 # 后提取摘要
656
720
  const fmMatch = raw.match(/^---[\s\S]*?description:\s*["']?(.+?)["']?\s*$/m);
657
721
  if (fmMatch) {
658
722
  summary = fmMatch[1];
659
723
  } else {
660
- // fallback: 取首个非空非标题行
661
724
  const lines = raw.split('\n');
662
725
  for (const line of lines) {
663
726
  const trimmed = line.trim();
@@ -668,10 +731,88 @@ ${skillSection}
668
731
  }
669
732
  }
670
733
  } catch { /* SKILL.md not found */ }
671
- return { name, summary };
672
- });
734
+ skillMap.set(name, { name, summary });
735
+ }
736
+ } catch { /* directory not found */ }
737
+ }
738
+
739
+ /**
740
+ * 构建项目概况注入到系统提示词(每次 execute 刷新一次)
741
+ * 单次 SQL 聚合 < 5ms,静默降级
742
+ */
743
+ async #buildProjectBriefing() {
744
+ try {
745
+ const db = this.#container?.get('database');
746
+ if (!db) return '';
747
+ // knowledge_type → kind 映射:
748
+ // rule: code-standard, code-style, best-practice, boundary-constraint
749
+ // pattern: code-pattern, architecture, solution
750
+ // fact: code-relation, inheritance, call-chain, data-flow, module-dependency
751
+ const stats = db.prepare(`
752
+ SELECT
753
+ (SELECT COUNT(*) FROM recipes) as recipeCount,
754
+ (SELECT COUNT(*) FROM recipes WHERE knowledge_type IN ('code-standard','code-style','best-practice','boundary-constraint')) as ruleCount,
755
+ (SELECT COUNT(*) FROM recipes WHERE knowledge_type IN ('code-pattern','architecture','solution')) as patternCount,
756
+ (SELECT COUNT(*) FROM recipes WHERE knowledge_type IN ('code-relation','inheritance','call-chain','data-flow','module-dependency')) as factCount,
757
+ (SELECT COUNT(*) FROM recipes WHERE knowledge_type = 'boundary-constraint') as guardRuleCount,
758
+ (SELECT COUNT(*) FROM candidates WHERE status='pending') as pendingCandidates,
759
+ (SELECT COUNT(*) FROM candidates) as totalCandidates
760
+ `).get();
761
+ if (!stats || stats.recipeCount === 0) {
762
+ return '\n## 项目状态\n⚠️ 知识库为空。建议先执行冷启动(bootstrap_knowledge)。\n';
763
+ }
764
+ let section = `\n## 项目状态\n- 知识库: ${stats.recipeCount} 条 Recipe(${stats.ruleCount || 0} rule / ${stats.patternCount || 0} pattern / ${stats.factCount || 0} fact)\n- Guard 规则: ${stats.guardRuleCount || 0} 条\n- 候选: ${stats.pendingCandidates} 条待审 / ${stats.totalCandidates} 条总计\n`;
765
+ if (stats.pendingCandidates > 10) {
766
+ section += `\n⚠️ 有 ${stats.pendingCandidates} 条候选积压,建议执行批量审核。\n`;
767
+ }
768
+ return section;
673
769
  } catch {
674
- return [];
770
+ return ''; // DB 不可用时静默降级
771
+ }
772
+ }
773
+
774
+ /**
775
+ * 从用户消息中提取偏好/决策写入 Memory
776
+ * 使用正则匹配,不调 AI — 零延迟
777
+ */
778
+ #extractMemory(prompt, _reply) {
779
+ if (!this.#memory) return;
780
+ try {
781
+ const prefPatterns = [
782
+ /我们(项目|团队)?(不用|不使用|禁止|避免|偏好|习惯|规范是)/,
783
+ /以后(都|请|要)/,
784
+ /记住/,
785
+ ];
786
+ if (prefPatterns.some(p => p.test(prompt))) {
787
+ this.#memory.append({
788
+ type: 'preference',
789
+ content: prompt.substring(0, 200),
790
+ ttl: 30,
791
+ });
792
+ }
793
+ } catch { /* memory write failure is non-critical */ }
794
+ }
795
+
796
+ /**
797
+ * 事件驱动入口(P2 预留接口)
798
+ * @param {{ type: string, payload: object, source?: string }} event
799
+ */
800
+ async executeEvent(event) {
801
+ const { type, payload } = event;
802
+ const prompt = this.#eventToPrompt(type, payload);
803
+ return this.execute(prompt, { history: [] });
804
+ }
805
+
806
+ #eventToPrompt(type, payload) {
807
+ switch (type) {
808
+ case 'file_saved':
809
+ return `文件 ${payload.filePath} 刚被保存,变更了 ${payload.changedLines} 行。请分析是否有值得提取为 Recipe 的代码模式。如果有,说明原因;没有就说"无需操作"。`;
810
+ case 'candidate_backlog':
811
+ return `当前有 ${payload.count} 条候选积压(最早 ${payload.oldest})。请按质量分类:哪些值得审核、哪些可以直接拒绝、哪些需要补充信息。`;
812
+ case 'scheduled_health':
813
+ return `请执行知识库健康检查:Recipe 覆盖率、过时标记、Guard 规则有效性。给出简要报告。`;
814
+ default:
815
+ return `事件: ${type}\n${JSON.stringify(payload)}`;
675
816
  }
676
817
  }
677
818
 
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Memory — 跨对话轻量记忆
3
+ *
4
+ * 设计:
5
+ * - JSONL 文件存储,每行一条记忆
6
+ * - 支持 TTL 自动过期
7
+ * - 上限 maxEntries,超出时截断旧条目
8
+ * - 读写均做静默降级(Memory 是增强,不是核心路径)
9
+ *
10
+ * 记忆类型:
11
+ * - preference: 用户偏好("我们不用 singleton"、"以后用 DI")
12
+ * - decision: 关键决策("Network 模块审核通过")
13
+ * - context: 项目上下文("主语言是 Swift,使用 SPM")
14
+ *
15
+ * 文件路径: .autosnippet/memory.jsonl
16
+ */
17
+
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+
21
+ export class Memory {
22
+ #filePath;
23
+ #maxEntries;
24
+
25
+ /**
26
+ * @param {string} projectRoot — 用户项目根目录
27
+ * @param {object} [opts]
28
+ * @param {number} [opts.maxEntries=50] — 最大记忆条数
29
+ */
30
+ constructor(projectRoot, { maxEntries = 50 } = {}) {
31
+ this.#filePath = path.join(projectRoot, '.autosnippet', 'memory.jsonl');
32
+ this.#maxEntries = maxEntries;
33
+ }
34
+
35
+ /**
36
+ * 读取最近 N 条记忆,过滤过期项
37
+ * @param {number} [limit=20]
38
+ * @returns {{ ts: string, type: string, content: string, ttl?: number }[]}
39
+ */
40
+ load(limit = 20) {
41
+ try {
42
+ if (!fs.existsSync(this.#filePath)) return [];
43
+ const raw = fs.readFileSync(this.#filePath, 'utf-8').trim();
44
+ if (!raw) return [];
45
+ const lines = raw.split('\n').filter(Boolean);
46
+ const now = Date.now();
47
+ return lines
48
+ .map(l => { try { return JSON.parse(l); } catch { return null; } })
49
+ .filter(Boolean)
50
+ .filter(m => !m.ttl || (now - new Date(m.ts).getTime()) < m.ttl * 86400000)
51
+ .slice(-limit);
52
+ } catch {
53
+ return [];
54
+ }
55
+ }
56
+
57
+ /**
58
+ * 追加一条记忆
59
+ * @param {{ type: string, content: string, ttl?: number }} entry
60
+ */
61
+ append(entry) {
62
+ try {
63
+ const dir = path.dirname(this.#filePath);
64
+ fs.mkdirSync(dir, { recursive: true });
65
+ const line = JSON.stringify({ ts: new Date().toISOString(), ...entry });
66
+ fs.appendFileSync(this.#filePath, line + '\n', 'utf-8');
67
+ this.#compact();
68
+ } catch { /* write failure non-critical */ }
69
+ }
70
+
71
+ /**
72
+ * 生成供系统提示词的记忆摘要
73
+ * @returns {string}
74
+ */
75
+ toPromptSection() {
76
+ const memories = this.load();
77
+ if (memories.length === 0) return '';
78
+ const lines = memories.map(m => `- [${m.type}] ${m.content}`).join('\n');
79
+ return `\n## 历史记忆\n以下是之前对话中积累的项目偏好和决策,请参考:\n${lines}\n`;
80
+ }
81
+
82
+ /**
83
+ * 当前记忆条数
84
+ */
85
+ get size() {
86
+ return this.load(this.#maxEntries).length;
87
+ }
88
+
89
+ /**
90
+ * 超过 maxEntries 时截断旧条目
91
+ */
92
+ #compact() {
93
+ try {
94
+ const raw = fs.readFileSync(this.#filePath, 'utf-8').trim();
95
+ if (!raw) return;
96
+ const lines = raw.split('\n').filter(Boolean);
97
+ if (lines.length > this.#maxEntries) {
98
+ fs.writeFileSync(this.#filePath, lines.slice(-this.#maxEntries).join('\n') + '\n', 'utf-8');
99
+ }
100
+ } catch { /* ignore */ }
101
+ }
102
+ }
103
+
104
+ export default Memory;