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,92 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join, dirname } from 'node:path';
3
+ import { SKILL_DIR, diff } from './schema.mjs';
4
+ import { nowLocal } from './time.mjs';
5
+
6
+ /**
7
+ * 按 schema 补齐目录与生成物。只做加法,永不删除。
8
+ * @returns {{created: string[], errors: {path:string,reason:string}[], skipped: string[]}}
9
+ */
10
+ export function ensureStructure(workspaceDir, schema, { capabilities = {}, dryRun = false } = {}) {
11
+ const created = [];
12
+ const errors = [];
13
+ const skipped = [];
14
+ const result = diff(workspaceDir, schema, { capabilities });
15
+
16
+ for (const m of result.missing) {
17
+ const abs = join(workspaceDir, m.path);
18
+ try {
19
+ if (m.kind === 'dir') {
20
+ if (!dryRun) mkdirSync(abs, { recursive: true });
21
+ created.push(m.path);
22
+ continue;
23
+ }
24
+
25
+ // 文件:只自动生成标记为 generated 的
26
+ if (!m.generated) {
27
+ errors.push({ path: m.path, reason: '非生成物缺失,需人工确认来源' });
28
+ continue;
29
+ }
30
+
31
+ if (!dryRun) {
32
+ mkdirSync(dirname(abs), { recursive: true });
33
+ writeFileSync(abs, renderFile(m, workspaceDir, schema), 'utf8');
34
+ }
35
+ created.push(m.path);
36
+ } catch (e) {
37
+ errors.push({ path: m.path, reason: e.message });
38
+ }
39
+ }
40
+
41
+ return { created, errors, skipped };
42
+ }
43
+
44
+ /** 渲染一个生成物 */
45
+ export function renderFile(spec, workspaceDir, schema, extra = {}) {
46
+ // state.json 有固定结构,不走模板
47
+ if (spec.path.endsWith('state.json')) {
48
+ return JSON.stringify({
49
+ workspace_version: schema.workspace_version,
50
+ skill_version: extra.skillVersion || '',
51
+ created_at: nowLocal(),
52
+ updated_at: nowLocal(),
53
+ owner: extra.owner || '',
54
+ triggers: [],
55
+ capabilities: extra.capabilities || {},
56
+ ...(extra.recovered ? { recovered: true } : {}),
57
+ }, null, 2);
58
+ }
59
+
60
+ const tpl = spec.template ? join(SKILL_DIR, spec.template) : null;
61
+ if (!tpl || !existsSync(tpl)) return '';
62
+
63
+ return readFileSync(tpl, 'utf8')
64
+ .replaceAll('{{workspace_name}}', workspaceDir.split(/[\\/]/).filter(Boolean).pop() || '')
65
+ .replaceAll('{{owner_name}}', extra.owner || '主人')
66
+ .replaceAll('{{workspace_version}}', String(schema.workspace_version))
67
+ .replaceAll('{{skill_version}}', extra.skillVersion || '')
68
+ .replaceAll('{{created_at}}', extra.createdAt || nowLocal())
69
+ .replaceAll('{{generated_at}}', nowLocal())
70
+ .replaceAll('{{owner}}', extra.owner || '');
71
+ }
72
+
73
+ /** 读 state.json,读不到返回 null */
74
+ export function readState(workspaceDir) {
75
+ const p = join(workspaceDir, '.assistant', 'state.json');
76
+ if (!existsSync(p)) return null;
77
+ try {
78
+ return JSON.parse(readFileSync(p, 'utf8'));
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ /** 合并写 state.json */
85
+ export function writeState(workspaceDir, patch) {
86
+ const p = join(workspaceDir, '.assistant', 'state.json');
87
+ mkdirSync(dirname(p), { recursive: true });
88
+ const cur = readState(workspaceDir) || {};
89
+ const next = { ...cur, ...patch, updated_at: nowLocal() };
90
+ writeFileSync(p, JSON.stringify(next, null, 2), 'utf8');
91
+ return next;
92
+ }
@@ -0,0 +1,96 @@
1
+ import { readFileSync, existsSync, readdirSync } from 'node:fs';
2
+ import { join, dirname } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const HERE = dirname(fileURLToPath(import.meta.url));
6
+ export const SKILL_DIR = join(HERE, '..', '..');
7
+ export const SCHEMA_DIR = join(SKILL_DIR, 'schema');
8
+
9
+ /** 读某个版本的结构定义 */
10
+ export function loadSchema(version) {
11
+ const p = join(SCHEMA_DIR, `workspace.v${version}.json`);
12
+ if (!existsSync(p)) throw new Error(`找不到 schema:${p}`);
13
+ return JSON.parse(readFileSync(p, 'utf8'));
14
+ }
15
+
16
+ /** 列出所有已定义的版本号,升序 */
17
+ export function listVersions() {
18
+ return readdirSync(SCHEMA_DIR)
19
+ .map(f => /^workspace\.v(\d+)\.json$/.exec(f))
20
+ .filter(Boolean)
21
+ .map(m => Number(m[1]))
22
+ .sort((a, b) => a - b);
23
+ }
24
+
25
+ /** 最新版本号 */
26
+ export function latestVersion() {
27
+ const v = listVersions();
28
+ return v.length ? v[v.length - 1] : 0;
29
+ }
30
+
31
+ /** 读工作区自己的版本号 */
32
+ export function readWorkspaceVersion(workspaceDir) {
33
+ const p = join(workspaceDir, '.assistant', 'state.json');
34
+ if (!existsSync(p)) return 0;
35
+ try {
36
+ const s = JSON.parse(readFileSync(p, 'utf8'));
37
+ return Number(s.workspace_version) || 0;
38
+ } catch {
39
+ return 0;
40
+ }
41
+ }
42
+
43
+ /** 读工作区能力标志,缺省全 false */
44
+ export function readCapabilities(workspaceDir) {
45
+ const p = join(workspaceDir, '.assistant', 'state.json');
46
+ if (!existsSync(p)) return {};
47
+ try {
48
+ return JSON.parse(readFileSync(p, 'utf8')).capabilities || {};
49
+ } catch {
50
+ return {};
51
+ }
52
+ }
53
+
54
+ /**
55
+ * 比对工作区与目标 schema,只读。
56
+ * 返回 { missing: [], extra: [], ok: [] }
57
+ */
58
+ export function diff(workspaceDir, schema, { capabilities = {} } = {}) {
59
+ const missing = [];
60
+ const ok = [];
61
+
62
+ for (const d of schema.directories) {
63
+ // 可选目录:依赖能力未开启时跳过,不算缺失
64
+ if (d.required === false && d.gated_by && !capabilities[d.gated_by]) {
65
+ continue;
66
+ }
67
+ const abs = join(workspaceDir, d.path);
68
+ if (existsSync(abs)) {
69
+ ok.push({ kind: 'dir', path: d.path });
70
+ } else {
71
+ missing.push({ kind: 'dir', path: d.path, purpose: d.purpose, layer: d.layer });
72
+ }
73
+ }
74
+
75
+ for (const f of schema.files) {
76
+ const abs = join(workspaceDir, f.path);
77
+ if (existsSync(abs)) {
78
+ ok.push({ kind: 'file', path: f.path });
79
+ } else {
80
+ missing.push({ kind: 'file', path: f.path, template: f.template, generated: !!f.generated });
81
+ }
82
+ }
83
+
84
+ // EXTRA:现场扫一层,schema 没定义的只报告不处理
85
+ const extra = [];
86
+ const knownTop = new Set(schema.roots || []);
87
+ if (existsSync(workspaceDir)) {
88
+ for (const name of readdirSync(workspaceDir, { withFileTypes: true })) {
89
+ if (!knownTop.has(name.name)) {
90
+ extra.push({ kind: name.isDirectory() ? 'dir' : 'file', path: name.name });
91
+ }
92
+ }
93
+ }
94
+
95
+ return { missing, extra, ok };
96
+ }
@@ -0,0 +1,28 @@
1
+ /** 本地时间 ISO 字符串,保留时区偏移,例:2026-10-27T23:20:53+08:00 */
2
+ export function nowLocal(d = new Date()) {
3
+ const pad = n => String(Math.abs(n)).padStart(2, '0');
4
+ const off = -d.getTimezoneOffset(); // 分钟,东八区为 480
5
+ const sign = off >= 0 ? '+' : '-';
6
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
7
+ + `T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
8
+ + `${sign}${pad(Math.floor(Math.abs(off) / 60))}:${pad(Math.abs(off) % 60)}`;
9
+ }
10
+
11
+ /** 本地日期串 YYYY-MM-DD */
12
+ export function todayLocal(d = new Date()) {
13
+ const pad = n => String(n).padStart(2, '0');
14
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
15
+ }
16
+
17
+ /** 把 epoch 毫秒转成本地时区的 ISO 串,例:2026-10-27T09:19:27+08:00 */
18
+ export function localIsoOf(ms) {
19
+ if (!ms) return null;
20
+ return nowLocal(new Date(ms));
21
+ }
22
+
23
+ /** 解析 frontmatter 里的 date 字段,失败返回 null */
24
+ export function parseDate(v) {
25
+ if (!v) return null;
26
+ const d = new Date(v);
27
+ return Number.isNaN(d.getTime()) ? null : d;
28
+ }
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * migrate.mjs —— 把工作区结构修正到当前 schema 版本(幂等、只做加法)
4
+ *
5
+ * 用法:
6
+ * node "<技能目录>/scripts/migrate.mjs" --workspace "<路径>" [--dry-run] [--json]
7
+ *
8
+ * 硬规则:
9
+ * 1. 只做加法:建目录、补生成物。永不删用户数据。
10
+ * 2. 可回滚:执行前把结构快照写进 .assistant/logs/migrate-<ts>.json
11
+ * 3. 幂等:重复执行不产生副作用
12
+ * 4. 顺序执行:从当前版本逐级升到目标版本,不跳级
13
+ * 5. EXTRA 不清理:用户自建目录一律保留
14
+ *
15
+ * 退出码:0 成功 / 10 无需操作 / 20 部分失败 / 30 前置条件不满足
16
+ */
17
+ import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
18
+ import { join, resolve, dirname } from 'node:path';
19
+ import {
20
+ SKILL_DIR, loadSchema, listVersions, latestVersion,
21
+ readWorkspaceVersion, readCapabilities, diff,
22
+ } from './lib/schema.mjs';
23
+
24
+ function parseArgs(argv) {
25
+ const out = { json: false, dryRun: false };
26
+ for (let i = 2; i < argv.length; i++) {
27
+ const a = argv[i];
28
+ if (a === '--workspace' || a === '-w') out.workspace = argv[++i];
29
+ else if (a === '--json') out.json = true;
30
+ else if (a === '--dry-run') out.dryRun = true;
31
+ else if (a === '--help' || a === '-h') out.help = true;
32
+ }
33
+ return out;
34
+ }
35
+
36
+ const args = parseArgs(process.argv);
37
+ if (args.help || !args.workspace) {
38
+ console.log(`用法:node migrate.mjs --workspace <路径> [--dry-run] [--json]
39
+
40
+ 把工作区修正到当前 schema 版本。幂等、只做加法、不删数据。`);
41
+ process.exit(args.help ? 0 : 30);
42
+ }
43
+
44
+ const workspace = resolve(args.workspace);
45
+ const target = latestVersion();
46
+ const from = readWorkspaceVersion(workspace);
47
+ const capabilities = readCapabilities(workspace);
48
+
49
+ const report = {
50
+ workspace,
51
+ from: from || 'uninitialized',
52
+ to: target,
53
+ dryRun: args.dryRun,
54
+ steps: [],
55
+ created: [],
56
+ skipped: [],
57
+ errors: [],
58
+ };
59
+
60
+ // ── 快照(可回滚依据) ──────────────────────────────────────────
61
+ if (!args.dryRun && from > 0) {
62
+ const logDir = join(workspace, '.assistant', 'logs');
63
+ mkdirSync(logDir, { recursive: true });
64
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
65
+ const snapPath = join(logDir, `migrate-${stamp}.json`);
66
+ const snap = { at: new Date().toISOString(), from, to: target, schema: loadSchema(from) };
67
+ writeFileSync(snapPath, JSON.stringify(snap, null, 2), 'utf8');
68
+ report.snapshot = snapPath;
69
+ }
70
+
71
+ // ── 逐级迁移 ────────────────────────────────────────────────────
72
+ const versions = listVersions().filter(v => v > from);
73
+ if (!versions.length && from >= target) {
74
+ if (args.json) {
75
+ console.log(JSON.stringify({ ...report, ok: true, noop: true }, null, 2));
76
+ } else {
77
+ console.log(`✅ 已是 v${target},无需迁移`);
78
+ }
79
+ process.exit(10);
80
+ }
81
+
82
+ // 每级迁移:这里各版本共用一个通用落地器(建目录 + 补生成物)。
83
+ // 将来若某版本需要改结构(移动/重命名),在该版本分支里加专用步骤。
84
+ for (const v of versions) {
85
+ const schema = loadSchema(v);
86
+ const step = { version: v, dirs: 0, files: 0 };
87
+ const result = diff(workspace, schema, { capabilities });
88
+
89
+ for (const m of result.missing) {
90
+ const abs = join(workspace, m.path);
91
+ try {
92
+ if (m.kind === 'dir') {
93
+ if (!args.dryRun) mkdirSync(abs, { recursive: true });
94
+ report.created.push(m.path);
95
+ step.dirs++;
96
+ } else if (m.kind === 'file') {
97
+ // 只自动重建标记为 generated 的;其它文件缺失属于异常,报告但不伪造
98
+ if (!m.generated) {
99
+ report.errors.push({ path: m.path, reason: '非生成物缺失,需人工确认来源' });
100
+ continue;
101
+ }
102
+ if (!args.dryRun) {
103
+ mkdirSync(dirname(abs), { recursive: true });
104
+ const tpl = m.template ? join(SKILL_DIR, m.template) : null;
105
+ let body = '';
106
+ if (tpl && existsSync(tpl)) {
107
+ body = readFileSync(tpl, 'utf8')
108
+ .replaceAll('{{workspace_name}}', workspace.split(/[\\/]/).pop())
109
+ .replaceAll('{{created_at}}', new Date().toISOString());
110
+ }
111
+ // state.json 由 init 写完整内容;这里只保证存在,避免后续读取失败
112
+ if (m.path.endsWith('state.json')) {
113
+ body = JSON.stringify({
114
+ workspace_version: v,
115
+ skill_version: '',
116
+ created_at: new Date().toISOString(),
117
+ updated_at: new Date().toISOString(),
118
+ triggers: [],
119
+ capabilities,
120
+ recovered: true,
121
+ }, null, 2);
122
+ }
123
+ writeFileSync(abs, body, 'utf8');
124
+ }
125
+ report.created.push(m.path);
126
+ step.files++;
127
+ }
128
+ } catch (e) {
129
+ report.errors.push({ path: m.path, reason: e.message });
130
+ }
131
+ }
132
+ report.steps.push(step);
133
+ }
134
+
135
+ // ── 写版本号 ────────────────────────────────────────────────────
136
+ if (!args.dryRun && !report.errors.length) {
137
+ const statePath = join(workspace, '.assistant', 'state.json');
138
+ try {
139
+ let state = {};
140
+ if (existsSync(statePath)) state = JSON.parse(readFileSync(statePath, 'utf8'));
141
+ state.workspace_version = target;
142
+ state.updated_at = new Date().toISOString();
143
+ writeFileSync(statePath, JSON.stringify(state, null, 2), 'utf8');
144
+ } catch (e) {
145
+ report.errors.push({ path: '.assistant/state.json', reason: e.message });
146
+ }
147
+ }
148
+
149
+ report.ok = report.errors.length === 0;
150
+ const exitCode = report.errors.length ? 20 : 0;
151
+
152
+ if (args.json) {
153
+ console.log(JSON.stringify(report, null, 2));
154
+ process.exit(exitCode);
155
+ }
156
+
157
+ if (args.dryRun) console.log('[dry-run] 以下改动不会真的执行\n');
158
+ console.log(`迁移:v${report.from} → v${report.to}`);
159
+ if (report.snapshot) console.log(`快照:${report.snapshot}`);
160
+ console.log('');
161
+ console.log(`新建 ${report.created.length} 项:`);
162
+ for (const p of report.created) console.log(` · ${p}`);
163
+ if (report.errors.length) {
164
+ console.log('');
165
+ console.log(`⚠️ ${report.errors.length} 项失败:`);
166
+ for (const e of report.errors) console.log(` · ${e.path}:${e.reason}`);
167
+ console.log('\n失败项未写入版本号,修好后可重跑。');
168
+ } else if (!args.dryRun) {
169
+ console.log(`\n✅ 完成,工作区现在是 v${target}`);
170
+ }
171
+
172
+ process.exit(exitCode);
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * search.mjs —— 本地全文检索
4
+ *
5
+ * 用法:
6
+ * node "<技能目录>/scripts/search.mjs" --workspace "<路径>" [选项]
7
+ *
8
+ * 选项:
9
+ * --text <关键词> 必填,支持正则(--literal 关闭正则)
10
+ * --literal 按字面量匹配,不解析正则
11
+ * --since <日期> 起始日期 YYYY-MM-DD(按文件日期或消息时间)
12
+ * --until <日期> 截止日期
13
+ * --type <类型,...> 限定 frontmatter 的 type(note,report,conversation…)
14
+ * --dir <子路径> 限定目录,如 capture/conversation
15
+ * --max <N> 最多输出 N 条,默认 50
16
+ * --context <N> md 命中行前后展示 N 行,默认 0
17
+ * --json 机器可读输出
18
+ *
19
+ * 为什么需要它:ec thread history 只能按时间翻,不能按内容筛。
20
+ * 落地之后这里就是真正的检索入口。
21
+ */
22
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
23
+ import { join, resolve, relative, sep } from 'node:path';
24
+
25
+ function parseArgs(argv) {
26
+ const out = { max: 50, context: 0, json: false, literal: false };
27
+ for (let i = 2; i < argv.length; i++) {
28
+ const a = argv[i];
29
+ if (a === '--workspace' || a === '-w') out.workspace = argv[++i];
30
+ else if (a === '--text' || a === '-t') out.text = argv[++i];
31
+ else if (a === '--literal') out.literal = true;
32
+ else if (a === '--since') out.since = argv[++i];
33
+ else if (a === '--until') out.until = argv[++i];
34
+ else if (a === '--type') out.type = argv[++i].split(',').map(s => s.trim());
35
+ else if (a === '--dir') out.dir = argv[++i];
36
+ else if (a === '--max') out.max = Number(argv[++i]) || 50;
37
+ else if (a === '--context' || a === '-C') out.context = Number(argv[++i]) || 0;
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 || !args.text) {
46
+ console.log(`用法:node search.mjs --workspace <路径> --text <关键词> [选项]
47
+
48
+ --literal 按字面量匹配
49
+ --since / --until 日期范围 YYYY-MM-DD
50
+ --type <列表> frontmatter type 过滤
51
+ --dir <子路径> 限定目录
52
+ --max <N> 最多输出条数(默认 50)
53
+ --context <N> md 命中行上下文行数
54
+ --json 机器可读输出`);
55
+ process.exit(args.help ? 0 : 30);
56
+ }
57
+
58
+ const workspace = resolve(args.workspace);
59
+ if (!existsSync(workspace)) {
60
+ console.error(`❌ 工作区不存在:${workspace}`);
61
+ process.exit(30);
62
+ }
63
+
64
+ let re;
65
+ try {
66
+ re = new RegExp(args.literal ? args.text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : args.text, 'i');
67
+ } catch (e) {
68
+ console.error(`❌ 正则无效:${e.message}`);
69
+ process.exit(30);
70
+ }
71
+
72
+ const ROOTS = args.dir ? [args.dir] : ['capture', 'output'];
73
+ const SKIP = new Set(['_archive', 'node_modules', '.assistant']);
74
+
75
+ function walk(dir, out = []) {
76
+ if (!existsSync(dir)) return out;
77
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
78
+ if (SKIP.has(e.name)) continue;
79
+ const abs = join(dir, e.name);
80
+ if (e.isDirectory()) walk(abs, out);
81
+ else if (/\.(md|jsonl|txt)$/.test(e.name)) out.push(abs);
82
+ }
83
+ return out;
84
+ }
85
+
86
+ /** 从路径或 frontmatter 里推日期:YYYY-MM-DD */
87
+ function dateOf(file, text) {
88
+ const m = /(\d{4})[/-](\d{2})[/-](\d{2})/.exec(file.replace(/\\/g, '/'));
89
+ if (m) return `${m[1]}-${m[2]}-${m[3]}`;
90
+ const fm = /^date:\s*(.+)$/m.exec(text.slice(0, 800));
91
+ if (fm) {
92
+ const d = new Date(fm[1].trim().replace(/^["']|["']$/g, ''));
93
+ if (!Number.isNaN(d.getTime())) {
94
+ const pad = n => String(n).padStart(2, '0');
95
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
96
+ }
97
+ }
98
+ return null;
99
+ }
100
+
101
+ function typeOf(text) {
102
+ const m = /^type:\s*(\S+)$/m.exec(text.slice(0, 800));
103
+ return m ? m[1].trim() : null;
104
+ }
105
+
106
+ const hits = [];
107
+ for (const root of ROOTS) {
108
+ for (const file of walk(join(workspace, root))) {
109
+ const rel = relative(workspace, file).split(sep).join('/');
110
+ const text = readFileSync(file, 'utf8');
111
+ const date = dateOf(rel, text);
112
+
113
+ if (args.since && date && date < args.since) continue;
114
+ if (args.until && date && date > args.until) continue;
115
+ if (args.type) {
116
+ const t = rel.endsWith('.jsonl') ? 'conversation' : typeOf(text);
117
+ if (!t || !args.type.includes(t)) continue;
118
+ }
119
+
120
+ if (file.endsWith('.jsonl')) {
121
+ const lines = text.split(/\r?\n/);
122
+ for (let i = 0; i < lines.length; i++) {
123
+ if (!lines[i] || !re.test(lines[i])) continue;
124
+ let snippet = lines[i];
125
+ try {
126
+ const o = JSON.parse(lines[i]);
127
+ snippet = `${o.time || ''} ${o.dir === 'out' ? '→' : '←'} ${(o.text || '').slice(0, 200)}`;
128
+ } catch { /* 保留原始行 */ }
129
+ hits.push({ file: rel, line: i + 1, date, snippet });
130
+ if (hits.length >= args.max) break;
131
+ }
132
+ } else {
133
+ const lines = text.split(/\r?\n/);
134
+ for (let i = 0; i < lines.length; i++) {
135
+ if (!re.test(lines[i])) continue;
136
+ const from = Math.max(0, i - args.context);
137
+ const to = Math.min(lines.length, i + args.context + 1);
138
+ hits.push({
139
+ file: rel,
140
+ line: i + 1,
141
+ date,
142
+ snippet: lines.slice(from, to).join('\n').slice(0, 400),
143
+ });
144
+ if (hits.length >= args.max) break;
145
+ }
146
+ }
147
+ if (hits.length >= args.max) break;
148
+ }
149
+ if (hits.length >= args.max) break;
150
+ }
151
+
152
+ if (args.json) {
153
+ console.log(JSON.stringify({ ok: true, query: args.text, count: hits.length, hits }, null, 2));
154
+ process.exit(0);
155
+ }
156
+
157
+ if (!hits.length) {
158
+ console.log(`没有找到「${args.text}」`);
159
+ process.exit(0);
160
+ }
161
+
162
+ console.log(`找到 ${hits.length} 处(上限 ${args.max})\n`);
163
+ let lastFile = '';
164
+ for (const h of hits) {
165
+ if (h.file !== lastFile) {
166
+ console.log(`📄 ${h.file}`);
167
+ lastFile = h.file;
168
+ }
169
+ console.log(` ${h.line}: ${h.snippet.split('\n')[0].slice(0, 160)}`);
170
+ }
171
+ console.log('');
172
+ console.log('提示:--context 3 可看更多上下文,--json 拿结构化结果。');