@askexenow/exe-os 0.9.289 → 0.9.290

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 (244) hide show
  1. package/dist/active-agent-L22OENGJ.js +26 -0
  2. package/dist/active-agent-SVG6F6HY.js +27 -0
  3. package/dist/agentic-ontology-3GHJHLDY.js +25 -0
  4. package/dist/backfill-metadata-HJNVBORD.js +599 -0
  5. package/dist/behaviors-ROOZS234.js +39 -0
  6. package/dist/bin/agentic-ontology-backfill.js +5 -5
  7. package/dist/bin/agentic-reflection-backfill.js +6 -6
  8. package/dist/bin/agentic-semantic-label.js +5 -5
  9. package/dist/bin/backfill-conversations.js +4 -4
  10. package/dist/bin/backfill-responses.js +4 -4
  11. package/dist/bin/backfill-vectors.js +98 -13
  12. package/dist/bin/bulk-sync-postgres.js +6 -6
  13. package/dist/bin/cc-doctor.js +4 -4
  14. package/dist/bin/cleanup-stale-review-tasks.js +9 -9
  15. package/dist/bin/cli.js +51 -15
  16. package/dist/bin/exe-agent-config.js +2 -2
  17. package/dist/bin/exe-agent.js +4 -4
  18. package/dist/bin/exe-assign.js +5 -5
  19. package/dist/bin/exe-boot.js +16 -16
  20. package/dist/bin/exe-call.js +4 -4
  21. package/dist/bin/exe-cloud.js +23 -5
  22. package/dist/bin/exe-dispatch.js +9 -9
  23. package/dist/bin/exe-doctor.js +1 -1
  24. package/dist/bin/exe-export-behaviors.js +7 -7
  25. package/dist/bin/exe-forget.js +6 -6
  26. package/dist/bin/exe-gateway.js +7 -7
  27. package/dist/bin/exe-healthcheck.js +4 -4
  28. package/dist/bin/exe-heartbeat.js +9 -9
  29. package/dist/bin/exe-kill.js +12 -12
  30. package/dist/bin/exe-launch-agent.js +16 -16
  31. package/dist/bin/exe-new-employee.js +6 -6
  32. package/dist/bin/exe-pending-messages.js +10 -10
  33. package/dist/bin/exe-pending-notifications.js +9 -9
  34. package/dist/bin/exe-pending-reviews.js +9 -9
  35. package/dist/bin/exe-rename.js +4 -4
  36. package/dist/bin/exe-review.js +11 -11
  37. package/dist/bin/exe-search.js +5 -5
  38. package/dist/bin/exe-session-cleanup.js +14 -14
  39. package/dist/bin/exe-settings.js +4 -4
  40. package/dist/bin/exe-start-codex.js +11 -11
  41. package/dist/bin/exe-start-opencode.js +8 -8
  42. package/dist/bin/exe-status.js +10 -10
  43. package/dist/bin/exe-team.js +3 -3
  44. package/dist/bin/git-sweep.js +10 -10
  45. package/dist/bin/graph-backfill.js +4 -4
  46. package/dist/bin/graph-export.js +5 -5
  47. package/dist/bin/import-history.js +7 -7
  48. package/dist/bin/install.js +6 -6
  49. package/dist/bin/intercom-check.js +4 -4
  50. package/dist/bin/mcp-sessions.js +2 -2
  51. package/dist/bin/orchestration-metrics.js +4 -4
  52. package/dist/bin/postgres-agentic-reflection-backfill.js +2 -2
  53. package/dist/bin/postgres-agentic-semantic-backfill.js +1 -1
  54. package/dist/bin/scan-tasks.js +9 -9
  55. package/dist/bin/setup.js +1 -1
  56. package/dist/bin/shard-migrate.js +4 -4
  57. package/dist/capability-cards-O6XB2AU4.js +88 -0
  58. package/dist/capacity-monitor-ZE7CFVWH.js +50 -0
  59. package/dist/catchup-brief-3NONSIMA.js +174 -0
  60. package/dist/chunk-232DHK5C.js +1119 -0
  61. package/dist/chunk-272SJ4RN.js +129 -0
  62. package/dist/chunk-4NMTGHUE.js +127 -0
  63. package/dist/chunk-5PLW3QL6.js +668 -0
  64. package/dist/chunk-66EIYAF2.js +157 -0
  65. package/dist/chunk-6IPJF5QD.js +630 -0
  66. package/dist/chunk-6NSJTOXE.js +122 -0
  67. package/dist/chunk-6TLURATK.js +4318 -0
  68. package/dist/chunk-73JAJQRY.js +85 -0
  69. package/dist/chunk-7FTKXL5A.js +286 -0
  70. package/dist/chunk-7IRQSO3F.js +735 -0
  71. package/dist/chunk-7MINWZ3J.js +214 -0
  72. package/dist/chunk-7T5PS5DG.js +14439 -0
  73. package/dist/chunk-A74WXY4S.js +227 -0
  74. package/dist/chunk-AVD5C3NG.js +197 -0
  75. package/dist/chunk-B36MRLEP.js +58 -0
  76. package/dist/chunk-B4TCZ3PS.js +373 -0
  77. package/dist/chunk-BPLEJ3EU.js +411 -0
  78. package/dist/chunk-BTDPLFGK.js +221 -0
  79. package/dist/chunk-BU45UYTK.js +185 -0
  80. package/dist/chunk-CCAA6XOZ.js +284 -0
  81. package/dist/chunk-DBQ6I6K2.js +3276 -0
  82. package/dist/chunk-DDWFHEPG.js +345 -0
  83. package/dist/chunk-DSOKTUTT.js +167 -0
  84. package/dist/chunk-ETCARC76.js +836 -0
  85. package/dist/chunk-EZHTLPOS.js +280 -0
  86. package/dist/chunk-F3DQ3HDH.js +333 -0
  87. package/dist/chunk-F6ZCUDCN.js +244 -0
  88. package/dist/chunk-FI5Q6F5S.js +382 -0
  89. package/dist/chunk-FNQZGNSG.js +1094 -0
  90. package/dist/chunk-FVKTXXKK.js +128 -0
  91. package/dist/chunk-HHR5NB6N.js +377 -0
  92. package/dist/chunk-HRZLGHT6.js +290 -0
  93. package/dist/chunk-HSSRWMVA.js +68 -0
  94. package/dist/chunk-I3NVB5MG.js +85 -0
  95. package/dist/chunk-I7Z6MK2B.js +240 -0
  96. package/dist/chunk-ID4SMRYX.js +2078 -0
  97. package/dist/chunk-JXGHDROV.js +546 -0
  98. package/dist/chunk-KQY4QIEN.js +731 -0
  99. package/dist/chunk-LRSU2ZU2.js +38 -0
  100. package/dist/chunk-MFCL4GAN.js +2113 -0
  101. package/dist/chunk-MFGMVKGM.js +150 -0
  102. package/dist/chunk-NHGBVLCD.js +210 -0
  103. package/dist/chunk-NOEBJMNN.js +33 -0
  104. package/dist/chunk-NQ2VNTGL.js +538 -0
  105. package/dist/chunk-O4PZPM6H.js +204 -0
  106. package/dist/chunk-O5OW3YGQ.js +262 -0
  107. package/dist/chunk-OJQTONDJ.js +171 -0
  108. package/dist/chunk-OKZGUHE5.js +76 -0
  109. package/dist/chunk-OOH5M36Q.js +448 -0
  110. package/dist/chunk-P5ARTZP2.js +128 -0
  111. package/dist/chunk-PKRSYS7F.js +402 -0
  112. package/dist/chunk-PQWO5D3F.js +348 -0
  113. package/dist/chunk-Q6MJIJ2O.js +1352 -0
  114. package/dist/chunk-QKDRYZ2N.js +231 -0
  115. package/dist/chunk-RAV356E6.js +30 -0
  116. package/dist/chunk-RK7EAA53.js +1157 -0
  117. package/dist/chunk-RSLVAYWS.js +192 -0
  118. package/dist/chunk-SL6WJP2Q.js +123 -0
  119. package/dist/chunk-T57DOVGE.js +97 -0
  120. package/dist/chunk-TMCKL43Q.js +181 -0
  121. package/dist/chunk-TQZABASE.js +97 -0
  122. package/dist/chunk-UBWBEY6I.js +81 -0
  123. package/dist/chunk-UP7DNYG7.js +456 -0
  124. package/dist/chunk-V5MGYIZS.js +70 -0
  125. package/dist/chunk-XCPVYQVK.js +336 -0
  126. package/dist/chunk-XWVBLZRP.js +50 -0
  127. package/dist/chunk-YBTN5F2U.js +1068 -0
  128. package/dist/chunk-Z772TGD2.js +54 -0
  129. package/dist/chunk-ZAMPIXLH.js +1350 -0
  130. package/dist/chunk-ZYEOHGU5.js +362 -0
  131. package/dist/co-activation-WJTFJOTK.js +73 -0
  132. package/dist/co-occurrence-KFP6ZS7G.js +94 -0
  133. package/dist/core-memory-DBZJ72TV.js +110 -0
  134. package/dist/crdt-sync-6DVGRMTV.js +33 -0
  135. package/dist/crm-webhook-55T4Z6XJ.js +10 -0
  136. package/dist/cto-delegation-gate-SPM6LAL2.js +279 -0
  137. package/dist/daemon-orchestration-XZLWWIV4.js +138 -0
  138. package/dist/db-backup-JHCI47JQ.js +37 -0
  139. package/dist/doc-graph-extractor-4X23NP4I.js +132 -0
  140. package/dist/dreaming-TFZDGA72.js +33 -0
  141. package/dist/exe-drift-TEM7ELNY.js +69 -0
  142. package/dist/exe-export-CRCA4T4S.js +75 -0
  143. package/dist/exe-import-UZMMWNHJ.js +78 -0
  144. package/dist/exe-key-NQQXEDUA.js +672 -0
  145. package/dist/exe-snapshot-P7PUAJTV.js +337 -0
  146. package/dist/fast-db-init-G63PRINQ.js +7 -0
  147. package/dist/gateway/index.js +8 -8
  148. package/dist/git-staleness-42TTCFDP.js +111 -0
  149. package/dist/git-task-sweep-4LW5RYYO.js +41 -0
  150. package/dist/global-procedures-BVFRWJAV.js +21 -0
  151. package/dist/graph-auto-extract-4ZA7UC6C.js +182 -0
  152. package/dist/hooks/bug-report-worker.js +11 -11
  153. package/dist/hooks/codex-stop-task-finalizer.js +11 -11
  154. package/dist/hooks/commit-complete.js +11 -11
  155. package/dist/hooks/error-recall.js +6 -6
  156. package/dist/hooks/exe-heartbeat-hook.js +3 -3
  157. package/dist/hooks/ingest.js +6 -6
  158. package/dist/hooks/instructions-loaded.js +4 -4
  159. package/dist/hooks/manifest.json +19 -19
  160. package/dist/hooks/notification.js +4 -4
  161. package/dist/hooks/post-compact.js +10 -10
  162. package/dist/hooks/post-tool-combined.js +5 -5
  163. package/dist/hooks/pre-compact.js +11 -11
  164. package/dist/hooks/pre-tool-use.js +14 -14
  165. package/dist/hooks/prompt-submit.js +21 -21
  166. package/dist/hooks/session-end.js +15 -15
  167. package/dist/hooks/session-start.js +12 -12
  168. package/dist/hooks/stop.js +14 -14
  169. package/dist/hooks/subagent-stop.js +10 -10
  170. package/dist/hooks/summary-worker.js +14 -14
  171. package/dist/index.js +17 -17
  172. package/dist/installer-CBGRTGIF.js +297 -0
  173. package/dist/installer-DGU4WZKJ.js +39 -0
  174. package/dist/installer-WTWEOSEK.js +343 -0
  175. package/dist/lib/cloud-sync.js +4 -4
  176. package/dist/lib/consolidation.js +7 -5
  177. package/dist/lib/database.js +2 -2
  178. package/dist/lib/db.js +2 -2
  179. package/dist/lib/employee-templates.js +4 -4
  180. package/dist/lib/employees.js +2 -2
  181. package/dist/lib/exe-daemon.js +64 -43
  182. package/dist/lib/hybrid-search.js +5 -5
  183. package/dist/lib/identity.js +2 -2
  184. package/dist/lib/messaging.js +9 -9
  185. package/dist/lib/reminders.js +3 -3
  186. package/dist/lib/schedules.js +5 -5
  187. package/dist/lib/session-registry.js +4 -4
  188. package/dist/lib/skill-learning.js +6 -6
  189. package/dist/lib/store.js +4 -4
  190. package/dist/lib/task-router.js +3 -3
  191. package/dist/lib/tasks.js +10 -10
  192. package/dist/lib/tmux-routing.js +8 -8
  193. package/dist/lib/token-spend.js +3 -3
  194. package/dist/license-gate-OSPA2OD7.js +16 -0
  195. package/dist/mcp/register-tools.js +55 -55
  196. package/dist/mcp/server.js +117 -73
  197. package/dist/mcp/tools/complete-reminder.js +4 -4
  198. package/dist/mcp/tools/create-reminder.js +4 -4
  199. package/dist/mcp/tools/create-task.js +12 -12
  200. package/dist/mcp/tools/deactivate-behavior.js +7 -7
  201. package/dist/mcp/tools/list-reminders.js +4 -4
  202. package/dist/mcp/tools/list-tasks.js +12 -12
  203. package/dist/mcp/tools/send-message.js +11 -11
  204. package/dist/mcp/tools/update-task.js +11 -11
  205. package/dist/mcp-http-config-OGFPLJYH.js +28 -0
  206. package/dist/memory-cards-GJ3VHKAM.js +179 -0
  207. package/dist/memory-graph-extractor-TCTCM7PZ.js +21 -0
  208. package/dist/memory-poisoning-defense-FVLGA35X.js +223 -0
  209. package/dist/memory-reflection-BYJFIFSV.js +243 -0
  210. package/dist/notifications-AQKZFSR3.js +46 -0
  211. package/dist/orchestration-events-RDSYLFXZ.js +26 -0
  212. package/dist/orchestrator-2JTJQLPG.js +34 -0
  213. package/dist/pipeline-router-HBSTKHG5.js +14 -0
  214. package/dist/plan-limits-GQENSNTG.js +27 -0
  215. package/dist/project-boot-W2LTP7WW.js +299 -0
  216. package/dist/projection-worker-ZMT5KNJJ.js +1084 -0
  217. package/dist/prospective-memory-LANRNOJX.js +231 -0
  218. package/dist/reranker-QGJO6EHO.js +19 -0
  219. package/dist/retrieval-health-JE66LJ3I.js +11 -0
  220. package/dist/review-polling-IXJ57M6Q.js +125 -0
  221. package/dist/runtime/index.js +11 -11
  222. package/dist/session-events-XKG66APL.js +37 -0
  223. package/dist/session-kill-telemetry-VTU7YBII.js +30 -0
  224. package/dist/session-scope-TQZONLZL.js +87 -0
  225. package/dist/setup-wizard-PXK6SC2D.js +12 -0
  226. package/dist/skill-refinement-Y6LLKYRL.js +158 -0
  227. package/dist/steward-gate-QV2APBFB.js +14 -0
  228. package/dist/task-enforcement-GLDD2W5D.js +505 -0
  229. package/dist/task-scope-HMPIP6XB.js +36 -0
  230. package/dist/tasks-crud-FH2SFCNQ.js +78 -0
  231. package/dist/tasks-notify-3ZW2GLCS.js +39 -0
  232. package/dist/tasks-review-XERV6KZD.js +48 -0
  233. package/dist/telemetry-upload-R77W7I7G.js +740 -0
  234. package/dist/token-budget-NA4WQAY6.js +85 -0
  235. package/dist/tool-telemetry-D4Q76LAS.js +17 -0
  236. package/dist/tui/App.js +16 -16
  237. package/dist/tui-data-NJSEIA2Q.js +259 -0
  238. package/dist/wiki-acl-RE5IR5VV.js +111 -0
  239. package/dist/worker-gate-VN2POPFL.js +21 -0
  240. package/dist/workflow-engine-D7ALMSDM.js +28 -0
  241. package/dist/worktree-6I45JV5N.js +27 -0
  242. package/dist/worktree-sweep-IMDR3XHT.js +20 -0
  243. package/package.json +1 -1
  244. package/release-notes.json +88 -88
@@ -0,0 +1,204 @@
1
+ import {
2
+ getClient
3
+ } from "./chunk-DBQ6I6K2.js";
4
+
5
+ // src/lib/pipeline-router.ts
6
+ import crypto from "crypto";
7
+ async function sinkConversationStore(msg, agentResponse, agentName) {
8
+ try {
9
+ const client = getClient();
10
+ const id = crypto.randomUUID();
11
+ const mediaJson = msg.media ? JSON.stringify(msg.media) : null;
12
+ await client.execute({
13
+ sql: `INSERT INTO conversations
14
+ (id, platform, external_id, sender_id, sender_name, sender_phone, sender_email,
15
+ recipient_id, channel_id, thread_id, reply_to_id,
16
+ content_text, content_media, agent_response, agent_name,
17
+ timestamp, ingested_at)
18
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
19
+ args: [
20
+ id,
21
+ msg.platform,
22
+ msg.messageId,
23
+ msg.senderId,
24
+ msg.senderName ?? null,
25
+ msg.senderPhone ?? null,
26
+ msg.senderEmail ?? null,
27
+ msg.accountId ?? null,
28
+ msg.channelId,
29
+ msg.threadId ?? `${msg.platform}:${msg.channelId}`,
30
+ msg.replyTo?.messageId ?? null,
31
+ msg.text ?? null,
32
+ mediaJson,
33
+ agentResponse ?? null,
34
+ agentName ?? null,
35
+ msg.timestamp,
36
+ (/* @__PURE__ */ new Date()).toISOString()
37
+ ]
38
+ });
39
+ return true;
40
+ } catch (err) {
41
+ process.stderr.write(
42
+ `[pipeline] conversation-store error: ${err instanceof Error ? err.message : String(err)}
43
+ `
44
+ );
45
+ return false;
46
+ }
47
+ }
48
+ async function sinkMemory(msg, agentResponse, agentName) {
49
+ try {
50
+ const { embed } = await import("./lib/embedder.js");
51
+ const { writeMemory, flushBatch } = await import("./lib/store.js");
52
+ const direction = agentResponse ? "conversation" : "inbound";
53
+ const rawText = [
54
+ `[${msg.platform}] ${direction} from ${msg.senderName ?? msg.senderId}`,
55
+ msg.text ? `Message: ${msg.text}` : null,
56
+ agentResponse ? `Agent (${agentName ?? "unknown"}): ${agentResponse}` : null
57
+ ].filter(Boolean).join("\n");
58
+ const vector = await embed(rawText);
59
+ await writeMemory({
60
+ id: crypto.randomUUID(),
61
+ agent_id: agentName ?? "gateway",
62
+ agent_role: "gateway",
63
+ session_id: `gateway-${msg.platform}`,
64
+ timestamp: msg.timestamp,
65
+ tool_name: `gateway-${msg.platform}`,
66
+ project_name: "exe-os",
67
+ has_error: false,
68
+ raw_text: rawText,
69
+ vector,
70
+ importance: 4,
71
+ confidence: 0.8
72
+ });
73
+ await flushBatch();
74
+ return true;
75
+ } catch (err) {
76
+ process.stderr.write(
77
+ `[pipeline] memory-sink error: ${err instanceof Error ? err.message : String(err)}
78
+ `
79
+ );
80
+ return false;
81
+ }
82
+ }
83
+ async function sinkCRM(msg, agentResponse, agentName) {
84
+ try {
85
+ const { isCRMBridgeEnabled, pushConversationToCRM, pushInboundMessageToCRM } = await import("./crm-bridge-BVTB6LZK.js");
86
+ if (!isCRMBridgeEnabled()) return false;
87
+ if (agentResponse) {
88
+ await pushConversationToCRM({
89
+ platform: msg.platform,
90
+ senderId: msg.senderId,
91
+ senderName: msg.senderName,
92
+ messageText: msg.text,
93
+ agentResponse,
94
+ agentName: agentName ?? "unknown",
95
+ timestamp: msg.timestamp,
96
+ accountId: msg.accountId
97
+ });
98
+ } else {
99
+ await pushInboundMessageToCRM({
100
+ platform: msg.platform,
101
+ senderId: msg.senderId,
102
+ senderName: msg.senderName,
103
+ messageText: msg.text,
104
+ timestamp: msg.timestamp,
105
+ accountId: msg.accountId
106
+ });
107
+ }
108
+ return true;
109
+ } catch (err) {
110
+ process.stderr.write(
111
+ `[pipeline] crm-sink error: ${err instanceof Error ? err.message : String(err)}
112
+ `
113
+ );
114
+ return false;
115
+ }
116
+ }
117
+ async function sinkWiki(msg, agentResponse) {
118
+ try {
119
+ const { createWikiClient } = await import("./wiki-client-XZ6VZTH6.js");
120
+ const client = await createWikiClient();
121
+ if (!client) return false;
122
+ const content = msg.text ?? "";
123
+ if (content.length < 50) return false;
124
+ const { chatInWorkspace } = await import("./wiki-client-XZ6VZTH6.js");
125
+ const ingestText = [
126
+ `[${msg.platform}] Message from ${msg.senderName ?? msg.senderId} (${msg.timestamp}):`,
127
+ content,
128
+ agentResponse ? `
129
+ Agent response: ${agentResponse}` : ""
130
+ ].join("\n");
131
+ await chatInWorkspace(client, "conversations", ingestText, "chat");
132
+ return true;
133
+ } catch (err) {
134
+ process.stderr.write(
135
+ `[pipeline] wiki-sink error: ${err instanceof Error ? err.message : String(err)}
136
+ `
137
+ );
138
+ return false;
139
+ }
140
+ }
141
+ async function sinkEntityExtraction(msg, agentResponse, agentName) {
142
+ try {
143
+ const { extractFromConversation } = await import("./conversation-entity-extractor-W25VJFOH.js");
144
+ const { storeExtraction } = await import("./graph-rag-4BVYONA4.js");
145
+ if ((msg.text?.length ?? 0) < 20) return false;
146
+ if (msg.isHistorical) return false;
147
+ const extraction = await extractFromConversation(msg, agentResponse, agentName);
148
+ if (extraction.entities.length === 0) return false;
149
+ const client = getClient();
150
+ const memoryId = `conv:${msg.messageId}`;
151
+ await storeExtraction(client, extraction, memoryId, msg.timestamp);
152
+ import("./conversation-wiki-populator-IMHNWKEU.js").then(
153
+ ({ populateWikiFromExtraction }) => populateWikiFromExtraction(extraction, msg, agentResponse, agentName)
154
+ ).catch((err) => {
155
+ process.stderr.write(
156
+ `[pipeline] wiki-population error: ${err instanceof Error ? err.message : String(err)}
157
+ `
158
+ );
159
+ });
160
+ return true;
161
+ } catch (err) {
162
+ process.stderr.write(
163
+ `[pipeline] entity-extraction-sink error: ${err instanceof Error ? err.message : String(err)}
164
+ `
165
+ );
166
+ return false;
167
+ }
168
+ }
169
+ async function ingest(msg, agentResponse, agentName) {
170
+ const errors = [];
171
+ const [conversationStored, memorySunk, crmSunk, wikiSunk, entityExtracted] = await Promise.all([
172
+ sinkConversationStore(msg, agentResponse, agentName).catch((e) => {
173
+ errors.push(`conversation: ${e}`);
174
+ return false;
175
+ }),
176
+ sinkMemory(msg, agentResponse, agentName).catch((e) => {
177
+ errors.push(`memory: ${e}`);
178
+ return false;
179
+ }),
180
+ sinkCRM(msg, agentResponse, agentName).catch((e) => {
181
+ errors.push(`crm: ${e}`);
182
+ return false;
183
+ }),
184
+ sinkWiki(msg, agentResponse).catch((e) => {
185
+ errors.push(`wiki: ${e}`);
186
+ return false;
187
+ }),
188
+ sinkEntityExtraction(msg, agentResponse, agentName).catch((e) => {
189
+ errors.push(`entity-extraction: ${e}`);
190
+ return false;
191
+ })
192
+ ]);
193
+ if (errors.length > 0) {
194
+ process.stderr.write(
195
+ `[pipeline] ${errors.length} sink error(s): ${errors.join("; ")}
196
+ `
197
+ );
198
+ }
199
+ return { conversationStored, memorySunk, crmSunk, wikiSunk, entityExtracted, errors };
200
+ }
201
+
202
+ export {
203
+ ingest
204
+ };
@@ -0,0 +1,262 @@
1
+ // src/lib/agentic-ontology.ts
2
+ import { createHash } from "crypto";
3
+ function stableId(...parts) {
4
+ return createHash("sha256").update(parts.map((p) => String(p ?? "")).join("::")).digest("hex").slice(0, 32);
5
+ }
6
+ function clean(text, max = 240) {
7
+ return text.replace(/\u0000/g, "").replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
8
+ }
9
+ function inferOntologyEventType(row) {
10
+ const lower = row.raw_text.toLowerCase();
11
+ if (row.has_error) return "error";
12
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published)\b/.test(lower)) return "milestone";
13
+ if (/\b(blocked|failed|error|bug|regression|broken)\b/.test(lower)) return "problem";
14
+ if (/\b(decided|decision|adr|we chose|approved|rejected)\b/.test(lower)) return "decision";
15
+ if (/\b(goal|need to|we need|want to|trying to|objective)\b/.test(lower)) return "goal_signal";
16
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) return "tool_action";
17
+ if (row.tool_name.startsWith("memory_card")) return "memory_card";
18
+ return "memory_observation";
19
+ }
20
+ function inferIntention(row) {
21
+ if (row.intent) return clean(row.intent, 220);
22
+ const text = clean(row.raw_text, 1e3);
23
+ const patterns = [
24
+ /(?:we need to|need to|let'?s|i want to|we should|goal is to|objective is to|trying to)\s+([^.!?\n]{8,220})/i,
25
+ /(?:so that|in order to)\s+([^.!?\n]{8,220})/i,
26
+ /(?:task|plan):\s*([^.!?\n]{8,220})/i
27
+ ];
28
+ for (const p of patterns) {
29
+ const m = text.match(p);
30
+ if (m?.[1]) return clean(m[1], 220);
31
+ }
32
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) {
33
+ return `${row.tool_name} during ${row.project_name}`;
34
+ }
35
+ return null;
36
+ }
37
+ function inferOutcome(row) {
38
+ if (row.outcome) return clean(row.outcome, 220);
39
+ if (row.has_error) return "error";
40
+ const lower = row.raw_text.toLowerCase();
41
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published|passed)\b/.test(lower)) return "success_signal";
42
+ if (/\b(blocked|failed|error|regression|broken|not working|could not)\b/.test(lower)) return "failure_signal";
43
+ if (/\b(warning|risk|concern|caveat)\b/.test(lower)) return "risk_signal";
44
+ return null;
45
+ }
46
+ function extractGoalCandidates(row) {
47
+ const text = clean(row.raw_text, 1600);
48
+ const patterns = [
49
+ /(?:we need to|need to|i want to|we should|goal is to|objective is to|trying to|let'?s)\s+([^.!?\n]{12,220})/gi,
50
+ /(?:success means|success criteria|so that)\s+([^.!?\n]{12,220})/gi
51
+ ];
52
+ const out = [];
53
+ for (const pattern of patterns) {
54
+ for (const m of text.matchAll(pattern)) {
55
+ const candidate = clean(m[1] ?? "", 220);
56
+ if (candidate.length >= 12 && !out.some((x) => x.toLowerCase() === candidate.toLowerCase())) out.push(candidate);
57
+ if (out.length >= 3) return out;
58
+ }
59
+ }
60
+ return out;
61
+ }
62
+ function uniq(values, max = 6) {
63
+ const out = [];
64
+ for (const value of values.map((v) => clean(v, 220)).filter(Boolean)) {
65
+ if (!out.some((x) => x.toLowerCase() === value.toLowerCase())) out.push(value);
66
+ if (out.length >= max) break;
67
+ }
68
+ return out;
69
+ }
70
+ function extractMatches(text, patterns, max = 5) {
71
+ const out = [];
72
+ for (const pattern of patterns) {
73
+ for (const match of text.matchAll(pattern)) {
74
+ const value = match[1] ?? match[0];
75
+ if (value) out.push(value);
76
+ if (out.length >= max) return uniq(out, max);
77
+ }
78
+ }
79
+ return uniq(out, max);
80
+ }
81
+ function inferSemanticLabel(row) {
82
+ const text = clean(row.raw_text, 2400);
83
+ const eventType = inferOntologyEventType(row);
84
+ const intention = inferIntention(row);
85
+ const outcome = inferOutcome(row);
86
+ const goals = extractGoalCandidates(row);
87
+ const milestones = extractMatches(text, [
88
+ /\b(?:completed|finished|fixed|resolved|shipped|deployed|published|pushed|passed)\b([^.!?\n]{0,180})/gi,
89
+ /(?:milestone|done):\s*([^.!?\n]{8,220})/gi
90
+ ]);
91
+ const problems = extractMatches(text, [
92
+ /\b(?:blocked by|failed because|bug|regression|broken|not working|error)\b([^.!?\n]{0,180})/gi,
93
+ /(?:problem|issue|risk):\s*([^.!?\n]{8,220})/gi
94
+ ]);
95
+ const decisions = extractMatches(text, [
96
+ /(?:decided|decision|adr|we chose|approved|rejected)\s+([^.!?\n]{8,220})/gi
97
+ ]);
98
+ const temporalAnchors = extractMatches(text, [
99
+ /\b(\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]+)?)\b/g,
100
+ /\b(today|yesterday|tomorrow|this week|next week|last week|morning|afternoon|tonight)\b/gi
101
+ ], 8);
102
+ const nextActions = extractMatches(text, [
103
+ /(?:next|todo|follow[- ]?up|remaining|need to)\s*:?\s*([^.!?\n]{8,220})/gi
104
+ ]);
105
+ const actors = uniq([
106
+ row.agent_id,
107
+ ...extractMatches(text, [/\b(?:agent|employee|owner|assignee)[:= ]+([a-zA-Z][a-zA-Z0-9_-]{1,40})/gi], 5)
108
+ ], 6);
109
+ const successSignals = milestones.length ? milestones : outcome === "success_signal" ? [clean(text, 180)] : [];
110
+ const failureSignals = problems.length ? problems : outcome === "failure_signal" || row.has_error ? [clean(text, 180)] : [];
111
+ const impact = successSignals.length && failureSignals.length ? "mixed" : failureSignals.length ? "negative" : successSignals.length ? "positive" : "neutral";
112
+ const signalCount = goals.length + milestones.length + problems.length + decisions.length + nextActions.length;
113
+ return {
114
+ labeler: "deterministic",
115
+ schemaVersion: 1,
116
+ eventType,
117
+ intention,
118
+ outcome,
119
+ impact,
120
+ confidence: Math.min(0.95, 0.45 + signalCount * 0.08 + (intention ? 0.1 : 0) + (outcome ? 0.1 : 0)),
121
+ goals,
122
+ milestones,
123
+ problems,
124
+ decisions,
125
+ actors,
126
+ temporalAnchors,
127
+ successSignals,
128
+ failureSignals,
129
+ nextActions,
130
+ summary: clean(text, 280)
131
+ };
132
+ }
133
+ function ontologyPayload(row) {
134
+ const semantic = inferSemanticLabel(row);
135
+ return {
136
+ tool_name: row.tool_name,
137
+ memory_version: row.version ?? null,
138
+ domain: row.domain ?? null,
139
+ trajectory: row.trajectory ? safeJson(row.trajectory) : null,
140
+ semantic
141
+ };
142
+ }
143
+ function safeJson(value) {
144
+ try {
145
+ return JSON.parse(value);
146
+ } catch {
147
+ return value.slice(0, 1e3);
148
+ }
149
+ }
150
+ async function resolveClient(client) {
151
+ if (client) return client;
152
+ const { getClient } = await import("./lib/database.js");
153
+ return getClient();
154
+ }
155
+ async function insertOntologyForMemory(row, client) {
156
+ const db = await resolveClient(client);
157
+ const occurredAt = row.timestamp;
158
+ const sequence = Number(row.version ?? 0) || Math.floor(new Date(occurredAt).getTime() / 1e3);
159
+ const eventType = inferOntologyEventType(row);
160
+ const intention = inferIntention(row);
161
+ const outcome = inferOutcome(row);
162
+ const eventId = stableId("event", row.id);
163
+ const now = (/* @__PURE__ */ new Date()).toISOString();
164
+ await db.execute({
165
+ sql: `INSERT INTO agent_sessions (id, agent_id, project_name, started_at, last_event_at, event_count, properties)
166
+ VALUES (?, ?, ?, ?, ?, 1, ?)
167
+ ON CONFLICT(id) DO UPDATE SET last_event_at = MAX(last_event_at, excluded.last_event_at),
168
+ event_count = event_count + 1`,
169
+ args: [row.session_id, row.agent_id, row.project_name, occurredAt, occurredAt, JSON.stringify({ agent_role: row.agent_role })]
170
+ });
171
+ await db.execute({
172
+ sql: `INSERT OR IGNORE INTO agent_events
173
+ (id, event_type, occurred_at, sequence_index, actor_agent_id, agent_role, project_name,
174
+ session_id, task_id, goal_id, parent_event_id, intention, outcome, evidence_memory_id,
175
+ impact, payload, created_at)
176
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`,
177
+ args: [
178
+ eventId,
179
+ eventType,
180
+ occurredAt,
181
+ sequence,
182
+ row.agent_id,
183
+ row.agent_role,
184
+ row.project_name,
185
+ row.session_id,
186
+ row.task_id ?? null,
187
+ intention,
188
+ outcome,
189
+ row.id,
190
+ row.has_error ? "negative" : outcome === "success_signal" ? "positive" : "neutral",
191
+ JSON.stringify(ontologyPayload(row)),
192
+ now
193
+ ]
194
+ });
195
+ const semantic = inferSemanticLabel(row);
196
+ await db.execute({
197
+ sql: `INSERT INTO agent_semantic_labels
198
+ (id, source_memory_id, event_id, labeler, schema_version, confidence, labels, created_at, updated_at)
199
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
200
+ ON CONFLICT(id) DO UPDATE SET confidence = excluded.confidence,
201
+ labels = excluded.labels, updated_at = excluded.updated_at`,
202
+ args: [
203
+ stableId("semantic", row.id, semantic.labeler, semantic.schemaVersion),
204
+ row.id,
205
+ eventId,
206
+ semantic.labeler,
207
+ semantic.schemaVersion,
208
+ semantic.confidence,
209
+ JSON.stringify(semantic),
210
+ now,
211
+ now
212
+ ]
213
+ });
214
+ for (const statement of extractGoalCandidates(row)) {
215
+ const goalId = stableId("goal", row.project_name, statement.toLowerCase());
216
+ await db.execute({
217
+ sql: `INSERT INTO agent_goals
218
+ (id, statement, owner_agent_id, project_name, status, priority, success_criteria,
219
+ parent_goal_id, due_at, achieved_at, supersedes_id, created_at, updated_at, source_memory_id)
220
+ VALUES (?, ?, ?, ?, 'open', 5, NULL, NULL, NULL, NULL, NULL, ?, ?, ?)
221
+ ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`,
222
+ args: [goalId, statement, row.agent_id, row.project_name, now, now, row.id]
223
+ });
224
+ await db.execute({
225
+ sql: `INSERT OR IGNORE INTO agent_goal_links
226
+ (id, goal_id, link_type, target_id, target_type, created_at)
227
+ VALUES (?, ?, 'evidence', ?, 'memory', ?)`,
228
+ args: [stableId("goal_link", goalId, row.id, "memory"), goalId, row.id, now]
229
+ });
230
+ await db.execute({
231
+ sql: `INSERT OR IGNORE INTO agent_goal_links
232
+ (id, goal_id, link_type, target_id, target_type, created_at)
233
+ VALUES (?, ?, 'event', ?, 'event', ?)`,
234
+ args: [stableId("goal_link", goalId, eventId, "event"), goalId, eventId, now]
235
+ });
236
+ }
237
+ }
238
+ async function insertOntologyForBatch(rows, client) {
239
+ const db = await resolveClient(client);
240
+ let count = 0;
241
+ for (const row of rows) {
242
+ try {
243
+ await insertOntologyForMemory(row, db);
244
+ count++;
245
+ } catch {
246
+ }
247
+ }
248
+ return count;
249
+ }
250
+
251
+ export {
252
+ stableId,
253
+ clean,
254
+ inferOntologyEventType,
255
+ inferIntention,
256
+ inferOutcome,
257
+ extractGoalCandidates,
258
+ inferSemanticLabel,
259
+ ontologyPayload,
260
+ insertOntologyForMemory,
261
+ insertOntologyForBatch
262
+ };
@@ -0,0 +1,171 @@
1
+ import {
2
+ writeMemoryViaDaemon
3
+ } from "./chunk-YMMYZXVZ.js";
4
+
5
+ // src/lib/auto-checkpoint.ts
6
+ var FILE_RE = /(?:^|\s)([\w./-]+\.(?:ts|tsx|js|jsx|json|md|yml|yaml|sql|go|py|css|scss|html|sh))(?:\b|$)/g;
7
+ var DECISION_RE = /\b(decision:|decided:|we decided|founder directive|captured in .*architecture|source of truth)\b/i;
8
+ function asString(value, fallback = "") {
9
+ if (value == null) return fallback;
10
+ return String(value);
11
+ }
12
+ function compactLine(text, max = 220) {
13
+ return text.replace(/\s+/g, " ").trim().slice(0, max);
14
+ }
15
+ function topEntries(counts, limit) {
16
+ return [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, limit).map(([name, count]) => `${name}(${count})`);
17
+ }
18
+ function buildAutoCheckpoint(input) {
19
+ const maxSamples = input.maxSamples ?? 8;
20
+ const projectCounts = /* @__PURE__ */ new Map();
21
+ const toolCounts = /* @__PURE__ */ new Map();
22
+ const files = /* @__PURE__ */ new Set();
23
+ const errors = [];
24
+ const samples = [];
25
+ const decisionTexts = [];
26
+ for (const row of input.memories) {
27
+ const tool = asString(row.tool_name, "unknown");
28
+ const project = asString(row.project_name, input.projectName || "unknown");
29
+ const raw = asString(row.raw_text);
30
+ const hasError = row.has_error === 1 || row.has_error === true;
31
+ toolCounts.set(tool, (toolCounts.get(tool) ?? 0) + 1);
32
+ projectCounts.set(project, (projectCounts.get(project) ?? 0) + 1);
33
+ if (hasError && errors.length < 5) errors.push(compactLine(raw, 180));
34
+ if (samples.length < maxSamples && raw.length > 30) {
35
+ samples.push(`[${tool}] ${compactLine(raw)}`);
36
+ }
37
+ if (DECISION_RE.test(raw) && decisionTexts.length < 5) {
38
+ decisionTexts.push(`AUTO DECISION CANDIDATE [${input.agentId}]: ${compactLine(raw, 500)}`);
39
+ }
40
+ for (const match of raw.matchAll(FILE_RE)) {
41
+ if (match[1]) files.add(match[1]);
42
+ if (files.size >= 20) break;
43
+ }
44
+ }
45
+ const taskLines = (input.tasks ?? []).slice(0, 10).map((task) => {
46
+ const status = asString(task.status, "unknown");
47
+ const priority = asString(task.priority, "?").toUpperCase();
48
+ const title = asString(task.title, "untitled");
49
+ const taskFile = asString(task.task_file);
50
+ return `- [${status}/${priority}] ${title}${taskFile ? ` (${taskFile})` : ""}`;
51
+ });
52
+ const parts = [
53
+ `CONTEXT CHECKPOINT [auto:${input.reason}]`,
54
+ `Agent: ${input.agentId} (${input.agentRole})`,
55
+ `Session: ${input.sessionId}`,
56
+ `Project: ${input.projectName}`,
57
+ `Time: ${(/* @__PURE__ */ new Date()).toISOString()}`,
58
+ "",
59
+ "## Recent Activity",
60
+ `- Memories scanned: ${input.memories.length}`,
61
+ `- Projects: ${topEntries(projectCounts, 5).join(", ") || input.projectName}`,
62
+ `- Tools: ${topEntries(toolCounts, 8).join(", ") || "none"}`
63
+ ];
64
+ if (taskLines.length > 0) {
65
+ parts.push("", "## Open / Active Tasks", ...taskLines);
66
+ }
67
+ if (files.size > 0) {
68
+ parts.push("", "## Files Mentioned", ...[...files].slice(0, 20).map((f) => `- ${f}`));
69
+ }
70
+ if (samples.length > 0) {
71
+ parts.push("", "## Important Recent Traces", ...samples.map((s) => `- ${s}`));
72
+ }
73
+ if (errors.length > 0) {
74
+ parts.push("", "## Errors / Risks", ...errors.map((e) => `- ${e}`));
75
+ }
76
+ if (decisionTexts.length > 0) {
77
+ parts.push("", "## Decision Candidates", ...decisionTexts.map((d) => `- ${d.replace(/^AUTO DECISION CANDIDATE \\[[^\\]]+\\]: /, "")}`));
78
+ }
79
+ return {
80
+ checkpointText: parts.join("\n"),
81
+ decisionTexts
82
+ };
83
+ }
84
+
85
+ // src/lib/checkpoint-orchestrator.ts
86
+ function toolNameForReason(reason) {
87
+ switch (reason) {
88
+ case "periodic":
89
+ return "auto-summary";
90
+ case "session-end":
91
+ return "SessionEnd";
92
+ case "pre-compact":
93
+ return "pre-compact-hook";
94
+ case "capacity-signal":
95
+ return "auto-checkpoint";
96
+ }
97
+ }
98
+ function importanceForReason(reason, override) {
99
+ if (override !== void 0) return override;
100
+ switch (reason) {
101
+ case "periodic":
102
+ return 7;
103
+ case "session-end":
104
+ case "pre-compact":
105
+ case "capacity-signal":
106
+ return 8;
107
+ }
108
+ }
109
+ function buildContinuityCheckpoint(input) {
110
+ const { checkpointText, decisionTexts } = buildAutoCheckpoint({
111
+ agentId: input.agentId,
112
+ agentRole: input.agentRole,
113
+ sessionId: input.sessionId,
114
+ projectName: input.projectName,
115
+ reason: input.reason,
116
+ memories: input.memories ?? [],
117
+ tasks: input.tasks ?? [],
118
+ maxSamples: input.maxSamples
119
+ });
120
+ const extra = input.extraSections?.filter((section) => section.trim().length > 0) ?? [];
121
+ return {
122
+ checkpointText: extra.length > 0 ? `${checkpointText}
123
+
124
+ ${extra.join("\n\n")}` : checkpointText,
125
+ decisionTexts
126
+ };
127
+ }
128
+ async function writeContinuityCheckpoint(input) {
129
+ const result = buildContinuityCheckpoint(input);
130
+ const now = (/* @__PURE__ */ new Date()).toISOString();
131
+ await writeMemoryViaDaemon({
132
+ raw_text: result.checkpointText,
133
+ agent_id: input.agentId,
134
+ agent_role: input.agentRole,
135
+ session_id: input.sessionId,
136
+ tool_name: toolNameForReason(input.reason),
137
+ project_name: input.projectName,
138
+ timestamp: now,
139
+ importance: importanceForReason(input.reason, input.importance),
140
+ task_id: input.taskId,
141
+ memory_type: "checkpoint"
142
+ });
143
+ const decisionLimit = input.reason === "periodic" ? 3 : 5;
144
+ for (const decisionText of result.decisionTexts.slice(0, decisionLimit)) {
145
+ await writeMemoryViaDaemon({
146
+ raw_text: decisionText,
147
+ agent_id: input.agentId,
148
+ agent_role: input.agentRole,
149
+ session_id: input.sessionId,
150
+ tool_name: "auto-decision",
151
+ project_name: input.projectName,
152
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
153
+ importance: 8,
154
+ memory_type: "decision"
155
+ });
156
+ }
157
+ return result;
158
+ }
159
+ async function checkpointActiveTask(input) {
160
+ const { writeCheckpoint } = await import("./lib/tasks.js");
161
+ await writeCheckpoint({
162
+ taskId: input.taskId,
163
+ step: input.step ?? "pre-compaction-checkpoint",
164
+ contextSummary: `Auto-checkpoint before context compaction. Task: ${input.taskTitle}. Session: ${input.sessionId}. Project: ${input.projectName}.`
165
+ });
166
+ }
167
+
168
+ export {
169
+ writeContinuityCheckpoint,
170
+ checkpointActiveTask
171
+ };