team-anya-cli 0.1.8 → 1.0.1

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 (168) hide show
  1. package/README.md +1 -37
  2. package/package.json +6 -37
  3. package/anya/prompts/execution-guides/git-delivery.md +0 -38
  4. package/anya/prompts/execution-guides/testing-and-self-heal.md +0 -28
  5. package/anya/prompts/protocols/brief-assembly.md +0 -55
  6. package/anya/prompts/protocols/report.md +0 -175
  7. package/anya/prompts/protocols/review.md +0 -90
  8. package/anya/prompts/task-claude-md.template.md +0 -32
  9. package/apps/server/dist/broker/cc-broker.js +0 -261
  10. package/apps/server/dist/cli.js +0 -296
  11. package/apps/server/dist/config.js +0 -76
  12. package/apps/server/dist/daemon.js +0 -51
  13. package/apps/server/dist/franky/context-builder.js +0 -160
  14. package/apps/server/dist/franky/franky-mcp-server.js +0 -107
  15. package/apps/server/dist/franky/franky-orchestrator.js +0 -450
  16. package/apps/server/dist/franky/index.js +0 -5
  17. package/apps/server/dist/franky/topic-router.js +0 -16
  18. package/apps/server/dist/gateway/chat-sync.js +0 -135
  19. package/apps/server/dist/gateway/command-router.js +0 -114
  20. package/apps/server/dist/gateway/commands/cancel.js +0 -32
  21. package/apps/server/dist/gateway/commands/help.js +0 -16
  22. package/apps/server/dist/gateway/commands/index.js +0 -26
  23. package/apps/server/dist/gateway/commands/restart.js +0 -34
  24. package/apps/server/dist/gateway/commands/status.js +0 -34
  25. package/apps/server/dist/gateway/commands/tasks.js +0 -33
  26. package/apps/server/dist/gateway/feishu-sender.js +0 -410
  27. package/apps/server/dist/gateway/feishu-ws.js +0 -256
  28. package/apps/server/dist/gateway/http.js +0 -1019
  29. package/apps/server/dist/gateway/media-downloader.js +0 -149
  30. package/apps/server/dist/gateway/message-events.js +0 -10
  31. package/apps/server/dist/gateway/message-intake.js +0 -67
  32. package/apps/server/dist/gateway/message-queue.js +0 -118
  33. package/apps/server/dist/gateway/session-reader.js +0 -142
  34. package/apps/server/dist/gateway/ws-push.js +0 -115
  35. package/apps/server/dist/loid/brain.js +0 -105
  36. package/apps/server/dist/loid/clarifier.js +0 -162
  37. package/apps/server/dist/loid/context-builder.js +0 -413
  38. package/apps/server/dist/loid/mcp-server.js +0 -106
  39. package/apps/server/dist/loid/memory-settler.js +0 -189
  40. package/apps/server/dist/loid/opportunity-manager.js +0 -148
  41. package/apps/server/dist/loid/profile-updater.js +0 -179
  42. package/apps/server/dist/loid/reporter.js +0 -148
  43. package/apps/server/dist/loid/schemas.js +0 -117
  44. package/apps/server/dist/loid/self-calibrator.js +0 -314
  45. package/apps/server/dist/loid/session-manager.js +0 -301
  46. package/apps/server/dist/loid/session.js +0 -271
  47. package/apps/server/dist/loid/worktree-manager.js +0 -191
  48. package/apps/server/dist/main.js +0 -393
  49. package/apps/server/dist/tracing/index.js +0 -2
  50. package/apps/server/dist/tracing/trace-context.js +0 -92
  51. package/apps/server/dist/types/message.js +0 -2
  52. package/apps/server/dist/yor/yor-mcp-server.js +0 -104
  53. package/apps/server/dist/yor/yor-orchestrator.js +0 -233
  54. package/apps/web/dist/assets/index-BiiEB0qZ.css +0 -1
  55. package/apps/web/dist/assets/index-D1AK5ZEE.js +0 -798
  56. package/apps/web/dist/index.html +0 -13
  57. package/packages/cc-client/dist/claude-code-backend.js +0 -664
  58. package/packages/cc-client/dist/index.js +0 -2
  59. package/packages/cc-client/package.json +0 -11
  60. package/packages/core/dist/constants.js +0 -59
  61. package/packages/core/dist/errors.js +0 -35
  62. package/packages/core/dist/index.js +0 -7
  63. package/packages/core/dist/office-init.js +0 -101
  64. package/packages/core/dist/scope/checker.js +0 -114
  65. package/packages/core/dist/scope/defaults.js +0 -55
  66. package/packages/core/dist/scope/index.js +0 -3
  67. package/packages/core/dist/state-machine.js +0 -85
  68. package/packages/core/dist/types/audit.js +0 -12
  69. package/packages/core/dist/types/backend.js +0 -2
  70. package/packages/core/dist/types/commitment.js +0 -17
  71. package/packages/core/dist/types/communication.js +0 -18
  72. package/packages/core/dist/types/index.js +0 -8
  73. package/packages/core/dist/types/opportunity.js +0 -27
  74. package/packages/core/dist/types/org.js +0 -26
  75. package/packages/core/dist/types/task.js +0 -46
  76. package/packages/core/package.json +0 -10
  77. package/packages/db/dist/client.js +0 -69
  78. package/packages/db/dist/index.js +0 -691
  79. package/packages/db/dist/schema/audit-events.js +0 -13
  80. package/packages/db/dist/schema/cc-sessions.js +0 -14
  81. package/packages/db/dist/schema/chats.js +0 -33
  82. package/packages/db/dist/schema/commitments.js +0 -18
  83. package/packages/db/dist/schema/communication-events.js +0 -14
  84. package/packages/db/dist/schema/index.js +0 -13
  85. package/packages/db/dist/schema/message-log.js +0 -20
  86. package/packages/db/dist/schema/opportunities.js +0 -23
  87. package/packages/db/dist/schema/org.js +0 -36
  88. package/packages/db/dist/schema/projects.js +0 -23
  89. package/packages/db/dist/schema/tasks.js +0 -48
  90. package/packages/db/dist/schema/topics.js +0 -20
  91. package/packages/db/dist/schema/trace-spans.js +0 -19
  92. package/packages/db/package.json +0 -12
  93. package/packages/db/src/migrations/0000_baseline.sql +0 -251
  94. package/packages/db/src/migrations/meta/_journal.json +0 -13
  95. package/packages/mcp-tools/dist/index.js +0 -41
  96. package/packages/mcp-tools/dist/layer1/audit-append.js +0 -38
  97. package/packages/mcp-tools/dist/layer1/audit-query.js +0 -51
  98. package/packages/mcp-tools/dist/layer1/memory-brief.js +0 -168
  99. package/packages/mcp-tools/dist/layer1/memory-context.js +0 -124
  100. package/packages/mcp-tools/dist/layer1/memory-digest.js +0 -126
  101. package/packages/mcp-tools/dist/layer1/memory-forget.js +0 -108
  102. package/packages/mcp-tools/dist/layer1/memory-learn.js +0 -63
  103. package/packages/mcp-tools/dist/layer1/memory-recall.js +0 -287
  104. package/packages/mcp-tools/dist/layer1/memory-reflect.js +0 -80
  105. package/packages/mcp-tools/dist/layer1/memory-remember.js +0 -119
  106. package/packages/mcp-tools/dist/layer1/memory-search.js +0 -263
  107. package/packages/mcp-tools/dist/layer1/memory-write.js +0 -21
  108. package/packages/mcp-tools/dist/layer1/org-lookup.js +0 -47
  109. package/packages/mcp-tools/dist/layer1/project-get.js +0 -28
  110. package/packages/mcp-tools/dist/layer1/project-list.js +0 -20
  111. package/packages/mcp-tools/dist/layer1/report-daily.js +0 -68
  112. package/packages/mcp-tools/dist/layer1/task-get.js +0 -29
  113. package/packages/mcp-tools/dist/layer1/task-update.js +0 -34
  114. package/packages/mcp-tools/dist/layer2/franky/topic-checkpoint.js +0 -43
  115. package/packages/mcp-tools/dist/layer2/franky/topic-escalate.js +0 -19
  116. package/packages/mcp-tools/dist/layer2/loid/decision-log.js +0 -15
  117. package/packages/mcp-tools/dist/layer2/loid/decision-no-action.js +0 -15
  118. package/packages/mcp-tools/dist/layer2/loid/delivery-create-pr.js +0 -30
  119. package/packages/mcp-tools/dist/layer2/loid/delivery-share.js +0 -12
  120. package/packages/mcp-tools/dist/layer2/loid/delivery-submit.js +0 -77
  121. package/packages/mcp-tools/dist/layer2/loid/delivery-upload.js +0 -18
  122. package/packages/mcp-tools/dist/layer2/loid/project-remove.js +0 -16
  123. package/packages/mcp-tools/dist/layer2/loid/project-upsert.js +0 -33
  124. package/packages/mcp-tools/dist/layer2/loid/task-dispatch.js +0 -196
  125. package/packages/mcp-tools/dist/layer2/loid/task-lookup.js +0 -38
  126. package/packages/mcp-tools/dist/layer2/loid/topic-close.js +0 -22
  127. package/packages/mcp-tools/dist/layer2/loid/topic-create.js +0 -56
  128. package/packages/mcp-tools/dist/layer2/loid/yor-approve.js +0 -8
  129. package/packages/mcp-tools/dist/layer2/loid/yor-kill.js +0 -7
  130. package/packages/mcp-tools/dist/layer2/loid/yor-rework.js +0 -7
  131. package/packages/mcp-tools/dist/layer2/loid/yor-spawn.js +0 -15
  132. package/packages/mcp-tools/dist/layer2/loid/yor-status.js +0 -8
  133. package/packages/mcp-tools/dist/layer2/yor/task-block.js +0 -11
  134. package/packages/mcp-tools/dist/layer2/yor/task-deliver.js +0 -35
  135. package/packages/mcp-tools/dist/layer2/yor/task-progress.js +0 -21
  136. package/packages/mcp-tools/dist/layer3/adapters/feishu-adapter.js +0 -192
  137. package/packages/mcp-tools/dist/layer3/adapters/types.js +0 -28
  138. package/packages/mcp-tools/dist/layer3/channel-receive.js +0 -11
  139. package/packages/mcp-tools/dist/layer3/channel-send.js +0 -91
  140. package/packages/mcp-tools/dist/layer3/file-upload.js +0 -44
  141. package/packages/mcp-tools/dist/registry.js +0 -871
  142. package/packages/mcp-tools/package.json +0 -13
  143. package/workspace/.claude/settings.local.json +0 -9
  144. package/workspace/.mcp.json +0 -12
  145. package/workspace/CHARTER.md +0 -76
  146. package/workspace/CLAUDE.md +0 -58
  147. package/workspace/PROTOCOL.md +0 -160
  148. package/workspace/TOOLS.md +0 -470
  149. package/workspace/audit/.gitkeep +0 -0
  150. package/workspace/franky/CLAUDE.md +0 -37
  151. package/workspace/franky/PLAYBOOK.md +0 -215
  152. package/workspace/franky/PROFILE.md +0 -80
  153. package/workspace/loid/CLAUDE.md +0 -12
  154. package/workspace/loid/PLAYBOOK.md +0 -198
  155. package/workspace/loid/PROFILE.md +0 -78
  156. package/workspace/memory/commitments/.gitkeep +0 -0
  157. package/workspace/memory/execution/.gitkeep +0 -0
  158. package/workspace/memory/people/.gitkeep +0 -0
  159. package/workspace/memory/projects/.gitkeep +0 -0
  160. package/workspace/memory/self/.gitkeep +0 -0
  161. package/workspace/reference/identity/.gitkeep +0 -0
  162. package/workspace/reference/org/escalation.yaml +0 -24
  163. package/workspace/reference/org/ownership.yaml +0 -28
  164. package/workspace/reports/.gitkeep +0 -0
  165. package/workspace/yor/CLAUDE.md +0 -22
  166. package/workspace/yor/PLAYBOOK.md +0 -73
  167. package/workspace/yor/PROFILE.md +0 -52
  168. package/workspace/yor/SELF-HEAL.md +0 -39
@@ -1,148 +0,0 @@
1
- import { join } from 'node:path';
2
- // ── 进行中状态集合 ──
3
- const IN_PROGRESS_STATUSES = new Set(['IN_PROGRESS', 'TESTING', 'FIXING']);
4
- const PR_STATUSES = new Set(['PR_OPEN', 'WAITING_REVIEW']);
5
- // ── Reporter ──
6
- export class Reporter {
7
- deps;
8
- config;
9
- constructor(deps, config) {
10
- this.deps = deps;
11
- this.config = config;
12
- }
13
- /**
14
- * 生成日报 Markdown 内容
15
- */
16
- async generateDailyReport(date) {
17
- const allTasks = this.deps.getAllTasks();
18
- const commitments = this.deps.getActiveCommitments();
19
- const opportunities = this.deps.getOpenOpportunities();
20
- const auditEvents = this.deps.getAuditEventsByDate(date);
21
- const lines = [];
22
- const done = allTasks.filter((t) => t.status === 'DONE' && t.updated_at?.startsWith(date));
23
- const prOpen = allTasks.filter((t) => PR_STATUSES.has(t.status));
24
- const inProgress = allTasks.filter((t) => IN_PROGRESS_STATUSES.has(t.status));
25
- const blocked = allTasks.filter((t) => t.status === 'BLOCKED');
26
- // 开头一句话总结
27
- const totalActive = inProgress.length + prOpen.length;
28
- if (done.length > 0 && blocked.length === 0) {
29
- lines.push(`今天完成了 ${done.length} 个任务${totalActive > 0 ? `,还有 ${totalActive} 个在跑` : ''}。\n`);
30
- }
31
- else if (done.length > 0 && blocked.length > 0) {
32
- lines.push(`今天完成了 ${done.length} 个任务,但有 ${blocked.length} 个卡住了。\n`);
33
- }
34
- else if (blocked.length > 0) {
35
- lines.push(`有 ${blocked.length} 个任务卡住了,需要关注。\n`);
36
- }
37
- else if (totalActive > 0) {
38
- lines.push(`${totalActive} 个任务进行中。\n`);
39
- }
40
- // 完成的
41
- if (done.length > 0) {
42
- lines.push('**已完成**');
43
- for (const t of done) {
44
- const pr = t.pr_url ? ` → ${t.pr_url}` : '';
45
- lines.push(`- ${t.title} (${t.task_id})${pr}`);
46
- }
47
- lines.push('');
48
- }
49
- // 等 Review 的
50
- if (prOpen.length > 0) {
51
- lines.push('**等 Review**');
52
- for (const t of prOpen) {
53
- const pr = t.pr_url ? ` → ${t.pr_url}` : '';
54
- lines.push(`- ${t.title} (${t.task_id})${pr}`);
55
- }
56
- lines.push('');
57
- }
58
- // 进行中的
59
- if (inProgress.length > 0) {
60
- lines.push('**进行中**');
61
- for (const t of inProgress) {
62
- lines.push(`- ${t.title} (${t.task_id})`);
63
- }
64
- lines.push('');
65
- }
66
- // 卡住的(重点标出)
67
- if (blocked.length > 0) {
68
- lines.push('**卡住了**');
69
- for (const t of blocked) {
70
- lines.push(`- ${t.title} (${t.task_id}) — ${t.blocked_reason ?? '原因待查'}`);
71
- }
72
- lines.push('');
73
- }
74
- // 承诺追踪
75
- if (commitments.length > 0) {
76
- lines.push('**还欠着的**');
77
- for (const c of commitments) {
78
- const deadline = c.deadline ? `,截止 ${c.deadline}` : '';
79
- lines.push(`- ${c.promise} (答应 ${c.promised_to} 的${deadline})`);
80
- }
81
- lines.push('');
82
- }
83
- // 机会
84
- if (opportunities.length > 0) {
85
- lines.push('**发现了几个可以做的事**');
86
- for (const o of opportunities) {
87
- lines.push(`- ${o.summary}`);
88
- }
89
- lines.push('');
90
- }
91
- return lines.join('\n');
92
- }
93
- /**
94
- * 将日报写入文件
95
- */
96
- async saveDailyReport(date, content) {
97
- const reportsDir = join(this.config.workspacePath, 'reports');
98
- await this.deps.mkdirp(reportsDir);
99
- const filePath = join(reportsDir, `daily-${date}.md`);
100
- await this.deps.writeFile(filePath, content);
101
- return filePath;
102
- }
103
- /**
104
- * 端到端:生成 + 写文件 + 飞书推送
105
- */
106
- async publishDailyReport(date) {
107
- const content = await this.generateDailyReport(date);
108
- // 写文件(总是执行)
109
- await this.saveDailyReport(date, content);
110
- // 飞书推送(可选,失败不影响文件写入)
111
- if (this.config.feishuDailyReportChatId) {
112
- try {
113
- await this.deps.sendDailyReport({
114
- chatId: this.config.feishuDailyReportChatId,
115
- reportContent: content,
116
- date,
117
- });
118
- }
119
- catch {
120
- // 飞书发送失败不影响日报文件保存
121
- }
122
- }
123
- }
124
- /**
125
- * 实时告警:任务 BLOCKED
126
- */
127
- async notifyBlocked(params) {
128
- await this.deps.sendBlockedAlert({
129
- targetUserIds: params.targetUserIds,
130
- taskId: params.taskId,
131
- reason: params.reason,
132
- });
133
- }
134
- /**
135
- * 任务完成通知
136
- */
137
- async notifyTaskDone(params) {
138
- if (!params.chatId)
139
- return;
140
- await this.deps.sendTaskDone({
141
- chatId: params.chatId,
142
- taskId: params.taskId,
143
- prUrl: params.prUrl,
144
- summary: params.summary,
145
- });
146
- }
147
- }
148
- //# sourceMappingURL=reporter.js.map
@@ -1,117 +0,0 @@
1
- import { z } from 'zod';
2
- // ── Loid 行动工具 Input Schemas ──
3
- export const DispatchTaskInputSchema = z.object({
4
- title: z.string().describe('任务标题'),
5
- brief: z.string().describe('执行 brief(Markdown 格式,只写做什么和标准,不写怎么做)'),
6
- project_id: z.string().optional().describe('目标项目/仓库 ID'),
7
- objective: z.string().describe('任务目标(一句话概括要达成什么)'),
8
- acceptance_criteria: z.array(z.string()).describe('验收标准列表(至少一条可验证的完成条件)'),
9
- context: z.string().optional().describe('背景信息(业务上下文、技术约束等)'),
10
- conversation_id: z.string().optional().describe('关联的对话 ID(用于后续回复)'),
11
- source_message_id: z.string().optional().describe('触发消息 ID'),
12
- created_by: z.string().optional().describe('任务创建者(从当前事件的 sender_name 或 sender_id 提取)'),
13
- source_chat_id: z.string().optional().describe('触发任务的聊天 ID(从当前对话的 chat_id 提取)'),
14
- });
15
- export const AskHumanInputSchema = z.object({
16
- message: z.string().describe('要发送给人类的消息内容'),
17
- chat_id: z.string().optional().describe('目标群聊 ID'),
18
- reply_to_message_id: z.string().optional().describe('回复的消息 ID'),
19
- task_id: z.string().optional().describe('关联任务 ID'),
20
- intent: z.enum(['clarification', 'report', 'notification']).describe('消息意图'),
21
- });
22
- export const ApproveDeliveryInputSchema = z.object({
23
- task_id: z.string().describe('要验收的任务 ID'),
24
- summary: z.string().optional().describe('验收通过的简评'),
25
- notify_human: z.boolean().default(true).describe('是否通知人类'),
26
- });
27
- export const RejectDeliveryInputSchema = z.object({
28
- task_id: z.string().describe('要打回的任务 ID'),
29
- reason: z.string().describe('打回原因'),
30
- feedback: z.string().describe('给执行者的修改意见'),
31
- });
32
- export const LookupTaskInputSchema = z.object({
33
- task_id: z.string().optional().describe('指定任务 ID'),
34
- status: z.string().optional().describe('按状态过滤'),
35
- });
36
- export const LogDecisionInputSchema = z.object({
37
- decision: z.string().describe('决策内容'),
38
- reasoning: z.string().describe('决策理由'),
39
- task_id: z.string().optional().describe('关联任务 ID'),
40
- });
41
- export const NoActionInputSchema = z.object({
42
- reason: z.string().describe('不处理的原因'),
43
- });
44
- // ── Output Schemas(工具执行后返回给 Loid 的结果)──
45
- export const DispatchTaskOutputSchema = z.object({
46
- task_id: z.string(),
47
- status: z.literal('dispatched'),
48
- });
49
- export const AskHumanOutputSchema = z.object({
50
- sent: z.boolean(),
51
- message_id: z.string().optional(),
52
- });
53
- export const ApproveDeliveryOutputSchema = z.object({
54
- approved: z.boolean(),
55
- task_id: z.string(),
56
- });
57
- export const RejectDeliveryOutputSchema = z.object({
58
- rejected: z.boolean(),
59
- task_id: z.string(),
60
- retry_count: z.number(),
61
- max_retries: z.number(),
62
- });
63
- export const LookupTaskOutputSchema = z.object({
64
- tasks: z.array(z.object({
65
- task_id: z.string(),
66
- title: z.string(),
67
- status: z.string(),
68
- assignee: z.string().nullable(),
69
- created_at: z.string().nullable(),
70
- pr_url: z.string().nullable().optional(),
71
- })),
72
- });
73
- export const LogDecisionOutputSchema = z.object({
74
- logged: z.boolean(),
75
- });
76
- export const NoActionOutputSchema = z.object({
77
- acknowledged: z.boolean(),
78
- });
79
- // ── Tool 注册表 ──
80
- export const LOID_TOOL_REGISTRY = {
81
- dispatch_task: {
82
- description: '派工给执行者(Yor)。创建任务、写入 brief、启动执行。',
83
- inputSchema: DispatchTaskInputSchema,
84
- outputSchema: DispatchTaskOutputSchema,
85
- },
86
- ask_human: {
87
- description: '向人类发送消息(提问、汇报结果、通知)。',
88
- inputSchema: AskHumanInputSchema,
89
- outputSchema: AskHumanOutputSchema,
90
- },
91
- approve_delivery: {
92
- description: '验收通过执行者的交付成果。标记任务完成,可选通知人类。',
93
- inputSchema: ApproveDeliveryInputSchema,
94
- outputSchema: ApproveDeliveryOutputSchema,
95
- },
96
- reject_delivery: {
97
- description: '打回执行者的交付,附带修改意见并重新派工。最多返工 3 次。',
98
- inputSchema: RejectDeliveryInputSchema,
99
- outputSchema: RejectDeliveryOutputSchema,
100
- },
101
- lookup_task: {
102
- description: '查询任务状态和历史。可按 task_id 或 status 过滤。',
103
- inputSchema: LookupTaskInputSchema,
104
- outputSchema: LookupTaskOutputSchema,
105
- },
106
- log_decision: {
107
- description: '记录决策理由到审计日志。',
108
- inputSchema: LogDecisionInputSchema,
109
- outputSchema: LogDecisionOutputSchema,
110
- },
111
- no_action: {
112
- description: '明确表示不处理此消息。记录原因到日志。',
113
- inputSchema: NoActionInputSchema,
114
- outputSchema: NoActionOutputSchema,
115
- },
116
- };
117
- //# sourceMappingURL=schemas.js.map
@@ -1,314 +0,0 @@
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