SLOPSHOPPER

roclaude

Roblox Studio safety layer for Claude Code (Studio MCP): RemoteEvent security audit, undo, Team Create protection, a confirmation before destructive Luau, and…

panebandrowsguardcommandtoast
v0.5.1MITupdated 2026-10-10vinkdc/roclaude
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · roclaude
│ ┃ roclaude-remotes ✕ › fix the failing auth test and add an audit log call │ ┃ Run /roclaude remotes to audit this game's │ ┃ RemoteEvents. ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /roclaude │ ⎿ roclaude: roclaude is waiting: Claude has not used the Roblox St │ │ ● Roblox Studio Not connected ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
● Roblox Studio Not connected
Pane · roclaude-remotes
Run /roclaude remotes to audit this game's RemoteEvents.
Pane · roclaude-activity
╭──────────────────────────────────────────────────────╮ │ IDLE │ │ Nothing touched yet │ ╰──────────────────────────────────────────────────────╯ CLAUDE TOUCHED 0 ITEMS Scripts and objects Claude reads or changes in Studio show up here. Select something Claude touched to see what changed.
README

roclaude

A safety layer for building Roblox games with Claude Code through Roblox Studio's built-in MCP server. Claude edits your open place directly; roclaude makes that safe: it audits your RemoteEvents, keeps undo copies of Claude's edits, protects Team Create collaborators' work, and asks you before destructive Luau runs.

Requires Claude Code 2.1.287 or later and Roblox Studio with the MCP server enabled.

What it does

Studio activity: see and replay every change

/roclaude activity (or Activity above the prompt) shows what Claude did in your place. A card says whether Claude is working or done and sums it up ("Claude edited 2 scripts, changed 1 object"). Below it, everything Claude touched is listed by service with a badge: Read, Edited, Created or Changed; rows in progress light up as reading… or editing….

Click a row to see its change, or step through the changes in order with Prev and Next:

  • Scripts show a red and green diff from before Claude's first edit to after its last.
  • Objects Claude changed with Luau show each property before → after (Anchored false → true, Color rgb(99, 68, 44) → rgb(255, 0, 0)), or Created / Deleted. roclaude reads up to five objects' properties just before and after each execute_luau call; changes made through a local variable aren't seen.

Where the app can place a side pane, the view opens beside the conversation (the first time Claude touches Studio, and on /roclaude activity). Where it can't, /roclaude activity draws the same view as a live card in the chat. When a turn ends with changes, a note in the transcript lists them with Claude's own summary.

/roclaude remotes: audit your whole game

It finds every OnServerEvent and OnServerInvoke handler in the open place and sorts each one:

StatusMeaning
UNCHECKEDUses client values without checking them. Exploiters can send anything.
admin-onlyChecks who is calling first (isAdmin(player), player.UserId ~= ..., group rank).
checkedChecks every client value (typeof, tonumber, ranges, lookups).
no argsTakes nothing from the client.

Handlers inside third-party modules (admin kits like Kohl's Admin or Adonis, Packages) are listed separately, so your own code stands out. The results open in a pane with a button that asks Claude to fix the unchecked handlers.

Team Create

  • No edits against a stale copy. roclaude remembers what Claude last read of each script. If a collaborator changed the script since, Claude's multi_edit is refused, and Claude is told to read the script again and redo its edit on the current version, so it never overwrites their work. Claude's own edits don't count as changes.
  • Who's in the session. Collaborators who join or leave the live editing session (as reported in Studio's Output) show in the band and in /roclaude. Destructive-Luau confirmations name them too.
  • Teammate-safe undo. /roclaude undo refuses when the script changed after Claude's edit; /roclaude undo force overrides.

Undo for Claude's edits

Before each multi_edit, roclaude reads the script and keeps a copy. /roclaude undo puts back the latest one, and a script Claude created is deleted. /roclaude history lists what Claude changed this session. Studio edits made through MCP have no git history, so this is your safety net. Up to 50 copies are kept per session.

A confirmation before destructive Luau

When Claude wants to run execute_luau code that deletes instances (:Destroy, :ClearAllChildren), writes DataStores (SetAsync, UpdateAsync, RemoveAsync), kicks or bans players, overwrites .Source, or loads code by asset id, you're asked first, even if you've allowed the tool. Read-only code runs as usual.

A review of every edit

What Claude writes through multi_edit is checked, and findings go back to Claude so it fixes them in the same turn:

  • RemoteEvent handlers that use client values unchecked. Luau type annotations don't count, because exploiters can send any value.
  • wait/spawn/delay instead of the task library, game.Players instead of GetService, lowercase :connect, Instance.new with a parent argument, and LocalPlayer in server scripts.

After Claude changes a script, it's reminded to playtest, read the Output and fix errors before telling you it's done. Claude also gets these conventions in the multi_edit tool's description, so it sees them exactly when it edits.

The band

A band above the prompt shows the place, the Team Create collaborators, how many edits can be undone, the last playtest result and the last check, for example: ◆ test2 · 👥 alex_dev · 3 edit(s) undoable · playtest: clean · Shop clean.

Install

At the prompt of a Claude Code terminal session:

/plugin install roclaude --marketplace vinkdc/roclaude

Answer y to add the marketplace, then choose a scope.

To connect Claude Code to Studio, turn on Assistant → … → Manage MCP Servers → Enable Studio as MCP server in Roblox Studio, then:

claude mcp add --scope user --transport stdio Roblox_Studio -- cmd.exe /c %LOCALAPPDATA%\Roblox\mcp.bat

On macOS, use /Applications/RobloxStudio.app/Contents/MacOS/StudioMCP as the command. roclaude recognizes any MCP server whose name contains "roclaude" or "studio".

Commands

CommandWhat it does
/roclaudeStudio, Team Create and playtest status, and the last check's findings
/roclaude activityShows what Claude touched and replays each change, in a side pane or as a card in the chat
/roclaude remotesAudits every RemoteEvent and RemoteFunction handler, and opens the results in a pane
/roclaude undoRestores the script from Claude's latest edit; /roclaude undo force restores it even if it changed since
/roclaude historyLists Claude's Studio edits this session
/roclaude hide / showHides or shows the band

Footprint

roclaude only talks to the Roblox Studio MCP server. It reads no files, makes no network requests, runs no processes and makes no model calls.

AccessWhy
tool.call on the Studio server's toolsLets each call run, then: reads script_read results to know what Claude saw; around multi_edit, refuses a stale edit, keeps undo copies and attaches findings; reads the studio name, errors and collaborators from list_roblox_studios and get_console_output results.
tool.check on execute_luauChanges "allow" to "ask" for destructive code. It never allows anything that was going to be refused.
tool.describe on multi_editAppends the Roblox and Team Create notes to the tool's description.
$.mcp.call → script_readSaves a script before and after Claude's multi_edit, and reads handler scripts for /roclaude remotes.
$.mcp.call → list_roblox_studios, script_grepOnly for /roclaude remotes: finds the open studio and the scripts that handle remotes.
$.mcp.call → multi_edit, execute_luauOnly when you run /roclaude undo: puts back the saved source, or deletes a script Claude created.

Undo copies and audit results stay in the session's memory. Claude Code asks you once to allow the Studio tools roclaude calls itself.

Develop

claude plugin validate .
claude plugin test .
claude --plugin-dir .

License

MIT

Source 6 files
hooks/register.tsx 1075 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { PropMap, RemoteReport, Snapshot, StudioInfo, TouchAction, TouchedItem } from '../types'
5import { firstSentence, lineDiff } from './diff'
6import {
7  leafOf,
8  normalizePath,
9  parseProps,
10  pathsChanged,
11  propChanges,
12  serviceOf,
13  settle,
14  summarize,
15  touch,
16} from './activity'
17import { auditRemotes, formatIssues, lintLuau, scanRemotes } from './lint'
18import {
19  changesPlace,
20  countErrors,
21  dangersIn,
22  GREP_CAP,
23  grepScripts,
24  isVendor,
25  luauLookup,
26  saysPlaying,
27  scriptKey,
28  stillAsSeen,
29  stripLineNumbers,
30  studioId,
31  studioMode,
32  studioName,
33  studioTool,
34  teamFrom,
35  writesScripts,
36} from './studio'
37import type { SeenText } from './studio'
38
39const lastLint = atom({ plugin: 'roclaude', key: 'lastLint' } as const, null)
40const isHidden = atom({ plugin: 'roclaude', key: 'isHidden' } as const, false)
41const studio = atom({ plugin: 'roclaude', key: 'studio' } as const, null)
42const history = atom({ plugin: 'roclaude', key: 'history' } as const, [])
43const remotes = atom({ plugin: 'roclaude', key: 'remotes' } as const, null)
44const team = atom({ plugin: 'roclaude', key: 'team' } as const, [])
45const staleBlocks = atom({ plugin: 'roclaude', key: 'staleBlocks' } as const, 0)
46const touched = atom({ plugin: 'roclaude', key: 'touched' } as const, [])
47const isWorking = atom({ plugin: 'roclaude', key: 'isWorking' } as const, false)
48const turnNo = atom({ plugin: 'roclaude', key: 'turn' } as const, 0)
49const selected = atom({ plugin: 'roclaude', key: 'selected' } as const, null)
50const cardRun = atom({ plugin: 'roclaude', key: 'cardRun' } as const, 0)
51
52const MAX_SNAPSHOTS = 50
53const STUDIO_TOOL = /^mcp__.*(roblox|studio).*__[a-z_]+$/i
54const DEFAULT_SERVER = 'Roblox_Studio'
55const REMOTES_PANE = 'roclaude-remotes'
56const ACTIVITY_PANE = 'roclaude-activity'
57// The Studio tools roclaude calls itself through $.mcp.call.
58const OWN_CALLS = new Set([
59  'list_roblox_studios',
60  'get_studio_state',
61  'inspect_instance',
62  'script_grep',
63  'script_read',
64  'multi_edit',
65  'execute_luau',
66])
67const NO_STUDIO: StudioInfo = { name: null, server: null, id: null, errors: null, mode: null, untested: 0 }
68const POLL_MS = 10_000
69// At most this many objects per execute_luau get a before → after record.
70const MAX_INSPECT = 5
71const TEST_PROMPT =
72  'Playtest the open place: start it with start_stop_play, give it a few seconds, read get_console_output, stop play, then fix any errors you find and tell me what you changed.'
73
74// A studio_id argument, or none when no studio is known yet.
75const withStudio = (sid: string) => (sid === '' ? {} : { studio_id: sid })
76
77const textOf = (content: readonly { type: string; text?: string }[]) =>
78  content.map(block => (block.type === 'text' ? (block.text ?? '') : '')).join('')
79const shortName = (path: string) => path.split('.').pop() ?? path
80
81// Reads a script through the Studio MCP server: its source, null when it
82// does not exist yet, undefined when it could not be read.
83async function readScript(
84  $: EngineInterface,
85  server: string,
86  sid: string,
87  path: string,
88): Promise<string | null | undefined> {
89  try {
90    const target = path.startsWith('game.') ? path : `game.${path}`
91    const res = await $.mcp.call(server, 'script_read', { ...withStudio(sid), target_file: target })
92    const text = textOf(res.content)
93    if (res.isError) return /Script not found/i.test(text) ? null : undefined
94    return stripLineNumbers(text)
95  } catch {
96    return undefined
97  }
98}
99
100async function undo($: EngineInterface, isForced: boolean): Promise<string> {
101  const list = await read($, history)
102  const last = list[list.length - 1]
103  if (last === undefined) return 'Nothing to undo: Claude has not edited a Studio script this session.'
104
105  const { server, studioId: sid, path } = last
106  const current = await readScript($, server, sid, path)
107  if (current === undefined) {
108    return `Could not read ${path} to undo it. Is Studio still open and in Edit mode?`
109  }
110  // Without the script as Claude's edit left it, there is no telling whether
111  // someone changed it since: only a forced undo goes ahead.
112  if (!isForced && last.afterStatus !== 'read') {
113    return `${path} could not be read right after Claude's edit, so roclaude cannot tell whether you or a teammate changed it since. Run /roclaude undo force to restore Claude's saved copy anyway.`
114  }
115  // In Team Create someone else may have edited the script since: never
116  // overwrite that work unless asked to.
117  if (!isForced && last.after !== null && current !== null && current !== last.after) {
118    return `${path} changed after Claude's edit (by you or a teammate), so undo would discard that work. Run /roclaude undo force to restore Claude's saved copy anyway.`
119  }
120
121  let res
122  if (last.source === null) {
123    if (current === null) {
124      await update($, history, all => all.slice(0, -1))
125      return `${path} is already gone; dropped that step.`
126    }
127    const code = [`local s = ${luauLookup(path)}`, 'if s then s:Destroy() end', 'return s ~= nil'].join('\n')
128    res = await $.mcp.call(server, 'execute_luau', { ...withStudio(sid), datamodel_type: 'Edit', code })
129  } else {
130    if (current === last.source) {
131      await update($, history, all => all.slice(0, -1))
132      return `${path} already matches its saved copy; dropped that step.`
133    }
134    if (current === null) {
135      return `${path} no longer exists, so there is nothing to restore into.`
136    }
137    res = await $.mcp.call(server, 'multi_edit', {
138      ...withStudio(sid),
139      datamodel_type: 'Edit',
140      file_path: path,
141      edits: [{ old_string: current, new_string: last.source }],
142    })
143  }
144
145  if (res.isError) return `Undo of ${path} failed: ${textOf(res.content).slice(0, 300)}`
146  await update($, history, all => all.slice(0, -1))
147  return last.source === null
148    ? `Undid the creation of ${path} (deleted it).`
149    : `Restored ${path} to how it was before Claude's edit.`
150}
151
152type Target = {
153  path: string
154  kind: TouchedItem['kind']
155  action: TouchAction
156  propsBefore?: PropMap | null
157  propsAfter?: PropMap | null
158}
159let isActivityOpened = false
160// What Claude changed in the running turn, for the note when it ends.
161const changedThisTurn: string[] = []
162const CARD_MARK = 'roclaude activity #'
163
164// Shows the activity view: as a pane where the surface places one, or else
165// as a card in the chat (the command's row draws it). Answers the row's text.
166async function showActivity($: EngineInterface): Promise<string> {
167  const isShown = async () => {
168    try {
169      return (await $.ui.panes()).some(pane => pane.id === ACTIVITY_PANE && pane.isPlaced)
170    } catch {
171      return false
172    }
173  }
174  // Open (or bring forward) the pane, but never wait on it for long: a
175  // surface may hold the open until it can seat the pane.
176  const opening = $.ui.open({ id: ACTIVITY_PANE, title: 'Studio activity' }).then(
177    opened => opened.isPlaced,
178    () => false,
179  )
180  const isPlaced = await Promise.race([opening, $.clock.sleep(1_500).then(() => null)])
181  if (isPlaced === true || (isPlaced === null && (await isShown()))) {
182    return 'Studio activity is open beside the conversation.'
183  }
184  const run = (await read($, cardRun)) + 1
185  await update($, cardRun, () => run)
186  return `${CARD_MARK}${run}`
187}
188
189// An object's properties through the Studio MCP server: null when it does
190// not exist, undefined when they could not be read.
191async function inspectProps(
192  $: EngineInterface,
193  server: string,
194  sid: string,
195  path: string,
196): Promise<PropMap | null | undefined> {
197  try {
198    const res = await $.mcp.call(server, 'inspect_instance', { ...withStudio(sid), path })
199    const text = textOf(res.content)
200    if (res.isError) return /not found|no instance|does not exist|could not find/i.test(text) ? null : undefined
201    return parseProps(text)
202  } catch {
203    return undefined
204  }
205}
206
207// A call on these is starting: show them as being read, edited or changed,
208// and open the activity pane the first time Claude touches the place.
209async function begin($: EngineInterface, targets: readonly Target[], as: NonNullable<TouchedItem['activeAs']>) {
210  if (targets.length === 0) return
211  await update($, touched, list =>
212    targets.reduce<TouchedItem[]>((all, target) => {
213      const known = all.find(one => one.path === normalizePath(target.path))
214      return touch(all, { ...target, action: known?.action ?? 'read', isActive: true, activeAs: as })
215    }, [...list]),
216  )
217  if (!isActivityOpened) {
218    isActivityOpened = true
219    // Where no pane can be placed (an app without side panes, a headless
220    // run) this waits unseen; the band's Activity button shows a card instead.
221    $.ui.open({ id: ACTIVITY_PANE, title: 'Studio activity' }).catch(() => undefined)
222  }
223}
224
225// The call ended: record what it did, or only settle the rows when it failed.
226// A change becomes the one the activity view shows.
227async function finish($: EngineInterface, targets: readonly Target[], isDone: boolean) {
228  if (targets.length === 0) return
229  await update($, touched, list =>
230    targets.reduce<TouchedItem[]>(
231      (all, target) =>
232        isDone ? touch(all, { ...target, isActive: false, activeAs: null }) : settle(all, target.path),
233      [...list],
234    ),
235  )
236  const changes = isDone ? targets.filter(target => target.action !== 'read') : []
237  for (const target of changes) {
238    const path = normalizePath(target.path)
239    if (!changedThisTurn.includes(path)) changedThisTurn.push(path)
240  }
241  const last = changes[changes.length - 1]
242  if (last !== undefined) await update($, selected, () => normalizePath(last.path))
243}
244
245// Asks the Studio MCP server which place is open and whether it is playing,
246// for the band. Writes only what changed, so an idle poll redraws nothing.
247async function probeStudio($: EngineInterface): Promise<void> {
248  try {
249    const known = await read($, studio)
250    const server = known?.server ?? DEFAULT_SERVER
251    let { id, name } = known ?? NO_STUDIO
252    if (id === null || name === null) {
253      const text = textOf((await $.mcp.call(server, 'list_roblox_studios', {})).content)
254      id = studioId(text)
255      name = studioName(text)
256      if (id === null) return
257    }
258    const sid = id
259    const state = await $.mcp.call(server, 'get_studio_state', { studio_id: sid })
260    const mode = state.isError ? (known?.mode ?? null) : studioMode(textOf(state.content))
261
262    if (known?.id === sid && known.name === name && known.server === server && known.mode === mode) return
263    await update($, studio, info => noteMode({ ...(info ?? NO_STUDIO), server, id: sid, name }, mode))
264  } catch {
265    // No Studio MCP server, or Studio is closed: the band says not connected.
266  }
267}
268
269// A playtest that starts counts as testing what came before it.
270function noteMode(info: StudioInfo, mode: StudioInfo['mode']): StudioInfo {
271  if (mode === 'play' && info.mode !== 'play') return { ...info, mode, untested: 0, errors: null }
272  return { ...info, mode }
273}
274
275// Audits every RemoteEvent and RemoteFunction handler in the open place.
276async function scanStudio($: EngineInterface): Promise<RemoteReport | string> {
277  const seen = await read($, studio)
278  const server = seen?.server ?? DEFAULT_SERVER
279  let id = seen?.id ?? null
280  try {
281    // A server that just started needs a few seconds before Studio registers.
282    for (let attempt = 0; id === null && attempt < 4; attempt += 1) {
283      if (attempt > 0) await $.clock.sleep(2_000)
284      const listed = await $.mcp.call(server, 'list_roblox_studios', {})
285      id = studioId(textOf(listed.content))
286    }
287    if (id === null) return 'No Roblox Studio is connected. Open your place with the MCP server enabled in Assistant settings.'
288
289    const grep = await $.mcp.call(server, 'script_grep', { studio_id: id, query: 'OnServer' })
290    if (grep.isError) return `Could not search the place's scripts: ${textOf(grep.content).slice(0, 200)}`
291    const found = grepScripts(textOf(grep.content))
292
293    const handlers: RemoteReport['handlers'][number][] = []
294    for (const script of found.scripts) {
295      const source = await readScript($, server, id, script)
296      if (typeof source !== 'string') continue
297      handlers.push(...scanRemotes(source).map(handler => ({ ...handler, script, isVendor: isVendor(script) })))
298    }
299
300    return {
301      scripts: found.scripts.length,
302      handlers,
303      note:
304        found.matches >= GREP_CAP
305          ? `Studio's script search stops at ${GREP_CAP} matches, so some handlers may be missing.`
306          : null,
307    }
308  } catch (error) {
309    return `Could not reach the Roblox Studio MCP server "${server}": ${error instanceof Error ? error.message : String(error)}`
310  }
311}
312
313const STATUS_ORDER = { unchecked: 0, gated: 1, checked: 2, 'no-args': 3 } as const
314
315// The game's own handlers, worst first, and the third-party ones apart.
316function orderHandlers(report: RemoteReport) {
317  const sorted = [...report.handlers].sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status])
318  const own = sorted.filter(handler => !handler.isVendor)
319  const vendor = sorted.filter(handler => handler.isVendor)
320  const bad = own.filter(handler => handler.status === 'unchecked').length
321  return { own, vendor, bad }
322}
323
324function remotesText(report: RemoteReport): string {
325  const { own, vendor, bad } = orderHandlers(report)
326  const row = (handler: RemoteReport['handlers'][number]) =>
327    `  [${handler.status}] ${handler.script}:${handler.line} ${handler.remote}${handler.unchecked.length > 0 ? ` uses ${handler.unchecked.join(', ')} unchecked` : ''}`
328  return [
329    `RemoteEvent audit: ${own.length} server handler(s) in the game's own scripts, ${bad} unchecked.`,
330    ...own.map(row),
331    ...(vendor.length === 0
332      ? []
333      : [`Third-party modules (${vendor.length} handler(s); review or update them upstream):`, ...vendor.map(row)]),
334    ...(report.note === null ? [] : [report.note]),
335  ].join('\n')
336}
337
338const CONVENTIONS = [
339  '',
340  'roclaude notes for editing this place:',
341  '- Create and change scripts only with multi_edit (new scripts: className plus a first edit with an empty old_string), and read them with script_read. roclaude refuses execute_luau code that writes script source (.Source =, UpdateSourceAsync, Instance.new of a script), because only multi_edit edits can be undone, reviewed and kept safe in Team Create.',
342  '- Read a script in full with script_read before you edit it. In Team Create collaborators may be editing too: if a script changed since you last read it, roclaude refuses the edit and you must read it again first.',
343  '- Use the task library (task.wait, task.spawn, task.defer, task.delay), never the deprecated wait, spawn or delay. Get services with game:GetService("Name"); use PascalCase methods.',
344  '- The server never trusts what a client sends through a RemoteEvent or RemoteFunction: check types with typeof, ranges, rate and ownership. Luau type annotations are not runtime checks.',
345  '- Wrap DataStore, HttpService and MarketplaceService calls in pcall. Players.LocalPlayer exists only on the client.',
346  '- After changing scripts, playtest (start_stop_play), read get_console_output, stop, and fix errors before saying you are done. The person can undo your edits with /roclaude undo.',
347].join('\n')
348
349const EXECUTE_NOTE = [
350  '',
351  'roclaude: do not use this tool to read or write script source. Read scripts with script_read; create and change them with multi_edit. Code that writes source (.Source =, UpdateSourceAsync, Instance.new of a Script, LocalScript or ModuleScript) is refused.',
352].join('\n')
353
354const SCRIPT_WRITE_REFUSAL =
355  'roclaude: this Luau writes script source. Create or change scripts with multi_edit instead (for a new script: file_path like game.ServerScriptService.Name, className Script, LocalScript or ModuleScript, and a first edit with old_string "" holding the source). multi_edit edits can be undone with /roclaude undo, are reviewed for exploits, and are kept safe for Team Create collaborators.'
356
357// The activity view: what Claude touched, each row clickable, and the
358// selected change below it, a script's diff or an object's properties.
359async function drawActivity($: EngineInterface, e: Parameters<EngineInterface['ui']['resolve']>[0], width: number) {
360  const { Box, Button, Code, Text } = $.ui.resolve(e)
361  const list = await read($, touched)
362  const working = await read($, isWorking)
363  const snapshots = await read($, history)
364  const { title, detail } = summarize(list)
365  const isBusy = working || list.some(one => one.isActive)
366
367  const color = { read: 'merged', edited: 'claude', created: 'success', changed: 'suggestion' } as const
368  const label = { read: 'Read', edited: 'Edited', created: 'Created', changed: 'Changed' } as const
369  const status = isBusy ? 'WORKING' : list.length > 0 ? 'DONE' : 'IDLE'
370  const statusColor = isBusy ? 'warning' : list.length > 0 ? 'claude' : 'inactive'
371
372  const changes = list.filter(one => one.action !== 'read')
373  const chosen = (await read($, selected)) ?? changes[changes.length - 1]?.path ?? null
374  const current = list.find(one => one.path === chosen) ?? null
375  const at = current === null ? -1 : changes.findIndex(one => one.path === current.path)
376  const pick = (path: string) => update($, selected, () => path)
377
378  const services: string[] = []
379  for (const one of list) if (!services.includes(serviceOf(one.path))) services.push(serviceOf(one.path))
380
381  // The selected item's change.
382  let body = <Text dimColor>Select something Claude touched to see what changed.</Text>
383  if (current !== null && current.kind === 'script') {
384    const edits = snapshots.filter(one => normalizePath(one.path) === current.path && one.after !== null)
385    const first = edits[0]
386    const last = edits[edits.length - 1]
387    if (current.action === 'read' || first === undefined || last === undefined) {
388      body = <Text dimColor>Claude read this script and did not change it.</Text>
389    } else {
390      const diff = lineDiff(first.source, last.after ?? '')
391      body = (
392        <Box flexDirection="column">
393          <Text>
394            <Text color="success">+{diff.added}</Text> <Text color="error">−{diff.removed}</Text>
395            <Text dimColor>
396              {' '}
397              over {edits.length} edit{edits.length === 1 ? '' : 's'}
398            </Text>
399          </Text>
400          <Box borderStyle="round" borderColor="inactive">
401            {diff.unified === '' ? (
402              <Text dimColor>No line changes.</Text>
403            ) : (
404              <Code key={`diff-${current.path}`} source={diff.unified} format="diff" language="lua" path={leafOf(current.path)} />
405            )}
406          </Box>
407        </Box>
408      )
409    }
410  } else if (current !== null) {
411    const { propsBefore: before, propsAfter: after } = current
412    if (current.action === 'read') body = <Text dimColor>Claude looked at this object and did not change it.</Text>
413    else if (before === undefined && after === undefined) {
414      body = <Text dimColor>Claude changed this with Luau; its properties could not be read.</Text>
415    } else if (after === null) body = <Text color="error">Deleted.</Text>
416    else if (before === null || before === undefined) body = <Text color="success">Created by Claude.</Text>
417    else {
418      const rows = after === undefined ? [] : propChanges(before, after)
419      body =
420        rows.length === 0 ? (
421          <Text dimColor>No property changes seen.</Text>
422        ) : (
423          <Box flexDirection="column" borderStyle="round" borderColor="inactive" paddingX={1}>
424            {rows.slice(0, 12).map(row => (
425              <Box key={`prop-${row.name}`} justifyContent="space-between" gap={2}>
426                <Text dimColor>{row.name}</Text>
427                <Text wrap="truncate-start">
428                  <Text color="error">{row.before}</Text>
429                  <Text dimColor> → </Text>
430                  <Text color="success">{row.after}</Text>
431                </Text>
432              </Box>
433            ))}
434            {rows.length > 12 && <Text dimColor>…and {rows.length - 12} more</Text>}
435          </Box>
436        )
437    }
438  }
439
440  return (
441    <Box flexDirection="column" width={width}>
442      <Box borderStyle="round" borderColor={isBusy ? 'warning' : 'inactive'} paddingX={1} flexDirection="column">
443        <Text bold color={statusColor}>
444          {status}
445        </Text>
446        <Text bold>{title}</Text>
447        {detail !== '' && <Text dimColor>{detail}</Text>}
448      </Box>
449
450      <Box justifyContent="space-between" marginTop={1}>
451        <Text bold dimColor>
452          CLAUDE TOUCHED
453        </Text>
454        <Text bold dimColor>
455          {list.length} {list.length === 1 ? 'ITEM' : 'ITEMS'}
456        </Text>
457      </Box>
458      {list.length === 0 && <Text dimColor>Scripts and objects Claude reads or changes in Studio show up here.</Text>}
459      {services.map(service => (
460        <Box flexDirection="column" key={`svc-${service}`}>
461          <Text dimColor>{service}</Text>
462          {list
463            .filter(one => serviceOf(one.path) === service)
464            .map(one => {
465              const isChosen = current?.path === one.path
466              const where = normalizePath(one.path).split('.').slice(1, -1).join('.')
467              const badge = one.isActive ? (one.activeAs === 'reading' ? 'merged' : 'claude') : color[one.action]
468              return (
469                <Box
470                  key={`row-${one.path}`}
471                  justifyContent="space-between"
472                  alignItems="center"
473                  gap={1}
474                  paddingLeft={1}
475                  backgroundColor={isChosen ? 'subtle' : undefined}
476                >
477                  <Box gap={1} flexShrink={1} alignItems="center">
478                    <Text bold color={one.kind === 'script' ? 'suggestion' : 'success'}>
479                      {one.kind === 'script' ? 'LUA' : 'OBJ'}
480                    </Text>
481                    <Button key={`pick-${one.path}`} label={leafOf(one.path)} plain onPress={() => pick(one.path)} />
482                    {where !== '' && (
483                      <Text dimColor wrap="truncate-end">
484                        {where}
485                      </Text>
486                    )}
487                  </Box>
488                  <Box flexShrink={0} paddingX={1} backgroundColor={badge}>
489                    <Text bold color="inverseText">
490                      {one.isActive ? `${one.activeAs}…` : label[one.action]}
491                    </Text>
492                  </Box>
493                </Box>
494              )
495            })}
496        </Box>
497      ))}
498
499      {current !== null && (
500        <Box flexDirection="column" marginTop={1}>
501          <Text bold color="claude">
502            {at >= 0 ? `CHANGE ${at + 1} OF ${changes.length}` : 'READ ONLY'}
503          </Text>
504          <Text bold>{leafOf(current.path)}</Text>
505          <Text dimColor>
506            {current.path} · {label[current.action]}
507          </Text>
508        </Box>
509      )}
510      <Box marginTop={current === null ? 1 : 0}>{body}</Box>
511
512      <Box marginTop={1} gap={1}>
513        {changes.length > 1 && (
514          <>
515            <Button key="prev" label="Prev" onPress={() => pick(changes[Math.max(0, at - 1)]!.path)} />
516            <Button
517              key="next"
518              label="Next"
519              variant="primary"
520              onPress={() => pick(changes[Math.min(changes.length - 1, at + 1)]!.path)}
521            />
522          </>
523        )}
524        {snapshots.length > 0 && (
525          <Button
526            key="undo-last"
527            label="Undo last edit"
528            onPress={async () => {
529              $.ui.toast(await undo($, false))
530            }}
531          />
532        )}
533        {list.length > 0 && !isBusy && (
534          <Button
535            key="clear"
536            label="Clear"
537            onPress={async () => {
538              await update($, touched, () => [])
539              await update($, selected, () => null)
540            }}
541          />
542        )}
543      </Box>
544    </Box>
545  )
546}
547
548export const register: Register = on => {
549  let nudgedThisTurn = false
550  // What Claude last read of each script, to catch edits against a stale copy.
551  const seenText = new Map<string, SeenText>()
552
553  on('session.start', async ($, e, next) => {
554    await $.command.register({
555      name: 'roclaude',
556      description: 'Roblox Studio: audit RemoteEvents, undo Claude’s edits, Team Create status',
557      argumentHint: '[activity|remotes|undo|history|show|hide]',
558    })
559    // Find the open place once the MCP server has had a moment to start.
560    $.clock.after(3_000, () => void probeStudio($))
561    $.clock.every(POLL_MS, () => void probeStudio($))
562    return next(e)
563  })
564
565  on('prompt.submit', async ($, e, next) => {
566    nudgedThisTurn = false
567    changedThisTurn.length = 0
568    await update($, isWorking, () => true)
569    await update($, turnNo, n => n + 1)
570    return next(e)
571  }).catch(($, e, next) => next(e))
572
573  on('turn.complete', async ($, e, next) => {
574    await update($, isWorking, () => false)
575    await update($, touched, list => (list.some(one => one.isActive) ? list.map(one => ({ ...one, isActive: false, activeAs: null })) : list))
576
577    // A turn that changed the place: say so in the transcript, with how to look.
578    if (changedThisTurn.length > 0) {
579      const names = changedThisTurn.map(leafOf)
580      const shown = names.slice(0, 4).join(' · ') + (names.length > 4 ? ` +${names.length - 4}` : '')
581      $.session
582        .append({
583          message: {
584            type: 'system',
585            content: [
586              {
587                type: 'text',
588                text: `Studio activity · Claude changed ${names.length} thing${names.length === 1 ? '' : 's'}: ${shown}\nClaude: ${firstSentence(e.answer)}\nPress Activity above the prompt, or type /roclaude activity, to see each change.`,
589              },
590            ],
591          },
592        })
593        .catch(() => undefined)
594    }
595    return next(e)
596  })
597
598  // Claude reads the notes where it needs them: in multi_edit's description.
599  on('tool.describe', { tool: STUDIO_TOOL }, async ($, e, next) => {
600    const described = await next(e)
601    const name = studioTool(e.tool)?.name
602    if (name === 'multi_edit') return { ...described, description: described.description + CONVENTIONS }
603    if (name === 'execute_luau') return { ...described, description: described.description + EXECUTE_NOTE }
604    return described
605  }).catch(($, e, next) => next(e))
606
607  on('tool.call', { tool: STUDIO_TOOL }, async ($, e, next) => {
608    const found = studioTool(e.tool)
609    if (found === null) return next(e)
610    const args = e as unknown as Record<string, unknown>
611    const usedId = typeof args.studio_id === 'string' ? args.studio_id : null
612
613    const known = await read($, studio)
614    if (known === null || known.server !== found.server || (usedId !== null && known.id !== usedId)) {
615      await update($, studio, info => ({ ...(info ?? NO_STUDIO), server: found.server, id: usedId ?? info?.id ?? null }))
616    }
617
618    if (found.name === 'get_studio_state') {
619      const ran = await next(e)
620      const mode = ran.deny === undefined && ran.isError !== true ? studioMode(ran.text ?? '') : null
621      if (mode !== null) await update($, studio, info => noteMode(info ?? NO_STUDIO, mode))
622      return ran
623    }
624
625    if (found.name === 'start_stop_play') {
626      const ran = await next(e)
627      if (ran.deny === undefined && ran.isError !== true) {
628        await update($, studio, info => noteMode(info ?? NO_STUDIO, args.is_start === true ? 'play' : 'edit'))
629      }
630      return ran
631    }
632
633    if (found.name === 'execute_luau') {
634      const code = typeof args.code === 'string' ? args.code : ''
635      const paths = args.datamodel_type === 'Edit' && changesPlace(code) ? pathsChanged(code).slice(0, MAX_INSPECT) : []
636      const sid = usedId ?? known?.id ?? ''
637      await begin(
638        $,
639        paths.map(path => ({ path, kind: 'instance' as const, action: 'changed' as const })),
640        'changing',
641      )
642      // Each object's properties just before and after, for the before → after view.
643      const before = await Promise.all(paths.map(path => inspectProps($, found.server, sid, path)))
644      const ran = await next(e)
645      const isDone = ran.deny === undefined && ran.isError !== true
646      const after = isDone ? await Promise.all(paths.map(path => inspectProps($, found.server, sid, path))) : []
647      await finish(
648        $,
649        paths.map((path, i) => ({
650          path,
651          kind: 'instance' as const,
652          action: before[i] === null && after[i] != null ? ('created' as const) : ('changed' as const),
653          propsBefore: before[i],
654          propsAfter: after[i],
655        })),
656        isDone,
657      )
658      if (ran.isError === true && saysPlaying(ran.text ?? '')) {
659        await update($, studio, info => noteMode(info ?? NO_STUDIO, 'play'))
660      } else if (ran.deny === undefined && ran.isError !== true && args.datamodel_type === 'Edit' && changesPlace(code)) {
661        await update($, studio, info => ({ ...(info ?? NO_STUDIO), untested: (info?.untested ?? 0) + 1 }))
662      }
663      return ran
664    }
665
666    if (found.name === 'list_roblox_studios') {
667      const ran = await next(e)
668      if (ran.deny === undefined && ran.isError !== true) {
669        const name = studioName(ran.text ?? '')
670        const id = studioId(ran.text ?? '')
671        await update($, studio, info => ({ ...(info ?? NO_STUDIO), name, id: info?.id ?? id }))
672      }
673      return ran
674    }
675
676    if (found.name === 'get_console_output') {
677      const ran = await next(e)
678      if (ran.deny === undefined && ran.isError !== true) {
679        const output = ran.text ?? ''
680        await update($, studio, info => ({ ...(info ?? NO_STUDIO), errors: countErrors(output) }))
681        await update($, team, members => teamFrom(output, members))
682      }
683      return ran
684    }
685
686    if (found.name === 'script_read') {
687      const path = typeof args.target_file === 'string' ? args.target_file : ''
688      const reading = path === '' ? [] : [{ path, kind: 'script' as const, action: 'read' as const }]
689      await begin($, reading, 'reading')
690      const ran = await next(e)
691      await finish($, reading, ran.deny === undefined && ran.isError !== true)
692      if (ran.deny === undefined && ran.isError !== true && path !== '') {
693        const isWhole = args.should_read_entire_file !== false
694        const start = isWhole ? 1 : typeof args.start_line_one_indexed === 'number' ? args.start_line_one_indexed : 1
695        seenText.set(scriptKey(path), { start, lines: stripLineNumbers(ran.text ?? '').split('\n'), isWhole })
696      }
697      return ran
698    }
699
700    if (found.name === 'inspect_instance' || found.name === 'insert_asset') {
701      const isInsert = found.name === 'insert_asset'
702      const parent = typeof args.parentPath === 'string' ? args.parentPath : 'Workspace'
703      const target = isInsert
704        ? `${parent}.${typeof args.assetName === 'string' ? args.assetName : 'Asset'}`
705        : typeof args.path === 'string'
706          ? args.path
707          : ''
708      const items =
709        target === '' ? [] : [{ path: target, kind: 'instance' as const, action: isInsert ? ('created' as const) : ('read' as const) }]
710      await begin($, items, isInsert ? 'changing' : 'reading')
711      const ran = await next(e)
712      const ok = ran.deny === undefined && ran.isError !== true
713      const added = ok && isInsert ? await inspectProps($, found.server, usedId ?? known?.id ?? '', target) : undefined
714      await finish($, isInsert ? items.map(item => ({ ...item, propsBefore: null, propsAfter: added })) : items, ok)
715      if (ok && isInsert) await update($, studio, info => ({ ...(info ?? NO_STUDIO), untested: (info?.untested ?? 0) + 1 }))
716      return ran
717    }
718
719    if (found.name !== 'multi_edit') return next(e)
720
721    const path = typeof args.file_path === 'string' ? args.file_path : ''
722    const editing = [{ path, kind: 'script' as const, action: 'edited' as const }]
723    await begin($, editing, 'editing')
724    const sid = usedId ?? known?.id ?? ''
725    const before = await readScript($, found.server, sid, path)
726
727    // Team Create: refuse an edit made against a copy someone has since changed.
728    const seen = seenText.get(scriptKey(path))
729    if (seen !== undefined && typeof before === 'string' && !stillAsSeen(seen, before)) {
730      seenText.delete(scriptKey(path))
731      await update($, staleBlocks, count => count + 1)
732      await finish($, editing, false)
733      return {
734        deny: `roclaude: ${path} changed after you last read it, likely a Team Create collaborator editing it. Read it again with script_read, then redo your edit on the current version so you don't overwrite their work.`,
735      }
736    }
737
738    const ran = await next(e)
739    if (ran.isError === true && saysPlaying(ran.text ?? '')) {
740      await update($, studio, info => noteMode(info ?? NO_STUDIO, 'play'))
741    }
742    const isEdited = ran.deny === undefined && ran.isError !== true
743    await finish($, before === null ? [{ ...editing[0]!, action: 'created' }] : editing, isEdited)
744    if (!isEdited) return ran
745    await update($, studio, info => ({ ...(info ?? NO_STUDIO), untested: (info?.untested ?? 0) + 1 }))
746
747    // An unreadable script (undefined) is not a missing one (null): undo must know which.
748    const afterRead = before !== undefined ? await readScript($, found.server, sid, path) : undefined
749    const after = typeof afterRead === 'string' ? afterRead : null
750    const afterStatus = typeof afterRead === 'string' ? 'read' : afterRead === null ? 'missing' : 'unknown'
751    if (before !== undefined) {
752      const turn = await read($, turnNo)
753      await update($, history, list => {
754        const id = (list[list.length - 1]?.id ?? 0) + 1
755        const snapshot: Snapshot = { id, server: found.server, studioId: sid, path, source: before, after, afterStatus, turn }
756        return [...list, snapshot].slice(-MAX_SNAPSHOTS)
757      })
758    }
759    if (after !== null) {
760      await update($, remotes, report => {
761        if (report === null) return report
762        const key = scriptKey(path)
763        const kept = report.handlers.filter(handler => scriptKey(handler.script) !== key)
764        const fresh = scanRemotes(after).map(handler => ({ ...handler, script: key, isVendor: isVendor(key) }))
765        if (fresh.length === 0 && kept.length === report.handlers.length) return report
766        return { ...report, handlers: [...kept, ...fresh] }
767      })
768    }
769    // Claude knows the script as its own edit left it.
770    if (after !== null) seenText.set(scriptKey(path), { start: 1, lines: after.split('\n'), isWhole: true })
771    else seenText.delete(scriptKey(path))
772
773    const edits = Array.isArray(args.edits) ? (args.edits as { new_string?: unknown }[]) : []
774    const written = edits.map(edit => (typeof edit.new_string === 'string' ? edit.new_string : '')).join('\n')
775    const className = typeof args.className === 'string' ? args.className : ''
776    const lintPath = className === 'Script' ? `${path}.server.luau` : path
777    const issues = [...lintLuau(lintPath, written), ...auditRemotes(written)].map(issue => ({ ...issue, line: 0 }))
778    await update($, lastLint, () => ({ file: path, issues }))
779
780    const context = [...(ran.context ?? [])]
781    if (issues.length > 0) context.push(formatIssues(path, issues).replace(/^ {2}L0 /gm, '  - '))
782    if (!nudgedThisTurn) {
783      nudgedThisTurn = true
784      context.push(
785        'roclaude: you changed a script in the open place. Before you finish, playtest with start_stop_play, read get_console_output, stop play, and fix any errors. The person can undo your edit with /roclaude undo.',
786      )
787    }
788
789    return { ...ran, context }
790  }).catch(($, e, next) => next(e))
791
792  // Ask the person before Luau that deletes, writes player data or loads outside code.
793  on('tool.check', { tool: STUDIO_TOOL }, async ($, e, next) => {
794    const found = studioTool(e.tool)
795    const verdict = await next(e)
796
797    // roclaude's own calls: reads for /roclaude remotes and snapshots, and the
798    // restore of a /roclaude undo the person typed. Auto mode's classifier gives
799    // no verdict on a plugin's call, so the plugin answers for its own; a deny
800    // rule the person wrote in settings still stands.
801    if (next.origin.plugin === 'roclaude' && found !== null && OWN_CALLS.has(found.name)) {
802      if (verdict.decision === 'deny' && verdict.rule !== undefined) return verdict
803      return { decision: 'allow', reason: `roclaude's own ${found.name}` }
804    }
805
806    if (found?.name !== 'execute_luau' || verdict.decision === 'deny') return verdict
807
808    const input = e.input as { code?: unknown } | null
809    const code = typeof input?.code === 'string' ? input.code : ''
810    if (writesScripts(code)) return { decision: 'deny', reason: SCRIPT_WRITE_REFUSAL }
811
812    const dangers = dangersIn(code)
813    if (dangers.length === 0) return verdict
814
815    const members = await read($, team)
816    const shared = members.length > 1 ? ` Team Create: ${members.join(', ')} will see this change.` : ''
817    return {
818      decision: 'ask',
819      reason: `roclaude: this Luau ${dangers.map(danger => danger.reason).join('; ')}. roclaude cannot undo it.${shared}`,
820    }
821  }).catch(($, e, next) => next(e))
822
823  on('command.run', { command: 'roclaude' }, async ($, e) => {
824    const arg = e.args.trim().toLowerCase()
825    if (arg === 'hide' || arg === 'show') {
826      await update($, isHidden, () => arg === 'hide')
827      return { text: `roclaude band ${arg === 'hide' ? 'hidden' : 'shown'}.` }
828    }
829    if (arg === 'undo' || arg === 'undo force') {
830      return { text: await undo($, arg === 'undo force') }
831    }
832    if (arg === 'activity' || arg === 'files' || arg === 'replay') {
833      return { text: await showActivity($) }
834    }
835    if (arg === 'remotes') {
836      const report = await scanStudio($)
837      if (typeof report === 'string') return { text: report }
838      await update($, remotes, () => report)
839      await $.ui.open({ id: REMOTES_PANE, title: 'RemoteEvent audit' })
840      return { text: remotesText(report) }
841    }
842    if (arg === 'history') {
843      const list = await read($, history)
844      if (list.length === 0) return { text: 'No Studio edits by Claude this session.' }
845      return {
846        text: [
847          `Claude's Studio edits this session, newest last (/roclaude undo reverts the newest):`,
848          ...list.map(s => `  ${s.id}. ${s.path}${s.source === null ? ' (created)' : ''}`),
849        ].join('\n'),
850      }
851    }
852
853    const seen = await read($, studio)
854    if (seen === null) {
855      return {
856        text: 'roclaude is waiting: Claude has not used the Roblox Studio MCP server this session. Try /roclaude remotes, or ask Claude to look at your place.',
857      }
858    }
859    const lint = await read($, lastLint)
860    const list = await read($, history)
861    const members = await read($, team)
862    const blocks = await read($, staleBlocks)
863    return {
864      text: [
865        `Studio: ${seen.name ?? 'connected'}, ${list.length} script edit(s) saved for undo`,
866        `Team Create: ${members.length > 0 ? members.join(', ') : 'no one else seen in Output yet'}${blocks > 0 ? `; ${blocks} stale edit(s) refused` : ''}`,
867        `Last playtest output: ${seen.errors === null ? 'not read yet' : `${seen.errors} error line(s)`}`,
868        lint === null
869          ? 'Last Luau check: none yet.'
870          : lint.issues.length === 0
871            ? `Last Luau check: ${lint.file} is clean.`
872            : formatIssues(lint.file, lint.issues).replace(/^ {2}L0 /gm, '  - '),
873      ].join('\n'),
874    }
875  }).catch(($, e, next) => ({
876    // The command answers even when something in it fails, and says what.
877    text: `roclaude: /roclaude ${e.args} failed (${next.error.kind}). Try again; if it keeps failing, restart the session.`,
878  }))
879
880  on('ui.render', { component: 'Pane', requestId: REMOTES_PANE }, async ($, e) => {
881    const { Box, Button, Text } = $.ui.resolve(e)
882    const report = await read($, remotes)
883    if (report === null) return <Text dimColor>Run /roclaude remotes to audit this game's RemoteEvents.</Text>
884
885    const { own, vendor, bad } = orderHandlers(report)
886    const room = Math.max(3, (e.viewport?.rows ?? 24) - 8)
887    const color = { unchecked: 'error', gated: 'warning', checked: 'success', 'no-args': 'inactive' } as const
888    const label = { unchecked: 'UNCHECKED', gated: 'admin-only', checked: 'checked', 'no-args': 'no args' } as const
889    const unchecked = own
890      .filter(handler => handler.status === 'unchecked')
891      .map(handler => `- ${handler.script}:${handler.line} ${handler.remote} (uses ${handler.unchecked.join(', ')})`)
892
893    return (
894      <Box flexDirection="column">
895        <Text>
896          <Text bold>{own.length}</Text> handler(s) in the game's scripts ·{' '}
897          <Text color={bad > 0 ? 'error' : 'success'}>{bad} unchecked</Text>
898          {vendor.length > 0 && <Text dimColor> · {vendor.length} in third-party modules</Text>}
899        </Text>
900        {own.slice(0, room).map(handler => (
901          <Box flexDirection="column">
902            <Text wrap="truncate-start">
903              <Text color={color[handler.status]}>{label[handler.status].padEnd(10)}</Text> {handler.remote}{' '}
904              <Text dimColor>
905                {handler.script}:{handler.line}
906              </Text>
907            </Text>
908            {handler.unchecked.length > 0 && (
909              <Text dimColor>{'           '}trusts: {handler.unchecked.join(', ')}</Text>
910            )}
911          </Box>
912        ))}
913        {own.length > room && <Text dimColor>…and {own.length - room} more (see /roclaude remotes)</Text>}
914        {report.note !== null && <Text dimColor>{report.note}</Text>}
915        {bad > 0 && (
916          <Box>
917            <Button
918              key="fix"
919              label="Ask Claude to fix unchecked"
920              onPress={() =>
921                $.prompt.submit({
922                  text: [
923                    'Fix these RemoteEvent handlers that roclaude found using client values unchecked. For each, add a permission check or validate every client value (typeof, ranges, cooldowns, ownership), without changing behavior for legitimate players:',
924                    ...unchecked,
925                  ].join('\n'),
926                })
927              }
928            />
929          </Box>
930        )}
931      </Box>
932    )
933  })
934
935  on('ui.render', { component: 'Pane', requestId: ACTIVITY_PANE }, async ($, e) =>
936    drawActivity($, e, e.props.bodyColumns ?? e.viewport?.columns ?? 50),
937  )
938
939  // Where no pane can be placed, /roclaude activity draws the view in the chat.
940  // Only the newest card is live; older ones point to it.
941  on('ui.render', { component: 'CommandOutput', props: { command: 'roclaude' } }, async ($, e, next) => {
942    const match = e.props.text.match(/roclaude activity #(\d+)/)
943    if (match === null) return next(e)
944    const { Text } = $.ui.resolve(e)
945    if (Number(match[1]) !== (await read($, cardRun))) return <Text dimColor>Studio activity (a newer card is below).</Text>
946    return drawActivity($, e, Math.min(e.viewport?.columns ?? 80, 90))
947  })
948
949  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
950    const seen = await read($, studio)
951    if (e.props.hasSurvey || (await read($, isHidden))) return next(e)
952    const { Box, Button, Text } = $.ui.resolve(e)
953    const width = e.props.bodyColumns ?? e.viewport?.columns ?? 80
954
955    // A filled tag: the band's status words, like a progress label.
956    const pill = (key: string, text: string, color: 'warning' | 'success' | 'error' | 'inactive' | 'merged') => (
957      <Box key={key} backgroundColor={color} paddingX={1}>
958        <Text bold color="inverseText">
959          {text}
960        </Text>
961      </Box>
962    )
963    const hide = <Button key="hide" label="Hide" plain onPress={() => update($, isHidden, () => true)} />
964
965    if (seen === null) {
966      return (
967        <Box width={width} justifyContent="space-between" alignItems="center">
968          <Box gap={1} alignItems="center">
969            <Text color="inactive">●</Text>
970            <Text bold>Roblox Studio</Text>
971            {pill('state', 'Not connected', 'inactive')}
972            <Text dimColor>Open a place with the MCP server on</Text>
973          </Box>
974          {hide}
975        </Box>
976      )
977    }
978
979    const lint = await read($, lastLint)
980    const list = await read($, history)
981    const members = await read($, team)
982    const report = await read($, remotes)
983    const unchecked = report === null ? 0 : orderHandlers(report).bad
984    const issues = lint === null ? 0 : lint.issues.length
985    const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
986
987    // One colour says how the place is doing: red needs action, yellow a look.
988    const errors = seen.untested === 0 ? (seen.errors ?? 0) : 0
989    const health = unchecked > 0 || errors > 0 ? 'error' : seen.untested > 0 || issues > 0 ? 'warning' : 'success'
990
991    const left = [
992      <Text key="dot" color={health}>
993        ●
994      </Text>,
995      <Text key="name" bold>
996        {seen.name ?? 'Roblox Studio'}
997      </Text>,
998    ]
999    if (seen.mode === 'play') left.push(pill('mode', 'Playing', 'merged'))
1000    else if (seen.mode === 'edit') left.push(pill('mode', 'Edit', 'inactive'))
1001    if (seen.untested > 0) left.push(pill('result', `${seen.untested} untested`, 'warning'))
1002    else if (errors > 0) left.push(pill('result', plural(errors, 'error'), 'error'))
1003    else if (seen.errors !== null) left.push(pill('result', 'Tested', 'success'))
1004    if (unchecked > 0) {
1005      left.push(
1006        <Text key="remotes" color="error">
1007          {plural(unchecked, 'unchecked remote')}
1008        </Text>,
1009      )
1010    }
1011    if (issues > 0) {
1012      left.push(
1013        <Text key="issues" color="warning">
1014          {plural(issues, 'issue')} in {shortName(lint?.file ?? '')}
1015        </Text>,
1016      )
1017    }
1018    if (members.length > 0) {
1019      left.push(
1020        <Text key="team" dimColor>
1021          {members.length <= 2 ? members.join(', ') : plural(members.length, 'collaborator')}
1022        </Text>,
1023      )
1024    }
1025    if (list.length > 0) {
1026      left.push(
1027        <Text key="undoable" dimColor>
1028          {list.length} undoable
1029        </Text>,
1030      )
1031    }
1032
1033    const right = []
1034    if ((await read($, touched)).length > 0) {
1035      // Runs the command, so the view shows in a pane or, where none can be
1036      // placed, as a card in the chat.
1037      right.push(
1038        <Button
1039          key="activity"
1040          label="Activity"
1041          onPress={() => {
1042            void $.command.run({ command: 'roclaude', args: 'activity' }).catch(() => undefined)
1043          }}
1044        />,
1045      )
1046    }
1047    if (seen.untested > 0 && seen.mode !== 'play') {
1048      right.push(<Button key="test" label="Test" variant="primary" onPress={() => $.prompt.submit({ text: TEST_PROMPT })} />)
1049    }
1050    if (list.length > 0) {
1051      right.push(
1052        <Button
1053          key="undo"
1054          label="Undo"
1055          onPress={async () => {
1056            $.ui.toast(await undo($, false))
1057          }}
1058        />,
1059      )
1060    }
1061    right.push(hide)
1062
1063    return (
1064      <Box width={width} justifyContent="space-between" alignItems="center">
1065        <Box gap={1} alignItems="center" flexWrap="wrap" flexShrink={1}>
1066          {left}
1067        </Box>
1068        <Box gap={1} alignItems="center" flexShrink={0}>
1069          {right}
1070        </Box>
1071      </Box>
1072    )
1073  })
1074}
1075
hooks/diff.ts 111 lines
1// Line diffs of a script before and after an edit, for the replay theater.
2
3export type LineDiff = {
4  added: number
5  removed: number
6  /** A unified diff with @@ hunk headers, as a `Code` element draws it under `format: 'diff'`. */
7  unified: string
8}
9
10const CONTEXT = 2
11const MAX_CELLS = 4_000_000
12
13type Op = { kind: ' ' | '-' | '+'; line: string; oldNo: number; newNo: number }
14
15// The edit script between two line lists: a longest common subsequence on
16// what differs once the shared head and tail are set aside.
17function operations(a: readonly string[], b: readonly string[]): Op[] {
18  let head = 0
19  while (head < a.length && head < b.length && a[head] === b[head]) head += 1
20  let tail = 0
21  while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail += 1
22
23  const midA = a.slice(head, a.length - tail)
24  const midB = b.slice(head, b.length - tail)
25  const ops: Op[] = []
26  for (let i = 0; i < head; i += 1) ops.push({ kind: ' ', line: a[i] ?? '', oldNo: i + 1, newNo: i + 1 })
27
28  if (midA.length * midB.length > MAX_CELLS) {
29    // Too large to align: the middle reads as replaced.
30    midA.forEach((line, i) => ops.push({ kind: '-', line, oldNo: head + i + 1, newNo: head + 1 }))
31    midB.forEach((line, i) => ops.push({ kind: '+', line, oldNo: head + midA.length + 1, newNo: head + i + 1 }))
32  } else {
33    const n = midA.length
34    const m = midB.length
35    const table: number[][] = Array.from({ length: n + 1 }, () => new Array<number>(m + 1).fill(0))
36    for (let i = n - 1; i >= 0; i -= 1) {
37      for (let j = m - 1; j >= 0; j -= 1) {
38        table[i]![j] = midA[i] === midB[j] ? table[i + 1]![j + 1]! + 1 : Math.max(table[i + 1]![j]!, table[i]![j + 1]!)
39      }
40    }
41    let i = 0
42    let j = 0
43    while (i < n || j < m) {
44      if (i < n && j < m && midA[i] === midB[j]) {
45        ops.push({ kind: ' ', line: midA[i]!, oldNo: head + i + 1, newNo: head + j + 1 })
46        i += 1
47        j += 1
48      } else if (j < m && (i === n || table[i]![j + 1]! > table[i + 1]![j]!)) {
49        // On a tie the removal goes first, as diffs read.
50        ops.push({ kind: '+', line: midB[j]!, oldNo: head + i + 1, newNo: head + j + 1 })
51        j += 1
52      } else {
53        ops.push({ kind: '-', line: midA[i]!, oldNo: head + i + 1, newNo: head + j + 1 })
54        i += 1
55      }
56    }
57  }
58
59  for (let k = 0; k < tail; k += 1) {
60    const oldNo = a.length - tail + k + 1
61    const newNo = b.length - tail + k + 1
62    ops.push({ kind: ' ', line: a[oldNo - 1] ?? '', oldNo, newNo })
63  }
64  return ops
65}
66
67/** The diff of a script from `before` (null: it did not exist) to `after`. */
68export function lineDiff(before: string | null, after: string): LineDiff {
69  const a = before === null || before === '' ? [] : before.split('\n')
70  const b = after === '' ? [] : after.split('\n')
71  const ops = operations(a, b)
72  const added = ops.filter(op => op.kind === '+').length
73  const removed = ops.filter(op => op.kind === '-').length
74
75  // Hunks: each change with CONTEXT unchanged lines around it, merged when close.
76  const changed = ops.map((op, i) => (op.kind === ' ' ? -1 : i)).filter(i => i !== -1)
77  const hunks: [number, number][] = []
78  for (const i of changed) {
79    const from = Math.max(0, i - CONTEXT)
80    const to = Math.min(ops.length - 1, i + CONTEXT)
81    const last = hunks[hunks.length - 1]
82    if (last !== undefined && from <= last[1] + 1) last[1] = Math.max(last[1], to)
83    else hunks.push([from, to])
84  }
85
86  const lines: string[] = []
87  for (const [from, to] of hunks) {
88    const part = ops.slice(from, to + 1)
89    const oldCount = part.filter(op => op.kind !== '+').length
90    const newCount = part.filter(op => op.kind !== '-').length
91    const first = part[0]!
92    const oldStart = oldCount === 0 ? first.oldNo - 1 : first.oldNo
93    const newStart = newCount === 0 ? first.newNo - 1 : first.newNo
94    lines.push(`@@ -${oldStart},${oldCount} +${newStart},${newCount} @@`)
95    for (const op of part) lines.push(`${op.kind}${op.line}`)
96  }
97  return { added, removed, unified: lines.join('\n') }
98}
99
100/**
101 * The first sentence of Claude's reply that says something, short enough for
102 * a card: a bare "Done." or "All set!" is passed over.
103 */
104export function firstSentence(text: string, max = 160): string {
105  const plain = text.replace(/[`*_#>]/g, '').replace(/\s+/g, ' ').trim()
106  // A sentence ends at . ! or ? followed by a space, so Workspace.House.Door stays whole.
107  const sentences = plain.split(/(?<=[.!?])\s+/)
108  const sentence = (sentences.find(one => one.trim().split(' ').length >= 4) ?? sentences[0] ?? plain).trim()
109  return sentence.length > max ? `${sentence.slice(0, max - 1)}…` : sentence
110}
111
hooks/activity.ts 147 lines
1// What Claude touched in the open place, for the Studio activity pane.
2import type { PropMap, TouchAction, TouchedItem } from '../types'
3
4// Stronger actions win when Claude touches the same thing twice.
5const STRENGTH: Record<TouchAction, number> = { read: 0, changed: 1, edited: 2, created: 3 }
6
7/** A dot path as one display form: no `game.`, `workspace` as `Workspace`. */
8export function normalizePath(path: string): string {
9  return path
10    .trim()
11    .replace(/^game\./, '')
12    .replace(/^workspace(?=\.|$)/, 'Workspace')
13}
14
15/** The service a path lies in: its first segment. */
16export const serviceOf = (path: string) => normalizePath(path).split('.')[0] ?? path
17
18/** The last segment of a path, what a row shows. */
19export const leafOf = (path: string) => normalizePath(path).split('.').pop() ?? path
20
21/**
22 * Adds or updates one touched item: a new path goes to the end, a known one
23 * keeps its place and its strongest action. `isActive` marks a call in flight.
24 */
25export function touch(
26  list: readonly TouchedItem[],
27  item: Omit<TouchedItem, 'seq' | 'path'> & { path: string },
28): TouchedItem[] {
29  const path = normalizePath(item.path)
30  const at = list.findIndex(one => one.path === path)
31  if (at === -1) {
32    const seq = (list[list.length - 1]?.seq ?? 0) + 1
33    return [...list, { ...item, path, seq }]
34  }
35  const old = list[at]!
36  const action = STRENGTH[item.action] >= STRENGTH[old.action] ? item.action : old.action
37  const next = [...list]
38  next[at] = {
39    ...old,
40    action,
41    kind: item.kind,
42    isActive: item.isActive,
43    activeAs: item.activeAs,
44    // The first state Claude saw, and the latest it left.
45    propsBefore: old.propsBefore !== undefined ? old.propsBefore : item.propsBefore,
46    propsAfter: item.propsAfter !== undefined ? item.propsAfter : old.propsAfter,
47  }
48  return next
49}
50
51/** An object's properties from inspect_instance's JSON answer. */
52export function parseProps(text: string): PropMap | undefined {
53  try {
54    const info = JSON.parse(text) as { properties?: Record<string, unknown> }
55    if (info.properties === undefined) return undefined
56    const props: Record<string, string | number | boolean> = {}
57    for (const [name, value] of Object.entries(info.properties)) {
58      if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') props[name] = value
59    }
60    return props
61  } catch {
62    return undefined
63  }
64}
65
66// Properties that change by themselves or say nothing to a person.
67const NOISE = new Set(['UniqueId', 'AssemblyLinearVelocity', 'AssemblyAngularVelocity', 'Capabilities', 'Sandboxed'])
68
69/** The properties that differ between two states of an object, by name. */
70export function propChanges(before: PropMap, after: PropMap): { name: string; before: string; after: string }[] {
71  const names = [...new Set([...Object.keys(before), ...Object.keys(after)])].filter(name => !NOISE.has(name)).sort()
72  return names
73    .filter(name => before[name] !== after[name])
74    .map(name => ({ name, before: showValue(name, before[name]), after: showValue(name, after[name]) }))
75}
76
77/** A property value as a person reads it: colours as RGB, enums by name, rounded numbers. */
78export function showValue(name: string, value: string | number | boolean | undefined): string {
79  if (value === undefined) return '(none)'
80  if (typeof value === 'number') return String(Math.round(value * 1000) / 1000)
81  if (typeof value === 'boolean') return String(value)
82  if (/Color/.test(name) && /^-?[\d.]+, -?[\d.]+, -?[\d.]+$/.test(value)) {
83    const rgb = value.split(',').map(part => Math.round(Number(part) * 255))
84    return `rgb(${rgb.join(', ')})`
85  }
86  if (value.startsWith('Enum.')) return value.split('.').pop() ?? value
87  const numbers = value.split(',').map(part => part.trim())
88  if (numbers.length > 1 && numbers.every(part => /^-?[\d.e-]+$/.test(part))) {
89    return numbers.map(part => String(Math.round(Number(part) * 100) / 100)).join(', ')
90  }
91  return value.length > 40 ? `${value.slice(0, 39)}…` : value
92}
93
94/** Marks every item settled, at the end of a call. */
95export const settle = (list: readonly TouchedItem[], path: string) =>
96  list.map(one => (one.path === normalizePath(path) ? { ...one, isActive: false, activeAs: null } : one))
97
98const ROOT = String.raw`(?:game|workspace)(?:\.[A-Za-z_]\w*)+`
99const MUTATING = 'Destroy|ClearAllChildren|SetAttribute|PivotTo|MoveTo|AddTag|RemoveTag|Remove|ScaleTo|SetPrimaryPartCFrame'
100const ASSIGN = new RegExp(`\\b(${ROOT})\\s*=(?!=)`, 'g')
101const CALL = new RegExp(`\\b(${ROOT})\\s*:\\s*(?:${MUTATING})\\s*\\(`, 'g')
102
103/**
104 * The instances Luau changes, as far as its text shows: `workspace.Part.Color = x`
105 * changes Workspace.Part, `workspace.Old:Destroy()` changes Workspace.Old.
106 * Changes made through a local variable are not seen.
107 */
108export function pathsChanged(code: string): string[] {
109  const found: string[] = []
110  const add = (path: string) => {
111    const normal = normalizePath(path)
112    if (normal.includes('.') && !found.includes(normal)) found.push(normal)
113  }
114  for (const match of code.matchAll(ASSIGN)) {
115    const segments = (match[1] ?? '').split('.')
116    add(segments.slice(0, -1).join('.'))
117  }
118  for (const match of code.matchAll(CALL)) add(match[1] ?? '')
119  return found
120}
121
122/** One line saying what Claude did, for the pane's card. */
123export function summarize(list: readonly TouchedItem[]): { title: string; detail: string } {
124  const scripts = (action: TouchAction) => list.filter(one => one.kind === 'script' && one.action === action)
125  const edited = [...scripts('created'), ...scripts('edited')]
126  const changed = list.filter(one => one.kind === 'instance' && (one.action === 'changed' || one.action === 'created'))
127  const read = list.filter(one => one.action === 'read')
128
129  const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`
130  const parts: string[] = []
131  if (edited.length > 0) parts.push(`edited ${plural(edited.length, 'script')}`)
132  if (changed.length > 0) parts.push(`changed ${plural(changed.length, 'object')}`)
133  const title =
134    parts.length > 0
135      ? `Claude ${parts.join(', ')}`
136      : read.length > 0
137        ? `Claude read ${plural(read.length, 'item')}`
138        : 'Nothing touched yet'
139
140  const names = [...edited, ...changed].map(one => leafOf(one.path))
141  const shown = names.slice(0, 3).join(', ') + (names.length > 3 ? ` +${names.length - 3}` : '')
142  const detail = [shown, read.length > 0 && parts.length > 0 ? `read ${read.length}` : '']
143    .filter(text => text !== '')
144    .join(' · ')
145  return { title, detail }
146}
147
hooks/lint.ts 251 lines
1import type { LintIssue, RemoteHandler } from '../types'
2
3type Rule = {
4  id: string
5  pattern: RegExp
6  message: string
7  // Match against the line with string literals kept (default: blanked).
8  keepsStrings?: boolean
9  unless?: RegExp
10  when?: (path: string) => boolean
11}
12
13const SERVICES = [
14  'Players',
15  'ReplicatedStorage',
16  'ServerStorage',
17  'ServerScriptService',
18  'RunService',
19  'UserInputService',
20  'TweenService',
21  'DataStoreService',
22  'HttpService',
23  'MarketplaceService',
24  'CollectionService',
25  'SoundService',
26  'StarterGui',
27  'Debris',
28]
29
30// A script that runs on the server: under ServerScriptService or
31// ServerStorage, or named `*.server.luau` (how a new Script is passed in).
32export const isServerScript = (path: string) =>
33  /\.server\.luau?$/i.test(path) || /(^|\.)(ServerScriptService|ServerStorage)\./.test(path)
34
35export const RULES: readonly Rule[] = [
36  {
37    id: 'task-wait',
38    pattern: /(^|[^.:\w])wait\s*\(/,
39    unless: /function\s+wait\b/,
40    message: 'wait() is deprecated and throttled; use task.wait().',
41  },
42  {
43    id: 'task-spawn',
44    pattern: /(^|[^.:\w])spawn\s*\(/,
45    unless: /function\s+spawn\b/,
46    message: 'spawn() is deprecated; use task.spawn() or task.defer().',
47  },
48  {
49    id: 'task-delay',
50    pattern: /(^|[^.:\w])delay\s*\(/,
51    unless: /function\s+delay\b/,
52    message: 'delay() is deprecated; use task.delay().',
53  },
54  {
55    id: 'instance-parent-arg',
56    pattern: /Instance\.new\s*\(\s*(["'])[^"']*\1\s*,/,
57    keepsStrings: true,
58    message: "Instance.new's parent argument is slow; set properties first and .Parent last.",
59  },
60  {
61    id: 'get-service',
62    pattern: new RegExp(`\\bgame\\.(${SERVICES.join('|')})\\b`),
63    message: 'Get services with game:GetService("Name") instead of game.Name.',
64  },
65  {
66    id: 'lowercase-method',
67    pattern: /:(connect|disconnect|wait|findFirstChild|getChildren|remove|clone|destroy|isA)\s*\(/,
68    message: 'Lowercase Roblox methods are deprecated; use the PascalCase name (:Connect, :FindFirstChild, :Destroy, ...).',
69  },
70  {
71    id: 'server-localplayer',
72    pattern: /\bLocalPlayer\b/,
73    when: isServerScript,
74    message: 'Players.LocalPlayer is nil on the server; take the player from the event or Players:GetPlayers().',
75  },
76]
77
78const MAX_ISSUES = 30
79
80// Splits one line into code with strings kept and code with strings blanked,
81// dropping comments. `inBlock` carries a --[[ block comment across lines.
82function scanLine(line: string, inBlock: boolean) {
83  let code = ''
84  let bare = ''
85  let i = 0
86
87  if (inBlock) {
88    const end = line.indexOf(']]')
89    if (end === -1) return { code, bare, inBlock: true }
90    i = end + 2
91  }
92
93  while (i < line.length) {
94    const ch = line[i]
95    if (ch === '"' || ch === "'") {
96      let j = i + 1
97      while (j < line.length && line[j] !== ch) j += line[j] === '\\' ? 2 : 1
98      code += line.slice(i, j + 1)
99      bare += ch + ch
100      i = j + 1
101      continue
102    }
103    if (ch === '-' && line[i + 1] === '-') {
104      if (/^--\[=*\[/.test(line.slice(i))) {
105        const end = line.indexOf(']]', i)
106        if (end === -1) return { code, bare, inBlock: true }
107        i = end + 2
108        continue
109      }
110      break
111    }
112    code += ch
113    bare += ch
114    i += 1
115  }
116
117  return { code, bare, inBlock: false }
118}
119
120/**
121 * Checks Luau source for deprecated or risky Roblox patterns. `firstLine` is
122 * the 1-based line the source starts at in its file (for a snippet).
123 */
124export function lintLuau(path: string, source: string, firstLine = 1): LintIssue[] {
125  const issues: LintIssue[] = []
126  const rules = RULES.filter(rule => rule.when === undefined || rule.when(path))
127  let inBlock = false
128
129  source.split(/\r?\n/).forEach((line, index) => {
130    const scanned = scanLine(line, inBlock)
131    inBlock = scanned.inBlock
132
133    for (const rule of rules) {
134      const text = rule.keepsStrings ? scanned.code : scanned.bare
135      if (rule.pattern.test(text) && !rule.unless?.test(text)) {
136        issues.push({ line: firstLine + index, rule: rule.id, message: rule.message })
137      }
138    }
139  })
140
141  return issues.slice(0, MAX_ISSUES)
142}
143
144const HANDLER =
145  /(OnServerEvent:Connect\s*\(\s*function|OnServerInvoke\s*=\s*function)\s*\(([^)]*)\)/
146const HANDLER_LINES = 200
147const GATE_LINES = 6
148const GATE =
149  /\bif\s+not\s+\w*(admin|owner|allowed|whitelist|permi|authori[sz]|staff|mod)\w*\s*\(\s*\w+|\.UserId\s*[~=]=|:GetRankInGroup\s*\(|:IsInGroup\s*\(/i
150
151// Ways a server handler checks a value it got from the client.
152const checks = (name: string) => {
153  const n = name === '...' ? '\\.\\.\\.' : name
154  return new RegExp(
155    [
156      `typeof\\s*\\(\\s*${n}\\b`,
157      `\\btype\\s*\\(\\s*${n}\\b`,
158      `tonumber\\s*\\(\\s*${n}\\b`,
159      `assert\\s*\\([^)]*\\b${n}\\b`,
160      `\\bif\\s+not\\s+${n}\\b`,
161      `\\b${n}\\s*[~=]=`,
162      `[=~]=\\s*${n}\\b`,
163      `table\\.find\\s*\\([^)]*\\b${n}\\b`,
164      `\\[\\s*${n}\\s*\\]`,
165      `math\\.clamp\\s*\\(\\s*${n}\\b`,
166      `select\\s*\\(\\s*["']#["']`,
167    ].join('|'),
168  )
169}
170
171// The lines of the function that opens on lines[start], found by counting
172// Luau blocks (function/do/then/repeat against end/until) outside strings and
173// comments; at most HANDLER_LINES lines.
174function handlerBody(lines: readonly string[], start: number): string[] {
175  let depth = 0
176  let inBlock = false
177  const body: string[] = []
178  for (let i = start; i < lines.length && body.length < HANDLER_LINES; i += 1) {
179    const scanned = scanLine(lines[i] ?? '', inBlock)
180    inBlock = scanned.inBlock
181    for (const word of scanned.bare.match(/\b(function|do|then|repeat|elseif|end|until)\b/g) ?? []) {
182      depth += word === 'end' || word === 'until' || word === 'elseif' ? -1 : 1
183    }
184    if (i > start) body.push(lines[i] ?? '')
185    if (depth <= 0) break
186  }
187  return body
188}
189
190/**
191 * Every RemoteEvent and RemoteFunction server handler in a script, and how it
192 * treats what the client sends: `unchecked` uses values without checking
193 * them, `gated` first limits who may call it (admins, the owner), `checked`
194 * checks every value, `no-args` takes nothing from the client. Luau type
195 * annotations are not checks: an exploiter can send any value whatever the
196 * annotation says.
197 */
198export function scanRemotes(source: string, firstLine = 1): RemoteHandler[] {
199  const lines = source.split(/\r?\n/)
200  const handlers: RemoteHandler[] = []
201
202  lines.forEach((line, index) => {
203    const match = HANDLER.exec(line)
204    if (match === null) return
205
206    const params = (match[2] ?? '')
207      .split(',')
208      .map(param => (param.split(':')[0] ?? '').trim())
209      .filter(param => param.length > 0)
210      .slice(1)
211    const remote = /(\w+)\s*\.\s*OnServer(?:Event|Invoke)/.exec(line)?.[1] ?? '?'
212    const kind = /OnServerInvoke/.test(match[1] ?? '') ? 'function' : 'event'
213    const bodyLines = handlerBody(lines, index)
214    const body = bodyLines.join('\n')
215    const opening = bodyLines.slice(0, GATE_LINES).join('\n')
216    const unchecked = params.filter(param => !checks(param).test(body))
217    const status =
218      params.length === 0 ? 'no-args' : GATE.test(opening) ? 'gated' : unchecked.length > 0 ? 'unchecked' : 'checked'
219
220    handlers.push({
221      line: firstLine + index,
222      remote,
223      kind,
224      status,
225      unchecked: status === 'unchecked' ? unchecked : [],
226    })
227  })
228
229  return handlers
230}
231
232/** The unchecked handlers of `scanRemotes`, as findings for Claude. */
233export function auditRemotes(source: string, firstLine = 1): LintIssue[] {
234  return scanRemotes(source, firstLine)
235    .filter(handler => handler.status === 'unchecked')
236    .map(handler => ({
237      line: handler.line,
238      rule: 'remote-unchecked',
239      message: `This server handler uses ${handler.unchecked.join(', ')} from the client without checking it. Exploiters can send any value (type annotations are not enforced): check typeof, ranges, cooldowns and ownership before use.`,
240    }))
241}
242
243export function formatIssues(file: string, issues: readonly LintIssue[]): string {
244  const lines = issues.map(issue => `  L${issue.line} ${issue.rule}: ${issue.message}`)
245  return [
246    `roclaude found ${issues.length} Roblox/Luau issue(s) in ${file}:`,
247    ...lines,
248    'Fix these in the code you just wrote unless the legacy behavior is intended.',
249  ].join('\n')
250}
251
hooks/studio.ts 163 lines
1// Pure helpers for the Roblox Studio MCP server's tools.
2
3/** `mcp__Roblox_Studio__multi_edit` → { server: 'Roblox_Studio', name: 'multi_edit' } */
4export function studioTool(tool: string): { server: string; name: string } | null {
5  const match = /^mcp__(.+?)__([a-z_]+)$/.exec(tool)
6  if (match === null || !/roclaude|studio/i.test(match[1] ?? '')) return null
7  return { server: match[1] ?? '', name: match[2] ?? '' }
8}
9
10/** script_read answers `     1→line`; this gives back the source. */
11export function stripLineNumbers(text: string): string {
12  return text
13    .split('\n')
14    .map(line => line.replace(/^\s*\d+→/, ''))
15    .join('\n')
16}
17
18/** Luau that finds an instance by its dot path (`game.ServerScriptService.Main`). */
19export function luauLookup(path: string): string {
20  const parts = path.replace(/^game\./, '').split('.')
21  const steps = parts.map(part => `:FindFirstChild(${JSON.stringify(part)})`).join('')
22  return `game${steps}`
23}
24
25const SCRIPT_WRITE =
26  /\.Source\s*=(?!=)|UpdateSourceAsync|Instance\.new\s*\(\s*["'](Script|LocalScript|ModuleScript)["']/
27
28/**
29 * Whether Luau run in Studio writes or creates script source, which belongs
30 * in multi_edit, where roclaude can keep undo copies, review the code and
31 * protect Team Create collaborators.
32 */
33export const writesScripts = (code: string) => SCRIPT_WRITE.test(code)
34
35const MUTATION =
36  /[\w\])]\.[A-Za-z_]\w*\s*=(?!=)|:(Destroy|ClearAllChildren|Clone|SetAttribute|PivotTo|MoveTo|AddTag|RemoveTag|Remove|ScaleTo|SetPrimaryPartCFrame)\s*\(|Instance\.new\s*\(/
37
38/** Whether Luau run in Studio likely changes the place (sets a property, adds or removes things). */
39export const changesPlace = (code: string) => MUTATION.test(code)
40
41/** Studio's mode from get_studio_state's answer: `Current Studio Mode: Edit`. */
42export function studioMode(text: string): 'edit' | 'play' | null {
43  const mode = /Current Studio Mode:\s*(\w+)/i.exec(text)?.[1]
44  if (mode === undefined) return null
45  return mode.toLowerCase() === 'edit' ? 'edit' : 'play'
46}
47
48/** Whether a tool's error says the place is in a playtest. */
49export const saysPlaying = (text: string) => /not available in Play mode|in Play mode/i.test(text)
50
51export type Danger = { id: string; reason: string }
52
53const DANGERS: readonly (Danger & { pattern: RegExp })[] = [
54  {
55    id: 'destroy',
56    pattern: /:(Destroy|ClearAllChildren)\s*\(|Debris:AddItem\s*\(/,
57    reason: 'deletes instances from the place',
58  },
59  {
60    id: 'datastore-write',
61    pattern: /:(SetAsync|UpdateAsync|RemoveAsync|IncrementAsync)\s*\(/,
62    reason: 'writes to DataStores, which can change real player data',
63  },
64  {
65    id: 'players',
66    pattern: /:(BanAsync|UnbanAsync|Kick)\s*\(/,
67    reason: 'kicks or bans players',
68  },
69  {
70    id: 'remote-code',
71    pattern: /\brequire\s*\(\s*\d{5,}\s*\)|InsertService:LoadAsset/,
72    reason: 'loads code or assets by id from outside the place',
73  },
74]
75
76/** What a piece of Luau run in Studio would do that the person should approve first. */
77export function dangersIn(code: string): Danger[] {
78  return DANGERS.filter(danger => danger.pattern.test(code)).map(({ id, reason }) => ({ id, reason }))
79}
80
81/** Counts error lines in Studio's Output, as get_console_output returns it. */
82export function countErrors(output: string): number {
83  return output
84    .split('\n')
85    .filter(line => /^[\w.]+:\d+: /.test(line) || /^(Error|Script error)/i.test(line)).length
86}
87
88/** The studio name from list_roblox_studios' JSON answer. */
89export function studioName(text: string): string | null {
90  try {
91    const info = JSON.parse(text) as { studios?: { name?: unknown }[] }
92    const name = info.studios?.[0]?.name
93    return typeof name === 'string' ? name.replace(/\s*\(placeId:.*\)$/, '') : null
94  } catch {
95    return null
96  }
97}
98
99export const GREP_CAP = 50
100
101// Third-party code a game embeds: admin kits and package folders.
102const VENDOR =
103  /Kohl'?s Admin|Adonis|HD ?Admin|Building Tools|(^|[\\/.])Cmdr([\\/.]|$)|(^|[\\/.])(Dev)?Packages([\\/.]|$)|_Index/i
104
105/** Whether a script path (dot or file) lies inside third-party code. */
106export const isVendor = (path: string) => VENDOR.test(path)
107
108/** The scripts script_grep found, in order, from its `Path: X | Line: N | ...` lines. */
109export function grepScripts(text: string): { scripts: string[]; matches: number } {
110  const scripts: string[] = []
111  let matches = 0
112  for (const line of text.split('\n')) {
113    const match = /^Path: (.+?) \| Line: \d+ \|/.exec(line)
114    if (match === null) continue
115    matches += 1
116    const path = match[1] ?? ''
117    if (!scripts.includes(path)) scripts.push(path)
118  }
119  return { scripts, matches }
120}
121
122/**
123 * Who is in the Team Create session, from Studio's Output: `X joined live
124 * editing session.` adds X and a line saying X left removes them.
125 */
126export function teamFrom(output: string, before: readonly string[]): string[] {
127  const team = [...before]
128  for (const line of output.split('\n')) {
129    const joined = /^(\S+) joined (the )?live editing session/i.exec(line)
130    const left = /^(\S+) (left|disconnected from|has left) (the )?live editing session/i.exec(line)
131    const name = joined?.[1] ?? left?.[1]
132    if (name === undefined) continue
133    const at = team.indexOf(name)
134    if (joined !== null && at === -1) team.push(name)
135    if (left !== null && at !== -1) team.splice(at, 1)
136  }
137  return team
138}
139
140/** What Claude last read of a script: its lines from `start` (1-based), whole or a range. */
141export type SeenText = { start: number; lines: readonly string[]; isWhole: boolean }
142
143/** Whether a script still reads as Claude last saw it. */
144export function stillAsSeen(seen: SeenText, source: string): boolean {
145  const lines = source.split('\n')
146  if (seen.isWhole && lines.length !== seen.lines.length) return false
147  return seen.lines.every((line, i) => lines[seen.start - 1 + i] === line)
148}
149
150/** A script path as one key, with or without the leading `game.`. */
151export const scriptKey = (path: string) => path.replace(/^game\./, '')
152
153/** The first studio's id from list_roblox_studios' JSON answer. */
154export function studioId(text: string): string | null {
155  try {
156    const info = JSON.parse(text) as { studios?: { id?: unknown }[] }
157    const id = info.studios?.[0]?.id
158    return typeof id === 'string' ? id : null
159  } catch {
160    return null
161  }
162}
163
types/index.d.ts 99 lines
1export type LintIssue = { line: number; rule: string; message: string }
2export type LintReport = { file: string; issues: readonly LintIssue[] }
3
4/**
5 * A script as it was before Claude's multi_edit (`source`, null when the edit
6 * created it) and right after (`after`, null unless `afterStatus` is `read`).
7 */
8export type Snapshot = {
9  id: number
10  server: string
11  studioId: string
12  path: string
13  source: string | null
14  after: string | null
15  /**
16   * How the read right after the edit went: `read`, the script was `missing`,
17   * or `unknown` when Studio did not answer. Only `read` lets a plain undo
18   * tell whether someone changed the script since.
19   */
20  afterStatus: 'read' | 'missing' | 'unknown'
21  /** The turn the edit was made in, for replaying one turn. */
22  turn: number
23}
24
25/**
26 * The Studio MCP server last used and the place's state: its mode, how many
27 * changes Claude made since the last playtest, and that playtest's errors.
28 */
29export type StudioInfo = {
30  name: string | null
31  server: string | null
32  id: string | null
33  errors: number | null
34  mode: 'edit' | 'play' | null
35  untested: number
36}
37
38export type RemoteStatus = 'unchecked' | 'gated' | 'checked' | 'no-args'
39export type RemoteHandler = {
40  line: number
41  remote: string
42  kind: 'event' | 'function'
43  status: RemoteStatus
44  unchecked: readonly string[]
45}
46export type RemoteReport = {
47  scripts: number
48  /** `isVendor`: inside a third-party module (an admin kit, a package), reported apart. */
49  handlers: readonly (RemoteHandler & { script: string; isVendor: boolean })[]
50  note: string | null
51}
52
53export type TouchAction = 'read' | 'edited' | 'created' | 'changed'
54/** An object's properties as Studio's inspect_instance reports them. */
55export type PropMap = Readonly<Record<string, string | number | boolean>>
56/** Something in the place Claude read or changed this session. */
57export type TouchedItem = {
58  path: string
59  kind: 'script' | 'instance'
60  action: TouchAction
61  /** A call on it is in flight, and as what. */
62  isActive: boolean
63  activeAs: 'reading' | 'editing' | 'changing' | null
64  seq: number
65  /**
66   * An object's properties before Claude first changed it this session (null:
67   * it did not exist) and after its latest change (null: it was deleted);
68   * absent when they were not captured.
69   */
70  propsBefore?: PropMap | null
71  propsAfter?: PropMap | null
72}
73
74declare module 'claude-code' {
75  interface PluginState {
76    'roclaude': {
77      lastLint: LintReport | null
78      isHidden: boolean
79      studio: StudioInfo | null
80      history: readonly Snapshot[]
81      remotes: RemoteReport | null
82      /** Who Studio's Output says is in the Team Create session. */
83      team: readonly string[]
84      /** Edits refused because the script changed after Claude read it. */
85      staleBlocks: number
86      /** What Claude read and changed this session, for the activity pane. */
87      touched: readonly TouchedItem[]
88      /** Whether Claude's turn is running. */
89      isWorking: boolean
90      /** Counts the person's prompts, so edits can be grouped by turn. */
91      turn: number
92      /** The touched item whose change the activity view shows. */
93      selected: string | null
94      /** Counts activity cards drawn in the chat; only the newest is live. */
95      cardRun: number
96    }
97  }
98}
99