evolcore 0.0.43-test.4 → 0.0.43-test.6

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 (186) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/bin/ecmsg.js +437 -91
  3. package/dist/agents/baseagent-availability.js +19 -4
  4. package/dist/agents/baseagent.js +2 -2
  5. package/dist/agents/claude-runner.js +19 -4
  6. package/dist/agents/codex/app-server-client.js +14 -3
  7. package/dist/agents/codex-runner.js +18 -23
  8. package/dist/aun/aid/agentmd.js +25 -0
  9. package/dist/aun/aid/control-aid.js +15 -0
  10. package/dist/aun/aid/identity.js +8 -0
  11. package/dist/aun/aid/ownership-operation.js +12 -3
  12. package/dist/aun/group/invite-service.js +3 -2
  13. package/dist/aun/service-proxy.js +18 -6
  14. package/dist/channels/aun.js +99 -23
  15. package/dist/channels/daemon.js +2 -2
  16. package/dist/cli/agent-create.js +19 -7
  17. package/dist/cli/aid-bind-command.js +3 -0
  18. package/dist/cli/aun-commands.js +19 -4
  19. package/dist/cli/code-stats.js +451 -213
  20. package/dist/cli/ctl-command.js +1 -3
  21. package/dist/cli/daemon-commands.js +42 -4
  22. package/dist/cli/directory.js +3 -1
  23. package/dist/cli/ecmsg-gateway.js +206 -0
  24. package/dist/cli/index.js +6 -0
  25. package/dist/cli/init.js +120 -13
  26. package/dist/cli/provider-command.js +82 -5
  27. package/dist/cli/restart-monitor.js +35 -24
  28. package/dist/cli/stats.js +8 -1
  29. package/dist/cli/task-context.js +41 -1
  30. package/dist/cli/watch-logs.js +6 -4
  31. package/dist/config/boot-log.js +16 -3
  32. package/dist/config/builtin-roles.js +2 -2
  33. package/dist/config/config-manager.js +5 -14
  34. package/dist/config/daemon-services.js +1 -0
  35. package/dist/config/peer-role-resolver.js +6 -6
  36. package/dist/config/provider-identity-migration.js +277 -0
  37. package/dist/config/provider-identity.js +37 -0
  38. package/dist/config/provider-ipc-service.js +40 -3
  39. package/dist/config/provider-local-sync.js +155 -0
  40. package/dist/config/providers-config.js +45 -4
  41. package/dist/config/providers-management.js +242 -76
  42. package/dist/config/providers.js +4 -1
  43. package/dist/config/role-service.js +8 -8
  44. package/dist/config/role-store.js +22 -22
  45. package/dist/config/schema-migration.js +143 -86
  46. package/dist/config/snapshot.js +70 -41
  47. package/dist/core/agent-runtime.js +48 -9
  48. package/dist/core/auth/auth-gateway.js +5 -3
  49. package/dist/core/auth/delegation-diagnostics.js +6 -2
  50. package/dist/core/auth/operation-authorizer.js +3 -1
  51. package/dist/core/auth/operation-catalog.js +6 -4
  52. package/dist/core/baseagent-loader.js +114 -11
  53. package/dist/core/channel-loader.js +36 -13
  54. package/dist/core/channel-runtime.js +112 -42
  55. package/dist/core/command/cli-intent-parser.js +2 -1
  56. package/dist/core/command/command-handler.js +16 -11
  57. package/dist/core/command/menu-handler.js +8 -3
  58. package/dist/core/command/menu-protocol.js +80 -7
  59. package/dist/core/command/provider-menu.js +4 -2
  60. package/dist/core/command/role-menu.js +29 -17
  61. package/dist/core/command/slash-handler.js +52 -16
  62. package/dist/core/daemon-control.js +42 -15
  63. package/dist/core/daemon-lifecycle.js +411 -67
  64. package/dist/core/handoff/dispatcher.js +9 -3
  65. package/dist/core/handoff/runtime.js +139 -45
  66. package/dist/core/handoff/store.js +190 -2
  67. package/dist/core/handoff/types.js +5 -0
  68. package/dist/core/initialization/service.js +7 -6
  69. package/dist/core/ipc-registration.js +5 -4
  70. package/dist/core/lifecycle-notice.js +10 -4
  71. package/dist/core/message/aun-ipc-sender.js +83 -5
  72. package/dist/core/message/message-admission.js +2 -0
  73. package/dist/core/message/message-bridge.js +53 -4
  74. package/dist/core/message/message-queue.js +46 -4
  75. package/dist/core/message/pending-hints.js +4 -10
  76. package/dist/core/message/response-engine.js +33 -25
  77. package/dist/core/message/send-options.js +40 -0
  78. package/dist/core/message/send-routing.js +320 -0
  79. package/dist/core/ownership/owner-resolver.js +112 -8
  80. package/dist/core/permission/ec-command-parser.js +159 -16
  81. package/dist/core/permission/readonly-shell-query.js +66 -7
  82. package/dist/core/permission/tool-error-code.js +13 -1
  83. package/dist/core/permission/tool-policy.js +74 -20
  84. package/dist/core/relation/same-owner-proof.js +131 -0
  85. package/dist/core/session/adapters/claude-session-file-adapter.js +24 -0
  86. package/dist/core/session/adapters/codex-session-file-adapter.js +80 -0
  87. package/dist/core/session/adapters/ecagent-session-file-adapter.js +22 -0
  88. package/dist/core/session/adapters/gemini-session-file-adapter.js +39 -0
  89. package/dist/core/session/session-fs-store.js +164 -3
  90. package/dist/core/session/session-idle-monitor.js +103 -17
  91. package/dist/core/session/session-manager.js +105 -18
  92. package/dist/core/thread/thread-route.js +5 -2
  93. package/dist/directory/owner-directory-admission.js +26 -1
  94. package/dist/directory/owner-directory-cache.js +739 -109
  95. package/dist/directory/owner-directory-markdown.js +146 -36
  96. package/dist/directory/owner-directory-query-operation.js +6 -3
  97. package/dist/directory/owner-directory-scope.js +12 -0
  98. package/dist/directory/owner-directory-search.js +5 -1
  99. package/dist/directory/owner-directory-store.js +28 -0
  100. package/dist/ecweb/basic-settings-service.js +15 -1
  101. package/dist/ecweb/message-context-service.js +2 -2
  102. package/dist/ecweb/providers-service.js +3 -1
  103. package/dist/ecweb/runtime/lifecycle.js +26 -15
  104. package/dist/ecweb/runtime/supervisor.js +120 -51
  105. package/dist/index.js +551 -250
  106. package/dist/paths.js +2 -1
  107. package/dist/proxy/manager.js +40 -17
  108. package/dist/proxy/service-supervisor.js +67 -33
  109. package/dist/response-system/engines/v1/proactive-flow.js +4 -0
  110. package/dist/trigger/application-service.js +4 -1
  111. package/dist/trigger/audit.js +19 -4
  112. package/dist/trigger/authorization.js +14 -5
  113. package/dist/trigger/event-source.js +4 -0
  114. package/dist/trigger/feedback.js +26 -2
  115. package/dist/trigger/history.js +176 -7
  116. package/dist/trigger/manager.js +1 -3
  117. package/dist/trigger/scheduler.js +81 -8
  118. package/dist/trigger/system-definitions.js +2 -2
  119. package/dist/trigger/validation.js +4 -0
  120. package/dist/utils/autostart.js +2 -2
  121. package/dist/utils/cross-platform.js +188 -12
  122. package/dist/utils/host-info.js +11 -8
  123. package/dist/utils/npm-ops.js +48 -0
  124. package/dist/utils/process-introspect.js +64 -1
  125. package/dist/utils/public-suffix.js +5811 -0
  126. package/dist/utils/startup-trace.js +160 -19
  127. package/dist/utils/windows-autostart.js +41 -7
  128. package/ecagent/dist/harness/env/nodejs.js +46 -2
  129. package/kits/docs/aun/ABILITY_CALLING.md +6 -6
  130. package/kits/docs/channels/aun.md +1 -1
  131. package/kits/docs/channels/feishu.md +2 -2
  132. package/kits/docs/context-assembly.md +20 -4
  133. package/kits/docs/evolcore/INDEX.md +5 -3
  134. package/kits/docs/evolcore/agent.md +2 -2
  135. package/kits/docs/evolcore/aid.md +8 -2
  136. package/kits/docs/evolcore/ctl.md +15 -5
  137. package/kits/docs/evolcore/directory.md +48 -15
  138. package/kits/docs/evolcore/group.md +8 -8
  139. package/kits/docs/evolcore/memory-consolidation.md +1 -1
  140. package/kits/docs/evolcore/menu-exec-schema-commands.md +1 -1
  141. package/kits/docs/evolcore/menu-protocol.md +32 -3
  142. package/kits/docs/evolcore/msg.md +38 -30
  143. package/kits/docs/evolcore/provider.md +57 -5
  144. package/kits/docs/evolcore/response.md +2 -2
  145. package/kits/docs/evolcore/thread-chain.md +11 -13
  146. package/kits/docs/evolcore/tool-authorization.md +17 -0
  147. package/kits/docs/evolcore/trigger.md +2 -2
  148. package/kits/docs/identity/ROLE_DETAIL.md +1 -1
  149. package/kits/docs/prompt-loading-architecture.md +30 -20
  150. package/kits/eck_manifest.auxiliary.json +5 -5
  151. package/kits/eck_manifest.json +44 -32
  152. package/kits/eck_manifest.memory.json +18 -18
  153. package/kits/eck_message_manifest.json +3 -3
  154. package/kits/rules/01-overview.md +1 -1
  155. package/kits/rules/06-channel.md +7 -8
  156. package/kits/schemas/_meta.json +7 -1
  157. package/kits/schemas/daemon.schema.1.json +5 -0
  158. package/kits/schemas/daemon.schema.2.json +5 -0
  159. package/kits/schemas/daemon.schema.3.json +2 -1
  160. package/kits/schemas/daemon.schema.4.json +2 -1
  161. package/kits/schemas/daemon.schema.5.json +2 -1
  162. package/kits/schemas/daemon.schema.6.json +1 -1
  163. package/kits/schemas/daemon.schema.7.json +1 -1
  164. package/kits/schemas/daemon.schema.8.json +2 -1
  165. package/kits/schemas/daemon.schema.9.json +2 -1
  166. package/kits/schemas/providers.schema.2.json +74 -0
  167. package/kits/schemas/role-registry.schema.1.json +2 -2
  168. package/kits/schemas/single-session.schema.1.json +1 -1
  169. package/kits/schemas/single-session.schema.2.json +1 -1
  170. package/kits/schemas/single-session.schema.3.json +1 -1
  171. package/kits/skills/aid-ability/SKILL.md +7 -7
  172. package/kits/skills/ec-agent-create/SKILL.md +1 -0
  173. package/kits/skills/ec-group/SKILL.md +8 -5
  174. package/kits/skills/ec-group-collaboration/SKILL.md +7 -7
  175. package/kits/skills/ec-service-proxy/SKILL.md +3 -10
  176. package/kits/skills/ec-trigger/SKILL.md +9 -9
  177. package/kits/skills/ec-trigger/references/examples.md +1 -1
  178. package/kits/skills/thread-ops/SKILL.md +10 -10
  179. package/kits/templates/system-fragments/channel.md +5 -5
  180. package/kits/templates/system-fragments/commands.md +7 -6
  181. package/kits/templates/system-fragments/directory-contacts.md +10 -3
  182. package/kits/templates/system-fragments/personal-assistant.md +22 -3
  183. package/kits/templates/system-fragments/reply.md +48 -28
  184. package/kits/templates/system-fragments/session.md +3 -10
  185. package/kits/templates/system-fragments/thread.md +5 -5
  186. package/package.json +4 -4
@@ -1,10 +1,35 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
- const SOURCE_EXTENSIONS = new Set([
4
- '.ts', '.tsx', '.mts', '.cts',
5
- '.js', '.jsx', '.mjs', '.cjs',
3
+ import { execFileSync } from 'child_process';
4
+ // ── 语言定义 ────────────────────────────────────────────────
5
+ // 每个语言一条,扩展名不重叠。`kind` 只影响表头分组标题。
6
+ const LANGUAGES = [
7
+ { key: 'typescript', label: 'TypeScript', kind: '代码', extensions: ['.ts', '.tsx', '.mts', '.cts'] },
8
+ { key: 'javascript', label: 'JavaScript', kind: '代码', extensions: ['.js', '.jsx', '.mjs', '.cjs'] },
9
+ { key: 'vue', label: 'Vue', kind: '代码', extensions: ['.vue'] },
10
+ { key: 'css', label: 'CSS / 样式', kind: '代码', extensions: ['.css', '.scss', '.less'] },
11
+ { key: 'python', label: 'Python', kind: '代码', extensions: ['.py'] },
12
+ { key: 'shell', label: 'Shell', kind: '代码', extensions: ['.sh', '.ps1', '.bat', '.cmd'] },
13
+ { key: 'markdown', label: 'Markdown 文档', kind: '文档', extensions: ['.md', '.mdx'] },
14
+ { key: 'yaml', label: 'YAML 配置', kind: '配置', extensions: ['.yaml', '.yml'] },
15
+ { key: 'json', label: 'JSON 配置', kind: '配置', extensions: ['.json'] },
16
+ { key: 'other', label: '其他文本文档', kind: '文档', extensions: ['.txt', '.toml', '.ini', '.conf'] },
17
+ ];
18
+ /** 扩展名 → 语言键,用于单文件归类。 */
19
+ const EXTENSION_LANGUAGE = new Map();
20
+ for (const language of LANGUAGES) {
21
+ for (const extension of language.extensions)
22
+ EXTENSION_LANGUAGE.set(extension, language.key);
23
+ }
24
+ // 不统计的文件名(生成文件、体积巨大或纯噪声)。
25
+ const EXCLUDE_FILE_NAMES = new Set([
26
+ 'package-lock.json',
27
+ 'pnpm-lock.yaml',
28
+ 'yarn.lock',
6
29
  ]);
7
- const SECTION_DEFINITIONS = [
30
+ // ── 模块定义(EvolCore 专属)────────────────────────────────
31
+ // 按 src/ 一级目录归类;ecweb/src 单独算作 ECWeb。
32
+ const SECTIONS = [
8
33
  { key: 'core', label: '核心模块' },
9
34
  { key: 'agents', label: 'Agent 模块' },
10
35
  { key: 'channels', label: '渠道适配' },
@@ -17,17 +42,13 @@ const SECTION_DEFINITIONS = [
17
42
  { key: 'eck', label: 'ECK' },
18
43
  { key: 'response', label: '响应系统' },
19
44
  { key: 'ecweb', label: 'ECWeb' },
45
+ { key: 'ability', label: 'Ability 系统' },
46
+ { key: 'contracts', label: '协议契约' },
47
+ { key: 'directory', label: 'Owner 名录' },
48
+ { key: 'proxy', label: '代理服务' },
20
49
  { key: 'other', label: '其他源码目录' },
21
50
  { key: 'entry', label: '根入口文件' },
22
51
  ];
23
- const V2_SECTION_KEYS = [
24
- 'core', 'agents', 'channels', 'utils', 'cli', 'aun',
25
- 'subsystems', 'eck', 'response', 'other', 'entry', 'bin',
26
- ];
27
- const V3_SECTION_KEYS = [
28
- 'core', 'agents', 'channels', 'utils', 'cli', 'aun',
29
- 'trigger', 'config', 'stats', 'eck', 'response', 'other', 'entry', 'bin',
30
- ];
31
52
  const TOP_LEVEL_SECTION = {
32
53
  core: 'core',
33
54
  agents: 'agents',
@@ -40,7 +61,13 @@ const TOP_LEVEL_SECTION = {
40
61
  stats: 'stats',
41
62
  eck: 'eck',
42
63
  'response-system': 'response',
64
+ ecweb: 'ecweb',
65
+ ability: 'ability',
66
+ contracts: 'contracts',
67
+ directory: 'directory',
68
+ proxy: 'proxy',
43
69
  };
70
+ // ── 显示宽度(中文标签对齐)─────────────────────────────────
44
71
  const COMBINING_MARK_RE = /\p{Mark}/u;
45
72
  function isWideCodePoint(codePoint) {
46
73
  return codePoint >= 0x1100 && (codePoint <= 0x115f
@@ -76,9 +103,32 @@ function displayWidth(value) {
76
103
  function padDisplayEnd(value, targetWidth) {
77
104
  return value + ' '.repeat(Math.max(0, targetWidth - displayWidth(value)));
78
105
  }
79
- function isSourceFile(fileName) {
80
- return SOURCE_EXTENSIONS.has(path.extname(fileName).toLowerCase());
106
+ function padDisplayStart(value, targetWidth) {
107
+ return ' '.repeat(Math.max(0, targetWidth - displayWidth(value))) + value;
108
+ }
109
+ function formatCount(value) {
110
+ return value.toLocaleString('en-US');
111
+ }
112
+ function formatDelta(value) {
113
+ return value > 0 ? `+${formatCount(value)}` : formatCount(value);
114
+ }
115
+ // ── 颜色 ────────────────────────────────────────────────────
116
+ // 与 `ec status` 一致:只在 TTY 且未设置 NO_COLOR 时上色。
117
+ // 上色一律在补齐宽度之后做,转义码不参与列宽计算。
118
+ const COLOR_ENABLED = !!process.stdout.isTTY && !process.env.NO_COLOR;
119
+ const GREEN = '\x1b[32m';
120
+ const RED = '\x1b[31m';
121
+ const RESET = '\x1b[0m';
122
+ function paintDelta(text, value) {
123
+ if (!COLOR_ENABLED || value === 0)
124
+ return text;
125
+ return `${value > 0 ? GREEN : RED}${text}${RESET}`;
81
126
  }
127
+ /** 先按纯文本宽度补齐,再上色。 */
128
+ function deltaCell(value, width) {
129
+ return paintDelta(padDisplayStart(formatDelta(value), width), value);
130
+ }
131
+ // ── 文件遍历与统计 ──────────────────────────────────────────
82
132
  function countFileLines(filePath) {
83
133
  const content = fs.readFileSync(filePath, 'utf-8');
84
134
  if (content.length === 0)
@@ -86,244 +136,432 @@ function countFileLines(filePath) {
86
136
  const newlines = content.match(/\n/g)?.length ?? 0;
87
137
  return newlines + (content.endsWith('\n') ? 0 : 1);
88
138
  }
89
- function walkSourceFiles(dir) {
90
- if (!fs.existsSync(dir))
139
+ /** 模块行只统计源码目录;语言表覆盖整个项目。 */
140
+ const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.css', '.scss', '.less']);
141
+ /**
142
+ * 把相对项目根的路径映射到模块行。
143
+ * 只有 src/ 与 ecweb/src/ 下的源码参与模块统计,其余返回 null。
144
+ */
145
+ function classifySection(relative) {
146
+ const parts = relative.split(path.sep);
147
+ if (parts[0] === 'ecweb' && parts[1] === 'src')
148
+ return { key: 'ecweb' };
149
+ if (parts[0] !== 'src')
150
+ return null;
151
+ if (parts.length === 2)
152
+ return { key: 'entry' };
153
+ const sub = parts[1];
154
+ const key = TOP_LEVEL_SECTION[sub];
155
+ return key ? { key } : { key: 'other', other: sub };
156
+ }
157
+ /**
158
+ * 取「已入库」的文件清单。
159
+ *
160
+ * 判据直接交给 git:`git ls-files --cached` 只列出已被跟踪的文件,
161
+ * `.gitignore`、未 `git add` 的草稿、构建产物全部自动排除,
162
+ * 不需要在代码里再维护一份目录黑名单。
163
+ *
164
+ * 不是 git 仓库(例如 npm 全局安装的包)时退化为全量遍历。
165
+ */
166
+ function listTrackedFiles(pkgRoot) {
167
+ try {
168
+ const output = execFileSync('git', ['ls-files', '-z', '--cached'], {
169
+ cwd: pkgRoot,
170
+ encoding: 'utf-8',
171
+ maxBuffer: 64 * 1024 * 1024,
172
+ stdio: ['ignore', 'pipe', 'ignore'],
173
+ windowsHide: true,
174
+ });
175
+ return output.split('\0').filter(Boolean).map(relative => path.join(pkgRoot, relative));
176
+ }
177
+ catch {
178
+ return walkFiles(pkgRoot);
179
+ }
180
+ }
181
+ /**
182
+ * 取「未入库」的文件清单:被 .gitignore 忽略的 + 未跟踪的。
183
+ *
184
+ * 排除 node_modules 与临时目录——它们是依赖和构建副产物,
185
+ * 「未入库」在这里要表达的是「写了但没进版本库的自己的东西」。
186
+ */
187
+ function listUntrackedFiles(pkgRoot, pathspecs) {
188
+ try {
189
+ const output = execFileSync('git', ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--', ...pathspecs], {
190
+ cwd: pkgRoot,
191
+ encoding: 'utf-8',
192
+ maxBuffer: 64 * 1024 * 1024,
193
+ stdio: ['ignore', 'pipe', 'ignore'],
194
+ windowsHide: true,
195
+ });
196
+ // git 输出永远是正斜杠,不能用 path.sep 去匹配(Windows 上是反斜杠)。
197
+ const excludedSegments = new Set(['node_modules', '.git', 'test-tmp']);
198
+ return output.split('\0')
199
+ .filter(Boolean)
200
+ .filter(relative => !relative.split('/').some(segment => excludedSegments.has(segment)))
201
+ .map(relative => path.join(pkgRoot, relative));
202
+ }
203
+ catch {
91
204
  return [];
92
- const files = [];
93
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
94
- const full = path.join(dir, entry.name);
95
- if (entry.isDirectory()) {
96
- files.push(...walkSourceFiles(full));
205
+ }
206
+ }
207
+ function countFileSet(files) {
208
+ let lines = 0;
209
+ for (const file of files) {
210
+ try {
211
+ lines += countFileLines(file);
97
212
  }
98
- else if (entry.isFile() && isSourceFile(entry.name)) {
99
- files.push(full);
213
+ catch {
214
+ /* 读不到的文件跳过 */
100
215
  }
101
216
  }
102
- return files;
217
+ return { lines, files: files.length };
103
218
  }
104
- function resolveSourceRoot(pkgRoot) {
105
- const direct = path.join(pkgRoot, 'src');
106
- if (fs.existsSync(direct))
107
- return { packageDir: pkgRoot, sourceDir: direct };
108
- const parent = path.resolve(pkgRoot, '..');
109
- const sibling = path.join(parent, 'src');
110
- if (fs.existsSync(sibling))
111
- return { packageDir: parent, sourceDir: sibling };
112
- return { packageDir: pkgRoot, sourceDir: direct };
219
+ export function collectTrackedComparison(pkgRoot) {
220
+ const codeExt = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i;
221
+ const tracked = listTrackedFiles(pkgRoot).map(file => path.relative(pkgRoot, file));
222
+ const pick = (list, match) => list.filter(match);
223
+ const untrackedMarkdown = listUntrackedFiles(pkgRoot, ['*.md', '*.mdx']);
224
+ const untrackedTests = listUntrackedFiles(pkgRoot, ['tests']).filter(file => codeExt.test(file));
225
+ return {
226
+ markdown: {
227
+ tracked: countFileSet(pick(tracked, item => /\.(md|mdx)$/i.test(item)).map(item => path.join(pkgRoot, item))),
228
+ untracked: countFileSet(untrackedMarkdown),
229
+ },
230
+ tests: {
231
+ tracked: countFileSet(pick(tracked, item => item.split(path.sep)[0] === 'tests' && codeExt.test(item)).map(item => path.join(pkgRoot, item))),
232
+ untracked: countFileSet(untrackedTests),
233
+ },
234
+ };
113
235
  }
114
236
  /**
115
- * Scan EvolCore and ECWeb source files. Classification happens after discovery,
116
- * so a newly added main-package src directory or root source file is still
117
- * included even when it has not been assigned a named section yet.
237
+ * 遍历并统计。缓存按 mtime 命中,只对新增/修改的文件读盘。
238
+ * 先发现全部文件再归类,新目录/新扩展名不会被漏掉。
118
239
  */
119
- export function collectCodeStats(pkgRoot) {
120
- const { packageDir, sourceDir } = resolveSourceRoot(pkgRoot);
121
- const sections = new Map(SECTION_DEFINITIONS.map(def => [def.key, { ...def, lines: 0, files: 0 }]));
240
+ export function collectCodeStats(pkgRoot, cacheFile) {
241
+ const cache = cacheFile ? loadCache(cacheFile) : {};
242
+ const nextCache = {};
243
+ const sections = new Map(SECTIONS.map(def => [def.key, { ...def, lines: 0, files: 0 }]));
244
+ const languages = new Map(LANGUAGES.map(def => [def.key, { ...def, lines: 0, files: 0 }]));
122
245
  const otherDirectories = new Set();
123
- const scannedFiles = [];
124
- for (const file of walkSourceFiles(sourceDir)) {
125
- const relative = path.relative(sourceDir, file);
126
- const parts = relative.split(path.sep);
127
- let sectionKey;
128
- if (parts.length === 1) {
129
- sectionKey = 'entry';
246
+ let cacheHits = 0;
247
+ let cacheMisses = 0;
248
+ for (const filePath of listTrackedFiles(pkgRoot)) {
249
+ const fileName = path.basename(filePath);
250
+ // 锁文件动辄几万行,且是生成物 —— 即便入库也不计入。
251
+ if (EXCLUDE_FILE_NAMES.has(fileName))
252
+ continue;
253
+ const languageKey = EXTENSION_LANGUAGE.get(path.extname(fileName).toLowerCase());
254
+ if (!languageKey)
255
+ continue;
256
+ const relative = path.relative(pkgRoot, filePath);
257
+ // 非源码文件(.md/.json 等)也计入文件数与总行数,但不归属任何模块行 ——
258
+ // 模块行只反映源码分布。语言表则覆盖全部文件。
259
+ let lines;
260
+ let mtime;
261
+ try {
262
+ mtime = fs.statSync(filePath).mtimeMs;
263
+ }
264
+ catch {
265
+ continue;
266
+ }
267
+ const cached = cache[relative];
268
+ if (cached && cached.mtime === mtime) {
269
+ lines = cached.lines;
270
+ cacheHits++;
130
271
  }
131
272
  else {
132
- sectionKey = TOP_LEVEL_SECTION[parts[0]] ?? 'other';
133
- if (sectionKey === 'other')
134
- otherDirectories.add(parts[0]);
273
+ try {
274
+ lines = countFileLines(filePath);
275
+ }
276
+ catch {
277
+ continue;
278
+ }
279
+ cacheMisses++;
280
+ }
281
+ nextCache[relative] = { mtime, lines };
282
+ const language = languages.get(languageKey);
283
+ language.lines += lines;
284
+ language.files++;
285
+ if (SOURCE_EXTENSIONS.has(path.extname(fileName).toLowerCase())) {
286
+ const classified = classifySection(relative);
287
+ if (classified) {
288
+ if (classified.other)
289
+ otherDirectories.add(classified.other);
290
+ const section = sections.get(classified.key);
291
+ section.lines += lines;
292
+ section.files++;
293
+ }
135
294
  }
136
- const section = sections.get(sectionKey);
137
- section.lines += countFileLines(file);
138
- section.files++;
139
- scannedFiles.push(path.relative(packageDir, file));
140
- }
141
- const ecwebSourceDir = path.join(packageDir, 'ecweb', 'src');
142
- for (const file of walkSourceFiles(ecwebSourceDir)) {
143
- const section = sections.get('ecweb');
144
- section.lines += countFileLines(file);
145
- section.files++;
146
- scannedFiles.push(path.relative(packageDir, file));
147
295
  }
148
- const sectionList = SECTION_DEFINITIONS.map(def => sections.get(def.key));
296
+ if (cacheFile)
297
+ saveCache(nextCache, cacheFile);
298
+ const totalFiles = Object.keys(nextCache).length;
299
+ const sectionList = SECTIONS.map(def => sections.get(def.key));
300
+ const languageList = LANGUAGES.map(def => languages.get(def.key));
149
301
  return {
150
- sourceDir,
151
302
  sections: sectionList,
152
- totalLines: sectionList.reduce((sum, section) => sum + section.lines, 0),
153
- totalFiles: sectionList.reduce((sum, section) => sum + section.files, 0),
154
- scannedFiles: scannedFiles.sort(),
303
+ languages: languageList,
304
+ totalLines: languageList.reduce((sum, language) => sum + language.lines, 0),
305
+ totalFiles,
155
306
  otherDirectories: [...otherDirectories].sort(),
307
+ cacheInfo: {
308
+ totalFiles,
309
+ cacheHits,
310
+ cacheMisses,
311
+ hitRate: totalFiles > 0 ? `${((cacheHits / totalFiles) * 100).toFixed(1)}%` : '0%',
312
+ },
156
313
  };
157
314
  }
158
- function parseHistoryLine(line) {
159
- const parts = line.split('\t');
160
- const currentTotalIndex = SECTION_DEFINITIONS.length + 2;
161
- if (parts[1] === 'v4' && parts.length >= currentTotalIndex + 3) {
162
- const values = {};
163
- SECTION_DEFINITIONS.forEach((def, index) => {
164
- values[def.key] = Number.parseInt(parts[index + 2], 10) || 0;
165
- });
166
- return {
167
- time: parts[0],
168
- values,
169
- total: Number.parseInt(parts[currentTotalIndex], 10) || 0,
170
- files: Number.parseInt(parts[currentTotalIndex + 1], 10) || 0,
171
- delta: parts[currentTotalIndex + 2],
172
- version: 4,
173
- };
174
- }
175
- if (parts[1] === 'v3' && parts.length >= 19) {
176
- const values = {};
177
- V3_SECTION_KEYS.forEach((key, index) => {
178
- values[key] = Number.parseInt(parts[index + 2], 10) || 0;
179
- });
180
- return {
181
- time: parts[0],
182
- values,
183
- total: Number.parseInt(parts[16], 10) || 0,
184
- files: Number.parseInt(parts[17], 10) || 0,
185
- delta: parts[18],
186
- version: 3,
187
- };
188
- }
189
- if (parts[1] === 'v2' && parts.length >= 17) {
190
- const values = {};
191
- V2_SECTION_KEYS.forEach((key, index) => {
192
- values[key] = Number.parseInt(parts[index + 2], 10) || 0;
193
- });
194
- return {
195
- time: parts[0],
196
- values,
197
- total: Number.parseInt(parts[14], 10) || 0,
198
- files: Number.parseInt(parts[15], 10) || 0,
199
- delta: parts[16],
200
- version: 2,
201
- };
315
+ /** 无 git 时的退化路径。只跳过必然不属于项目的目录,其余交给扩展名过滤。 */
316
+ const FALLBACK_EXCLUDE_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'coverage']);
317
+ function walkFiles(dir) {
318
+ if (!fs.existsSync(dir))
319
+ return [];
320
+ const files = [];
321
+ let entries;
322
+ try {
323
+ entries = fs.readdirSync(dir, { withFileTypes: true });
202
324
  }
203
- // Legacy TSV formats, newest first:
204
- // 11 columns: time core agents channels utils cli aun sys entry total delta
205
- // 10 columns: time core agents channels utils cli aun entry total delta
206
- // 8 columns: time core agents channels utils entry total delta
207
- // 7 columns: time core agents channels utils entry total
208
- // 6 columns: time core channels utils entry total
209
- const values = {};
210
- let totalIndex;
211
- let deltaIndex;
212
- if (parts.length >= 11) {
213
- [values.core, values.agents, values.channels, values.utils, values.cli, values.aun, values.subsystems, values.entry]
214
- = [parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8]].map(Number);
215
- totalIndex = 9;
216
- deltaIndex = 10;
325
+ catch {
326
+ return files;
217
327
  }
218
- else if (parts.length >= 10) {
219
- [values.core, values.agents, values.channels, values.utils, values.cli, values.aun, values.entry]
220
- = [parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]].map(Number);
221
- totalIndex = 8;
222
- deltaIndex = 9;
328
+ for (const entry of entries) {
329
+ const full = path.join(dir, entry.name);
330
+ if (entry.isDirectory()) {
331
+ if (!FALLBACK_EXCLUDE_DIRS.has(entry.name))
332
+ files.push(...walkFiles(full));
333
+ }
334
+ else if (entry.isFile()) {
335
+ if (EXTENSION_LANGUAGE.has(path.extname(entry.name).toLowerCase()))
336
+ files.push(full);
337
+ }
223
338
  }
224
- else if (parts.length >= 8) {
225
- [values.core, values.agents, values.channels, values.utils, values.entry]
226
- = [parts[1], parts[2], parts[3], parts[4], parts[5]].map(Number);
227
- totalIndex = 6;
228
- deltaIndex = 7;
339
+ return files;
340
+ }
341
+ // ── 缓存 ────────────────────────────────────────────────────
342
+ function loadCache(cacheFile) {
343
+ if (!fs.existsSync(cacheFile))
344
+ return {};
345
+ try {
346
+ const parsed = JSON.parse(fs.readFileSync(cacheFile, 'utf-8'));
347
+ return parsed && typeof parsed === 'object' ? parsed : {};
229
348
  }
230
- else if (parts.length >= 7) {
231
- [values.core, values.agents, values.channels, values.utils, values.entry]
232
- = [parts[1], parts[2], parts[3], parts[4], parts[5]].map(Number);
233
- totalIndex = 6;
349
+ catch {
350
+ return {};
234
351
  }
235
- else if (parts.length >= 6) {
236
- [values.core, values.channels, values.utils, values.entry]
237
- = [parts[1], parts[2], parts[3], parts[4]].map(Number);
238
- totalIndex = 5;
352
+ }
353
+ function saveCache(cache, cacheFile) {
354
+ try {
355
+ fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
356
+ fs.writeFileSync(cacheFile, JSON.stringify(cache, null, 2), 'utf-8');
239
357
  }
240
- else {
241
- return null;
358
+ catch {
359
+ /* 缓存写不进去不影响本次统计 */
242
360
  }
243
- const total = Number.parseInt(parts[totalIndex], 10);
244
- if (!Number.isFinite(total))
245
- return null;
361
+ }
362
+ // ── 历史记录 ────────────────────────────────────────────────
363
+ function buildRecord(stats) {
246
364
  return {
247
- time: parts[0],
248
- values,
249
- total,
250
- delta: deltaIndex === undefined ? undefined : parts[deltaIndex],
251
- version: 1,
365
+ timestamp: formatTimestamp(new Date()),
366
+ total: stats.totalLines,
367
+ files: stats.totalFiles,
368
+ sections: Object.fromEntries(stats.sections.map(section => [section.key, section.lines])),
369
+ languages: Object.fromEntries(stats.languages.map(language => [language.key, language.lines])),
252
370
  };
253
371
  }
254
- function historyRecords(statsFile) {
255
- if (!fs.existsSync(statsFile))
256
- return [];
257
- return fs.readFileSync(statsFile, 'utf-8')
258
- .split('\n')
259
- .filter(Boolean)
260
- .map(parseHistoryLine)
261
- .filter((record) => record !== null);
262
- }
263
- function appendHistory(statsFile, stats, previous) {
264
- const values = Object.fromEntries(stats.sections.map(section => [section.key, section.lines]));
265
- const unchanged = previous?.version === 4
266
- && previous.files === stats.totalFiles
267
- && SECTION_DEFINITIONS.every(def => previous.values[def.key] === values[def.key]);
268
- if (unchanged)
269
- return;
270
- const now = new Date();
372
+ function formatTimestamp(date) {
271
373
  const pad = (n) => String(n).padStart(2, '0');
272
- const timestamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
273
- const delta = stats.totalLines - (previous?.total ?? 0);
274
- const fields = [
275
- timestamp,
276
- 'v4',
277
- ...SECTION_DEFINITIONS.map(def => values[def.key]),
278
- stats.totalLines,
279
- stats.totalFiles,
280
- delta >= 0 ? `+${delta}` : String(delta),
281
- ];
282
- fs.mkdirSync(path.dirname(statsFile), { recursive: true });
283
- fs.appendFileSync(statsFile, `${fields.join('\t')}\n`);
374
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `
375
+ + `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
284
376
  }
285
- function showHistory(records) {
286
- if (records.length < 2)
287
- return;
288
- console.log('\n==================================================');
289
- console.log('历史记录(最近 10 次)');
290
- console.log('==================================================');
291
- console.log(`${'Time'.padEnd(19)} ${'Files'.padStart(7)} ${'Total'.padStart(8)} ${'Delta'.padStart(8)}`);
292
- console.log('--------------------------------------------------');
293
- let previousTotal = null;
294
- for (const record of records.slice(-10)) {
295
- const inferredDelta = previousTotal === null ? '-' : record.total - previousTotal;
296
- const delta = record.delta ?? (typeof inferredDelta === 'number' && inferredDelta >= 0 ? `+${inferredDelta}` : String(inferredDelta));
297
- console.log(`${record.time.padEnd(19)} ${String(record.files ?? '-').padStart(7)} ${String(record.total).padStart(8)} ${delta.padStart(8)}`);
298
- previousTotal = record.total;
377
+ /** JSON 数组:整体重写,人工可读、便于外部工具消费。 */
378
+ function readJsonArrayFile(file) {
379
+ if (!fs.existsSync(file))
380
+ return [];
381
+ try {
382
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));
383
+ return Array.isArray(parsed) ? parsed : [];
384
+ }
385
+ catch {
386
+ return [];
299
387
  }
300
- console.log('==================================================');
301
- }
302
- export function printCodeStats(pkgRoot, logDir) {
303
- console.log('\n[launcher] 正在统计代码行数...\n');
304
- const stats = collectCodeStats(pkgRoot);
305
- const statsFile = path.join(logDir, 'line-stats.log');
306
- console.log('==================================================');
307
- console.log('EvolCore 代码统计');
308
- console.log('==================================================');
388
+ }
389
+ function saveJsonArray(records, file) {
390
+ fs.mkdirSync(path.dirname(file), { recursive: true });
391
+ fs.writeFileSync(file, `${JSON.stringify(records, null, 2)}\n`, 'utf-8');
392
+ }
393
+ // ── 展示 ────────────────────────────────────────────────────
394
+ // 只用一条标题线,不加框。启动输出本来就长,横杠越多越难读。
395
+ const RULE = '─'.repeat(50);
396
+ function heading(title) {
397
+ console.log(`\n${title}`);
398
+ console.log(RULE);
399
+ }
400
+ function printLanguageTable(stats) {
401
+ heading('EvolCore 代码统计');
402
+ const present = stats.languages.filter(language => language.files > 0);
403
+ const labelWidth = Math.max(20, ...present.map(language => displayWidth(language.label)));
404
+ for (const language of present) {
405
+ console.log(`${padDisplayEnd(`${language.label}:`, labelWidth)} ${padDisplayStart(formatCount(language.lines), 9)} 行 ${padDisplayStart(String(language.files), 4)} 文件`);
406
+ }
407
+ console.log(`${padDisplayEnd('总计:', labelWidth)} ${padDisplayStart(formatCount(stats.totalLines), 9)} 行 ${padDisplayStart(String(stats.totalFiles), 4)} 文件`);
408
+ console.log(`缓存命中率: ${stats.cacheInfo.hitRate} (${stats.cacheInfo.cacheHits}/${stats.cacheInfo.totalFiles})`);
409
+ }
410
+ function printSectionTable(stats) {
411
+ heading('EvolCore 模块代码分布(仅源码)');
309
412
  const rows = stats.sections
310
- .filter(section => section.key !== 'other' || section.files > 0)
413
+ .filter(section => section.files > 0)
311
414
  .map(section => {
312
415
  const suffix = section.key === 'other' && stats.otherDirectories.length > 0
313
416
  ? ` (${stats.otherDirectories.join(', ')})`
314
417
  : '';
315
418
  return { section, label: `${section.label}${suffix}:` };
316
419
  });
317
- const labelWidth = Math.max(24, ...rows.map(row => displayWidth(row.label)));
420
+ const labelWidth = Math.max(20, ...rows.map(row => displayWidth(row.label)));
318
421
  for (const { section, label } of rows) {
319
- console.log(`${padDisplayEnd(label, labelWidth)} ${String(section.lines).padStart(8)} 行 ${String(section.files).padStart(4)} 文件`);
422
+ console.log(`${padDisplayEnd(label, labelWidth)} ${padDisplayStart(formatCount(section.lines), 9)} 行 ${padDisplayStart(String(section.files), 4)} 文件`);
320
423
  }
321
- console.log('--------------------------------------------------');
322
- console.log(`${padDisplayEnd('总计:', labelWidth)} ${String(stats.totalLines).padStart(8)} 行 ${String(stats.totalFiles).padStart(4)} 文件`);
323
- console.log(`扫描范围: src + ecweb/src (${SOURCE_EXTENSIONS.size} 种源码扩展名)`);
324
- console.log('==================================================');
325
- const records = historyRecords(statsFile);
326
- appendHistory(statsFile, stats, records.at(-1));
327
- showHistory(historyRecords(statsFile));
424
+ const sourceLines = stats.sections.reduce((sum, section) => sum + section.lines, 0);
425
+ const sourceFiles = stats.sections.reduce((sum, section) => sum + section.files, 0);
426
+ console.log(`${padDisplayEnd('源码总计:', labelWidth)} ${padDisplayStart(formatCount(sourceLines), 9)} 行 ${padDisplayStart(String(sourceFiles), 4)} 文件`);
427
+ }
428
+ /**
429
+ * 入库 / 未入库对比表。
430
+ *
431
+ * 未入库的文档和测试代码不参与上面的总量——它们是本地草稿、
432
+ * 实验用例,写得多但没交付。单独列出来,避免把「写了多少」
433
+ * 误当成「交付了多少」。
434
+ */
435
+ function printTrackedComparison(comparison) {
436
+ const rows = [
437
+ { label: 'Markdown 文档', ...comparison.markdown },
438
+ { label: '测试代码', ...comparison.tests },
439
+ ];
440
+ const labelWidth = Math.max(16, ...rows.map(row => displayWidth(row.label)));
441
+ heading('入库 / 未入库对比');
442
+ const cellWidth = 24;
443
+ console.log(`${padDisplayEnd('类别', labelWidth)} ${padDisplayEnd('入库', cellWidth)}${padDisplayEnd('未入库', cellWidth)}${padDisplayStart('合计', 12)}`);
444
+ for (const row of rows) {
445
+ const combined = row.tracked.lines + row.untracked.lines;
446
+ const trackedText = `${formatCount(row.tracked.lines)} 行 / ${row.tracked.files} 文件`;
447
+ const untrackedText = `${formatCount(row.untracked.lines)} 行 / ${row.untracked.files} 文件`;
448
+ console.log(`${padDisplayEnd(row.label, labelWidth)} ${padDisplayEnd(trackedText, cellWidth)}${padDisplayEnd(untrackedText, cellWidth)}${padDisplayStart(formatCount(combined), 12)}`);
449
+ }
450
+ console.log('未入库 = 被 .gitignore 忽略 + 未 git add(已排除 node_modules / 临时目录)');
451
+ }
452
+ /**
453
+ * 每日变化:当天最后一条 − 当天第一条。
454
+ *
455
+ * 与 Kite 的口径一致。`mainTotal` 用于总量表,`pick` 用于各模块/各语言表。
456
+ */
457
+ function dailyChanges(records, pick) {
458
+ const byDay = new Map();
459
+ for (const record of records) {
460
+ const value = pick(record);
461
+ // 该类别在这条记录里没有数据(例如新增语言之前的历史),
462
+ // 不等于「当天是 0 行」——直接跳过,不要拉出一条假的归零曲线。
463
+ if (value === undefined)
464
+ continue;
465
+ const date = record.timestamp.slice(0, 10);
466
+ const day = byDay.get(date);
467
+ if (day) {
468
+ day.last = value;
469
+ }
470
+ else {
471
+ byDay.set(date, { first: value, last: value });
472
+ }
473
+ }
474
+ return [...byDay.entries()]
475
+ .sort(([a], [b]) => a.localeCompare(b))
476
+ .map(([date, day]) => ({ date, last: day.last, change: day.last - day.first }));
477
+ }
478
+ function printDailyTable(title, records, pick, limit) {
479
+ const days = dailyChanges(records, pick);
480
+ if (days.length === 0)
481
+ return;
482
+ const shown = days.slice(-limit);
483
+ heading(title);
484
+ console.log(`${padDisplayEnd('日期', 14)} ${padDisplayStart('代码量', 10)} ${padDisplayStart('变化', 10)}`);
485
+ for (const day of shown) {
486
+ console.log(`${padDisplayEnd(day.date, 14)} ${padDisplayStart(formatCount(day.last), 10)} ${deltaCell(day.change, 10)}`);
487
+ }
488
+ }
489
+ function printHistory(records, limit = 10) {
490
+ if (records.length < 2)
491
+ return;
492
+ const shown = records.slice(-limit);
493
+ heading(`历史记录(最近 ${shown.length} 次)`);
494
+ console.log(`${padDisplayEnd('时间', 22)} ${padDisplayStart('文件', 7)} ${padDisplayStart('总计', 10)} ${padDisplayStart('变化', 10)}`);
495
+ let previousTotal = records.length > shown.length
496
+ ? records[records.length - shown.length - 1].total
497
+ : null;
498
+ for (const record of shown) {
499
+ const change = previousTotal === null ? 0 : record.total - previousTotal;
500
+ const deltaCellText = previousTotal === null ? padDisplayStart('-', 10) : deltaCell(change, 10);
501
+ console.log(`${padDisplayEnd(record.timestamp, 22)} ${padDisplayStart(String(record.files), 7)} ${padDisplayStart(formatCount(record.total), 10)} ${deltaCellText}`);
502
+ previousTotal = record.total;
503
+ }
504
+ }
505
+ function printLanguageDailyTables(records) {
506
+ if (records.length < 2)
507
+ return;
508
+ // 只列真正有历史数据的语言:至少两条记录里出现过,且至少跨两天。
509
+ const languagesWithHistory = LANGUAGES.filter(def => {
510
+ const days = dailyChanges(records, record => record.languages?.[def.key]);
511
+ return days.length >= 2 && days.some(day => day.last > 0);
512
+ });
513
+ for (const def of languagesWithHistory) {
514
+ printDailyTable(`${def.label} 每日变化`, records, record => record.languages?.[def.key], 10);
515
+ }
516
+ }
517
+ /**
518
+ * 统计并展示代码量,同时写入历史记录与缓存。
519
+ *
520
+ * 返回本次统计结果,调用方(`ec start`)无需再读文件。
521
+ */
522
+ export function printCodeStats(pkgRoot, logDir, options = {}) {
523
+ const startedAt = Date.now();
524
+ const historyFile = options.historyFile ?? path.join(logDir, 'code-stats.json');
525
+ const cacheFile = options.cacheFile ?? path.join(logDir, 'code-stats-cache.json');
526
+ const dailyLimit = options.dailyLimit ?? 10;
527
+ console.log('\n[launcher] 正在统计代码行数...');
528
+ const stats = collectCodeStats(pkgRoot, cacheFile);
529
+ console.log(`[launcher] 统计耗时: ${((Date.now() - startedAt) / 1000).toFixed(2)}秒\n`);
530
+ printLanguageTable(stats);
531
+ printSectionTable(stats);
532
+ printTrackedComparison(collectTrackedComparison(pkgRoot));
533
+ const records = readJsonArrayFile(historyFile);
534
+ const record = buildRecord(stats);
535
+ const previous = records.at(-1);
536
+ const unchanged = previous !== undefined
537
+ && previous.total === record.total
538
+ && previous.files === record.files
539
+ && sameNumberMap(previous.sections, record.sections)
540
+ && sameNumberMap(previous.languages, record.languages);
541
+ if (!unchanged)
542
+ records.push(record);
543
+ saveJsonArray(records, historyFile);
544
+ printHistory(records, dailyLimit);
545
+ printDailyTable('每日代码量变化(全部)', records, item => item.total, dailyLimit);
546
+ printLanguageDailyTables(records);
328
547
  return stats;
329
548
  }
549
+ function sameNumberMap(a, b) {
550
+ const keysA = Object.keys(a);
551
+ const keysB = Object.keys(b);
552
+ if (keysA.length !== keysB.length)
553
+ return false;
554
+ return keysA.every(key => a[key] === b[key]);
555
+ }
556
+ /** `ec stats code` 只读历史,不重新扫描。 */
557
+ export function showCodeStatsHistory(logDir, options = {}) {
558
+ const historyFile = options.historyFile ?? path.join(logDir, 'code-stats.json');
559
+ const records = readJsonArrayFile(historyFile);
560
+ if (records.length === 0) {
561
+ console.log('暂无历史记录');
562
+ return;
563
+ }
564
+ printHistory(records, options.dailyLimit ?? 10);
565
+ printDailyTable('每日代码量变化(全部)', records, item => item.total, options.dailyLimit ?? 10);
566
+ printLanguageDailyTables(records);
567
+ }