@askexenow/exe-os 0.8.0 → 0.8.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 (107) hide show
  1. package/README.md +178 -79
  2. package/package.json +1 -1
  3. package/dist/bin/backfill-responses.js +0 -1912
  4. package/dist/bin/backfill-vectors.js +0 -1642
  5. package/dist/bin/cleanup-stale-review-tasks.js +0 -1339
  6. package/dist/bin/cli.js +0 -18800
  7. package/dist/bin/exe-agent.js +0 -1858
  8. package/dist/bin/exe-assign.js +0 -1957
  9. package/dist/bin/exe-boot.js +0 -6460
  10. package/dist/bin/exe-call.js +0 -197
  11. package/dist/bin/exe-cloud.js +0 -850
  12. package/dist/bin/exe-dispatch.js +0 -1146
  13. package/dist/bin/exe-doctor.js +0 -1657
  14. package/dist/bin/exe-export-behaviors.js +0 -1494
  15. package/dist/bin/exe-forget.js +0 -1627
  16. package/dist/bin/exe-gateway.js +0 -7732
  17. package/dist/bin/exe-healthcheck.js +0 -207
  18. package/dist/bin/exe-heartbeat.js +0 -1647
  19. package/dist/bin/exe-kill.js +0 -1479
  20. package/dist/bin/exe-launch-agent.js +0 -1704
  21. package/dist/bin/exe-link.js +0 -192
  22. package/dist/bin/exe-new-employee.js +0 -852
  23. package/dist/bin/exe-pending-messages.js +0 -1446
  24. package/dist/bin/exe-pending-notifications.js +0 -1321
  25. package/dist/bin/exe-pending-reviews.js +0 -1468
  26. package/dist/bin/exe-repo-drift.js +0 -95
  27. package/dist/bin/exe-review.js +0 -1590
  28. package/dist/bin/exe-search.js +0 -2651
  29. package/dist/bin/exe-session-cleanup.js +0 -3173
  30. package/dist/bin/exe-settings.js +0 -354
  31. package/dist/bin/exe-status.js +0 -1532
  32. package/dist/bin/exe-team.js +0 -1324
  33. package/dist/bin/git-sweep.js +0 -2185
  34. package/dist/bin/graph-backfill.js +0 -1968
  35. package/dist/bin/graph-export.js +0 -1604
  36. package/dist/bin/install.js +0 -656
  37. package/dist/bin/list-providers.js +0 -140
  38. package/dist/bin/scan-tasks.js +0 -1820
  39. package/dist/bin/setup.js +0 -951
  40. package/dist/bin/shard-migrate.js +0 -1494
  41. package/dist/bin/update.js +0 -95
  42. package/dist/bin/wiki-sync.js +0 -1514
  43. package/dist/gateway/index.js +0 -8848
  44. package/dist/hooks/bug-report-worker.js +0 -2743
  45. package/dist/hooks/commit-complete.js +0 -2108
  46. package/dist/hooks/error-recall.js +0 -2861
  47. package/dist/hooks/exe-heartbeat-hook.js +0 -232
  48. package/dist/hooks/ingest-worker.js +0 -4793
  49. package/dist/hooks/ingest.js +0 -684
  50. package/dist/hooks/instructions-loaded.js +0 -1880
  51. package/dist/hooks/notification.js +0 -1726
  52. package/dist/hooks/post-compact.js +0 -1751
  53. package/dist/hooks/pre-compact.js +0 -1746
  54. package/dist/hooks/pre-tool-use.js +0 -2191
  55. package/dist/hooks/prompt-ingest-worker.js +0 -2126
  56. package/dist/hooks/prompt-submit.js +0 -4693
  57. package/dist/hooks/response-ingest-worker.js +0 -1936
  58. package/dist/hooks/session-end.js +0 -1752
  59. package/dist/hooks/session-start.js +0 -2795
  60. package/dist/hooks/stop.js +0 -1835
  61. package/dist/hooks/subagent-stop.js +0 -1726
  62. package/dist/hooks/summary-worker.js +0 -2661
  63. package/dist/index.js +0 -11834
  64. package/dist/lib/cloud-sync.js +0 -495
  65. package/dist/lib/config.js +0 -222
  66. package/dist/lib/consolidation.js +0 -476
  67. package/dist/lib/crypto.js +0 -51
  68. package/dist/lib/database.js +0 -730
  69. package/dist/lib/device-registry.js +0 -900
  70. package/dist/lib/embedder.js +0 -632
  71. package/dist/lib/employee-templates.js +0 -543
  72. package/dist/lib/employees.js +0 -177
  73. package/dist/lib/error-detector.js +0 -156
  74. package/dist/lib/exe-daemon-client.js +0 -451
  75. package/dist/lib/exe-daemon.js +0 -8285
  76. package/dist/lib/file-grep.js +0 -199
  77. package/dist/lib/hybrid-search.js +0 -1819
  78. package/dist/lib/identity-templates.js +0 -320
  79. package/dist/lib/identity.js +0 -223
  80. package/dist/lib/keychain.js +0 -145
  81. package/dist/lib/license.js +0 -377
  82. package/dist/lib/messaging.js +0 -1376
  83. package/dist/lib/reminders.js +0 -63
  84. package/dist/lib/schedules.js +0 -1396
  85. package/dist/lib/session-registry.js +0 -52
  86. package/dist/lib/skill-learning.js +0 -477
  87. package/dist/lib/status-brief.js +0 -235
  88. package/dist/lib/store.js +0 -1551
  89. package/dist/lib/task-router.js +0 -62
  90. package/dist/lib/tasks.js +0 -2456
  91. package/dist/lib/tmux-routing.js +0 -2836
  92. package/dist/lib/tmux-status.js +0 -261
  93. package/dist/lib/tmux-transport.js +0 -83
  94. package/dist/lib/transport.js +0 -128
  95. package/dist/lib/ws-auth.js +0 -19
  96. package/dist/lib/ws-client.js +0 -160
  97. package/dist/mcp/server.js +0 -10538
  98. package/dist/mcp/tools/complete-reminder.js +0 -67
  99. package/dist/mcp/tools/create-reminder.js +0 -52
  100. package/dist/mcp/tools/create-task.js +0 -1853
  101. package/dist/mcp/tools/deactivate-behavior.js +0 -263
  102. package/dist/mcp/tools/list-reminders.js +0 -62
  103. package/dist/mcp/tools/list-tasks.js +0 -463
  104. package/dist/mcp/tools/send-message.js +0 -1382
  105. package/dist/mcp/tools/update-task.js +0 -1692
  106. package/dist/runtime/index.js +0 -6809
  107. package/dist/tui/App.js +0 -17479
@@ -1,52 +0,0 @@
1
- // src/lib/session-registry.ts
2
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
3
- import { execSync } from "child_process";
4
- import path from "path";
5
- import os from "os";
6
- var REGISTRY_PATH = path.join(os.homedir(), ".exe-os", "session-registry.json");
7
- function registerSession(entry) {
8
- const dir = path.dirname(REGISTRY_PATH);
9
- if (!existsSync(dir)) {
10
- mkdirSync(dir, { recursive: true });
11
- }
12
- const sessions = listSessions();
13
- const idx = sessions.findIndex((s) => s.windowName === entry.windowName);
14
- if (idx >= 0) {
15
- sessions[idx] = entry;
16
- } else {
17
- sessions.push(entry);
18
- }
19
- writeFileSync(REGISTRY_PATH, JSON.stringify(sessions, null, 2));
20
- }
21
- function listSessions() {
22
- try {
23
- const raw = readFileSync(REGISTRY_PATH, "utf8");
24
- return JSON.parse(raw);
25
- } catch {
26
- return [];
27
- }
28
- }
29
- function pruneStaleSessions() {
30
- const sessions = listSessions();
31
- if (sessions.length === 0) return 0;
32
- let liveSessions = [];
33
- try {
34
- liveSessions = execSync("tmux list-sessions -F '#{session_name}' 2>/dev/null", {
35
- encoding: "utf8"
36
- }).trim().split("\n").filter(Boolean);
37
- } catch {
38
- return 0;
39
- }
40
- const liveSet = new Set(liveSessions);
41
- const alive = sessions.filter((s) => liveSet.has(s.windowName));
42
- const pruned = sessions.length - alive.length;
43
- if (pruned > 0) {
44
- writeFileSync(REGISTRY_PATH, JSON.stringify(alive, null, 2));
45
- }
46
- return pruned;
47
- }
48
- export {
49
- listSessions,
50
- pruneStaleSessions,
51
- registerSession
52
- };
@@ -1,477 +0,0 @@
1
- // src/lib/skill-learning.ts
2
- import crypto2 from "crypto";
3
-
4
- // src/lib/database.ts
5
- import { createClient } from "@libsql/client";
6
- var _client = null;
7
- function getClient() {
8
- if (!_client) {
9
- throw new Error("Database client not initialized. Call initDatabase() first.");
10
- }
11
- return _client;
12
- }
13
-
14
- // src/lib/behaviors.ts
15
- import crypto from "crypto";
16
- async function storeBehavior(opts) {
17
- const client = getClient();
18
- const id = crypto.randomUUID();
19
- const now = (/* @__PURE__ */ new Date()).toISOString();
20
- await client.execute({
21
- sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, priority, content, active, created_at, updated_at)
22
- VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)`,
23
- args: [id, opts.agentId, opts.projectName ?? null, opts.domain ?? null, opts.priority ?? "p1", opts.content, now, now]
24
- });
25
- return id;
26
- }
27
-
28
- // src/lib/config.ts
29
- import { readFile, writeFile, mkdir } from "fs/promises";
30
- import { readFileSync, existsSync, renameSync } from "fs";
31
- import path from "path";
32
- import os from "os";
33
- function resolveDataDir() {
34
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
35
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
36
- const newDir = path.join(os.homedir(), ".exe-os");
37
- const legacyDir = path.join(os.homedir(), ".exe-mem");
38
- if (!existsSync(newDir) && existsSync(legacyDir)) {
39
- try {
40
- renameSync(legacyDir, newDir);
41
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
42
- `);
43
- } catch {
44
- return legacyDir;
45
- }
46
- }
47
- return newDir;
48
- }
49
- var EXE_AI_DIR = resolveDataDir();
50
- var DB_PATH = path.join(EXE_AI_DIR, "memories.db");
51
- var MODELS_DIR = path.join(EXE_AI_DIR, "models");
52
- var CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
53
- var LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
54
- var CURRENT_CONFIG_VERSION = 1;
55
- var DEFAULT_CONFIG = {
56
- config_version: CURRENT_CONFIG_VERSION,
57
- dbPath: DB_PATH,
58
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
59
- embeddingDim: 1024,
60
- batchSize: 20,
61
- flushIntervalMs: 1e4,
62
- autoIngestion: true,
63
- autoRetrieval: true,
64
- searchMode: "hybrid",
65
- hookSearchMode: "hybrid",
66
- fileGrepEnabled: true,
67
- splashEffect: true,
68
- consolidationEnabled: true,
69
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
70
- consolidationModel: "claude-haiku-4-5-20251001",
71
- consolidationMaxCallsPerRun: 20,
72
- selfQueryRouter: true,
73
- selfQueryModel: "claude-haiku-4-5-20251001",
74
- rerankerEnabled: true,
75
- scalingRoadmap: {
76
- rerankerAutoTrigger: {
77
- enabled: true,
78
- broadQueryMinCardinality: 5e4,
79
- fetchTopK: 150,
80
- returnTopK: 5
81
- }
82
- },
83
- graphRagEnabled: true,
84
- wikiEnabled: false,
85
- wikiUrl: "",
86
- wikiApiKey: "",
87
- wikiSyncIntervalMs: 30 * 60 * 1e3,
88
- wikiWorkspaceMapping: {
89
- exe: "Executive",
90
- yoshi: "Engineering",
91
- mari: "Marketing",
92
- tom: "Engineering",
93
- sasha: "Production"
94
- },
95
- wikiAutoUpdate: true,
96
- wikiAutoUpdateThreshold: 0.5,
97
- wikiAutoUpdateCreateNew: true,
98
- skillLearning: true,
99
- skillThreshold: 3,
100
- skillModel: "claude-haiku-4-5-20251001",
101
- exeHeartbeat: {
102
- enabled: true,
103
- intervalSeconds: 60,
104
- staleInProgressThresholdHours: 2
105
- },
106
- sessionLifecycle: {
107
- idleKillEnabled: true,
108
- idleKillTicksRequired: 3,
109
- idleKillIntercomAckWindowMs: 1e4,
110
- maxAutoInstances: 10
111
- }
112
- };
113
- function migrateLegacyConfig(raw) {
114
- if ("r2" in raw) {
115
- process.stderr.write(
116
- "[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
117
- );
118
- delete raw.r2;
119
- }
120
- if ("syncIntervalMs" in raw) {
121
- delete raw.syncIntervalMs;
122
- }
123
- return raw;
124
- }
125
- var CONFIG_MIGRATIONS = [
126
- {
127
- from: 0,
128
- to: 1,
129
- migrate: (cfg) => {
130
- cfg.config_version = 1;
131
- return cfg;
132
- }
133
- }
134
- ];
135
- function migrateConfig(raw) {
136
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
137
- let currentVersion = fromVersion;
138
- let migrated = false;
139
- if (currentVersion > CURRENT_CONFIG_VERSION) {
140
- return { config: raw, migrated: false, fromVersion };
141
- }
142
- for (const migration of CONFIG_MIGRATIONS) {
143
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
144
- raw = migration.migrate(raw);
145
- currentVersion = migration.to;
146
- migrated = true;
147
- }
148
- }
149
- return { config: raw, migrated, fromVersion };
150
- }
151
- function normalizeScalingRoadmap(raw) {
152
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
153
- const userRoadmap = raw.scalingRoadmap ?? {};
154
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
155
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
156
- userAuto.enabled = raw.rerankerEnabled;
157
- }
158
- raw.scalingRoadmap = {
159
- ...userRoadmap,
160
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
161
- };
162
- }
163
- function normalizeSessionLifecycle(raw) {
164
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
165
- const userSL = raw.sessionLifecycle ?? {};
166
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
167
- }
168
- async function loadConfig() {
169
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
170
- await mkdir(dir, { recursive: true });
171
- const configPath = path.join(dir, "config.json");
172
- if (!existsSync(configPath)) {
173
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
174
- }
175
- const raw = await readFile(configPath, "utf-8");
176
- try {
177
- let parsed = JSON.parse(raw);
178
- parsed = migrateLegacyConfig(parsed);
179
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
180
- if (migrated) {
181
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
182
- `);
183
- try {
184
- await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
185
- } catch {
186
- }
187
- }
188
- normalizeScalingRoadmap(migratedCfg);
189
- normalizeSessionLifecycle(migratedCfg);
190
- const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
191
- if (config.dbPath.startsWith("~")) {
192
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
193
- }
194
- return config;
195
- } catch {
196
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
197
- }
198
- }
199
-
200
- // src/lib/skill-learning.ts
201
- var DEFAULT_SKILL_THRESHOLD = 3;
202
- async function extractTrajectory(taskId, agentId) {
203
- const client = getClient();
204
- const result = await client.execute({
205
- sql: `SELECT tool_name, raw_text
206
- FROM memories
207
- WHERE task_id = ? AND agent_id = ?
208
- ORDER BY timestamp ASC`,
209
- args: [taskId, agentId]
210
- });
211
- if (result.rows.length === 0) return [];
212
- const rawTools = result.rows.map((r) => {
213
- const toolName = String(r.tool_name);
214
- if (toolName === "Bash") {
215
- const text = String(r.raw_text);
216
- const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
217
- return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
218
- }
219
- return toolName;
220
- });
221
- const signature = [];
222
- for (const tool of rawTools) {
223
- if (signature.length === 0 || signature[signature.length - 1] !== tool) {
224
- signature.push(tool);
225
- }
226
- }
227
- return signature;
228
- }
229
- function hashSignature(signature) {
230
- return crypto2.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
231
- }
232
- async function storeTrajectory(opts) {
233
- const client = getClient();
234
- const id = crypto2.randomUUID();
235
- const now = (/* @__PURE__ */ new Date()).toISOString();
236
- const signatureHash = hashSignature(opts.signature);
237
- await client.execute({
238
- sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
239
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
240
- args: [
241
- id,
242
- opts.taskId,
243
- opts.agentId,
244
- opts.projectName,
245
- opts.taskTitle,
246
- JSON.stringify(opts.signature),
247
- signatureHash,
248
- opts.signature.length,
249
- now
250
- ]
251
- });
252
- return id;
253
- }
254
- async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
255
- const client = getClient();
256
- const hash = hashSignature(signature);
257
- const result = await client.execute({
258
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
259
- FROM trajectories
260
- WHERE signature_hash = ?
261
- ORDER BY created_at DESC
262
- LIMIT 20`,
263
- args: [hash]
264
- });
265
- const mapRow = (r) => ({
266
- id: String(r.id),
267
- taskId: String(r.task_id),
268
- agentId: String(r.agent_id),
269
- projectName: String(r.project_name),
270
- taskTitle: String(r.task_title),
271
- signature: JSON.parse(String(r.signature)),
272
- signatureHash: String(r.signature_hash),
273
- toolCount: Number(r.tool_count),
274
- skillId: r.skill_id ? String(r.skill_id) : null,
275
- createdAt: String(r.created_at)
276
- });
277
- const matches = result.rows.map(mapRow);
278
- if (matches.length >= threshold) return matches;
279
- const nearResult = await client.execute({
280
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
281
- FROM trajectories
282
- WHERE tool_count BETWEEN ? AND ?
283
- AND signature_hash != ?
284
- ORDER BY created_at DESC
285
- LIMIT 50`,
286
- args: [
287
- Math.max(1, signature.length - 3),
288
- signature.length + 3,
289
- hash
290
- ]
291
- });
292
- for (const r of nearResult.rows) {
293
- const candidateSig = JSON.parse(String(r.signature));
294
- if (editDistance(signature, candidateSig) <= 2) {
295
- matches.push(mapRow(r));
296
- }
297
- }
298
- return matches;
299
- }
300
- async function captureTrajectory(opts) {
301
- const signature = await extractTrajectory(opts.taskId, opts.agentId);
302
- if (signature.length < 3) {
303
- return { trajectoryId: "", similarCount: 0, similar: [] };
304
- }
305
- const trajectoryId = await storeTrajectory({
306
- taskId: opts.taskId,
307
- agentId: opts.agentId,
308
- projectName: opts.projectName,
309
- taskTitle: opts.taskTitle,
310
- signature
311
- });
312
- const similar = await findSimilarTrajectories(
313
- signature,
314
- opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
315
- );
316
- return { trajectoryId, similarCount: similar.length, similar };
317
- }
318
- function buildExtractionPrompt(trajectories) {
319
- const items = trajectories.map((t, i) => {
320
- const sig = t.signature.join(" \u2192 ");
321
- return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
322
- Signature: ${sig}`;
323
- }).join("\n\n");
324
- return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
325
-
326
- ${items}
327
-
328
- Extract the reusable procedure. Format your response EXACTLY like this:
329
-
330
- SKILL: {name \u2014 short, descriptive}
331
- TRIGGER: {when to use this \u2014 one sentence}
332
- STEPS:
333
- 1. ...
334
- 2. ...
335
- PITFALLS: {common mistakes to avoid}
336
-
337
- Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
338
- }
339
- async function extractSkill(trajectories, model) {
340
- if (trajectories.length === 0) return null;
341
- const config = await loadConfig();
342
- const skillModel = model ?? config.skillModel;
343
- const Anthropic = (await import("@anthropic-ai/sdk")).default;
344
- const client = new Anthropic();
345
- const prompt = buildExtractionPrompt(trajectories);
346
- const response = await client.messages.create({
347
- model: skillModel,
348
- max_tokens: 500,
349
- messages: [{ role: "user", content: prompt }]
350
- });
351
- const textBlock = response.content.find((b) => b.type === "text");
352
- const skillText = textBlock?.text;
353
- if (!skillText) return null;
354
- const agentId = trajectories[0].agentId;
355
- const projectName = trajectories[0].projectName;
356
- const skillId = await storeBehavior({
357
- agentId,
358
- content: skillText,
359
- domain: "skill",
360
- projectName
361
- });
362
- const dbClient = getClient();
363
- for (const t of trajectories) {
364
- await dbClient.execute({
365
- sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
366
- args: [skillId, t.id]
367
- });
368
- }
369
- process.stderr.write(
370
- `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
371
- `
372
- );
373
- return skillId;
374
- }
375
- async function captureAndLearn(opts) {
376
- try {
377
- const config = await loadConfig();
378
- if (!config.skillLearning) return;
379
- const { trajectoryId, similarCount, similar } = await captureTrajectory({
380
- ...opts,
381
- skillThreshold: config.skillThreshold
382
- });
383
- if (!trajectoryId) return;
384
- if (similarCount >= config.skillThreshold) {
385
- const unprocessed = similar.filter((t) => !t.skillId);
386
- if (unprocessed.length >= config.skillThreshold) {
387
- extractSkill(unprocessed, config.skillModel).catch((err) => {
388
- process.stderr.write(
389
- `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
390
- `
391
- );
392
- });
393
- }
394
- }
395
- } catch (err) {
396
- process.stderr.write(
397
- `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
398
- `
399
- );
400
- }
401
- }
402
- async function sweepTrajectories(threshold, model) {
403
- const config = await loadConfig();
404
- if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
405
- const t = threshold ?? config.skillThreshold;
406
- const client = getClient();
407
- const result = await client.execute({
408
- sql: `SELECT signature_hash, COUNT(*) as cnt
409
- FROM trajectories
410
- WHERE skill_id IS NULL
411
- GROUP BY signature_hash
412
- HAVING cnt >= ?
413
- ORDER BY cnt DESC
414
- LIMIT 10`,
415
- args: [t]
416
- });
417
- let clustersProcessed = 0;
418
- let skillsExtracted = 0;
419
- for (const row of result.rows) {
420
- const hash = String(row.signature_hash);
421
- const trajResult = await client.execute({
422
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
423
- FROM trajectories
424
- WHERE signature_hash = ? AND skill_id IS NULL
425
- ORDER BY created_at DESC
426
- LIMIT 10`,
427
- args: [hash]
428
- });
429
- const trajectories = trajResult.rows.map((r) => ({
430
- id: String(r.id),
431
- taskId: String(r.task_id),
432
- agentId: String(r.agent_id),
433
- projectName: String(r.project_name),
434
- taskTitle: String(r.task_title),
435
- signature: JSON.parse(String(r.signature)),
436
- signatureHash: String(r.signature_hash),
437
- toolCount: Number(r.tool_count),
438
- skillId: null,
439
- createdAt: String(r.created_at)
440
- }));
441
- if (trajectories.length >= t) {
442
- clustersProcessed++;
443
- const skillId = await extractSkill(trajectories, model ?? config.skillModel);
444
- if (skillId) skillsExtracted++;
445
- }
446
- }
447
- return { clustersProcessed, skillsExtracted };
448
- }
449
- function editDistance(a, b) {
450
- const m = a.length;
451
- const n = b.length;
452
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
453
- for (let i = 0; i <= m; i++) dp[i][0] = i;
454
- for (let j = 0; j <= n; j++) dp[0][j] = j;
455
- for (let i = 1; i <= m; i++) {
456
- for (let j = 1; j <= n; j++) {
457
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
458
- dp[i][j] = Math.min(
459
- dp[i - 1][j] + 1,
460
- dp[i][j - 1] + 1,
461
- dp[i - 1][j - 1] + cost
462
- );
463
- }
464
- }
465
- return dp[m][n];
466
- }
467
- export {
468
- captureAndLearn,
469
- captureTrajectory,
470
- editDistance,
471
- extractSkill,
472
- extractTrajectory,
473
- findSimilarTrajectories,
474
- hashSignature,
475
- storeTrajectory,
476
- sweepTrajectories
477
- };