ruflo 3.6.27 → 3.6.29
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.
- package/package.json +1 -1
- package/src/ruvocal/.claude-flow/daemon-state.json +135 -0
- package/src/ruvocal/.claude-flow/data/pending-insights.jsonl +0 -25
- package/src/ruvocal/.claude-flow/data/ranked-context.json +5 -0
- package/src/ruvocal/.claude-flow/logs/daemon.log +31 -0
- package/src/ruvocal/.claude-flow/logs/headless/audit_1777949411822_juxau0_prompt.log +989 -0
- package/src/ruvocal/.claude-flow/logs/headless/audit_1777949411822_juxau0_result.log +67 -0
- package/src/ruvocal/.claude-flow/logs/headless/audit_1777950042278_jvj5xq_prompt.log +989 -0
- package/src/ruvocal/.claude-flow/logs/headless/audit_1777950042278_jvj5xq_result.log +93 -0
- package/src/ruvocal/.claude-flow/logs/headless/optimize_1777949531823_yt5yc2_prompt.log +1498 -0
- package/src/ruvocal/.claude-flow/logs/headless/optimize_1777949531823_yt5yc2_result.log +93 -0
- package/src/ruvocal/.claude-flow/logs/headless/testgaps_1777949771821_elw1j4_prompt.log +1498 -0
- package/src/ruvocal/.claude-flow/logs/headless/testgaps_1777949771821_elw1j4_result.log +100 -0
- package/src/ruvocal/.claude-flow/metrics/codebase-map.json +11 -0
- package/src/ruvocal/.claude-flow/metrics/consolidation.json +6 -0
- package/src/ruvocal/.claude-flow/sessions/current.json +13 -0
- package/src/ruvocal/.swarm/attestation.db +0 -0
- package/src/ruvocal/.swarm/hnsw.index +0 -0
- package/src/ruvocal/.swarm/hnsw.metadata.json +1 -0
- package/src/ruvocal/.swarm/memory.db +0 -0
- package/src/ruvocal/.swarm/schema.sql +305 -0
- package/src/ruvocal/src/lib/components/chat/ChatWindow.svelte +8 -8
- package/src/ruvocal/src/lib/server/mcp/clientPool.spec.ts +175 -0
- package/src/ruvocal/src/lib/server/mcp/clientPool.ts +0 -0
- package/src/ruvocal/src/lib/server/textGeneration/index.ts +1 -0
- package/src/ruvocal/src/lib/server/textGeneration/mcp/runMcpFlow.ts +10 -1
- package/src/ruvocal/src/lib/server/textGeneration/types.ts +3 -1
- package/src/ruvocal/src/routes/api/v2/user/settings/+server.ts +7 -0
- package/src/ruvocal/src/routes/conversation/[id]/+page.svelte +4 -0
- package/src/ruvocal/src/routes/conversation/[id]/+server.ts +4 -0
- package/src/ruvocal/src/routes/settings/(nav)/+server.ts +6 -0
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
[2026-05-05T02:53:25.860Z] RESULT
|
|
2
|
+
============================================================
|
|
3
|
+
{
|
|
4
|
+
"success": true,
|
|
5
|
+
"output": "I'll analyze the provided codebase snippets for the performance issues you listed.\n\n## Performance Analysis\n\n---\n\n### 1. N+1 Query Patterns\n\n**`src/lib/migrations/migrations.ts` — `Database.getInstance()` called twice per migration in a loop**\n\n```typescript\n// CURRENT: awaits getInstance() twice per loop iteration\nfor (const migration of migrations) {\n await (await Database.getInstance()).getCollections().migrationResults.updateOne(...); // call 1\n // ...\n await (await Database.getInstance()).getCollections().migrationResults.updateOne(...); // call 2\n}\n\n// FIX: hoist outside the loop\nconst db = await Database.getInstance();\nconst results = db.getCollections().migrationResults;\n\nfor (const migration of migrations) {\n await results.updateOne(...); // set \"ongoing\"\n // ...\n await results.updateOne(...); // set \"success\"/\"failure\"\n}\n```\n\n**`src/lib/jobs/refresh-conversation-stats.ts` — `getLastComputationTime()` hits DB on every stats check**\n\n```typescript\n// CURRENT: every shouldComputeStats() call issues a DB query\nasync function getLastComputationTime(): Promise<Date> {\n const lastStats = await collections.conversationStats.findOne({}, { sort: { \"date.at\": -1 } });\n return lastStats?.date?.at || new Date(0);\n}\n\n// FIX: cache in memory with TTL\nlet cachedLastComputed: Date | null = null;\nlet cacheExpiry = 0;\n\nasync function getLastComputationTime(): Promise<Date> {\n if (cachedLastComputed && Date.now() < cacheExpiry) return cachedLastComputed;\n const lastStats = await collections.conversationStats.findOne({}, { sort: { \"date.at\": -1 } });\n cachedLastComputed = lastStats?.date?.at || new Date(0);\n cacheExpiry = Date.now() + 60_000; // 1-minute TTL\n return cachedLastComputed;\n}\n```\n\n---\n\n### 2. Unnecessary Re-renders (Svelte reactivity)\n\n**`src/lib/actions/snapScrollToBottom.ts` — Double `scrollToBottom()` per RAF cycle causes redundant layout thrash**\n\n```typescript\n// CURRENT: scrolls twice per settle cycle, each triggers layout\nconst settleScrollAfterLayout = async () => {\n await raf();\n if (!userScrolling && !isDetached) scrollToBottom(); // reflow #1\n await raf();\n if (!userScrolling && !isDetached) scrollToBottom(); // reflow #2\n};\n\n// FIX: single scroll after two frames is sufficient; the second raf\n// just confirms layout is stable — no need to scroll twice\nconst settleScrollAfterLayout = async () => {\n await raf();\n await raf(); // let layout settle\n if (!userScrolling && !isDetached) scrollToBottom();\n};\n```\n\n**`src/lib/actions/snapScrollToBottom.ts` — `distanceFromBottom()` forces layout reflow each call**\n\nEach read of `scrollHeight`, `scrollTop`, and `clientHeight` can force a synchronous layout. `isAtBottom()` calls `distanceFromBottom()`, and both are called from multiple event handlers.\n\n```typescript\n// FIX: batch reads into a single function and cache within the same event tick\nconst getScrollState = () => {\n const { scrollHeight, scrollTop, clientHeight } = node;\n return { scrollHeight, scrollTop, clientHeight, distance: scrollHeight - scrollTop - clientHeight };\n};\n\nconst isAtBottom = () => getScrollState().distance <= BOTTOM_THRESHOLD;\n```\n\n---\n\n### 3. Caching Opportunities\n\n**`src/lib/buildPrompt.ts` — prompt truncation re-splits the full rendered string**\n\nThe word-split truncation is O(n) over the entire rendered prompt and allocates a large temporary array:\n\n```typescript\n// CURRENT: splits entire prompt into words just to slice the tail\n.split(\" \")\n.slice(-(model.parameters?.truncate ?? 0))\n.join(\" \")\n\n// FIX: character-budget truncation avoids the full-string allocation\n// (word count ≠ token count anyway, so precision isn't gained)\nconst truncateWords = model.parameters?.truncate ?? 0;\nconst prompt = rendered;\nif (truncateWords > 0) {\n // Scan from the end to find the Nth-from-last word boundary\n let words = 0;\n let i = prompt.length;\n while (i > 0 && words < truncateWords) {\n if (prompt[--i] === \" \") words++;\n }\n return words >= truncateWords ? prompt.slice(i + 1) : prompt;\n}\nreturn prompt;\n```\n\n**`src/lib/APIClient.ts` — `useAPIClient()` rebuilds the full endpoint tree on every call**\n\n```typescript\n// CURRENT: new URL objects + endpoint closures created every invocation\nexport function useAPIClient({ fetch, origin } = {}) {\n const baseUrl = browser ? `${window.location.origin}...` : `${origin}...`;\n return { conversations: ..., user: ..., models: ... };\n}\n\n// FIX: memoize by (fetch, origin) key in a WeakMap/Map when called from\n// a stable reactive context, or extract the base-URL computation:\nconst resolveBaseUrl = (origin?: string) =>\n browser\n ? `${window.location.origin}${base}/api/v2`\n : `${origin ?? \"http://localhost:5173\"}${base}/api/v2`;\n```\n\n---\n\n### 4. Memory Leaks\n\n**`src/lib/migrations/migrations.ts` — `setInterval` not cleaned up on exception**\n\nIf `migration.up()` throws and the `catch` block re-throws (it currently doesn't, but might in future), `clearInterval` is never called:\n\n```typescript\n// CURRENT: clearInterval only called at the happy-path end\nconst refreshInterval = setInterval(...);\ntry {\n result = await migration.up(...);\n} catch (e) { ... }\nclearInterval(refreshInterval); // not reached on uncaught throw\n\n// FIX: use try/finally\nconst refreshInterval = setInterval(...);\ntry {\n for (const migration of migrations) { ... }\n} finally {\n clearInterval(refreshInterval);\n await releaseLock(Semaphores.MIGRATION, lockId);\n}\n```\n\n**`src/lib/actions/snapScrollToBottom.ts` — `userScrollTimeout` may fire after action is destroyed**\n\nThe truncated file likely has a `destroy()` — verify it calls `clearUserScrollTimeout()`:\n\n```typescript\nreturn {\n update(newDep: MaybeScrollDependency) { ... },\n destroy() {\n clearUserScrollTimeout(); // ← required\n resizeObserver?.disconnect();\n intersectionObserver?.disconnect();\n sentinel?.remove();\n },\n};\n```\n\nWithout `clearUserScrollTimeout()` in `destroy()`, the debounced handler fires after the node is gone and accesses `node.scrollHeight`, which may reference a detached element.\n\n---\n\n### 5. Redundant Computations\n\n**`src/lib/buildPrompt.ts` — `filteredMessages` mutates the original input**\n\nThis is both a bug and a source of unexpected reactive side effects in Svelte:\n\n```typescript\n// CURRENT: not a copy — mutates the caller's array element\nconst filteredMessages = messages;\nif (filteredMessages[0].from === \"system\" && preprompt) {\n filteredMessages[0].content = preprompt; // mutates messages[0]!\n}\n\n// FIX: shallow clone the first element to avoid mutating the input\nconst filteredMessages = messages.map((m, i) =>\n i === 0 && m.from === \"system\" && preprompt ? { ...m, content: preprompt } : m\n);\n```\n\n**`src/lib/jobs/refresh-conversation-stats.ts` — `computeAllStats()` fires six parallel DB aggregations**\n\nAll six `computeStats()` calls fire simultaneously without coordination, creating a spike of six heavy aggregation pipelines at once:\n\n```typescript\n// CURRENT: all six fire simultaneously\nexport async function computeAllStats() {\n for (const span of [\"day\", \"week\", \"month\"] as const) {\n computeStats({ dateField: \"updatedAt\", type: \"conversation\", span }).catch(...);\n computeStats({ dateField: \"createdAt\", type: \"conversation\", span }).catch(...);\n computeStats({ dateField: \"createdAt\", type: \"message\", span }).catch(...);\n }\n}\n\n// FIX: run with controlled concurrency (e.g. 2 at a time)\nasync function computeAllStats() {\n const jobs = ([\"day\", \"week\", \"month\"] as const).flatMap((span) => [\n { dateField: \"updatedAt\" as const, type: \"conversation\" as const, span },\n { dateField: \"createdAt\" as const, type: \"conversation\" as const, span },\n { dateField: \"createdAt\" as const, type: \"message\" as const, span },\n ]);\n // process in pairs to avoid hammering MongoDB\n for (let i = 0; i < jobs.length; i += 2) {\n await Promise.all(\n jobs.slice(i, i + 2).map((j) => computeStats(j).catch((e) => logger.error(e)))\n );\n }\n}\n```\n\n---\n\n### Summary Table\n\n| Issue | File | Impact | Fix Type |\n|---|---|---|---|\n| `Database.getInstance()` in loop | `migrations.ts` | Extra `await` overhead per migration | Hoist outside loop |\n| DB query per stats check | `refresh-conversation-stats.ts` | Repeated DB roundtrips | In-memory TTL cache |\n| Double scroll-to-bottom per RAF | `snapScrollToBottom.ts` | Redundant layout reflows | Remove second scroll |\n| Input mutation in `buildPrompt` | `buildPrompt.ts` | Reactive side effects / bugs | Clone before mutate |\n| `setInterval` not in `finally` | `migrations.ts` | Potential interval leak | `try/finally` |\n| Parallel DB aggregation spike | `refresh-conversation-stats.ts` | MongoDB load spike | Concurrency limit |\n| Full-string word-split for truncation | `buildPrompt.ts` | O(n) array allocation | Scan from end |\n",
|
|
6
|
+
"parsedOutput": {
|
|
7
|
+
"sections": [
|
|
8
|
+
{
|
|
9
|
+
"title": "Performance Analysis",
|
|
10
|
+
"content": "\n---\n\n",
|
|
11
|
+
"level": 2
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
"title": "1. N+1 Query Patterns",
|
|
15
|
+
"content": "\n**`src/lib/migrations/migrations.ts` — `Database.getInstance()` called twice per migration in a loop**\n\n```typescript\n// CURRENT: awaits getInstance() twice per loop iteration\nfor (const migration of migrations) {\n await (await Database.getInstance()).getCollections().migrationResults.updateOne(...); // call 1\n // ...\n await (await Database.getInstance()).getCollections().migrationResults.updateOne(...); // call 2\n}\n\n// FIX: hoist outside the loop\nconst db = await Database.getInstance();\nconst results = db.getCollections().migrationResults;\n\nfor (const migration of migrations) {\n await results.updateOne(...); // set \"ongoing\"\n // ...\n await results.updateOne(...); // set \"success\"/\"failure\"\n}\n```\n\n**`src/lib/jobs/refresh-conversation-stats.ts` — `getLastComputationTime()` hits DB on every stats check**\n\n```typescript\n// CURRENT: every shouldComputeStats() call issues a DB query\nasync function getLastComputationTime(): Promise<Date> {\n const lastStats = await collections.conversationStats.findOne({}, { sort: { \"date.at\": -1 } });\n return lastStats?.date?.at || new Date(0);\n}\n\n// FIX: cache in memory with TTL\nlet cachedLastComputed: Date | null = null;\nlet cacheExpiry = 0;\n\nasync function getLastComputationTime(): Promise<Date> {\n if (cachedLastComputed && Date.now() < cacheExpiry) return cachedLastComputed;\n const lastStats = await collections.conversationStats.findOne({}, { sort: { \"date.at\": -1 } });\n cachedLastComputed = lastStats?.date?.at || new Date(0);\n cacheExpiry = Date.now() + 60_000; // 1-minute TTL\n return cachedLastComputed;\n}\n```\n\n---\n\n",
|
|
16
|
+
"level": 3
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"title": "2. Unnecessary Re-renders (Svelte reactivity)",
|
|
20
|
+
"content": "\n**`src/lib/actions/snapScrollToBottom.ts` — Double `scrollToBottom()` per RAF cycle causes redundant layout thrash**\n\n```typescript\n// CURRENT: scrolls twice per settle cycle, each triggers layout\nconst settleScrollAfterLayout = async () => {\n await raf();\n if (!userScrolling && !isDetached) scrollToBottom(); // reflow #1\n await raf();\n if (!userScrolling && !isDetached) scrollToBottom(); // reflow #2\n};\n\n// FIX: single scroll after two frames is sufficient; the second raf\n// just confirms layout is stable — no need to scroll twice\nconst settleScrollAfterLayout = async () => {\n await raf();\n await raf(); // let layout settle\n if (!userScrolling && !isDetached) scrollToBottom();\n};\n```\n\n**`src/lib/actions/snapScrollToBottom.ts` — `distanceFromBottom()` forces layout reflow each call**\n\nEach read of `scrollHeight`, `scrollTop`, and `clientHeight` can force a synchronous layout. `isAtBottom()` calls `distanceFromBottom()`, and both are called from multiple event handlers.\n\n```typescript\n// FIX: batch reads into a single function and cache within the same event tick\nconst getScrollState = () => {\n const { scrollHeight, scrollTop, clientHeight } = node;\n return { scrollHeight, scrollTop, clientHeight, distance: scrollHeight - scrollTop - clientHeight };\n};\n\nconst isAtBottom = () => getScrollState().distance <= BOTTOM_THRESHOLD;\n```\n\n---\n\n",
|
|
21
|
+
"level": 3
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"title": "3. Caching Opportunities",
|
|
25
|
+
"content": "\n**`src/lib/buildPrompt.ts` — prompt truncation re-splits the full rendered string**\n\nThe word-split truncation is O(n) over the entire rendered prompt and allocates a large temporary array:\n\n```typescript\n// CURRENT: splits entire prompt into words just to slice the tail\n.split(\" \")\n.slice(-(model.parameters?.truncate ?? 0))\n.join(\" \")\n\n// FIX: character-budget truncation avoids the full-string allocation\n// (word count ≠ token count anyway, so precision isn't gained)\nconst truncateWords = model.parameters?.truncate ?? 0;\nconst prompt = rendered;\nif (truncateWords > 0) {\n // Scan from the end to find the Nth-from-last word boundary\n let words = 0;\n let i = prompt.length;\n while (i > 0 && words < truncateWords) {\n if (prompt[--i] === \" \") words++;\n }\n return words >= truncateWords ? prompt.slice(i + 1) : prompt;\n}\nreturn prompt;\n```\n\n**`src/lib/APIClient.ts` — `useAPIClient()` rebuilds the full endpoint tree on every call**\n\n```typescript\n// CURRENT: new URL objects + endpoint closures created every invocation\nexport function useAPIClient({ fetch, origin } = {}) {\n const baseUrl = browser ? `${window.location.origin}...` : `${origin}...`;\n return { conversations: ..., user: ..., models: ... };\n}\n\n// FIX: memoize by (fetch, origin) key in a WeakMap/Map when called from\n// a stable reactive context, or extract the base-URL computation:\nconst resolveBaseUrl = (origin?: string) =>\n browser\n ? `${window.location.origin}${base}/api/v2`\n : `${origin ?? \"http://localhost:5173\"}${base}/api/v2`;\n```\n\n---\n\n",
|
|
26
|
+
"level": 3
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
"title": "4. Memory Leaks",
|
|
30
|
+
"content": "\n**`src/lib/migrations/migrations.ts` — `setInterval` not cleaned up on exception**\n\nIf `migration.up()` throws and the `catch` block re-throws (it currently doesn't, but might in future), `clearInterval` is never called:\n\n```typescript\n// CURRENT: clearInterval only called at the happy-path end\nconst refreshInterval = setInterval(...);\ntry {\n result = await migration.up(...);\n} catch (e) { ... }\nclearInterval(refreshInterval); // not reached on uncaught throw\n\n// FIX: use try/finally\nconst refreshInterval = setInterval(...);\ntry {\n for (const migration of migrations) { ... }\n} finally {\n clearInterval(refreshInterval);\n await releaseLock(Semaphores.MIGRATION, lockId);\n}\n```\n\n**`src/lib/actions/snapScrollToBottom.ts` — `userScrollTimeout` may fire after action is destroyed**\n\nThe truncated file likely has a `destroy()` — verify it calls `clearUserScrollTimeout()`:\n\n```typescript\nreturn {\n update(newDep: MaybeScrollDependency) { ... },\n destroy() {\n clearUserScrollTimeout(); // ← required\n resizeObserver?.disconnect();\n intersectionObserver?.disconnect();\n sentinel?.remove();\n },\n};\n```\n\nWithout `clearUserScrollTimeout()` in `destroy()`, the debounced handler fires after the node is gone and accesses `node.scrollHeight`, which may reference a detached element.\n\n---\n\n",
|
|
31
|
+
"level": 3
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"title": "5. Redundant Computations",
|
|
35
|
+
"content": "\n**`src/lib/buildPrompt.ts` — `filteredMessages` mutates the original input**\n\nThis is both a bug and a source of unexpected reactive side effects in Svelte:\n\n```typescript\n// CURRENT: not a copy — mutates the caller's array element\nconst filteredMessages = messages;\nif (filteredMessages[0].from === \"system\" && preprompt) {\n filteredMessages[0].content = preprompt; // mutates messages[0]!\n}\n\n// FIX: shallow clone the first element to avoid mutating the input\nconst filteredMessages = messages.map((m, i) =>\n i === 0 && m.from === \"system\" && preprompt ? { ...m, content: preprompt } : m\n);\n```\n\n**`src/lib/jobs/refresh-conversation-stats.ts` — `computeAllStats()` fires six parallel DB aggregations**\n\nAll six `computeStats()` calls fire simultaneously without coordination, creating a spike of six heavy aggregation pipelines at once:\n\n```typescript\n// CURRENT: all six fire simultaneously\nexport async function computeAllStats() {\n for (const span of [\"day\", \"week\", \"month\"] as const) {\n computeStats({ dateField: \"updatedAt\", type: \"conversation\", span }).catch(...);\n computeStats({ dateField: \"createdAt\", type: \"conversation\", span }).catch(...);\n computeStats({ dateField: \"createdAt\", type: \"message\", span }).catch(...);\n }\n}\n\n// FIX: run with controlled concurrency (e.g. 2 at a time)\nasync function computeAllStats() {\n const jobs = ([\"day\", \"week\", \"month\"] as const).flatMap((span) => [\n { dateField: \"updatedAt\" as const, type: \"conversation\" as const, span },\n { dateField: \"createdAt\" as const, type: \"conversation\" as const, span },\n { dateField: \"createdAt\" as const, type: \"message\" as const, span },\n ]);\n // process in pairs to avoid hammering MongoDB\n for (let i = 0; i < jobs.length; i += 2) {\n await Promise.all(\n jobs.slice(i, i + 2).map((j) => computeStats(j).catch((e) => logger.error(e)))\n );\n }\n}\n```\n\n---\n\n",
|
|
36
|
+
"level": 3
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
"title": "Summary Table",
|
|
40
|
+
"content": "| Issue | File | Impact | Fix Type |\n|---|---|---|---|\n| `Database.getInstance()` in loop | `migrations.ts` | Extra `await` overhead per migration | Hoist outside loop |\n| DB query per stats check | `refresh-conversation-stats.ts` | Repeated DB roundtrips | In-memory TTL cache |\n| Double scroll-to-bottom per RAF | `snapScrollToBottom.ts` | Redundant layout reflows | Remove second scroll |\n| Input mutation in `buildPrompt` | `buildPrompt.ts` | Reactive side effects / bugs | Clone before mutate |\n| `setInterval` not in `finally` | `migrations.ts` | Potential interval leak | `try/finally` |\n| Parallel DB aggregation spike | `refresh-conversation-stats.ts` | MongoDB load spike | Concurrency limit |\n| Full-string word-split for truncation | `buildPrompt.ts` | O(n) array allocation | Scan from end |",
|
|
41
|
+
"level": 3
|
|
42
|
+
}
|
|
43
|
+
],
|
|
44
|
+
"codeBlocks": [
|
|
45
|
+
{
|
|
46
|
+
"language": "typescript",
|
|
47
|
+
"code": "// CURRENT: awaits getInstance() twice per loop iteration\nfor (const migration of migrations) {\n await (await Database.getInstance()).getCollections().migrationResults.updateOne(...); // call 1\n // ...\n await (await Database.getInstance()).getCollections().migrationResults.updateOne(...); // call 2\n}\n\n// FIX: hoist outside the loop\nconst db = await Database.getInstance();\nconst results = db.getCollections().migrationResults;\n\nfor (const migration of migrations) {\n await results.updateOne(...); // set \"ongoing\"\n // ...\n await results.updateOne(...); // set \"success\"/\"failure\"\n}"
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"language": "typescript",
|
|
51
|
+
"code": "// CURRENT: every shouldComputeStats() call issues a DB query\nasync function getLastComputationTime(): Promise<Date> {\n const lastStats = await collections.conversationStats.findOne({}, { sort: { \"date.at\": -1 } });\n return lastStats?.date?.at || new Date(0);\n}\n\n// FIX: cache in memory with TTL\nlet cachedLastComputed: Date | null = null;\nlet cacheExpiry = 0;\n\nasync function getLastComputationTime(): Promise<Date> {\n if (cachedLastComputed && Date.now() < cacheExpiry) return cachedLastComputed;\n const lastStats = await collections.conversationStats.findOne({}, { sort: { \"date.at\": -1 } });\n cachedLastComputed = lastStats?.date?.at || new Date(0);\n cacheExpiry = Date.now() + 60_000; // 1-minute TTL\n return cachedLastComputed;\n}"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"language": "typescript",
|
|
55
|
+
"code": "// CURRENT: scrolls twice per settle cycle, each triggers layout\nconst settleScrollAfterLayout = async () => {\n await raf();\n if (!userScrolling && !isDetached) scrollToBottom(); // reflow #1\n await raf();\n if (!userScrolling && !isDetached) scrollToBottom(); // reflow #2\n};\n\n// FIX: single scroll after two frames is sufficient; the second raf\n// just confirms layout is stable — no need to scroll twice\nconst settleScrollAfterLayout = async () => {\n await raf();\n await raf(); // let layout settle\n if (!userScrolling && !isDetached) scrollToBottom();\n};"
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"language": "typescript",
|
|
59
|
+
"code": "// FIX: batch reads into a single function and cache within the same event tick\nconst getScrollState = () => {\n const { scrollHeight, scrollTop, clientHeight } = node;\n return { scrollHeight, scrollTop, clientHeight, distance: scrollHeight - scrollTop - clientHeight };\n};\n\nconst isAtBottom = () => getScrollState().distance <= BOTTOM_THRESHOLD;"
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
"language": "typescript",
|
|
63
|
+
"code": "// CURRENT: splits entire prompt into words just to slice the tail\n.split(\" \")\n.slice(-(model.parameters?.truncate ?? 0))\n.join(\" \")\n\n// FIX: character-budget truncation avoids the full-string allocation\n// (word count ≠ token count anyway, so precision isn't gained)\nconst truncateWords = model.parameters?.truncate ?? 0;\nconst prompt = rendered;\nif (truncateWords > 0) {\n // Scan from the end to find the Nth-from-last word boundary\n let words = 0;\n let i = prompt.length;\n while (i > 0 && words < truncateWords) {\n if (prompt[--i] === \" \") words++;\n }\n return words >= truncateWords ? prompt.slice(i + 1) : prompt;\n}\nreturn prompt;"
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"language": "typescript",
|
|
67
|
+
"code": "// CURRENT: new URL objects + endpoint closures created every invocation\nexport function useAPIClient({ fetch, origin } = {}) {\n const baseUrl = browser ? `${window.location.origin}...` : `${origin}...`;\n return { conversations: ..., user: ..., models: ... };\n}\n\n// FIX: memoize by (fetch, origin) key in a WeakMap/Map when called from\n// a stable reactive context, or extract the base-URL computation:\nconst resolveBaseUrl = (origin?: string) =>\n browser\n ? `${window.location.origin}${base}/api/v2`\n : `${origin ?? \"http://localhost:5173\"}${base}/api/v2`;"
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"language": "typescript",
|
|
71
|
+
"code": "// CURRENT: clearInterval only called at the happy-path end\nconst refreshInterval = setInterval(...);\ntry {\n result = await migration.up(...);\n} catch (e) { ... }\nclearInterval(refreshInterval); // not reached on uncaught throw\n\n// FIX: use try/finally\nconst refreshInterval = setInterval(...);\ntry {\n for (const migration of migrations) { ... }\n} finally {\n clearInterval(refreshInterval);\n await releaseLock(Semaphores.MIGRATION, lockId);\n}"
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
"language": "typescript",
|
|
75
|
+
"code": "return {\n update(newDep: MaybeScrollDependency) { ... },\n destroy() {\n clearUserScrollTimeout(); // ← required\n resizeObserver?.disconnect();\n intersectionObserver?.disconnect();\n sentinel?.remove();\n },\n};"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"language": "typescript",
|
|
79
|
+
"code": "// CURRENT: not a copy — mutates the caller's array element\nconst filteredMessages = messages;\nif (filteredMessages[0].from === \"system\" && preprompt) {\n filteredMessages[0].content = preprompt; // mutates messages[0]!\n}\n\n// FIX: shallow clone the first element to avoid mutating the input\nconst filteredMessages = messages.map((m, i) =>\n i === 0 && m.from === \"system\" && preprompt ? { ...m, content: preprompt } : m\n);"
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
"language": "typescript",
|
|
83
|
+
"code": "// CURRENT: all six fire simultaneously\nexport async function computeAllStats() {\n for (const span of [\"day\", \"week\", \"month\"] as const) {\n computeStats({ dateField: \"updatedAt\", type: \"conversation\", span }).catch(...);\n computeStats({ dateField: \"createdAt\", type: \"conversation\", span }).catch(...);\n computeStats({ dateField: \"createdAt\", type: \"message\", span }).catch(...);\n }\n}\n\n// FIX: run with controlled concurrency (e.g. 2 at a time)\nasync function computeAllStats() {\n const jobs = ([\"day\", \"week\", \"month\"] as const).flatMap((span) => [\n { dateField: \"updatedAt\" as const, type: \"conversation\" as const, span },\n { dateField: \"createdAt\" as const, type: \"conversation\" as const, span },\n { dateField: \"createdAt\" as const, type: \"message\" as const, span },\n ]);\n // process in pairs to avoid hammering MongoDB\n for (let i = 0; i < jobs.length; i += 2) {\n await Promise.all(\n jobs.slice(i, i + 2).map((j) => computeStats(j).catch((e) => logger.error(e)))\n );\n }\n}"
|
|
84
|
+
}
|
|
85
|
+
]
|
|
86
|
+
},
|
|
87
|
+
"durationMs": 74037,
|
|
88
|
+
"model": "sonnet",
|
|
89
|
+
"sandboxMode": "permissive",
|
|
90
|
+
"workerType": "optimize",
|
|
91
|
+
"timestamp": "2026-05-05T02:53:25.860Z",
|
|
92
|
+
"executionId": "optimize_1777949531823_yt5yc2"
|
|
93
|
+
}
|