Skip to content

Commit b857f97

Browse files
committed
Phase A0: sim half of the mship↔CLI translation layer — primitives only
lib/mothership/agent-cli/ executes the worker typed AgentCliRequest and nothing more: request-schema validates it, run-cli runs the embedded CLI (with the @token sandbox reads), pipeline applies already-parsed grep stages, sink lands stdout on the machine, and engines/ holds the augmentation engines keyed by the worker canonical names. The sim-side matcher, flag parser, pipe splitter, and help merge are deleted — the grammar lives in the mothership worker now, which is closed source and the one place a command meaning is decided. The sim_cli handler becomes a thin adapter: validate the request, execute, return the raw result. It refuses a frame without the typed request rather than falling back to re-parsing argv, so the worker must deploy first. scripts/check-agent-cli-boundary.ts (bun run check:agent-cli-boundary) holds the line: primitives-only export surface, no pipe/flag/command-name grammar under lib/mothership, runEmbeddedCli reachable only through the primitive runner, and no agent imports in the public CLI package. lib/mothership/generated/agent-cli.ts is the synced contract copy. https://claude.ai/code/session_01HFVhPDtRZuCgupPco633w8
1 parent fdc1ae9 commit b857f97

26 files changed

Lines changed: 860 additions & 984 deletions
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
/**
2+
* @vitest-environment node
3+
*/
4+
import { describe, expect, it, vi } from 'vitest'
5+
6+
const { buildWorkflowLintReport } = vi.hoisted(() => ({
7+
buildWorkflowLintReport: vi.fn().mockResolvedValue({
8+
sources: ['block-1'],
9+
sinks: ['block-2'],
10+
orphanBlocks: [],
11+
emptyOutgoingPorts: [],
12+
invalidBranchPorts: [],
13+
invalidConnectionTargets: [],
14+
fieldIssues: [
15+
{
16+
blockId: 'block-2',
17+
blockName: 'Summarize emails',
18+
missingRequiredFields: ['model'],
19+
inactiveModeValues: [],
20+
},
21+
],
22+
unresolvedReferences: [],
23+
}),
24+
}))
25+
26+
vi.mock('@/lib/workflows/editing/lint-report', () => ({ buildWorkflowLintReport }))
27+
28+
import { runEngine } from '@/lib/mothership/agent-cli/engines'
29+
import type { AgentCliRuntime } from '@/lib/mothership/agent-cli/types'
30+
31+
const WORKFLOW_STATE = {
32+
blocks: {
33+
'block-1': { type: 'starter', name: 'Start', enabled: true },
34+
'block-2': { type: 'agent', name: 'Summarize emails', enabled: true },
35+
},
36+
edges: [{ source: 'block-1', target: 'block-2', sourceHandle: 'source', id: 'edge-1' }],
37+
variables: { apiBase: 'https://api.example.com' },
38+
}
39+
40+
function runtimeWith(responses: Record<string, unknown>): AgentCliRuntime {
41+
return {
42+
workspaceId: 'ws-1',
43+
userId: 'user-1',
44+
client: {
45+
request: async <T>(path: string): Promise<T> => {
46+
const hit = responses[path]
47+
if (hit === undefined) throw new Error(`Unexpected request: ${path}`)
48+
return hit as T
49+
},
50+
},
51+
}
52+
}
53+
54+
const EXPORT_PATH = '/api/v2/workflows/wf-1/export'
55+
const exportResponse = { data: { state: WORKFLOW_STATE } }
56+
57+
describe('workflow views', () => {
58+
it('projects just the blocks', async () => {
59+
const result = await runEngine(
60+
'workflow blocks',
61+
['wf-1'],
62+
runtimeWith({ [EXPORT_PATH]: exportResponse }),
63+
{}
64+
)
65+
expect(result.exitCode).toBe(0)
66+
const blocks = JSON.parse(result.stdout)
67+
expect(blocks).toEqual([
68+
{ id: 'block-1', type: 'starter', name: 'Start', enabled: true },
69+
{ id: 'block-2', type: 'agent', name: 'Summarize emails', enabled: true },
70+
])
71+
})
72+
73+
it('projects just the edges', async () => {
74+
const result = await runEngine(
75+
'workflow edges',
76+
['wf-1'],
77+
runtimeWith({ [EXPORT_PATH]: exportResponse }),
78+
{}
79+
)
80+
expect(result.exitCode).toBe(0)
81+
expect(JSON.parse(result.stdout)).toEqual([
82+
{ source: 'block-1', target: 'block-2', sourceHandle: 'source' },
83+
])
84+
})
85+
86+
it('fails usefully without a workflow id', async () => {
87+
const result = await runEngine('workflow blocks', [], runtimeWith({}), {})
88+
expect(result.exitCode).toBe(1)
89+
expect(result.stderr).toContain('Usage:')
90+
})
91+
})
92+
93+
describe('files grep', () => {
94+
const FILES_LIST = {
95+
data: [
96+
{ id: 'f1', name: 'report.md', folderPath: 'docs' },
97+
{ id: 'f2', name: 'logo.png', folderPath: '' },
98+
],
99+
nextCursor: null,
100+
}
101+
const readText = (text: string, degraded = false) => ({
102+
data: { text, degraded },
103+
})
104+
105+
it('greps file contents with line numbers, skipping non-text files', async () => {
106+
const result = await runEngine(
107+
'files grep',
108+
['quarterly'],
109+
runtimeWith({
110+
'/api/v2/files': FILES_LIST,
111+
'/api/v2/files/f1/text': readText('# Report\nQuarterly revenue was up.\n'),
112+
'/api/v2/files/f2/text': readText('', true),
113+
}),
114+
{}
115+
)
116+
expect(result.exitCode).toBe(0)
117+
expect(result.stdout).toContain('docs/report.md:2: Quarterly revenue was up.')
118+
expect(result.stdout).not.toContain('logo.png')
119+
})
120+
121+
it('filters by folder prefix', async () => {
122+
const result = await runEngine(
123+
'files grep',
124+
['Quarterly', 'other'],
125+
runtimeWith({ '/api/v2/files': FILES_LIST }),
126+
{}
127+
)
128+
expect(result.exitCode).toBe(0)
129+
expect(result.stdout).toContain('No matches')
130+
})
131+
})
132+
133+
describe('workflow grep', () => {
134+
it('reports matches as path: value lines', async () => {
135+
const result = await runEngine(
136+
'workflow grep',
137+
['wf-1', 'Summarize'],
138+
runtimeWith({ [EXPORT_PATH]: exportResponse }),
139+
{}
140+
)
141+
expect(result.exitCode).toBe(0)
142+
expect(result.stdout).toContain('.blocks.block-2.name: Summarize emails')
143+
})
144+
145+
it('falls back to literal search on an invalid regex', async () => {
146+
const result = await runEngine(
147+
'workflow grep',
148+
['wf-1', 'api.example.com['],
149+
runtimeWith({ [EXPORT_PATH]: exportResponse }),
150+
{}
151+
)
152+
expect(result.exitCode).toBe(0)
153+
expect(result.stdout).toBe('No matches.')
154+
})
155+
156+
it('searches across all workspace workflows', async () => {
157+
const result = await runEngine(
158+
'workflows grep',
159+
['Summarize'],
160+
runtimeWith({
161+
'/api/v2/workflows': {
162+
data: [{ id: 'wf-1', name: 'Email digest' }],
163+
nextCursor: null,
164+
},
165+
[EXPORT_PATH]: exportResponse,
166+
}),
167+
{}
168+
)
169+
expect(result.exitCode).toBe(0)
170+
expect(result.stdout).toContain('Email digest (wf-1).blocks.block-2.name: Summarize emails')
171+
})
172+
173+
it('lints a workflow through the shared engine with the caller scoped as subject', async () => {
174+
const result = await runEngine(
175+
'workflow lint',
176+
['wf-1'],
177+
runtimeWith({ [EXPORT_PATH]: exportResponse }),
178+
{}
179+
)
180+
expect(result.stderr).toBe('')
181+
expect(result.exitCode).toBe(0)
182+
const report = JSON.parse(result.stdout)
183+
expect(report.fieldIssues).toHaveLength(1)
184+
expect(report.summary.length).toBeGreaterThan(0)
185+
expect(buildWorkflowLintReport).toHaveBeenCalledWith(expect.anything(), {
186+
workflowId: 'wf-1',
187+
workspaceId: 'ws-1',
188+
subjectUserId: 'user-1',
189+
})
190+
})
191+
192+
it('surfaces execution errors as a failed result, never a throw', async () => {
193+
const result = await runEngine('workflow grep', ['wf-missing', 'x'], runtimeWith({}), {})
194+
expect(result.exitCode).toBe(1)
195+
expect(result.stderr).toContain('Unexpected request')
196+
})
197+
})

apps/sim/lib/mothership/tools/handlers/agent-cli/commands/deps.ts renamed to apps/sim/lib/mothership/agent-cli/engines/deps.ts

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,5 @@
1-
import { fetchWorkflowState } from '@/lib/mothership/tools/handlers/agent-cli/commands/workflow-views'
2-
import {
3-
type AgentCliCommand,
4-
agentCliFail,
5-
agentCliOk,
6-
} from '@/lib/mothership/tools/handlers/agent-cli/types'
1+
import { fetchWorkflowState } from '@/lib/mothership/agent-cli/engines/workflow-views'
2+
import { type AgentCliEngine, agentCliFail, agentCliOk } from '@/lib/mothership/agent-cli/types'
73
import { normalizeName, SPECIAL_REFERENCE_PREFIXES } from '@/executor/constants'
84
import {
95
collectStringLeaves,
@@ -33,11 +29,7 @@ interface DepView {
3329
paths?: string[]
3430
}
3531

36-
export const workflowDepsCommand: AgentCliCommand = {
37-
path: ['workflow', 'deps'],
38-
summary:
39-
'List every reference one block consumes (upstream blocks, variables, env) — what to mock for an isolated run',
40-
usage: 'workflow deps <workflowId> <blockId>',
32+
export const workflowDepsCommand: AgentCliEngine = {
4133
async execute(rest, runtime) {
4234
const [workflowId, blockId] = rest
4335
if (!workflowId || !blockId)

apps/sim/lib/mothership/tools/handlers/agent-cli/commands/files-grep.ts renamed to apps/sim/lib/mothership/agent-cli/engines/files-grep.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import type { ListFilesResponse, ReadFileTextResponse } from 'sim/embed'
22
import {
3-
type AgentCliCommand,
3+
type AgentCliEngine,
44
type AgentCliRuntime,
55
agentCliFail,
66
agentCliOk,
7-
} from '@/lib/mothership/tools/handlers/agent-cli/types'
7+
} from '@/lib/mothership/agent-cli/types'
88

99
/**
1010
* Content grep across workspace files (the Go copilot's VFS-wide grep, files
@@ -59,10 +59,7 @@ async function listAllFiles(runtime: AgentCliRuntime): Promise<ListFilesResponse
5959
return rows.slice(0, MAX_FILES)
6060
}
6161

62-
export const filesGrepCommand: AgentCliCommand = {
63-
path: ['files', 'grep'],
64-
summary: 'Search the content of every workspace file for a pattern',
65-
usage: 'files grep <pattern> [folder-path-prefix]',
62+
export const filesGrepCommand: AgentCliEngine = {
6663
async execute(rest, runtime) {
6764
const [pattern, folderPrefix] = [rest[0], rest[1]]
6865
if (!pattern) return agentCliFail('Usage: sim files grep <pattern> [folder-path-prefix]')

apps/sim/lib/mothership/tools/handlers/agent-cli/commands/grep.ts renamed to apps/sim/lib/mothership/agent-cli/engines/grep.ts

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import type { ListWorkflowsResponse } from 'sim/embed'
2-
import { fetchWorkflowState } from '@/lib/mothership/tools/handlers/agent-cli/commands/workflow-views'
2+
import { fetchWorkflowState } from '@/lib/mothership/agent-cli/engines/workflow-views'
33
import {
4-
type AgentCliCommand,
4+
type AgentCliEngine,
55
type AgentCliRuntime,
66
agentCliFail,
77
agentCliOk,
8-
} from '@/lib/mothership/tools/handlers/agent-cli/types'
8+
} from '@/lib/mothership/agent-cli/types'
99

1010
/**
1111
* Structural grep over workflow state. Matches walk the exported JSON tree and
@@ -62,10 +62,7 @@ function renderMatches(lines: string[]): string {
6262
return capped.join('\n')
6363
}
6464

65-
export const workflowGrepCommand: AgentCliCommand = {
66-
path: ['workflow', 'grep'],
67-
summary: 'Search one workflow state (blocks, params, edges) for a pattern',
68-
usage: 'workflow grep <workflowId> <pattern>',
65+
export const workflowGrepCommand: AgentCliEngine = {
6966
async execute(rest, runtime) {
7067
const [workflowId, ...patternParts] = rest
7168
const pattern = patternParts.join(' ')
@@ -92,10 +89,7 @@ async function listAllWorkflows(runtime: AgentCliRuntime): Promise<ListWorkflows
9289
return rows
9390
}
9491

95-
export const workflowsGrepCommand: AgentCliCommand = {
96-
path: ['workflows', 'grep'],
97-
summary: 'Search every workflow in the workspace for a pattern',
98-
usage: 'workflows grep <pattern>',
92+
export const workflowsGrepCommand: AgentCliEngine = {
9993
async execute(rest, runtime) {
10094
const pattern = rest.join(' ')
10195
if (!pattern) return agentCliFail('Usage: sim workflows grep <pattern>')
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { getErrorMessage } from '@sim/utils/errors'
2+
import { workflowDepsCommand } from '@/lib/mothership/agent-cli/engines/deps'
3+
import { filesGrepCommand } from '@/lib/mothership/agent-cli/engines/files-grep'
4+
import { workflowGrepCommand, workflowsGrepCommand } from '@/lib/mothership/agent-cli/engines/grep'
5+
import { workflowLintCommand } from '@/lib/mothership/agent-cli/engines/lint'
6+
import { logsQueryCommand } from '@/lib/mothership/agent-cli/engines/query'
7+
import { workflowTraceCommand } from '@/lib/mothership/agent-cli/engines/trace'
8+
import {
9+
workflowBlocksCommand,
10+
workflowEdgesCommand,
11+
} from '@/lib/mothership/agent-cli/engines/workflow-views'
12+
import {
13+
type AgentCliEngine,
14+
type AgentCliFlags,
15+
type AgentCliResult,
16+
type AgentCliRuntime,
17+
agentCliFail,
18+
} from '@/lib/mothership/agent-cli/types'
19+
20+
/**
21+
* Every augmentation engine, keyed by the worker's canonical command name. The worker's
22+
* registry (grammar/augmentations.ts) and this map must agree exactly — the worker's
23+
* augmentation-drift check reads these keys.
24+
*/
25+
export const AUGMENTATION_ENGINES: Readonly<Record<string, AgentCliEngine>> = {
26+
'files grep': filesGrepCommand,
27+
'logs query': logsQueryCommand,
28+
'workflow blocks': workflowBlocksCommand,
29+
'workflow deps': workflowDepsCommand,
30+
'workflow edges': workflowEdgesCommand,
31+
'workflow grep': workflowGrepCommand,
32+
'workflow lint': workflowLintCommand,
33+
'workflow trace': workflowTraceCommand,
34+
'workflows grep': workflowsGrepCommand,
35+
}
36+
37+
/** Runs one engine by the worker's name; an engine that throws yields a failed result, never a throw. */
38+
export async function runEngine(
39+
name: string,
40+
positionals: string[],
41+
runtime: AgentCliRuntime,
42+
flags: AgentCliFlags
43+
): Promise<AgentCliResult> {
44+
const engine = AUGMENTATION_ENGINES[name]
45+
if (!engine) return agentCliFail(`No engine for agent command "${name}".`)
46+
try {
47+
return await engine.execute(positionals, runtime, flags)
48+
} catch (error) {
49+
return agentCliFail(getErrorMessage(error))
50+
}
51+
}

apps/sim/lib/mothership/tools/handlers/agent-cli/commands/lint.ts renamed to apps/sim/lib/mothership/agent-cli/engines/lint.ts

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import type { WorkflowState } from '@sim/workflow-types/workflow'
2-
import { fetchWorkflowState } from '@/lib/mothership/tools/handlers/agent-cli/commands/workflow-views'
2+
import { fetchWorkflowState } from '@/lib/mothership/agent-cli/engines/workflow-views'
33
import {
4-
type AgentCliCommand,
4+
type AgentCliEngine,
55
type AgentCliRuntime,
66
agentCliFail,
77
agentCliOk,
8-
} from '@/lib/mothership/tools/handlers/agent-cli/types'
8+
} from '@/lib/mothership/agent-cli/types'
99
import { formatWorkflowLintMessage, hasWorkflowLintIssues } from '@/lib/workflows/editing/lint'
1010
import { buildWorkflowLintReport } from '@/lib/workflows/editing/lint-report'
1111
import { createEnvVarPattern } from '@/executor/utils/reference-validation'
@@ -17,10 +17,7 @@ import { createEnvVarPattern } from '@/executor/utils/reference-validation'
1717
* same engine both graph writes publish, so a lint here can never disagree
1818
* with what an edit would have reported.
1919
*/
20-
export const workflowLintCommand: AgentCliCommand = {
21-
path: ['workflow', 'lint'],
22-
summary: 'Validate one workflow: orphans, unwired ports, missing fields, unresolved references',
23-
usage: 'workflow lint <workflowId>',
20+
export const workflowLintCommand: AgentCliEngine = {
2421
async execute(rest, runtime) {
2522
const workflowId = rest[0]
2623
if (!workflowId) return agentCliFail('Usage: sim workflow lint <workflowId>')

apps/sim/lib/mothership/tools/handlers/agent-cli/commands/query.ts renamed to apps/sim/lib/mothership/agent-cli/engines/query.ts

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import {
2-
type AgentCliCommand,
2+
type AgentCliEngine,
33
type AgentCliFlags,
44
type AgentCliRuntime,
55
agentCliFail,
66
agentCliOk,
7-
} from '@/lib/mothership/tools/handlers/agent-cli/types'
7+
} from '@/lib/mothership/agent-cli/types'
88
import { normalizeName } from '@/executor/constants'
99

1010
/**
@@ -67,14 +67,11 @@ function clipValue(value: unknown): unknown {
6767
}
6868

6969
function stringFlag(flags: AgentCliFlags, name: string): string | undefined {
70-
const value = flags.get(name)
70+
const value = flags[name]
7171
return typeof value === 'string' ? value : undefined
7272
}
7373

74-
export const logsQueryCommand: AgentCliCommand = {
75-
path: ['logs', 'query'],
76-
summary: 'One row per run: a block field across run history (--block, --field, --where)',
77-
usage: 'logs query <workflowId> --block <name>',
74+
export const logsQueryCommand: AgentCliEngine = {
7875
async execute(rest: string[], runtime: AgentCliRuntime, flags: AgentCliFlags) {
7976
const workflowId = rest[0]
8077
const blockName = stringFlag(flags, 'block') ?? ''

0 commit comments

Comments
 (0)