evolcore 0.0.41-test.0 → 0.0.41-test.2

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 (235) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/agents/baseagent-availability.js +1 -1
  3. package/dist/agents/baseagent.js +88 -49
  4. package/dist/agents/claude-runner.js +177 -92
  5. package/dist/agents/codex-runner.js +146 -71
  6. package/dist/agents/ecagent-runner.js +1 -1
  7. package/dist/agents/gemini-runner.js +1 -1
  8. package/dist/aun/aid/agentmd.js +98 -11
  9. package/dist/aun/aid/client.js +1 -1
  10. package/dist/aun/aid/control-aid.js +26 -2
  11. package/dist/aun/aid/identity.js +91 -0
  12. package/dist/aun/aid/index.js +1 -1
  13. package/dist/aun/aid/managed-operation.js +1 -1
  14. package/dist/aun/aid/ownership-operation.js +23 -22
  15. package/dist/aun/group/fs-download.js +39 -0
  16. package/dist/aun/group/identity.js +36 -21
  17. package/dist/aun/group/operations.js +5 -0
  18. package/dist/aun/menu/client.js +27 -0
  19. package/dist/aun/msg/managed-operation.js +68 -7
  20. package/dist/aun/msg/p2p.js +8 -8
  21. package/dist/aun/service-proxy.js +53 -12
  22. package/dist/channels/aun.js +633 -32
  23. package/dist/channels/daemon.js +15 -1
  24. package/dist/cli/agent-command.js +5 -2
  25. package/dist/cli/agent-create.js +991 -233
  26. package/dist/cli/agent.js +49 -10
  27. package/dist/cli/aid-bind-command.js +48 -19
  28. package/dist/cli/aun-commands.js +48 -36
  29. package/dist/cli/daemon-commands.js +679 -697
  30. package/dist/cli/fs-command.js +64 -2
  31. package/dist/cli/index.js +72 -5
  32. package/dist/cli/init-channel.js +1 -1
  33. package/dist/cli/init.js +75 -1
  34. package/dist/cli/managed-command-guard.js +17 -1
  35. package/dist/cli/model.js +40 -40
  36. package/dist/cli/provider-command.js +57 -0
  37. package/dist/cli/proxy-command.js +92 -0
  38. package/dist/cli/restart-monitor.js +4 -2
  39. package/dist/cli/role.js +85 -0
  40. package/dist/cli/stats.js +10 -3
  41. package/dist/cli/task-context.js +19 -0
  42. package/dist/config/access-policy.js +7 -2
  43. package/dist/config/boot-log.js +39 -1
  44. package/dist/config/config-field-policy.js +17 -39
  45. package/dist/config/config-manager.js +183 -44
  46. package/dist/config/config-operation-service.js +5 -19
  47. package/dist/config/contact-book-store.js +47 -21
  48. package/dist/config/contact-book.js +18 -12
  49. package/dist/config/contact-operation-service.js +3 -4
  50. package/dist/config/contact-request-service.js +11 -0
  51. package/dist/config/daemon-services.js +11 -0
  52. package/dist/config/gateway-config.js +88 -594
  53. package/dist/config/owner-config.js +2 -2
  54. package/dist/config/peer-role-resolver.js +15 -12
  55. package/dist/config/provider-ipc-service.js +132 -0
  56. package/dist/config/provider-menu-request.js +58 -0
  57. package/dist/config/providers-config.js +12 -7
  58. package/dist/config/providers-import.js +3 -21
  59. package/dist/config/providers-management.js +78 -5
  60. package/dist/config/resolved-config-op.js +11 -1
  61. package/dist/config/role-command-service.js +166 -0
  62. package/dist/config/role-request-service.js +193 -0
  63. package/dist/config/schema-migration.js +1000 -25
  64. package/dist/config-store.js +89 -4
  65. package/dist/contracts/ecweb-instance.js +41 -0
  66. package/dist/contracts/ecweb-service-protocol.js +4 -1
  67. package/dist/core/agent-application-service.js +60 -11
  68. package/dist/core/agent-create-status.js +203 -0
  69. package/dist/core/agent-creation-claim.js +177 -0
  70. package/dist/core/agent-ipc-registration.js +39 -18
  71. package/dist/core/agent-runtime.js +194 -24
  72. package/dist/core/auth/agent-delegation.js +6 -3
  73. package/dist/core/auth/auth-gateway.js +67 -2
  74. package/dist/core/auth/authorization-audit.js +58 -11
  75. package/dist/core/auth/delegation-authorization.js +5 -2
  76. package/dist/core/auth/operation-authorizer.js +43 -6
  77. package/dist/core/auth/operation-catalog.js +45 -7
  78. package/dist/core/channel-loader.js +2 -0
  79. package/dist/core/command/agent-control.js +260 -21
  80. package/dist/core/command/agent-storage-menu.js +5 -3
  81. package/dist/core/command/cli-intent-parser.js +8 -3
  82. package/dist/core/command/command-handler.js +112 -154
  83. package/dist/core/command/connect-menu.js +11 -3
  84. package/dist/core/command/data-root-resolver.js +5 -4
  85. package/dist/core/command/memory-slash.js +16 -8
  86. package/dist/core/command/menu-catalog.js +10 -6
  87. package/dist/core/command/menu-handler.js +106 -73
  88. package/dist/core/command/menu-protocol.js +15 -1
  89. package/dist/core/command/provider-menu.js +46 -0
  90. package/dist/core/command/role-menu.js +147 -30
  91. package/dist/core/command/slash-handler.js +125 -255
  92. package/dist/core/daemon-control.js +26 -27
  93. package/dist/core/event-catalog.js +10 -0
  94. package/dist/core/evolagent-registry.js +7 -5
  95. package/dist/core/evolagent.js +10 -8
  96. package/dist/core/file-integrity/store.js +11 -0
  97. package/dist/core/handoff/ipc-registration.js +3 -0
  98. package/dist/core/inference/text-inference.js +31 -40
  99. package/dist/core/initialization/service.js +491 -0
  100. package/dist/core/ipc-registration.js +40 -24
  101. package/dist/core/memory/consolidation-context.js +51 -5
  102. package/dist/core/memory/consolidation-ops-records.js +96 -1
  103. package/dist/core/memory/consolidation-trigger.js +208 -191
  104. package/dist/core/memory/consolidation.js +333 -35
  105. package/dist/core/memory/index-manager.js +27 -5
  106. package/dist/core/memory/memory-admin.js +45 -5
  107. package/dist/core/memory/memory-writer.js +163 -18
  108. package/dist/core/memory/relation-idle-monitor.js +119 -58
  109. package/dist/core/memory/relation-sweep.js +55 -45
  110. package/dist/core/message/aun-ipc-sender.js +81 -69
  111. package/dist/core/message/im-renderer.js +25 -4
  112. package/dist/core/message/message-admission.js +89 -4
  113. package/dist/core/message/message-bridge.js +66 -21
  114. package/dist/core/message/response-engine.js +108 -35
  115. package/dist/core/model/catalog-service.js +5 -3
  116. package/dist/core/model/config-scope.js +29 -71
  117. package/dist/core/model/field-scope.js +1 -1
  118. package/dist/core/model/model-catalog.js +30 -41
  119. package/dist/core/model/model-diagnostics.js +4 -3
  120. package/dist/core/model/model-fallback.js +10 -7
  121. package/dist/core/model/model-permission.js +3 -2
  122. package/dist/core/ownership/owner-resolver.js +772 -158
  123. package/dist/core/permission/approval-gateway.js +103 -403
  124. package/dist/core/permission/ec-command-parser.js +62 -6
  125. package/dist/core/permission/index.js +1 -0
  126. package/dist/core/permission/permission-result.js +78 -0
  127. package/dist/core/permission/sandbox-runtime.js +18 -1
  128. package/dist/core/permission/tool-policy.js +21 -46
  129. package/dist/core/relation/peer-identity.js +64 -1
  130. package/dist/core/role/runtime-policy.js +72 -13
  131. package/dist/core/session/session-capsule.js +1 -1
  132. package/dist/core/session/session-idle-monitor.js +1 -1
  133. package/dist/core/session/session-manager.js +20 -0
  134. package/dist/core/session/session-renew.js +3 -3
  135. package/dist/core/skill/index-generator.js +15 -5
  136. package/dist/core/system-session/memory.js +43 -8
  137. package/dist/core/thread/thread-service.js +19 -6
  138. package/dist/directory/owner-directory-admission.js +95 -0
  139. package/dist/directory/owner-directory-authorization.js +309 -0
  140. package/dist/directory/owner-directory-cache.js +635 -0
  141. package/dist/eck/kit-renderer.js +2 -2
  142. package/dist/ecweb/basic-settings-service.js +33 -40
  143. package/dist/ecweb/init-menu.js +32 -0
  144. package/dist/ecweb/message-context-service.js +110 -0
  145. package/dist/index.js +93 -19
  146. package/dist/ipc.js +247 -29
  147. package/dist/paths.js +7 -0
  148. package/dist/proxy/command.js +122 -0
  149. package/dist/proxy/ipc-service.js +68 -0
  150. package/dist/proxy/manager.js +484 -0
  151. package/dist/proxy/service-supervisor.js +603 -0
  152. package/dist/response-system/engines/v1/proactive-flow.js +16 -6
  153. package/dist/trigger/authorization.js +27 -17
  154. package/dist/trigger/feedback.js +2 -3
  155. package/dist/trigger/ipc-service.js +105 -78
  156. package/dist/trigger/local-files.js +2 -1
  157. package/dist/trigger/manager.js +5 -3
  158. package/dist/trigger/scheduler.js +88 -6
  159. package/dist/utils/atomic-write.js +28 -0
  160. package/dist/utils/cross-platform.js +14 -0
  161. package/dist/utils/ecweb-supervisor.js +258 -83
  162. package/dist/utils/error-utils.js +26 -2
  163. package/dist/utils/logger.js +92 -6
  164. package/dist/utils/package-version-info.js +4 -2
  165. package/dist/utils/welcome.js +1 -1
  166. package/kits/docs/INDEX.md +1 -0
  167. package/kits/docs/aun/SDK.md +4 -1
  168. package/kits/docs/channels/aun.md +9 -0
  169. package/kits/docs/evolcore/INDEX.md +1 -0
  170. package/kits/docs/evolcore/agent.md +8 -1
  171. package/kits/docs/evolcore/aid.md +67 -17
  172. package/kits/docs/evolcore/config.md +28 -7
  173. package/kits/docs/evolcore/contact.md +3 -0
  174. package/kits/docs/evolcore/fs.md +11 -0
  175. package/kits/docs/evolcore/group.md +1 -1
  176. package/kits/docs/evolcore/memory-architecture.md +2 -2
  177. package/kits/docs/evolcore/memory-consolidation.md +32 -8
  178. package/kits/docs/evolcore/memory.md +1 -1
  179. package/kits/docs/evolcore/menu-protocol.md +4 -0
  180. package/kits/docs/evolcore/model.md +23 -20
  181. package/kits/docs/evolcore/msg.md +4 -7
  182. package/kits/docs/evolcore/provider.md +50 -0
  183. package/kits/docs/identity/AID_PROFILE_SPEC.md +52 -17
  184. package/kits/migrations/migrate-contact-book-v2.mjs +30 -11
  185. package/kits/rules/01-overview.md +3 -0
  186. package/kits/rules/04-relation.md +1 -1
  187. package/kits/schemas/_meta.json +37 -4
  188. package/kits/schemas/agent-config.schema.13.json +8 -3
  189. package/kits/schemas/agent-config.schema.16.json +891 -0
  190. package/kits/schemas/daemon.schema.9.json +366 -0
  191. package/kits/schemas/defaults.schema.5.json +406 -127
  192. package/kits/schemas/relation-config.schema.11.json +277 -0
  193. package/kits/schemas/role-config.schema.1.json +7 -7
  194. package/kits/skills/.switches.json +4 -0
  195. package/kits/skills/ec-agent-create/SKILL.md +3 -0
  196. package/kits/skills/ec-identity/SKILL.md +2 -2
  197. package/kits/skills/ec-service-proxy/SKILL.md +118 -0
  198. package/kits/skills/ec-skill/scripts/skill.mjs +6 -0
  199. package/kits/skills/personal-assistant/SKILL.md +176 -0
  200. package/kits/skills/personal-assistant/references/01-workspace-spec.md +333 -0
  201. package/kits/skills/personal-assistant/references/02-bootstrap.md +205 -0
  202. package/kits/skills/personal-assistant/references/03-data-flow-and-gaps.md +177 -0
  203. package/kits/skills/personal-assistant/references/04-frontend-contract.md +439 -0
  204. package/kits/skills/personal-assistant/references/05-directory-reference.md +292 -0
  205. package/kits/skills/personal-assistant/references/06-render-config.md +350 -0
  206. package/kits/skills/personal-assistant/schema/workspace.schema.json +85 -0
  207. package/kits/skills/personal-assistant/schema/workspace.v1.json +66 -0
  208. package/kits/skills/personal-assistant/scripts/archive.mjs +154 -0
  209. package/kits/skills/personal-assistant/scripts/check.mjs +114 -0
  210. package/kits/skills/personal-assistant/scripts/index-rebuild.mjs +252 -0
  211. package/kits/skills/personal-assistant/scripts/ingest.mjs +344 -0
  212. package/kits/skills/personal-assistant/scripts/init.mjs +270 -0
  213. package/kits/skills/personal-assistant/scripts/lib/apply.mjs +92 -0
  214. package/kits/skills/personal-assistant/scripts/lib/schema.mjs +96 -0
  215. package/kits/skills/personal-assistant/scripts/lib/time.mjs +28 -0
  216. package/kits/skills/personal-assistant/scripts/migrate.mjs +172 -0
  217. package/kits/skills/personal-assistant/scripts/search.mjs +172 -0
  218. package/kits/skills/personal-assistant/scripts/verify.mjs +196 -0
  219. package/kits/skills/personal-assistant/templates/INDEX.md.tpl +24 -0
  220. package/kits/skills/personal-assistant/templates/README.md.tpl +108 -0
  221. package/kits/skills/personal-assistant/triggers/ingest-daily.json +23 -0
  222. package/kits/skills/personal-assistant/triggers/memory-consolidate.json +23 -0
  223. package/kits/skills/personal-assistant/triggers/report-daily.json +23 -0
  224. package/kits/skills/personal-assistant/triggers/report-weekly.json +23 -0
  225. package/kits/skills/thread-ops/SKILL.md +5 -0
  226. package/kits/templates/memory-consolidation/forget.md +19 -6
  227. package/kits/templates/memory-consolidation/notes.md +1 -1
  228. package/kits/templates/memory-consolidation/profile.md +2 -2
  229. package/kits/templates/memory-consolidation/promote.md +20 -3
  230. package/kits/templates/roles/member.json +8 -1
  231. package/kits/templates/system-fragments/baseagent.md +2 -2
  232. package/kits/templates/system-fragments/memory.md +4 -4
  233. package/kits/templates/system-fragments/venue.md +1 -1
  234. package/package.json +7 -3
  235. package/dist/core/message/create-status.js +0 -96
@@ -0,0 +1,344 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * ingest.mjs —— 把话题历史落地到 capture/conversation/
4
+ *
5
+ * 用法:
6
+ * node "<技能目录>/scripts/ingest.mjs" --workspace "<路径>" [--self <AID>]
7
+ * [--date today|YYYY-MM-DD] [--peer <AID>] [--limit 500] [--dry-run] [--json]
8
+ *
9
+ * 数据来源:ec thread peers / thread list / thread history
10
+ *
11
+ * 规则:
12
+ * · 幂等键 threadId + msgId —— 重复跑不会写两遍
13
+ * · 增量游标 lastTs 存在 .assistant/state.json 的 ingest.cursors
14
+ * · --date 只取那一天的本地时间;不带则取增量窗口内的全部
15
+ * · 每次落地写 capture/_manifest/<date>.json(大小 + sha256)
16
+ *
17
+ * 退出码:0 成功 / 20 有失败项 / 30 前置条件不满足
18
+ */
19
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync } from 'node:fs';
20
+ import { join, resolve, dirname } from 'node:path';
21
+ import { createHash } from 'node:crypto';
22
+ import { spawnSync } from 'node:child_process';
23
+ import { latestVersion, loadSchema } from './lib/schema.mjs';
24
+ import { ensureStructure, readState, writeState } from './lib/apply.mjs';
25
+ import { nowLocal, todayLocal, localIsoOf } from './lib/time.mjs';
26
+
27
+ // ── 参数 ────────────────────────────────────────────────────────
28
+ function parseArgs(argv) {
29
+ const out = { json: false, dryRun: false, limit: 500 };
30
+ for (let i = 2; i < argv.length; i++) {
31
+ const a = argv[i];
32
+ if (a === '--workspace' || a === '-w') out.workspace = argv[++i];
33
+ else if (a === '--self') out.self = argv[++i];
34
+ else if (a === '--date') out.date = argv[++i];
35
+ else if (a === '--peer') out.peer = argv[++i];
36
+ else if (a === '--limit') out.limit = Number(argv[++i]) || 500;
37
+ else if (a === '--dry-run') out.dryRun = true;
38
+ else if (a === '--json') out.json = true;
39
+ else if (a === '--help' || a === '-h') out.help = true;
40
+ }
41
+ return out;
42
+ }
43
+
44
+ const args = parseArgs(process.argv);
45
+ if (args.help || !args.workspace) {
46
+ console.log(`用法:node ingest.mjs --workspace <路径> [--self <AID>] [--date today|YYYY-MM-DD]
47
+ [--peer <AID>] [--limit 500] [--dry-run] [--json]
48
+
49
+ 把话题历史落地到 capture/conversation/。幂等,可重复执行。`);
50
+ process.exit(args.help ? 0 : 30);
51
+ }
52
+
53
+ const workspace = resolve(args.workspace);
54
+ const selfAid = args.self || process.env.EVOLCORE_SELF_AID || '';
55
+ if (!selfAid) {
56
+ console.error('❌ 缺少 --self <AID>(或用 EVOLCORE_SELF_AID 注入)');
57
+ process.exit(30);
58
+ }
59
+
60
+ // ── 调 ec ───────────────────────────────────────────────────────
61
+ function ec(ecArgs) {
62
+ const r = spawnSync('ec', ecArgs, {
63
+ encoding: 'utf8',
64
+ shell: process.platform === 'win32',
65
+ maxBuffer: 64 * 1024 * 1024,
66
+ });
67
+ if (r.status !== 0) {
68
+ throw new Error((r.stderr || r.stdout || '').trim().slice(0, 300) || `ec 退出码 ${r.status}`);
69
+ }
70
+ return r.stdout;
71
+ }
72
+
73
+ function ecJson(ecArgs) {
74
+ const out = ec([...ecArgs, '--format', 'json']);
75
+ return JSON.parse(out);
76
+ }
77
+
78
+ // ── 初始化工作区结构 ────────────────────────────────────────────
79
+ const schema = loadSchema(latestVersion());
80
+ ensureStructure(workspace, schema, { capabilities: readState(workspace)?.capabilities || {} });
81
+
82
+ const state = readState(workspace) || {};
83
+ const cursors = state.ingest?.cursors || {};
84
+
85
+ // ── 枚举对端与话题 ──────────────────────────────────────────────
86
+ const peers = args.peer ? [args.peer] : listPeers(selfAid);
87
+
88
+ function listPeers(self) {
89
+ const text = ec(['thread', 'peers', '--self', self]);
90
+ const out = [];
91
+ for (const line of text.split(/\r?\n/)) {
92
+ const m = /^(\S+\.\S+)\s/.exec(line.trim());
93
+ if (m) out.push(m[1]);
94
+ }
95
+ return out;
96
+ }
97
+
98
+ const targetDate = args.date === 'today' || !args.date ? null : args.date;
99
+ const todayStr = todayLocal();
100
+
101
+ const localDateOf = ts => {
102
+ const d = new Date(ts);
103
+ const pad = n => String(n).padStart(2, '0');
104
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
105
+ };
106
+
107
+ /** threadId 里可能有 ':'(如 main:aidA:aidB),Windows 路径不允许,换成 '-' */
108
+ const safeName = s => String(s).replace(/[\\/:*?"<>|]/g, '-');
109
+
110
+ // ── 主循环 ──────────────────────────────────────────────────────
111
+ const written = [];
112
+ const errors = [];
113
+ const stats = { peers: 0, threads: 0, messages: 0, skipped: 0 };
114
+
115
+ for (const peer of peers) {
116
+ stats.peers++;
117
+ let threads = [];
118
+ try {
119
+ threads = ecJson(['thread', 'list', peer, '--self', selfAid]).threads || [];
120
+ } catch (e) {
121
+ errors.push({ peer, reason: e.message });
122
+ continue;
123
+ }
124
+
125
+ for (const t of threads) {
126
+ stats.threads++;
127
+ const threadId = t.threadId;
128
+ if (!threadId) continue;
129
+
130
+ const cursorKey = threadId;
131
+ const since = cursors[cursorKey] || 0;
132
+
133
+ let msgs = [];
134
+ try {
135
+ let after = since;
136
+ for (let page = 0; page < 40; page++) {
137
+ const batch = ecJson(['thread', 'history', `${peer}/${threadId}`, '--self', selfAid,
138
+ ...(after ? ['--after', String(after)] : []),
139
+ '--limit', String(args.limit)]).messages || [];
140
+ if (!batch.length) break;
141
+ msgs.push(...batch);
142
+ const lastTs = batch[batch.length - 1].timestamp;
143
+ if (batch.length < args.limit) break;
144
+ if (lastTs <= after) break;
145
+ after = lastTs;
146
+ }
147
+ } catch (e) {
148
+ errors.push({ peer, threadId, reason: e.message });
149
+ continue;
150
+ }
151
+
152
+ // 按目标日期过滤
153
+ if (targetDate) {
154
+ msgs = msgs.filter(m => localDateOf(m.timestamp) === targetDate);
155
+ } else if (!args.date) {
156
+ // 不带 --date 时默认只取今天(增量场景由 --after 兜住)
157
+ msgs = msgs.filter(m => localDateOf(m.timestamp) === todayStr);
158
+ }
159
+
160
+ if (!msgs.length) { stats.skipped++; continue; }
161
+
162
+ // 按本地日期分桶
163
+ const byDate = new Map();
164
+ for (const m of msgs) {
165
+ const d = localDateOf(m.timestamp);
166
+ if (!byDate.has(d)) byDate.set(d, []);
167
+ byDate.get(d).push(m);
168
+ }
169
+
170
+ for (const [date, list] of byDate) {
171
+ const [y, mo, da] = date.split('-');
172
+ const dir = join(workspace, 'capture', 'conversation', y, mo, da, safeName(threadId));
173
+ const jsonlPath = join(dir, 'transcript.jsonl');
174
+ const mdPath = join(dir, 'transcript.md');
175
+ const metaPath = join(dir, 'meta.json');
176
+
177
+ // 与已有内容合并,按 msgId 去重
178
+ const existing = new Map();
179
+ if (existsSync(jsonlPath)) {
180
+ for (const line of readFileSync(jsonlPath, 'utf8').split(/\r?\n/)) {
181
+ if (!line.trim()) continue;
182
+ try {
183
+ const o = JSON.parse(line);
184
+ if (o.msgId) existing.set(o.msgId, o);
185
+ } catch { /* 跳过坏行 */ }
186
+ }
187
+ }
188
+ for (const m of list) {
189
+ existing.set(m.msgId, {
190
+ msgId: m.msgId,
191
+ dir: m.dir,
192
+ from: m.from,
193
+ to: m.to,
194
+ ts: m.timestamp,
195
+ time: m.time,
196
+ type: m.msgType,
197
+ text: m.content,
198
+ });
199
+ }
200
+
201
+ const merged = [...existing.values()].sort((a, b) => a.ts - b.ts);
202
+
203
+ if (!args.dryRun) {
204
+ mkdirSync(dir, { recursive: true });
205
+
206
+ writeFileSync(jsonlPath, merged.map(o => JSON.stringify(o)).join('\n') + '\n', 'utf8');
207
+
208
+ const mdLines = [
209
+ '---',
210
+ `id: ${threadId}-${date}`,
211
+ `date: ${merged[0]?.ts ? localIsoOf(merged[0].ts) : `${date}T00:00:00+08:00`}`,
212
+ 'type: conversation',
213
+ 'tags: [对话]',
214
+ `source: ec-thread:${threadId}`,
215
+ `thread_id: ${threadId}`,
216
+ `peer: ${peer}`,
217
+ `count: ${merged.length}`,
218
+ '---',
219
+ '',
220
+ `# ${t.name || threadId}`,
221
+ '',
222
+ `- 话题:\`${threadId}\``,
223
+ `- 对端:\`${peer}\``,
224
+ `- 日期:${date}`,
225
+ `- 消息:${merged.length} 条`,
226
+ `- 落地:${nowLocal()}`,
227
+ '',
228
+ '---',
229
+ '',
230
+ ];
231
+ for (const o of merged) {
232
+ const arrow = o.dir === 'out' ? '→' : '←';
233
+ const who = o.dir === 'out' ? selfAid : peer;
234
+ mdLines.push(`**${o.time}** ${arrow} \`${who}\``);
235
+ mdLines.push('');
236
+ mdLines.push(o.text || '');
237
+ mdLines.push('');
238
+ }
239
+ writeFileSync(mdPath, mdLines.join('\n'), 'utf8');
240
+
241
+ writeFileSync(metaPath, JSON.stringify({
242
+ threadId,
243
+ peer,
244
+ name: t.name || '',
245
+ date,
246
+ count: merged.length,
247
+ firstTs: merged[0]?.ts,
248
+ lastTs: merged[merged.length - 1]?.ts,
249
+ updatedAt: nowLocal(),
250
+ }, null, 2), 'utf8');
251
+ }
252
+
253
+ written.push({ path: `capture/conversation/${y}/${mo}/${da}/${safeName(threadId)}`, date, count: merged.length });
254
+ stats.messages += list.length;
255
+ }
256
+
257
+ // 更新游标
258
+ const maxTs = Math.max(...msgs.map(m => m.timestamp));
259
+ if (maxTs > since) cursors[cursorKey] = maxTs;
260
+ }
261
+ }
262
+
263
+ // ── 写游标与清单 ────────────────────────────────────────────────
264
+ if (!args.dryRun) {
265
+ writeState(workspace, {
266
+ ingest: { cursors, lastRunAt: nowLocal() },
267
+ });
268
+
269
+ // 按日期汇总写清单
270
+ const byDate = new Map();
271
+ for (const w of written) {
272
+ if (!byDate.has(w.date)) byDate.set(w.date, []);
273
+ byDate.get(w.date).push(w);
274
+ }
275
+
276
+ for (const [date, items] of byDate) {
277
+ const objects = [];
278
+ for (const it of items) {
279
+ for (const f of ['meta.json', 'transcript.md', 'transcript.jsonl']) {
280
+ const abs = join(workspace, it.path, f);
281
+ if (!existsSync(abs)) continue;
282
+ const buf = readFileSync(abs);
283
+ objects.push({
284
+ path: `${it.path}/${f}`,
285
+ size: buf.length,
286
+ sha256: createHash('sha256').update(buf).digest('hex'),
287
+ });
288
+ }
289
+ }
290
+ const manifestDir = join(workspace, 'capture', '_manifest');
291
+ mkdirSync(manifestDir, { recursive: true });
292
+ const manifestPath = join(manifestDir, `${date}.json`);
293
+
294
+ // 与已有清单合并,不覆盖别的来源
295
+ let manifest = { date, sources: [] };
296
+ if (existsSync(manifestPath)) {
297
+ try { manifest = JSON.parse(readFileSync(manifestPath, 'utf8')); } catch { /* 重建 */ }
298
+ }
299
+ manifest.sources = (manifest.sources || []).filter(s => s.type !== 'conversation');
300
+ manifest.sources.push({
301
+ type: 'conversation',
302
+ objects: objects.length,
303
+ bytes: objects.reduce((a, o) => a + o.size, 0),
304
+ ingestedAt: nowLocal(),
305
+ items: objects,
306
+ });
307
+ manifest.ingested_at = nowLocal();
308
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), 'utf8');
309
+ }
310
+ }
311
+
312
+ // ── 输出 ────────────────────────────────────────────────────────
313
+ const exitCode = errors.length ? 20 : 0;
314
+
315
+ if (args.json) {
316
+ console.log(JSON.stringify({
317
+ ok: !errors.length, workspace, self: selfAid,
318
+ date: targetDate || todayStr, dryRun: args.dryRun,
319
+ stats, written, errors,
320
+ }, null, 2));
321
+ process.exit(exitCode);
322
+ }
323
+
324
+ console.log(`工作区:${workspace}`);
325
+ console.log(`范围:${args.peer || '全部对端'} 日期:${targetDate || todayStr}`);
326
+ console.log(`扫描 ${stats.peers} 个对端、${stats.threads} 个话题`);
327
+ console.log('');
328
+
329
+ if (!written.length) {
330
+ console.log('没有新内容需要落地。');
331
+ } else {
332
+ console.log(`落地 ${written.length} 个话题:`);
333
+ for (const w of written) console.log(` · ${w.path} ${w.count} 条`);
334
+ console.log('');
335
+ console.log(`合计 ${stats.messages} 条消息`);
336
+ }
337
+
338
+ if (errors.length) {
339
+ console.log('');
340
+ console.log(`⚠️ ${errors.length} 项失败:`);
341
+ for (const e of errors.slice(0, 10)) console.log(` · ${e.threadId || e.peer}:${e.reason}`);
342
+ }
343
+
344
+ process.exit(exitCode);
@@ -0,0 +1,270 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * init.mjs —— 初始化个人助理工作区
4
+ *
5
+ * 用法:
6
+ * node "<技能目录>/scripts/init.mjs" --workspace "<路径>" [--owner <AID>]
7
+ * [--force] [--with-triggers] [--dry-run] [--json]
8
+ *
9
+ * 流程:
10
+ * 0. 占用检查 —— 目录里已有一堆别的东西?先说清楚再问
11
+ * 1. 建目录结构(按 schema)
12
+ * 2. 写 README / INDEX(已有 README 不覆盖,改名保留)
13
+ * 3. 写 .assistant/state.json
14
+ * 4. 可选:安装触发器
15
+ * 5. 输出验收清单
16
+ *
17
+ * 退出码:
18
+ * 0 成功
19
+ * 10 已是最新,无需操作
20
+ * 20 部分失败
21
+ * 30 前置条件不满足
22
+ * 40 目录已被占用,需要用户确认(加 --force 继续)
23
+ */
24
+ import { existsSync, mkdirSync, readdirSync, statSync, renameSync, readFileSync, writeFileSync } from 'node:fs';
25
+ import { execFileSync } from 'node:child_process';
26
+ import { join, resolve } from 'node:path';
27
+ import { SKILL_DIR, latestVersion, loadSchema, readWorkspaceVersion } from './lib/schema.mjs';
28
+ import { ensureStructure, readState, writeState } from './lib/apply.mjs';
29
+
30
+ // ── 参数 ────────────────────────────────────────────────────────
31
+ function parseArgs(argv) {
32
+ const out = { json: false, force: false, dryRun: false, withTriggers: false };
33
+ for (let i = 2; i < argv.length; i++) {
34
+ const a = argv[i];
35
+ if (a === '--workspace' || a === '-w') out.workspace = argv[++i];
36
+ else if (a === '--owner') out.owner = argv[++i];
37
+ else if (a === '--self') out.self = argv[++i];
38
+ else if (a === '--force') out.force = true;
39
+ else if (a === '--with-triggers') out.withTriggers = true;
40
+ else if (a === '--dry-run') out.dryRun = true;
41
+ else if (a === '--json') out.json = true;
42
+ else if (a === '--help' || a === '-h') out.help = true;
43
+ }
44
+ return out;
45
+ }
46
+
47
+ const args = parseArgs(process.argv);
48
+ if (args.help || !args.workspace) {
49
+ console.log(`用法:node init.mjs --workspace <路径> [选项]
50
+
51
+ --owner <AID> 工作区主人,写入 state.json
52
+ --force 目标目录已有其他内容时仍然继续
53
+ --with-triggers 同时安装定时触发器
54
+ --dry-run 只报告会做什么,不落盘
55
+ --json 机器可读输出
56
+
57
+ 初始化前会检查目标目录是否已被使用;发现其他内容会停下来等你确认。`);
58
+ process.exit(args.help ? 0 : 30);
59
+ }
60
+
61
+ const workspace = resolve(args.workspace);
62
+ const targetVersion = latestVersion();
63
+ const schema = loadSchema(targetVersion);
64
+
65
+ // ── 0. 占用检查 ─────────────────────────────────────────────────
66
+ /** 目录里已经有别的东西吗?这是初始化前必须先回答的问题 */
67
+ function scanOccupancy(dir) {
68
+ if (!existsSync(dir)) return { state: 'empty', entries: [], foreign: [], suspicious: [] };
69
+
70
+ const own = new Set(schema.roots);
71
+ const suspiciousNames = new Set([
72
+ '.git', 'package.json', 'node_modules', 'src', 'vault', '.obsidian',
73
+ 'pom.xml', 'Cargo.toml', 'go.mod', 'requirements.txt', '.venv',
74
+ ]);
75
+
76
+ const entries = readdirSync(dir, { withFileTypes: true }).map(e => {
77
+ const abs = join(dir, e.name);
78
+ let size = 0;
79
+ try {
80
+ size = e.isDirectory() ? 0 : statSync(abs).size;
81
+ } catch { /* 忽略不可读项 */ }
82
+ return { name: e.name, dir: e.isDirectory(), size, known: own.has(e.name) };
83
+ });
84
+
85
+ const foreign = entries.filter(e => !e.known);
86
+ const suspicious = foreign.filter(e => suspiciousNames.has(e.name)).map(e => e.name);
87
+
88
+ if (!entries.length) return { state: 'empty', entries, foreign, suspicious };
89
+ if (!foreign.length) return { state: 'own', entries, foreign, suspicious };
90
+ return { state: 'occupied', entries, foreign, suspicious };
91
+ }
92
+
93
+ const occ = scanOccupancy(workspace);
94
+
95
+ if (occ.state === 'occupied' && !args.force) {
96
+ const detail = occ.foreign.slice(0, 12).map(e =>
97
+ ` · ${e.name}${e.dir ? '/' : ''}${e.size ? `(${(e.size / 1024).toFixed(1)} KB)` : ''}`
98
+ ).join('\n');
99
+ const more = occ.foreign.length > 12 ? `\n …… 还有 ${occ.foreign.length - 12} 项` : '';
100
+
101
+ const warn = occ.suspicious.length
102
+ ? `\n ⚠️ 检测到工程特征:${occ.suspicious.join('、')}`
103
+ : '';
104
+
105
+ const msg = `⚠️ 这个目录已经在使用,不是空的
106
+
107
+ 路径:${workspace}
108
+ 已有内容:${occ.foreign.length} 项不属于个人助理工作区的条目
109
+
110
+ ${detail}${more}${warn}
111
+
112
+ 初始化会在这里建立个人助理的目录结构:
113
+ · 不会删除、不会移动任何已有内容
114
+ · 已有内容不会进入索引,也不会被本技能管理
115
+ · 如果已有同名 README.md,会被改名保留,不覆盖
116
+
117
+ 确认要把它初始化成个人助理工作区吗?
118
+ 确认请加 --force 重跑。`;
119
+
120
+ if (args.json) {
121
+ console.log(JSON.stringify({
122
+ ok: false, code: 'DIRECTORY_OCCUPIED', workspace,
123
+ foreign: occ.foreign, suspicious: occ.suspicious,
124
+ hint: '确认后加 --force 重跑',
125
+ }, null, 2));
126
+ } else {
127
+ console.log(msg);
128
+ }
129
+ process.exit(40);
130
+ }
131
+
132
+ // ── 1. 建结构 ───────────────────────────────────────────────────
133
+ const existingState = readState(workspace);
134
+ const isRepair = !!existingState || occ.state === 'own';
135
+
136
+ const result = ensureStructure(workspace, schema, {
137
+ capabilities: existingState?.capabilities || {},
138
+ dryRun: args.dryRun,
139
+ });
140
+
141
+ // ── 2. README 保护 ─────────────────────────────────────────────
142
+ // 已有 README 但不是本技能生成的,改名保留,不覆盖
143
+ let readmeBackup = null;
144
+ const readmePath = join(workspace, 'README.md');
145
+ if (!args.dryRun && existsSync(readmePath)) {
146
+ try {
147
+ const head = readFileSync(readmePath, 'utf8').slice(0, 400);
148
+ if (!head.includes('个人助理工作区') && !head.includes('个人助理')) {
149
+ readmeBackup = join(workspace, 'README.before-personal-assistant.md');
150
+ if (!existsSync(readmeBackup)) renameSync(readmePath, readmeBackup);
151
+ // 被改走的 README 需要重新生成
152
+ if (!result.created.includes('README.md')) result.created.push('README.md');
153
+ }
154
+ } catch { /* 读不了就保持原样 */ }
155
+ }
156
+
157
+ // ── 3. state.json ──────────────────────────────────────────────
158
+ let state = existingState;
159
+ if (!args.dryRun) {
160
+ state = writeState(workspace, {
161
+ workspace_version: targetVersion,
162
+ skill_version: state?.skill_version || '',
163
+ owner: args.owner || state?.owner || '',
164
+ capabilities: state?.capabilities || {},
165
+ });
166
+ }
167
+
168
+ // ── 4. 触发器(可选) ───────────────────────────────────────────
169
+ let triggerReport = null;
170
+ if (args.withTriggers && !args.dryRun) {
171
+ const selfAid = args.self || process.env.EVOLCORE_SELF_AID || '';
172
+ if (!selfAid) {
173
+ triggerReport = { ok: [], failed: [{ name: '(all)', reason: '缺少 --self <AID>,无法生成触发器定义' }] };
174
+ } else {
175
+ triggerReport = installTriggers(workspace, selfAid);
176
+ }
177
+ }
178
+
179
+ function installTriggers(ws, selfAid) {
180
+ // 触发器定义随技能发布;导入前把占位符替换成真实值
181
+ const dir = join(SKILL_DIR, 'triggers');
182
+ const tmpDir = join(ws, '.assistant', 'tmp');
183
+ mkdirSync(tmpDir, { recursive: true });
184
+
185
+ const defs = ['ingest-daily', 'report-daily', 'report-weekly', 'memory-consolidate'];
186
+ const ok = [];
187
+ const failed = [];
188
+
189
+ for (const name of defs) {
190
+ const src = join(dir, `${name}.json`);
191
+ if (!existsSync(src)) { failed.push({ name, reason: '定义文件不存在' }); continue; }
192
+ try {
193
+ const body = readFileSync(src, 'utf8')
194
+ .replaceAll('{{agent_aid}}', selfAid)
195
+ .replaceAll('{{workspace}}', ws.replace(/\\/g, '\\\\'))
196
+ .replaceAll('<技能目录>', SKILL_DIR.replace(/\\/g, '\\\\'));
197
+ const out = join(tmpDir, `${name}.json`);
198
+ writeFileSync(out, body, 'utf8');
199
+
200
+ execFileSync('ec', ['trigger', 'create', '--exec', 'trigger-session', '--file', out, '--enable'], {
201
+ stdio: 'pipe', encoding: 'utf8',
202
+ shell: process.platform === 'win32',
203
+ });
204
+ ok.push(name);
205
+ } catch (e) {
206
+ failed.push({ name, reason: String(e.stderr || e.message).slice(0, 200) });
207
+ }
208
+ }
209
+ return { ok, failed };
210
+ }
211
+
212
+ // ── 5. 验收清单 ─────────────────────────────────────────────────
213
+ const exitCode = result.errors.length ? 20 : (isRepair && !result.created.length ? 10 : 0);
214
+
215
+ if (args.json) {
216
+ console.log(JSON.stringify({
217
+ ok: exitCode === 0 || exitCode === 10,
218
+ workspace,
219
+ version: targetVersion,
220
+ mode: isRepair ? 'repair' : 'create',
221
+ created: result.created,
222
+ errors: result.errors,
223
+ readmeBackup,
224
+ triggers: triggerReport,
225
+ occupancy: { state: occ.state, foreign: occ.foreign.length },
226
+ }, null, 2));
227
+ process.exit(exitCode);
228
+ }
229
+
230
+ console.log(`${args.dryRun ? '[dry-run] ' : ''}工作区:${workspace}`);
231
+ console.log(`模式:${isRepair ? '修复(已有工作区)' : '新建'} 目标版本:v${targetVersion}`);
232
+ console.log('');
233
+
234
+ if (occ.foreign.length) {
235
+ console.log(`ℹ️ 保留原有内容 ${occ.foreign.length} 项(未删除、未纳入索引)`);
236
+ console.log('');
237
+ }
238
+
239
+ if (readmeBackup) {
240
+ console.log(`ℹ️ 原有 README 已改名保留:${readmeBackup.split(/[\\/]/).pop()}`);
241
+ console.log('');
242
+ }
243
+
244
+ if (result.created.length) {
245
+ console.log(`创建 ${result.created.length} 项:`);
246
+ for (const p of result.created.slice(0, 15)) console.log(` · ${p}`);
247
+ if (result.created.length > 15) console.log(` …… 还有 ${result.created.length - 15} 项`);
248
+ console.log('');
249
+ } else {
250
+ console.log('没有需要新建的项。');
251
+ console.log('');
252
+ }
253
+
254
+ if (result.errors.length) {
255
+ console.log(`⚠️ ${result.errors.length} 项失败:`);
256
+ for (const e of result.errors) console.log(` · ${e.path}:${e.reason}`);
257
+ console.log('');
258
+ }
259
+
260
+ if (triggerReport) {
261
+ console.log(`触发器:${triggerReport.ok.length} 个已装${triggerReport.failed.length ? `,${triggerReport.failed.length} 个失败` : ''}`);
262
+ for (const f of triggerReport.failed) console.log(` · ${f.name}:${f.reason}`);
263
+ console.log('');
264
+ }
265
+
266
+ if (exitCode === 0) console.log('✅ 完成');
267
+ else if (exitCode === 10) console.log('✅ 已是最新,无需改动');
268
+ else console.log('⚠️ 部分完成,见上面失败项');
269
+
270
+ process.exit(exitCode);