@askexenow/exe-os 0.8.1 → 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 (106) hide show
  1. package/package.json +1 -1
  2. package/dist/bin/backfill-responses.js +0 -2064
  3. package/dist/bin/backfill-vectors.js +0 -1771
  4. package/dist/bin/cleanup-stale-review-tasks.js +0 -1468
  5. package/dist/bin/cli.js +0 -21371
  6. package/dist/bin/exe-agent.js +0 -2016
  7. package/dist/bin/exe-assign.js +0 -2176
  8. package/dist/bin/exe-boot.js +0 -6332
  9. package/dist/bin/exe-call.js +0 -341
  10. package/dist/bin/exe-cloud.js +0 -861
  11. package/dist/bin/exe-dispatch.js +0 -1159
  12. package/dist/bin/exe-doctor.js +0 -1786
  13. package/dist/bin/exe-export-behaviors.js +0 -1637
  14. package/dist/bin/exe-forget.js +0 -1784
  15. package/dist/bin/exe-gateway.js +0 -8140
  16. package/dist/bin/exe-healthcheck.js +0 -207
  17. package/dist/bin/exe-heartbeat.js +0 -1778
  18. package/dist/bin/exe-kill.js +0 -1622
  19. package/dist/bin/exe-launch-agent.js +0 -1847
  20. package/dist/bin/exe-link.js +0 -192
  21. package/dist/bin/exe-new-employee.js +0 -1384
  22. package/dist/bin/exe-pending-messages.js +0 -1576
  23. package/dist/bin/exe-pending-notifications.js +0 -1450
  24. package/dist/bin/exe-pending-reviews.js +0 -1598
  25. package/dist/bin/exe-repo-drift.js +0 -95
  26. package/dist/bin/exe-review.js +0 -1742
  27. package/dist/bin/exe-search.js +0 -3116
  28. package/dist/bin/exe-session-cleanup.js +0 -3360
  29. package/dist/bin/exe-settings.js +0 -365
  30. package/dist/bin/exe-status.js +0 -1661
  31. package/dist/bin/exe-team.js +0 -1453
  32. package/dist/bin/git-sweep.js +0 -2441
  33. package/dist/bin/graph-backfill.js +0 -2111
  34. package/dist/bin/graph-export.js +0 -1747
  35. package/dist/bin/install.js +0 -661
  36. package/dist/bin/list-providers.js +0 -140
  37. package/dist/bin/scan-tasks.js +0 -2039
  38. package/dist/bin/setup.js +0 -2717
  39. package/dist/bin/shard-migrate.js +0 -1637
  40. package/dist/bin/update.js +0 -98
  41. package/dist/bin/wiki-sync.js +0 -1657
  42. package/dist/gateway/index.js +0 -9256
  43. package/dist/hooks/bug-report-worker.js +0 -2903
  44. package/dist/hooks/commit-complete.js +0 -2364
  45. package/dist/hooks/error-recall.js +0 -3327
  46. package/dist/hooks/exe-heartbeat-hook.js +0 -237
  47. package/dist/hooks/ingest-worker.js +0 -5065
  48. package/dist/hooks/ingest.js +0 -695
  49. package/dist/hooks/instructions-loaded.js +0 -2069
  50. package/dist/hooks/notification.js +0 -1915
  51. package/dist/hooks/post-compact.js +0 -1940
  52. package/dist/hooks/pre-compact.js +0 -1935
  53. package/dist/hooks/pre-tool-use.js +0 -2380
  54. package/dist/hooks/prompt-ingest-worker.js +0 -2291
  55. package/dist/hooks/prompt-submit.js +0 -5189
  56. package/dist/hooks/response-ingest-worker.js +0 -2431
  57. package/dist/hooks/session-end.js +0 -2196
  58. package/dist/hooks/session-start.js +0 -3259
  59. package/dist/hooks/stop.js +0 -2025
  60. package/dist/hooks/subagent-stop.js +0 -1915
  61. package/dist/hooks/summary-worker.js +0 -2931
  62. package/dist/index.js +0 -12327
  63. package/dist/lib/cloud-sync.js +0 -500
  64. package/dist/lib/config.js +0 -235
  65. package/dist/lib/consolidation.js +0 -481
  66. package/dist/lib/crypto.js +0 -51
  67. package/dist/lib/database.js +0 -834
  68. package/dist/lib/device-registry.js +0 -1009
  69. package/dist/lib/embedder.js +0 -645
  70. package/dist/lib/employee-templates.js +0 -570
  71. package/dist/lib/employees.js +0 -182
  72. package/dist/lib/error-detector.js +0 -156
  73. package/dist/lib/exe-daemon-client.js +0 -456
  74. package/dist/lib/exe-daemon.js +0 -8699
  75. package/dist/lib/file-grep.js +0 -215
  76. package/dist/lib/hybrid-search.js +0 -3064
  77. package/dist/lib/identity-templates.js +0 -441
  78. package/dist/lib/identity.js +0 -228
  79. package/dist/lib/keychain.js +0 -145
  80. package/dist/lib/license.js +0 -382
  81. package/dist/lib/messaging.js +0 -1389
  82. package/dist/lib/reminders.js +0 -63
  83. package/dist/lib/schedules.js +0 -1525
  84. package/dist/lib/session-registry.js +0 -52
  85. package/dist/lib/skill-learning.js +0 -488
  86. package/dist/lib/status-brief.js +0 -240
  87. package/dist/lib/store.js +0 -1740
  88. package/dist/lib/task-router.js +0 -128
  89. package/dist/lib/tasks.js +0 -2585
  90. package/dist/lib/tmux-routing.js +0 -2969
  91. package/dist/lib/tmux-status.js +0 -261
  92. package/dist/lib/tmux-transport.js +0 -83
  93. package/dist/lib/transport.js +0 -128
  94. package/dist/lib/ws-auth.js +0 -19
  95. package/dist/lib/ws-client.js +0 -160
  96. package/dist/mcp/server.js +0 -10812
  97. package/dist/mcp/tools/complete-reminder.js +0 -67
  98. package/dist/mcp/tools/create-reminder.js +0 -52
  99. package/dist/mcp/tools/create-task.js +0 -1903
  100. package/dist/mcp/tools/deactivate-behavior.js +0 -268
  101. package/dist/mcp/tools/list-reminders.js +0 -62
  102. package/dist/mcp/tools/list-tasks.js +0 -491
  103. package/dist/mcp/tools/send-message.js +0 -1395
  104. package/dist/mcp/tools/update-task.js +0 -1807
  105. package/dist/runtime/index.js +0 -7201
  106. package/dist/tui/App.js +0 -17874
@@ -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,488 +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
- autoUpdate: {
113
- checkOnBoot: true,
114
- autoInstall: false,
115
- checkIntervalMs: 24 * 60 * 60 * 1e3
116
- }
117
- };
118
- function migrateLegacyConfig(raw) {
119
- if ("r2" in raw) {
120
- process.stderr.write(
121
- "[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"
122
- );
123
- delete raw.r2;
124
- }
125
- if ("syncIntervalMs" in raw) {
126
- delete raw.syncIntervalMs;
127
- }
128
- return raw;
129
- }
130
- var CONFIG_MIGRATIONS = [
131
- {
132
- from: 0,
133
- to: 1,
134
- migrate: (cfg) => {
135
- cfg.config_version = 1;
136
- return cfg;
137
- }
138
- }
139
- ];
140
- function migrateConfig(raw) {
141
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
142
- let currentVersion = fromVersion;
143
- let migrated = false;
144
- if (currentVersion > CURRENT_CONFIG_VERSION) {
145
- return { config: raw, migrated: false, fromVersion };
146
- }
147
- for (const migration of CONFIG_MIGRATIONS) {
148
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
149
- raw = migration.migrate(raw);
150
- currentVersion = migration.to;
151
- migrated = true;
152
- }
153
- }
154
- return { config: raw, migrated, fromVersion };
155
- }
156
- function normalizeScalingRoadmap(raw) {
157
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
158
- const userRoadmap = raw.scalingRoadmap ?? {};
159
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
160
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
161
- userAuto.enabled = raw.rerankerEnabled;
162
- }
163
- raw.scalingRoadmap = {
164
- ...userRoadmap,
165
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
166
- };
167
- }
168
- function normalizeSessionLifecycle(raw) {
169
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
170
- const userSL = raw.sessionLifecycle ?? {};
171
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
172
- }
173
- function normalizeAutoUpdate(raw) {
174
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
175
- const userAU = raw.autoUpdate ?? {};
176
- raw.autoUpdate = { ...defaultAU, ...userAU };
177
- }
178
- async function loadConfig() {
179
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
180
- await mkdir(dir, { recursive: true });
181
- const configPath = path.join(dir, "config.json");
182
- if (!existsSync(configPath)) {
183
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
184
- }
185
- const raw = await readFile(configPath, "utf-8");
186
- try {
187
- let parsed = JSON.parse(raw);
188
- parsed = migrateLegacyConfig(parsed);
189
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
190
- if (migrated) {
191
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
192
- `);
193
- try {
194
- await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
195
- } catch {
196
- }
197
- }
198
- normalizeScalingRoadmap(migratedCfg);
199
- normalizeSessionLifecycle(migratedCfg);
200
- normalizeAutoUpdate(migratedCfg);
201
- const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
202
- if (config.dbPath.startsWith("~")) {
203
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
204
- }
205
- return config;
206
- } catch {
207
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
208
- }
209
- }
210
-
211
- // src/lib/skill-learning.ts
212
- var DEFAULT_SKILL_THRESHOLD = 3;
213
- async function extractTrajectory(taskId, agentId) {
214
- const client = getClient();
215
- const result = await client.execute({
216
- sql: `SELECT tool_name, raw_text
217
- FROM memories
218
- WHERE task_id = ? AND agent_id = ?
219
- ORDER BY timestamp ASC`,
220
- args: [taskId, agentId]
221
- });
222
- if (result.rows.length === 0) return [];
223
- const rawTools = result.rows.map((r) => {
224
- const toolName = String(r.tool_name);
225
- if (toolName === "Bash") {
226
- const text = String(r.raw_text);
227
- const cmdMatch = text.match(/(?:command|Command).*?[:\s]+"?(\w+)/);
228
- return cmdMatch ? `Bash:${cmdMatch[1]}` : "Bash";
229
- }
230
- return toolName;
231
- });
232
- const signature = [];
233
- for (const tool of rawTools) {
234
- if (signature.length === 0 || signature[signature.length - 1] !== tool) {
235
- signature.push(tool);
236
- }
237
- }
238
- return signature;
239
- }
240
- function hashSignature(signature) {
241
- return crypto2.createHash("sha256").update(signature.join("|")).digest("hex").slice(0, 16);
242
- }
243
- async function storeTrajectory(opts) {
244
- const client = getClient();
245
- const id = crypto2.randomUUID();
246
- const now = (/* @__PURE__ */ new Date()).toISOString();
247
- const signatureHash = hashSignature(opts.signature);
248
- await client.execute({
249
- sql: `INSERT INTO trajectories (id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at)
250
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
251
- args: [
252
- id,
253
- opts.taskId,
254
- opts.agentId,
255
- opts.projectName,
256
- opts.taskTitle,
257
- JSON.stringify(opts.signature),
258
- signatureHash,
259
- opts.signature.length,
260
- now
261
- ]
262
- });
263
- return id;
264
- }
265
- async function findSimilarTrajectories(signature, threshold = DEFAULT_SKILL_THRESHOLD) {
266
- const client = getClient();
267
- const hash = hashSignature(signature);
268
- const result = await client.execute({
269
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
270
- FROM trajectories
271
- WHERE signature_hash = ?
272
- ORDER BY created_at DESC
273
- LIMIT 20`,
274
- args: [hash]
275
- });
276
- const mapRow = (r) => ({
277
- id: String(r.id),
278
- taskId: String(r.task_id),
279
- agentId: String(r.agent_id),
280
- projectName: String(r.project_name),
281
- taskTitle: String(r.task_title),
282
- signature: JSON.parse(String(r.signature)),
283
- signatureHash: String(r.signature_hash),
284
- toolCount: Number(r.tool_count),
285
- skillId: r.skill_id ? String(r.skill_id) : null,
286
- createdAt: String(r.created_at)
287
- });
288
- const matches = result.rows.map(mapRow);
289
- if (matches.length >= threshold) return matches;
290
- const nearResult = await client.execute({
291
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, skill_id, created_at
292
- FROM trajectories
293
- WHERE tool_count BETWEEN ? AND ?
294
- AND signature_hash != ?
295
- ORDER BY created_at DESC
296
- LIMIT 50`,
297
- args: [
298
- Math.max(1, signature.length - 3),
299
- signature.length + 3,
300
- hash
301
- ]
302
- });
303
- for (const r of nearResult.rows) {
304
- const candidateSig = JSON.parse(String(r.signature));
305
- if (editDistance(signature, candidateSig) <= 2) {
306
- matches.push(mapRow(r));
307
- }
308
- }
309
- return matches;
310
- }
311
- async function captureTrajectory(opts) {
312
- const signature = await extractTrajectory(opts.taskId, opts.agentId);
313
- if (signature.length < 3) {
314
- return { trajectoryId: "", similarCount: 0, similar: [] };
315
- }
316
- const trajectoryId = await storeTrajectory({
317
- taskId: opts.taskId,
318
- agentId: opts.agentId,
319
- projectName: opts.projectName,
320
- taskTitle: opts.taskTitle,
321
- signature
322
- });
323
- const similar = await findSimilarTrajectories(
324
- signature,
325
- opts.skillThreshold ?? DEFAULT_SKILL_THRESHOLD
326
- );
327
- return { trajectoryId, similarCount: similar.length, similar };
328
- }
329
- function buildExtractionPrompt(trajectories) {
330
- const items = trajectories.map((t, i) => {
331
- const sig = t.signature.join(" \u2192 ");
332
- return `Task ${i + 1}: "${t.taskTitle}" (${t.agentId}, ${t.projectName}) \u2014 ${t.toolCount} tool calls
333
- Signature: ${sig}`;
334
- }).join("\n\n");
335
- return `You are analyzing ${trajectories.length} completed tasks that followed similar procedures:
336
-
337
- ${items}
338
-
339
- Extract the reusable procedure. Format your response EXACTLY like this:
340
-
341
- SKILL: {name \u2014 short, descriptive}
342
- TRIGGER: {when to use this \u2014 one sentence}
343
- STEPS:
344
- 1. ...
345
- 2. ...
346
- PITFALLS: {common mistakes to avoid}
347
-
348
- Be specific and actionable. Include tool names, file patterns, and concrete commands where applicable.`;
349
- }
350
- async function extractSkill(trajectories, model) {
351
- if (trajectories.length === 0) return null;
352
- const config = await loadConfig();
353
- const skillModel = model ?? config.skillModel;
354
- const Anthropic = (await import("@anthropic-ai/sdk")).default;
355
- const client = new Anthropic();
356
- const prompt = buildExtractionPrompt(trajectories);
357
- const response = await client.messages.create({
358
- model: skillModel,
359
- max_tokens: 500,
360
- messages: [{ role: "user", content: prompt }]
361
- });
362
- const textBlock = response.content.find((b) => b.type === "text");
363
- const skillText = textBlock?.text;
364
- if (!skillText) return null;
365
- const agentId = trajectories[0].agentId;
366
- const projectName = trajectories[0].projectName;
367
- const skillId = await storeBehavior({
368
- agentId,
369
- content: skillText,
370
- domain: "skill",
371
- projectName
372
- });
373
- const dbClient = getClient();
374
- for (const t of trajectories) {
375
- await dbClient.execute({
376
- sql: "UPDATE trajectories SET skill_id = ? WHERE id = ?",
377
- args: [skillId, t.id]
378
- });
379
- }
380
- process.stderr.write(
381
- `[skill-learning] Skill extracted from ${trajectories.length} trajectories \u2192 behavior ${skillId}
382
- `
383
- );
384
- return skillId;
385
- }
386
- async function captureAndLearn(opts) {
387
- try {
388
- const config = await loadConfig();
389
- if (!config.skillLearning) return;
390
- const { trajectoryId, similarCount, similar } = await captureTrajectory({
391
- ...opts,
392
- skillThreshold: config.skillThreshold
393
- });
394
- if (!trajectoryId) return;
395
- if (similarCount >= config.skillThreshold) {
396
- const unprocessed = similar.filter((t) => !t.skillId);
397
- if (unprocessed.length >= config.skillThreshold) {
398
- extractSkill(unprocessed, config.skillModel).catch((err) => {
399
- process.stderr.write(
400
- `[skill-learning] Extraction failed: ${err instanceof Error ? err.message : String(err)}
401
- `
402
- );
403
- });
404
- }
405
- }
406
- } catch (err) {
407
- process.stderr.write(
408
- `[skill-learning] captureAndLearn failed: ${err instanceof Error ? err.message : String(err)}
409
- `
410
- );
411
- }
412
- }
413
- async function sweepTrajectories(threshold, model) {
414
- const config = await loadConfig();
415
- if (!config.skillLearning) return { clustersProcessed: 0, skillsExtracted: 0 };
416
- const t = threshold ?? config.skillThreshold;
417
- const client = getClient();
418
- const result = await client.execute({
419
- sql: `SELECT signature_hash, COUNT(*) as cnt
420
- FROM trajectories
421
- WHERE skill_id IS NULL
422
- GROUP BY signature_hash
423
- HAVING cnt >= ?
424
- ORDER BY cnt DESC
425
- LIMIT 10`,
426
- args: [t]
427
- });
428
- let clustersProcessed = 0;
429
- let skillsExtracted = 0;
430
- for (const row of result.rows) {
431
- const hash = String(row.signature_hash);
432
- const trajResult = await client.execute({
433
- sql: `SELECT id, task_id, agent_id, project_name, task_title, signature, signature_hash, tool_count, created_at
434
- FROM trajectories
435
- WHERE signature_hash = ? AND skill_id IS NULL
436
- ORDER BY created_at DESC
437
- LIMIT 10`,
438
- args: [hash]
439
- });
440
- const trajectories = trajResult.rows.map((r) => ({
441
- id: String(r.id),
442
- taskId: String(r.task_id),
443
- agentId: String(r.agent_id),
444
- projectName: String(r.project_name),
445
- taskTitle: String(r.task_title),
446
- signature: JSON.parse(String(r.signature)),
447
- signatureHash: String(r.signature_hash),
448
- toolCount: Number(r.tool_count),
449
- skillId: null,
450
- createdAt: String(r.created_at)
451
- }));
452
- if (trajectories.length >= t) {
453
- clustersProcessed++;
454
- const skillId = await extractSkill(trajectories, model ?? config.skillModel);
455
- if (skillId) skillsExtracted++;
456
- }
457
- }
458
- return { clustersProcessed, skillsExtracted };
459
- }
460
- function editDistance(a, b) {
461
- const m = a.length;
462
- const n = b.length;
463
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
464
- for (let i = 0; i <= m; i++) dp[i][0] = i;
465
- for (let j = 0; j <= n; j++) dp[0][j] = j;
466
- for (let i = 1; i <= m; i++) {
467
- for (let j = 1; j <= n; j++) {
468
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
469
- dp[i][j] = Math.min(
470
- dp[i - 1][j] + 1,
471
- dp[i][j - 1] + 1,
472
- dp[i - 1][j - 1] + cost
473
- );
474
- }
475
- }
476
- return dp[m][n];
477
- }
478
- export {
479
- captureAndLearn,
480
- captureTrajectory,
481
- editDistance,
482
- extractSkill,
483
- extractTrajectory,
484
- findSimilarTrajectories,
485
- hashSignature,
486
- storeTrajectory,
487
- sweepTrajectories
488
- };