Skip to content

Commit ea279cd

Browse files
committed
refactor(mothership): sim-side quality pass + dead-code sweep from the parity hill-climb
Quality (25 verified findings from the review pass): the embedded CLI's soft-fail exit code rode the process-global exitCode two parallel invocations raced on — it now rides the EmbedContext (setSoftExitCode seam, global fallback for the standalone CLI). Model-authored wire params lose their bare as-casts for typeof guards (run segments, run-tool params, output-file declarations, function-execute refs via one refField helper); the six copy-pasted cancel-settlement blocks in the tool executor fold into one settleCancelled; five error-completion literals into one builder; three title-casing humanizers into one; the sandbox image cache moves from a hand-rolled TTL map to lru-cache; sleepWithAbort yields to interruptibleSleep; plus dead re-exports, a pass-through wrapper, a dead param, an unreachable busy-spin branch made an invariant, and misc rule violations (inline sleep/getErrorMessage/truncate, mid-file import, retired-tool literal). Dead code (verified-unreferenced, from the Go-era audit): four delegated use-cases replaced by sim_cli, the file-subagent doc raster pipeline, env secret-ref resolution, workflow-state prompt formatting, the runtime stream-schema mirror (sync script trimmed to match), the workflow checkpoint/revert feature (routes + contracts; table drop deferred), and five orphaned copilot routes (update-messages, models, credentials, rename, and the duplicate chat mount — /api/mothership/chat is the live path). LONG_RUNNING_TOOL_IDS trimmed to the live tool surface with tests re-anchored. Go-decommission-gated routes (tools/execute, key/byok validate, inbandOwned) and policy items (steering chain, Go-era replay titles) deliberately kept — listed in the audit doc for Sid. Claude-Session: https://claude.ai/code/session_01CgaxNAaeD3taGdghbXn17w
1 parent 63fdec9 commit ea279cd

34 files changed

Lines changed: 218 additions & 2358 deletions

‎apps/sim/app/api/copilot/chat/route.ts‎

Lines changed: 0 additions & 15 deletions
This file was deleted.

‎apps/sim/lib/api/contracts/copilot.ts‎

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -586,25 +586,6 @@ export const copilotChatStopContract = defineRouteContract({
586586
response: { mode: 'json', schema: successFlagSchema },
587587
})
588588

589-
export const copilotChatGetContract = defineRouteContract({
590-
method: 'GET',
591-
path: '/api/copilot/chat',
592-
query: copilotChatGetQuerySchema,
593-
response: {
594-
mode: 'json',
595-
schema: z.union([
596-
z.object({
597-
success: z.literal(true),
598-
chat: copilotChatGetChatSchema,
599-
}),
600-
z.object({
601-
success: z.literal(true),
602-
chats: z.array(copilotChatGetListItemSchema),
603-
}),
604-
]),
605-
},
606-
})
607-
608589
export const deleteCopilotChatContract = defineRouteContract({
609590
method: 'DELETE',
610591
path: '/api/copilot/chat/delete',

‎apps/sim/lib/execution/remote-sandbox/index.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -911,10 +911,11 @@ async function provisionWithinBudget(
911911
}
912912

913913
async function executeInSandboxWithinBudget(
914-
req: SandboxExecutionRequest
914+
// The budget wrapper always injects the signal; the required-signal type states that
915+
// invariant instead of a cast hiding it.
916+
req: SandboxExecutionRequest & { signal: AbortSignal }
915917
): Promise<SandboxExecutionResult> {
916-
const { code, language } = req
917-
const signal = req.signal as AbortSignal
918+
const { code, language, signal } = req
918919
const kind = req.sandboxKind ?? 'code'
919920
throwIfAborted(signal)
920921

@@ -1084,10 +1085,9 @@ export function executeInSandbox(req: SandboxExecutionRequest): Promise<SandboxE
10841085
}
10851086

10861087
async function executeShellInSandboxWithinBudget(
1087-
req: SandboxShellExecutionRequest
1088+
req: SandboxShellExecutionRequest & { signal: AbortSignal }
10881089
): Promise<SandboxExecutionResult> {
1089-
const { code, envs } = req
1090-
const signal = req.signal as AbortSignal
1090+
const { code, envs, signal } = req
10911091
const kind = req.sandboxKind ?? 'shell'
10921092
throwIfAborted(signal)
10931093

‎apps/sim/lib/execution/remote-sandbox/resolve.ts‎

Lines changed: 11 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createLogger } from '@sim/logger'
22
import { getErrorMessage } from '@sim/utils/errors'
3+
import { LRUCache } from 'lru-cache'
34
import { CodeLanguage } from '@/lib/execution/languages'
45
import { classifyInstallOutput, tailBuildLog } from '@/lib/execution/remote-sandbox/build-errors'
56
import {
@@ -114,21 +115,13 @@ interface CachedImage {
114115
errorMessage: string | null
115116
}
116117

117-
interface CacheEntry {
118-
expiresAt: number
119-
value: CachedImage
120-
}
121-
122118
/**
123-
* Both maps are process-lifetime and keyed by an unbounded space (every spec
124-
* hash ever executed), so each drops its oldest entry rather than growing for
125-
* the life of the worker.
119+
* Both caches are keyed by an unbounded space (every spec hash ever executed):
120+
* `max` is the memory backstop, `ttl` the freshness policy — lru-cache owns
121+
* expiry/eviction/ceiling per the caching rule (never hand-roll TTL arithmetic).
126122
*/
127-
const IMAGE_CACHE_LIMIT = 1000
128-
const LAST_USED_CACHE_LIMIT = 1000
129-
130-
const imageCache = new Map<string, CacheEntry>()
131-
const lastUsedWrites = new Map<string, number>()
123+
const imageCache = new LRUCache<string, CachedImage>({ max: 1000, ttl: IMAGE_TTL_MS })
124+
const lastUsedWrites = new LRUCache<string, number>({ max: 1000, ttl: LAST_USED_DEBOUNCE_MS })
132125

133126
/**
134127
* JavaScript packages live outside the default resolution roots, so Node needs
@@ -155,11 +148,9 @@ function envsFor(
155148
*/
156149
function touchImage(specHash: string, provider: string): void {
157150
const key = `${provider}:${specHash}`
158-
const now = Date.now()
159-
const written = lastUsedWrites.get(key)
160-
if (written && now - written < LAST_USED_DEBOUNCE_MS) return
161-
if (lastUsedWrites.size >= LAST_USED_CACHE_LIMIT) lastUsedWrites.clear()
162-
lastUsedWrites.set(key, now)
151+
// The TTL IS the debounce: a still-fresh entry means we wrote recently.
152+
if (lastUsedWrites.get(key) !== undefined) return
153+
lastUsedWrites.set(key, Date.now())
163154
void sandboxDb()
164155
.then(({ db, sandboxImage, and, eq }) =>
165156
db
@@ -381,10 +372,7 @@ async function readImage(
381372
): Promise<CachedImage | undefined> {
382373
const cacheKey = `${providerId}:${specHash}:${materializationGeneration}:${materializationRefPrefix}`
383374
const cached = imageCache.get(cacheKey)
384-
if (cached) {
385-
if (cached.expiresAt > Date.now()) return cached.value
386-
imageCache.delete(cacheKey)
387-
}
375+
if (cached !== undefined) return cached
388376

389377
const { db, sandboxImage, and, eq } = await sandboxDb()
390378
const [image] = await db
@@ -399,13 +387,7 @@ async function readImage(
399387
.where(and(eq(sandboxImage.provider, providerId), eq(sandboxImage.specHash, specHash)))
400388
.limit(1)
401389

402-
if (image?.status === 'ready') {
403-
if (imageCache.size >= IMAGE_CACHE_LIMIT) {
404-
const oldest = imageCache.keys().next()
405-
if (!oldest.done) imageCache.delete(oldest.value)
406-
}
407-
imageCache.set(cacheKey, { expiresAt: Date.now() + IMAGE_TTL_MS, value: image })
408-
}
390+
if (image?.status === 'ready') imageCache.set(cacheKey, image)
409391
return image
410392
}
411393

‎apps/sim/lib/mothership/application/execute-credential-use-case.ts‎

Lines changed: 0 additions & 14 deletions
This file was deleted.

‎apps/sim/lib/mothership/application/execute-log-use-case.ts‎

Lines changed: 0 additions & 34 deletions
This file was deleted.

‎apps/sim/lib/mothership/application/execute-mcp-server-use-case.ts‎

Lines changed: 0 additions & 14 deletions
This file was deleted.

‎apps/sim/lib/mothership/application/execute-skill-use-case.ts‎

Lines changed: 0 additions & 14 deletions
This file was deleted.

0 commit comments

Comments
 (0)