team-anya 0.2.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 (145) hide show
  1. package/README.md +38 -0
  2. package/apps/server/dist/broker/cc-broker.js +267 -0
  3. package/apps/server/dist/cli.js +296 -0
  4. package/apps/server/dist/config.js +78 -0
  5. package/apps/server/dist/daemon.js +51 -0
  6. package/apps/server/dist/franky/context-builder.js +161 -0
  7. package/apps/server/dist/franky/franky-mcp-server.js +110 -0
  8. package/apps/server/dist/franky/franky-orchestrator.js +629 -0
  9. package/apps/server/dist/franky/index.js +5 -0
  10. package/apps/server/dist/franky/topic-router.js +16 -0
  11. package/apps/server/dist/gateway/chat-sync.js +135 -0
  12. package/apps/server/dist/gateway/command-router.js +116 -0
  13. package/apps/server/dist/gateway/commands/cancel.js +32 -0
  14. package/apps/server/dist/gateway/commands/help.js +16 -0
  15. package/apps/server/dist/gateway/commands/index.js +26 -0
  16. package/apps/server/dist/gateway/commands/restart.js +43 -0
  17. package/apps/server/dist/gateway/commands/status.js +34 -0
  18. package/apps/server/dist/gateway/commands/tasks.js +33 -0
  19. package/apps/server/dist/gateway/feishu-sender.js +508 -0
  20. package/apps/server/dist/gateway/feishu-ws.js +353 -0
  21. package/apps/server/dist/gateway/health-monitor.js +154 -0
  22. package/apps/server/dist/gateway/http.js +1064 -0
  23. package/apps/server/dist/gateway/media-downloader.js +182 -0
  24. package/apps/server/dist/gateway/message-events.js +10 -0
  25. package/apps/server/dist/gateway/message-intake.js +72 -0
  26. package/apps/server/dist/gateway/message-queue.js +118 -0
  27. package/apps/server/dist/gateway/session-reader.js +142 -0
  28. package/apps/server/dist/gateway/ws-push.js +115 -0
  29. package/apps/server/dist/loid/brain.js +121 -0
  30. package/apps/server/dist/loid/clarifier.js +162 -0
  31. package/apps/server/dist/loid/context-builder.js +462 -0
  32. package/apps/server/dist/loid/mcp-server.js +119 -0
  33. package/apps/server/dist/loid/memory-settler.js +189 -0
  34. package/apps/server/dist/loid/opportunity-manager.js +148 -0
  35. package/apps/server/dist/loid/profile-updater.js +179 -0
  36. package/apps/server/dist/loid/project-registry.js +192 -0
  37. package/apps/server/dist/loid/reporter.js +148 -0
  38. package/apps/server/dist/loid/schemas.js +117 -0
  39. package/apps/server/dist/loid/self-calibrator.js +314 -0
  40. package/apps/server/dist/loid/session-manager.js +472 -0
  41. package/apps/server/dist/loid/session.js +276 -0
  42. package/apps/server/dist/main.js +528 -0
  43. package/apps/server/dist/tracing/index.js +2 -0
  44. package/apps/server/dist/tracing/trace-context.js +92 -0
  45. package/apps/server/dist/types/message.js +2 -0
  46. package/apps/server/dist/yor/yor-mcp-server.js +107 -0
  47. package/apps/server/dist/yor/yor-orchestrator.js +248 -0
  48. package/apps/web/dist/assets/index-BiiEB0qZ.css +1 -0
  49. package/apps/web/dist/assets/index-Dnb9LGZd.js +798 -0
  50. package/apps/web/dist/index.html +13 -0
  51. package/package.json +42 -0
  52. package/packages/cc-client/dist/claude-code-backend.js +792 -0
  53. package/packages/cc-client/dist/index.js +2 -0
  54. package/packages/cc-client/package.json +11 -0
  55. package/packages/core/dist/constants.js +60 -0
  56. package/packages/core/dist/errors.js +35 -0
  57. package/packages/core/dist/index.js +9 -0
  58. package/packages/core/dist/office-init.js +190 -0
  59. package/packages/core/dist/repo-cache.js +70 -0
  60. package/packages/core/dist/scope/checker.js +114 -0
  61. package/packages/core/dist/scope/defaults.js +55 -0
  62. package/packages/core/dist/scope/index.js +3 -0
  63. package/packages/core/dist/state-machine.js +86 -0
  64. package/packages/core/dist/types/audit.js +12 -0
  65. package/packages/core/dist/types/backend.js +2 -0
  66. package/packages/core/dist/types/commitment.js +17 -0
  67. package/packages/core/dist/types/communication.js +18 -0
  68. package/packages/core/dist/types/index.js +9 -0
  69. package/packages/core/dist/types/opportunity.js +27 -0
  70. package/packages/core/dist/types/org.js +26 -0
  71. package/packages/core/dist/types/task.js +46 -0
  72. package/packages/core/dist/types/workspace.js +39 -0
  73. package/packages/core/dist/workspace-manager.js +314 -0
  74. package/packages/core/package.json +10 -0
  75. package/packages/db/dist/client.js +69 -0
  76. package/packages/db/dist/index.js +756 -0
  77. package/packages/db/dist/schema/audit-events.js +13 -0
  78. package/packages/db/dist/schema/cc-sessions.js +14 -0
  79. package/packages/db/dist/schema/chats.js +35 -0
  80. package/packages/db/dist/schema/commitments.js +18 -0
  81. package/packages/db/dist/schema/communication-events.js +14 -0
  82. package/packages/db/dist/schema/index.js +14 -0
  83. package/packages/db/dist/schema/message-log.js +20 -0
  84. package/packages/db/dist/schema/opportunities.js +23 -0
  85. package/packages/db/dist/schema/org.js +36 -0
  86. package/packages/db/dist/schema/projects.js +23 -0
  87. package/packages/db/dist/schema/tasks.js +51 -0
  88. package/packages/db/dist/schema/topics.js +22 -0
  89. package/packages/db/dist/schema/trace-spans.js +19 -0
  90. package/packages/db/dist/schema/workspaces.js +15 -0
  91. package/packages/db/package.json +12 -0
  92. package/packages/db/src/migrations/0000_baseline.sql +251 -0
  93. package/packages/db/src/migrations/0001_workspaces.sql +19 -0
  94. package/packages/db/src/migrations/0002_workspace_parent.sql +1 -0
  95. package/packages/db/src/migrations/0003_chat_context.sql +3 -0
  96. package/packages/db/src/migrations/meta/_journal.json +34 -0
  97. package/packages/mcp-tools/dist/index.js +41 -0
  98. package/packages/mcp-tools/dist/layer1/audit-append.js +38 -0
  99. package/packages/mcp-tools/dist/layer1/audit-query.js +51 -0
  100. package/packages/mcp-tools/dist/layer1/memory-brief.js +168 -0
  101. package/packages/mcp-tools/dist/layer1/memory-context.js +124 -0
  102. package/packages/mcp-tools/dist/layer1/memory-digest.js +126 -0
  103. package/packages/mcp-tools/dist/layer1/memory-forget.js +108 -0
  104. package/packages/mcp-tools/dist/layer1/memory-learn.js +63 -0
  105. package/packages/mcp-tools/dist/layer1/memory-recall.js +287 -0
  106. package/packages/mcp-tools/dist/layer1/memory-reflect.js +80 -0
  107. package/packages/mcp-tools/dist/layer1/memory-remember.js +119 -0
  108. package/packages/mcp-tools/dist/layer1/memory-search.js +263 -0
  109. package/packages/mcp-tools/dist/layer1/memory-write.js +21 -0
  110. package/packages/mcp-tools/dist/layer1/org-lookup.js +47 -0
  111. package/packages/mcp-tools/dist/layer1/project-get.js +28 -0
  112. package/packages/mcp-tools/dist/layer1/project-list.js +20 -0
  113. package/packages/mcp-tools/dist/layer1/report-daily.js +68 -0
  114. package/packages/mcp-tools/dist/layer1/task-get.js +29 -0
  115. package/packages/mcp-tools/dist/layer1/task-update.js +34 -0
  116. package/packages/mcp-tools/dist/layer2/franky/topic-checkpoint.js +43 -0
  117. package/packages/mcp-tools/dist/layer2/franky/topic-escalate.js +19 -0
  118. package/packages/mcp-tools/dist/layer2/loid/decision-log.js +15 -0
  119. package/packages/mcp-tools/dist/layer2/loid/decision-no-action.js +15 -0
  120. package/packages/mcp-tools/dist/layer2/loid/delivery-create-pr.js +30 -0
  121. package/packages/mcp-tools/dist/layer2/loid/delivery-share.js +12 -0
  122. package/packages/mcp-tools/dist/layer2/loid/delivery-submit.js +77 -0
  123. package/packages/mcp-tools/dist/layer2/loid/delivery-upload.js +18 -0
  124. package/packages/mcp-tools/dist/layer2/loid/project-remove.js +16 -0
  125. package/packages/mcp-tools/dist/layer2/loid/project-upsert.js +33 -0
  126. package/packages/mcp-tools/dist/layer2/loid/task-dispatch.js +206 -0
  127. package/packages/mcp-tools/dist/layer2/loid/task-escalate-to-topic.js +170 -0
  128. package/packages/mcp-tools/dist/layer2/loid/task-lookup.js +45 -0
  129. package/packages/mcp-tools/dist/layer2/loid/topic-close.js +22 -0
  130. package/packages/mcp-tools/dist/layer2/loid/topic-create.js +60 -0
  131. package/packages/mcp-tools/dist/layer2/loid/yor-approve.js +8 -0
  132. package/packages/mcp-tools/dist/layer2/loid/yor-kill.js +7 -0
  133. package/packages/mcp-tools/dist/layer2/loid/yor-rework.js +7 -0
  134. package/packages/mcp-tools/dist/layer2/loid/yor-spawn.js +28 -0
  135. package/packages/mcp-tools/dist/layer2/loid/yor-status.js +8 -0
  136. package/packages/mcp-tools/dist/layer2/yor/task-block.js +11 -0
  137. package/packages/mcp-tools/dist/layer2/yor/task-deliver.js +35 -0
  138. package/packages/mcp-tools/dist/layer2/yor/task-progress.js +21 -0
  139. package/packages/mcp-tools/dist/layer3/adapters/feishu-adapter.js +203 -0
  140. package/packages/mcp-tools/dist/layer3/adapters/types.js +28 -0
  141. package/packages/mcp-tools/dist/layer3/channel-receive.js +11 -0
  142. package/packages/mcp-tools/dist/layer3/channel-send.js +75 -0
  143. package/packages/mcp-tools/dist/layer3/file-upload.js +44 -0
  144. package/packages/mcp-tools/dist/registry.js +911 -0
  145. package/packages/mcp-tools/package.json +13 -0
@@ -0,0 +1,314 @@
1
+ /**
2
+ * SelfCalibrator - 自我校准模块
3
+ *
4
+ * 从执行结果中自动校准能力评估:
5
+ * - 统计成功率(按项目/类型分组)
6
+ * - 识别常见失败模式
7
+ * - 计算自愈成功率
8
+ * - 更新 capability-notes.md
9
+ * - 提供项目风险提示
10
+ */
11
+ import { getAllTasks, getAuditEventsByType, insertAuditEvent } from '@team-anya/db';
12
+ import { writeFile } from 'node:fs/promises';
13
+ import { join } from 'node:path';
14
+ // ── 终态状态集 ──
15
+ const TERMINAL_STATUSES = new Set(['DONE', 'CANCELLED']);
16
+ const SUCCESS_STATUSES = new Set(['DONE']);
17
+ // ── 实现 ──
18
+ export class SelfCalibrator {
19
+ db;
20
+ workspacePath;
21
+ _lastStatus = {
22
+ lastCalibratedAt: null,
23
+ report: null,
24
+ deviationFactors: null,
25
+ warnings: [],
26
+ };
27
+ constructor(opts) {
28
+ this.db = opts.db;
29
+ this.workspacePath = opts.workspacePath;
30
+ }
31
+ /**
32
+ * 计算执行统计数据
33
+ */
34
+ computeStats() {
35
+ const allTasks = getAllTasks(this.db);
36
+ const terminalTasks = allTasks.filter(t => TERMINAL_STATUSES.has(t.status));
37
+ const successTasks = terminalTasks.filter(t => SUCCESS_STATUSES.has(t.status));
38
+ const totalCompleted = terminalTasks.length;
39
+ const successCount = successTasks.length;
40
+ const successRate = totalCompleted > 0 ? successCount / totalCompleted : 0;
41
+ // 平均重试次数
42
+ const avgRetryCount = totalCompleted > 0
43
+ ? terminalTasks.reduce((sum, t) => sum + (t.retry_count ?? 0), 0) / totalCompleted
44
+ : 0;
45
+ // 按项目分组
46
+ const byProject = {};
47
+ for (const task of terminalTasks) {
48
+ const pid = task.project_id;
49
+ if (!pid)
50
+ continue;
51
+ if (!byProject[pid]) {
52
+ byProject[pid] = { total: 0, success: 0, successRate: 0 };
53
+ }
54
+ byProject[pid].total++;
55
+ if (SUCCESS_STATUSES.has(task.status)) {
56
+ byProject[pid].success++;
57
+ }
58
+ }
59
+ for (const group of Object.values(byProject)) {
60
+ group.successRate = group.total > 0 ? group.success / group.total : 0;
61
+ }
62
+ // 按 source_type 分组
63
+ const bySourceType = {};
64
+ for (const task of terminalTasks) {
65
+ const st = task.source_type;
66
+ if (!bySourceType[st]) {
67
+ bySourceType[st] = { total: 0, success: 0, successRate: 0 };
68
+ }
69
+ bySourceType[st].total++;
70
+ if (SUCCESS_STATUSES.has(task.status)) {
71
+ bySourceType[st].success++;
72
+ }
73
+ }
74
+ for (const group of Object.values(bySourceType)) {
75
+ group.successRate = group.total > 0 ? group.success / group.total : 0;
76
+ }
77
+ return { totalCompleted, successCount, successRate, avgRetryCount, byProject, bySourceType };
78
+ }
79
+ /**
80
+ * 分析失败模式(从 task_blocked 审计事件中提取)
81
+ */
82
+ analyzeFailurePatterns() {
83
+ const blockedEvents = getAuditEventsByType(this.db, 'task_blocked');
84
+ const patternMap = new Map();
85
+ for (const event of blockedEvents) {
86
+ if (!event.detail)
87
+ continue;
88
+ try {
89
+ const detail = JSON.parse(event.detail);
90
+ const reason = detail.reason;
91
+ if (!reason)
92
+ continue;
93
+ const existing = patternMap.get(reason);
94
+ if (existing) {
95
+ existing.count++;
96
+ }
97
+ else {
98
+ patternMap.set(reason, { count: 1, type: detail.type });
99
+ }
100
+ }
101
+ catch {
102
+ // detail 不是有效 JSON,跳过
103
+ }
104
+ }
105
+ const patterns = [];
106
+ for (const [pattern, data] of patternMap) {
107
+ patterns.push({ pattern, count: data.count, type: data.type });
108
+ }
109
+ // 按出现次数降序排列
110
+ patterns.sort((a, b) => b.count - a.count);
111
+ return patterns;
112
+ }
113
+ /**
114
+ * 计算自愈成功率
115
+ */
116
+ computeSelfHealRate() {
117
+ const healEvents = getAuditEventsByType(this.db, 'self_heal_attempt');
118
+ if (healEvents.length === 0) {
119
+ return { total: 0, succeeded: 0, rate: 0 };
120
+ }
121
+ let succeeded = 0;
122
+ for (const event of healEvents) {
123
+ if (!event.detail)
124
+ continue;
125
+ try {
126
+ const detail = JSON.parse(event.detail);
127
+ if (detail.success)
128
+ succeeded++;
129
+ }
130
+ catch {
131
+ // 跳过
132
+ }
133
+ }
134
+ return {
135
+ total: healEvents.length,
136
+ succeeded,
137
+ rate: healEvents.length > 0 ? succeeded / healEvents.length : 0,
138
+ };
139
+ }
140
+ /**
141
+ * 生成完整的校准报告
142
+ */
143
+ generateReport() {
144
+ return {
145
+ stats: this.computeStats(),
146
+ failurePatterns: this.analyzeFailurePatterns(),
147
+ selfHealRate: this.computeSelfHealRate(),
148
+ generatedAt: new Date().toISOString(),
149
+ };
150
+ }
151
+ /**
152
+ * 更新 capability-notes.md 文件
153
+ */
154
+ async updateCapabilityNotes() {
155
+ const report = this.generateReport();
156
+ const content = this.formatCapabilityNotes(report);
157
+ const notesPath = join(this.workspacePath, 'memory', 'self', 'capability-notes.md');
158
+ await writeFile(notesPath, content, 'utf-8');
159
+ }
160
+ /**
161
+ * 获取指定项目的风险提示
162
+ */
163
+ getRiskHints(projectId) {
164
+ const stats = this.computeStats();
165
+ const projectStats = stats.byProject[projectId];
166
+ const hints = [];
167
+ if (!projectStats)
168
+ return hints;
169
+ // 低成功率警告(< 50%)
170
+ if (projectStats.successRate < 0.5) {
171
+ hints.push(`该项目成功率偏低 (${(projectStats.successRate * 100).toFixed(0)}%),建议关注失败原因`);
172
+ }
173
+ // 高重试率警告(平均重试 >= 2)
174
+ const projectTasks = getAllTasks(this.db).filter(t => t.project_id === projectId && TERMINAL_STATUSES.has(t.status));
175
+ if (projectTasks.length > 0) {
176
+ const avgRetry = projectTasks.reduce((sum, t) => sum + (t.retry_count ?? 0), 0) / projectTasks.length;
177
+ if (avgRetry >= 2) {
178
+ hints.push(`该项目平均重试次数较高 (${avgRetry.toFixed(1)}次),可能存在系统性问题`);
179
+ }
180
+ }
181
+ return hints;
182
+ }
183
+ /**
184
+ * 计算偏差校正因子
185
+ */
186
+ computeDeviationFactors() {
187
+ const allTasks = getAllTasks(this.db);
188
+ const terminalTasks = allTasks.filter(t => TERMINAL_STATUSES.has(t.status));
189
+ // 重试偏差:平均 retry_count / max_retries
190
+ let retryDeviation = 0;
191
+ if (terminalTasks.length > 0) {
192
+ const ratios = terminalTasks.map(t => {
193
+ const maxRetries = t.max_retries ?? 3;
194
+ if (maxRetries === 0)
195
+ return 0;
196
+ return (t.retry_count ?? 0) / maxRetries;
197
+ });
198
+ retryDeviation = ratios.reduce((a, b) => a + b, 0) / ratios.length;
199
+ }
200
+ // 承诺达成率
201
+ const fulfilledEvents = getAuditEventsByType(this.db, 'commitment_fulfilled');
202
+ const brokenEvents = getAuditEventsByType(this.db, 'commitment_broken');
203
+ const totalCommitmentEvents = fulfilledEvents.length + brokenEvents.length;
204
+ const commitmentFulfillRate = totalCommitmentEvents > 0
205
+ ? fulfilledEvents.length / totalCommitmentEvents
206
+ : 0;
207
+ // 校正因子:retryDeviation 越高说明低估复杂度
208
+ // 0 偏差 → 1.0(无需校正),1.0 偏差 → 1.5(需要 50% 更多缓冲)
209
+ const correctionFactor = terminalTasks.length > 0
210
+ ? 1.0 + retryDeviation * 0.5
211
+ : 1.0;
212
+ return { retryDeviation, commitmentFulfillRate, correctionFactor };
213
+ }
214
+ /**
215
+ * 执行一次完整校准,记录审计事件并缓存状态
216
+ */
217
+ runCalibration() {
218
+ const report = this.generateReport();
219
+ const deviationFactors = this.computeDeviationFactors();
220
+ const now = new Date().toISOString();
221
+ // 生成偏差警告
222
+ const warnings = [];
223
+ const RETRY_DEVIATION_THRESHOLD = 0.7;
224
+ if (deviationFactors.retryDeviation >= RETRY_DEVIATION_THRESHOLD) {
225
+ warnings.push(`重试偏差过高 (${(deviationFactors.retryDeviation * 100).toFixed(0)}%),建议调整复杂度预估`);
226
+ }
227
+ if (report.stats.successRate < 0.5 && report.stats.totalCompleted > 0) {
228
+ warnings.push(`整体成功率偏低 (${(report.stats.successRate * 100).toFixed(0)}%),需要关注系统性问题`);
229
+ }
230
+ // 记录审计事件
231
+ insertAuditEvent(this.db, {
232
+ event_type: 'calibration',
233
+ actor: 'loid',
234
+ summary: `自我校准完成: 成功率 ${(report.stats.successRate * 100).toFixed(1)}%, 校正因子 ${deviationFactors.correctionFactor.toFixed(2)}`,
235
+ detail: JSON.stringify({
236
+ stats: report.stats,
237
+ deviationFactors,
238
+ warnings,
239
+ }),
240
+ });
241
+ // 缓存状态
242
+ this._lastStatus = {
243
+ lastCalibratedAt: now,
244
+ report,
245
+ deviationFactors,
246
+ warnings,
247
+ };
248
+ return this._lastStatus;
249
+ }
250
+ /**
251
+ * 获取当前校准状态(返回上次 runCalibration 的缓存)
252
+ */
253
+ getCalibrationStatus() {
254
+ return this._lastStatus;
255
+ }
256
+ // ── 私有方法 ──
257
+ formatCapabilityNotes(report) {
258
+ const { stats, failurePatterns, selfHealRate } = report;
259
+ if (stats.totalCompleted === 0 && failurePatterns.length === 0 && selfHealRate.total === 0) {
260
+ return `# Anya Capability Notes\n\n> 自动生成于 ${report.generatedAt}\n\n无数据 — 尚无已完成的任务记录。\n`;
261
+ }
262
+ const lines = [
263
+ '# Anya Capability Notes',
264
+ '',
265
+ `> 自动生成于 ${report.generatedAt}`,
266
+ '',
267
+ '## 执行统计',
268
+ '',
269
+ `- 已完成任务: ${stats.totalCompleted}`,
270
+ `- 成功数: ${stats.successCount}`,
271
+ `- 整体成功率: ${(stats.successRate * 100).toFixed(1)}%`,
272
+ `- 平均重试次数: ${stats.avgRetryCount.toFixed(1)}`,
273
+ '',
274
+ ];
275
+ // 项目分组统计
276
+ const projectIds = Object.keys(stats.byProject);
277
+ if (projectIds.length > 0) {
278
+ lines.push('### 按项目', '');
279
+ for (const pid of projectIds) {
280
+ const g = stats.byProject[pid];
281
+ lines.push(`- **${pid}**: ${g.success}/${g.total} (成功率 ${(g.successRate * 100).toFixed(1)}%)`);
282
+ }
283
+ lines.push('');
284
+ }
285
+ // source_type 分组统计
286
+ const sourceTypes = Object.keys(stats.bySourceType);
287
+ if (sourceTypes.length > 0) {
288
+ lines.push('### 按来源类型', '');
289
+ for (const st of sourceTypes) {
290
+ const g = stats.bySourceType[st];
291
+ lines.push(`- **${st}**: ${g.success}/${g.total} (成功率 ${(g.successRate * 100).toFixed(1)}%)`);
292
+ }
293
+ lines.push('');
294
+ }
295
+ // 失败模式
296
+ if (failurePatterns.length > 0) {
297
+ lines.push('## 失败模式', '');
298
+ for (const p of failurePatterns) {
299
+ lines.push(`- **${p.pattern}**: ${p.count}次${p.type ? ` (类型: ${p.type})` : ''}`);
300
+ }
301
+ lines.push('');
302
+ }
303
+ // 自愈成功率
304
+ if (selfHealRate.total > 0) {
305
+ lines.push('## 自愈能力', '');
306
+ lines.push(`- 自愈尝试: ${selfHealRate.total}次`);
307
+ lines.push(`- 自愈成功: ${selfHealRate.succeeded}次`);
308
+ lines.push(`- 自愈成功率: ${(selfHealRate.rate * 100).toFixed(1)}%`);
309
+ lines.push('');
310
+ }
311
+ return lines.join('\n');
312
+ }
313
+ }
314
+ //# sourceMappingURL=self-calibrator.js.map