SLOPSHOPPER

linear-gate

Blocks Linear writes off shift; on shift, leaves them to your permission mode and asks only before a delete or cancel.

rowsguardtoast
★ 2v0.2.0no licenseupdated 2026-10-19cpeaustriajc/cj-stack/mods/linear-gate
A shopper browsing a rack in a slop shop
README

linear-gate

A mod (a plugin that adds a hook to Claude Code) that blocks Linear writes outside your shift. On shift, your permission mode decides, and the mod asks you only before a delete, retire or cancel.

Why

A Linear write is visible to your whole team, and Linear can post it to Slack. After your shift, one write can notify your team at night.

On shift, a dialog for every write costs you many clicks. Auto mode can decide most writes. linear-gate keeps a dialog only for writes that remove or cancel work, and shows a plain description with a diff.

Install

/plugin marketplace add cpeaustriajc/cj-stack
/plugin install linear-gate@cj-stack

To see that it is on, run claude plugin list and look for linear-gate. The install steps in the root README include this mod.

Example

  1. At 20:35, after your 18:00 shift end, Claude calls the Linear tool save_issue.
  2. The mod denies the call. No dialog opens.
  3. Claude reads the reason and puts the draft in the chat.

Claude reads:

linear-gate: off shift (09:00-18:00); a Linear write notifies the team's Slack. Do not retry: draft it in the chat for the next shift.

At 10:00, the same call goes to your permission mode. A call that moves ACME-77 to Canceled opens the dialog "Cancel issue ACME-77 — apply this change?". You pick "Cancel issue ACME-77" or "Leave it", or you type a note.

What it does

EventDecision
Claude or a subagent calls a Linear write tool off shiftDeny it, also in a headless session.
Claude calls a Linear write tool on shiftLeave it to your permission mode.
Claude calls a delete, retire or cancel on shiftAsk you in a dialog.
Claude calls a Linear read toolLet it pass.
You allow the writeRun it, then show a toast with the result.
You pick "Leave it" or type a noteDeny the call. Claude reads the reason.
You close the dialogDeny the call.
No surface (an interface) is attached to the session on shiftAsk nothing. The host decides.

The dialog names the action, such as "Create issue" or "Merge PR". It lists the changed fields. For a document edit, it shows removed text in red and added text in green.

A delete, a retire or a cancel adds the warning "⚠ Everyone on the team sees this."

The mod treats a tool as a write if its name is in the list in hooks/register.tsx. A tool on the linear-server server is also a write if its name starts with a write verb such as save_, delete_ or update_.

Settings

OptionDefaultMeaning
shiftStart09:00The local time your shift starts, 24-hour.
shiftEnd18:00The local time your shift ends. A start after the end crosses midnight.
timeZoneemptyAn IANA zone such as Asia/Manila. Empty uses the zone of your machine.
onShiftdrastichost: your permission mode decides every write. drastic: ask before a delete, retire or cancel. ask: ask before every write.

An hour that is not HH:MM makes both hours fall back to 09:00 and 18:00. Run claude plugin configure linear-gate@cj-stack to set them on your machine.

To turn the mod off, run claude plugin disable linear-gate@cj-stack.

Limits

  • A write tool from another server passes if its name is not in the list.
  • A write tool with a new name on linear-server is gated only if it starts with a write verb.
  • A long text or a long list of edits is cut in the dialog, with a count of what is hidden.
  • If the document title lookup fails, the dialog shows the document id.
  • The toast shows a failure only if the tool reports one.

More

Source 2 files
hooks/register.tsx 365 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4const asks = atom({ plugin: 'linear-gate', key: 'asks' } as const, {} as Record<string, string>)
5
6const LINEAR_WRITES = new Set([
7  'save_issue', 'save_comment', 'save_document', 'save_project', 'save_milestone',
8  'save_initiative', 'save_initiative_label', 'save_issue_label', 'save_project_label',
9  'save_release', 'save_release_note', 'save_status_update', 'save_diff_comment',
10  'create_attachment', 'create_attachment_from_upload', 'create_issue_label',
11  'create_initiative_label', 'delete_attachment', 'delete_comment', 'delete_diff_comment',
12  'delete_status_update', 'merge_diff', 'update_diff', 'submit_diff_review',
13  'resolve_diff_thread', 'retire_issue_label', 'retire_initiative_label',
14  'retire_project_label', 'restore_issue_label', 'restore_initiative_label',
15  'restore_project_label', 'share_issue', 'unshare_issue', 'mark_notification',
16])
17const LINEAR_SERVER_WRITE = /^(save|delete|create|update|merge|submit|resolve|retire|restore|share|unshare|mark)_/
18const LEAVE = 'Leave it'
19const HEADER = 'Linear'
20const CONFIRM = 'Apply this change?'
21const LOOKUP_MS = 3000
22const BUTTON_MAX = 40
23// The engine refuses a dialog with more rows than this around it and draws its own,
24// which would show only the staged question and hide the body.
25const ROWS_MAX = 12
26const NARROW = 60
27const DEFAULT_START = '09:00'
28const DEFAULT_END = '18:00'
29const ON_SHIFT = new Set(['host', 'drastic', 'ask'])
30
31function minutesOf(v: unknown): number | undefined {
32  const m = typeof v === 'string' ? /^([01]\d|2[0-3]):([0-5]\d)$/.exec(v) : null
33  return m ? Number(m[1]) * 60 + Number(m[2]) : undefined
34}
35
36function minuteOfDay(ms: number, zone: string | undefined): number {
37  const [h, m] = new Intl.DateTimeFormat('en-US', { timeZone: zone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
38    .format(new Date(ms)).split(':').map(Number)
39  return h * 60 + m
40}
41
42const inShift = (now: number, start: number, end: number) =>
43  start <= end ? now >= start && now < end : now >= start || now < end
44
45function linearWrite(tool: string): string | undefined {
46  const m = /^mcp__(.+?)__(.+)$/.exec(tool)
47  if (!m) return undefined
48  const [, server, name] = m
49  if (LINEAR_WRITES.has(name)) return name
50  if (server === 'linear-server' && LINEAR_SERVER_WRITE.test(name)) return name
51  return undefined
52}
53
54const EVENT_KEYS = new Set(['tool', 'tool_use_id', 'agentId'])
55const TEXT_KEYS = ['body', 'description', 'content']
56const PR_STATUS: Record<string, string> = {
57  markReadyForReview: 'ready for review', convertToDraft: 'back to draft', close: 'closed', reopen: 'reopened',
58}
59const REVIEW: Record<string, string> = { approved: 'Approve', changesRequested: 'Request changes on', commented: 'Leave a review comment on' }
60
61const HEALTH: Record<string, string> = { onTrack: 'on track', atRisk: 'at risk', offTrack: 'off track' }
62const clip = (s: string, max: number) => (s.length > max ? `${s.slice(0, max)}...` : s)
63const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
64const short = (v: string) => (UUID.test(v) ? `${v.slice(0, 8)}…` : v)
65const flat = (t: string) => t.replace(/^\s*(#+|[-*>]|\d+\.)\s+/gm, '').replace(/[*_`]/g, '').replace(/\s+/g, ' ').trim()
66const isNames = (v: unknown): v is string[] => Array.isArray(v) && v.every(x => typeof x === 'string')
67const shown = (v: unknown) =>
68  clip(typeof v === 'string' ? short(flat(v)) : isNames(v) ? v.map(short).join(', ') : JSON.stringify(v), 80)
69const words = (k: string) => k.replace(/Id$/, '').replace(/([A-Z])/g, ' $1').replace(/_/g, ' ').toLowerCase().trim()
70const FIELD: Record<string, string> = { state: 'Status' }
71const heading = (k: string) => FIELD[k] ?? words(k).replace(/^./, c => c.toUpperCase())
72const STATE_VERB: Record<string, string> = { canceled: 'Cancel', cancelled: 'Cancel', done: 'Complete', completed: 'Complete' }
73const people = (v: unknown) =>
74  (Array.isArray(v) ? v : []).map(r => String(r.user ?? r.externalUserId ?? r.githubTeamId)).join(', ')
75
76function whatItDoes(name: string, a: Record<string, unknown>): [string[], string[]] {
77  const s = (k: string) => (typeof a[k] === 'string' ? (a[k] as string) : undefined)
78  const pr = `PR ${s('urlOrId')}`
79  switch (name) {
80    case 'save_issue': {
81      if (s('id')) return [[`${STATE_VERB[s('state')?.toLowerCase() ?? ''] ?? 'Update'} issue ${short(s('id')!)}`], ['id']]
82      const template = s('template') ? `with template ${s('template')}` : 'with no template'
83      return [[`Create issue "${s('title')}" in ${s('team')} ${template}`], ['title', 'team', 'template']]
84    }
85    case 'save_comment': {
86      const parent = ['issueId', 'projectId', 'documentId', 'initiativeId', 'milestoneId', 'statusUpdateId'].find(k => s(k))
87      const noun = parent?.replace(/Id$/, '').replace(/([A-Z])/g, ' $1').toLowerCase()
88      const where = parent ? ` on ${noun} ${short(s(parent)!)}` : ''
89      if (s('id')) return [[`Edit comment ${short(s('id')!)}`], ['id', ...(parent ? [parent] : [])]]
90      if (s('parentId')) return [[`Reply to a comment${where}`], ['parentId', ...(parent ? [parent] : [])]]
91      return parent ? [[`Comment${where}`], [parent]] : [[], []]
92    }
93    case 'save_status_update': {
94      const health = s('health') ? `, health ${HEALTH[s('health')!] ?? s('health')}` : ''
95      const lines = s('id')
96        ? [`Edit the posted ${s('type')} status update ${s('id')}${health}`]
97        : [`Post a ${s('type')} status update on ${s('project') ?? s('initiative')}${health}`]
98      return [lines, ['type', 'id', 'health', 'project', 'initiative']]
99    }
100    case 'save_project': case 'save_milestone': case 'save_initiative': case 'save_document': {
101      const noun = name.split('_')[1]
102      if (s('id')) return [[`${STATE_VERB[s('state')?.toLowerCase() ?? ''] ?? 'Update'} ${noun} ${short(s('id')!)}`], ['id']]
103      const key = s('name') ? 'name' : 'title'
104      return [[`Create ${noun} "${s(key)}"`], [key]]
105    }
106    case 'delete_status_update':
107      return [[`Delete the ${s('type')} status update ${s('id')}`], ['type', 'id']]
108    case 'update_diff': {
109      const lines: string[] = []
110      if (a.addedReviewRequests) lines.push(`Request review from ${people(a.addedReviewRequests)} on ${pr}`)
111      if (a.removedReviewRequests) lines.push(`Withdraw the review request to ${people(a.removedReviewRequests)} on ${pr}`)
112      for (const l of (Array.isArray(a.addedIssueLinks) ? a.addedIssueLinks : []) as { issue: string; type: string }[])
113        lines.push(`Link ${l.issue} (${l.type}) to ${pr}`)
114      if (a.removedIssueLinks) lines.push(`Unlink ${(a.removedIssueLinks as string[]).join(', ')} from ${pr}`)
115      if (s('statusAction')) lines.push(`Mark ${pr} ${PR_STATUS[s('statusAction')!] ?? s('statusAction')}`)
116      if (!lines.length) lines.push(`Edit ${pr}`)
117      return [lines, ['urlOrId', 'addedReviewRequests', 'removedReviewRequests', 'addedIssueLinks', 'removedIssueLinks', 'statusAction']]
118    }
119    case 'merge_diff':
120      return [[`Merge ${pr}${s('mergeMethod') ? ` (${s('mergeMethod')!.toLowerCase()})` : ''}`], ['urlOrId', 'mergeMethod']]
121    case 'submit_diff_review':
122      return [[`${REVIEW[s('decision') ?? ''] ?? 'Review'} ${pr}`], ['urlOrId', 'decision']]
123    case 'save_diff_comment': {
124      const verb = a.draft ? 'Save a draft comment on' : s('commentId') ? 'Edit a comment on' : s('parentId') ? 'Reply on' : 'Comment on'
125      return [[`${verb} ${pr}`], ['urlOrId', 'draft', 'commentId', 'parentId', 'draftId', 'anchor', 'anchorContent']]
126    }
127    case 'create_issue_label': case 'create_initiative_label':
128    case 'save_issue_label': case 'save_initiative_label': case 'save_project_label': {
129      const noun = `${name.split('_')[1]} label`
130      if (name.startsWith('save_') && s('id')) return [[`Edit ${noun} ${s('id')}`], ['id']]
131      const where = s('teamId') ? `in team ${short(s('teamId')!)}` : 'for the whole workspace'
132      return [[`Create ${noun} "${s('name')}" ${where}`], ['name', 'teamId']]
133    }
134    case 'retire_issue_label': case 'retire_initiative_label': case 'retire_project_label':
135    case 'restore_issue_label': case 'restore_initiative_label': case 'restore_project_label': {
136      const [verb, kind] = name.split('_')
137      return [[`${heading(verb)} ${kind} label ${s('id') ?? s('name')}`], ['id', 'name']]
138    }
139    case 'resolve_diff_thread':
140      return [[`${a.resolved === false ? 'Reopen' : 'Resolve'} PR thread ${s('threadId')}`], ['threadId', 'resolved']]
141    default:
142      return [[], []]
143  }
144}
145
146const SHOWN_EDITS = 5
147const row = (t: string) => clip(t.replace(/\n/g, ' ⏎ ').replace(/[ \t]+/g, ' ').trim(), 160)
148const quote = (t: string) => `"${clip(row(t), 40)}"`
149const WRAP = 72
150const WRAP_ROWS = 11
151
152function wrapped(mark: string, text: string): string[] {
153  return block(`  ${mark} `, '    ', text, l => l)
154}
155
156const unmark = (l: string) => l.replace(/^\s*(#+|[-*>]|\d+\.)\s+/, '').replace(/[*_`]/g, '')
157
158function block(first: string, rest: string, text: string, tidy: (line: string) => string): string[] {
159  const rows = text.split('\n').map(l => tidy(l).replace(/\s+/g, ' ').trim()).filter(Boolean).flatMap(line => {
160    const out: string[] = []
161    let cur = ''
162    for (let word of line.split(' ')) {
163      while (word.length > WRAP) {
164        if (cur) out.push(cur), (cur = '')
165        out.push(word.slice(0, WRAP)), (word = word.slice(WRAP))
166      }
167      if (cur && cur.length + 1 + word.length > WRAP) out.push(cur), (cur = '')
168      cur = cur ? `${cur} ${word}` : word
169    }
170    return cur ? [...out, cur] : out
171  })
172  const kept = rows.slice(0, WRAP_ROWS).map((r, i) => (i ? `${rest}${r}` : `${first}${r}`))
173  const hidden = rows.slice(WRAP_ROWS).join(' ').length
174  return hidden ? [...kept, `${rest}… ${hidden} more characters`] : kept
175}
176
177function patchLines(patch: unknown[]): string[] {
178  const lines = patch.slice(0, SHOWN_EDITS).flatMap((raw, i) => {
179    const op = (raw ?? {}) as Record<string, string>
180    const added = (t: string | undefined) => (t ? wrapped('+', t) : [])
181    const body = (() => {
182      switch (op.op) {
183        case 'replace':
184          return [...(op.replace_all ? ['Every match:'] : []), ...wrapped('−', op.old_string), ...added(op.new_string)]
185        case 'insert_before': return [`Before ${quote(op.anchor)}:`, ...added(op.text)]
186        case 'insert_after': return [`After ${quote(op.anchor)}:`, ...added(op.text)]
187        case 'prepend': return ['At the start:', ...added(op.text)]
188        case 'append': return ['At the end:', ...added(op.text)]
189        case 'replace_range':
190          return [`From ${quote(op.from)} up to ${quote(op.to)}:`, ...added(op.new_string)]
191        default: return [`  ${shown(raw)}`]
192      }
193    })()
194    return [...(i ? [''] : []), ...body.map(l => (l.startsWith('  ') ? l : `  ${l}`))]
195  })
196  const rest = patch.length - SHOWN_EDITS
197  return rest > 0 ? [...lines, '', `  …and ${rest} more edit${rest === 1 ? '' : 's'}`] : lines
198}
199
200function actionOf(name: string, args: Record<string, unknown>): string[] {
201  const [lines] = whatItDoes(name, args)
202  return lines.length ? lines : [`${heading(name)} (${name})`]
203}
204
205function isChange(name: string, args: Record<string, unknown>): boolean {
206  return /^(update|merge|submit|resolve)_/.test(name) || (/^save_/.test(name) && typeof args.id === 'string')
207}
208
209function isDrastic(name: string, args: Record<string, unknown>): boolean {
210  return /^(delete|retire)_/.test(name) || STATE_VERB[String(args.state).toLowerCase()] === 'Cancel'
211}
212
213function describeWrite(name: string, args: Record<string, unknown>): string {
214  const [, covered] = whatItDoes(name, args)
215  const change = isChange(name, args)
216  const sep = change ? ' → ' : ': '
217  const label = (k: string) => (change ? heading(k) : heading(k.replace(/^add([A-Z])/, (_, c: string) => c.toLowerCase())))
218  const textKey = TEXT_KEYS.find(k => typeof args[k] === 'string')
219  const patch = Array.isArray(args.patch) ? args.patch : undefined
220  const fields = Object.keys(args)
221    .filter(k => !EVENT_KEYS.has(k) && !covered.includes(k) && k !== textKey && !(patch && k === 'patch'))
222    .map(k => `  ${label(k)}${sep}${shown(args[k])}`)
223  if (textKey) {
224    const text = args[textKey] as string
225    if (name === 'save_comment') fields.push(...(fields.length ? [''] : []), ...block('  ', '  ', text, unmark))
226    else {
227      const head = `  ${label(textKey)}${change ? ' →' : ':'}`
228      const rows = block('    ', '    ', text, unmark)
229      const inline = rows.length === 1 && head.length + rows[0].length - 3 <= 76
230      fields.push(...(inline ? [`${head} ${rows[0].trim()}`] : [...(fields.length ? [''] : []), head, ...rows]))
231    }
232  }
233  if (patch) fields.push(...(fields.length ? [''] : []), ...patchLines(patch))
234  const warning = isDrastic(name, args) ? ['', '⚠ Everyone on the team sees this.'] : []
235  return [...actionOf(name, args), ...(fields.length ? ['', ...fields] : []), ...warning, '', CONFIRM].join('\n')
236}
237
238function allowLabel(name: string, args: Record<string, unknown>): string {
239  if (name === 'save_comment') return args.id ? 'Save edit' : args.parentId ? 'Post reply' : 'Post comment'
240  const line = actionOf(name, args)[0]
241  if (line.length <= BUTTON_MAX) return line
242  const cut = line.includes('"') ? -1 : line.search(/ (in|with|on|for) /)
243  const head = cut > 0 && cut <= BUTTON_MAX ? line.slice(0, cut) : line
244  return head.length <= BUTTON_MAX ? head : `${head.slice(0, BUTTON_MAX - 1)}…`
245}
246
247function failure(out: { text?: string; isError?: boolean }): string | undefined {
248  const text = out.text ?? ''
249  if (out.isError) return clip(text || 'the tool reported an error', 100)
250  if (/"success"\s*:\s*false/.test(text)) return clip(text, 100)
251  return undefined
252}
253
254function bodyOf(description: string): string[] {
255  return description.split('\n').slice(2, -2)
256}
257
258function drawnRows(description: string): number {
259  return bodyOf(description).reduce((n, line) => n + Math.max(1, Math.ceil(line.length / NARROW)), 0)
260}
261
262// The dialog's question must reach the engine unchanged: a free-text answer is keyed by
263// the question the dialog drew, and $.ui.ask drops one keyed by anything else.
264async function stage($: Parameters<typeof read>[0], description: string): Promise<string> {
265  const base = `${description.split('\n')[0]} — ${CONFIRM.toLowerCase()}`
266  let question = base
267  await update($, asks, pending => {
268    question = base
269    for (let n = 2; question in pending; n++) question = `${base} (${n})`
270    return { ...pending, [question]: description }
271  })
272  return question
273}
274
275async function documentTitle($: Parameters<typeof read>[0], server: string, id: string): Promise<string | undefined> {
276  try {
277    const timeout = $.clock.sleep(LOOKUP_MS).then(() => undefined, () => new Promise<never>(() => {}))
278    const out = await Promise.race([$.mcp.call(server, 'get_document', { id }), timeout])
279    if (!out || out.isError) return undefined
280    for (const block of out.content) {
281      if (block.type !== 'text') continue
282      const title = (JSON.parse((block as { text: string }).text) as { title?: unknown }).title
283      if (typeof title === 'string' && title) return title
284    }
285  } catch {
286    return undefined
287  }
288  return undefined
289}
290
291
292function diffColor(line: string, current: string | undefined): string | undefined {
293  if (line.startsWith('  − ')) return 'red'
294  if (line.startsWith('  + ')) return 'green'
295  if (line.startsWith('    ') && line.trim()) return current
296  if (line.startsWith('⚠')) return 'yellow'
297  return undefined
298}
299
300export const register: Register = (on, options) => {
301  const set = minutesOf(options.shiftStart) !== undefined && minutesOf(options.shiftEnd) !== undefined
302  const [from, to] = set ? [options.shiftStart as string, options.shiftEnd as string] : [DEFAULT_START, DEFAULT_END]
303  const [start, end] = [minutesOf(from)!, minutesOf(to)!]
304  const zone = typeof options.timeZone === 'string' && options.timeZone ? options.timeZone : undefined
305  const onShift = ON_SHIFT.has(options.onShift as string) ? (options.onShift as string) : 'drastic'
306
307  on('tool.call', async ($, e, next) => {
308    let args = e as unknown as Record<string, unknown>
309
310    const name = linearWrite(e.tool)
311    if (!name) return next(e)
312    const now = minuteOfDay(await $.clock.now(), zone)
313    if (!inShift(now, start, end))
314      return { deny: `${$.plugin.name}: off shift (${from}-${to}); a Linear write notifies the team's Slack. Do not retry: draft it in the chat for the next shift.` }
315    if (onShift === 'host' || (onShift === 'drastic' && !isDrastic(name, args))) return next(e)
316    if ((await $.session.surfaces()).length === 0) return next(e)
317
318    const server = /^mcp__(.+?)__/.exec(e.tool)![1]
319    const title =
320      name === 'save_document' && typeof args.id === 'string' ? await documentTitle($, server, args.id) : undefined
321    if (title) args = { ...args, id: `"${title}"` }
322    const allow = allowLabel(name, args)
323    const description = describeWrite(name, args)
324    const question = drawnRows(description) <= ROWS_MAX ? await stage($, description) : description
325    let answer: string
326    try {
327      answer = await $.ui.ask(question, { options: [allow, LEAVE], header: HEADER })
328    } catch {
329      return { deny: `${$.plugin.name}: the Linear write was not approved (dialog closed or no one to ask).` }
330    } finally {
331      await update($, asks, ({ [question]: _, ...rest }) => rest)
332    }
333    const action = actionOf(name, args).join('; ')
334    if (answer !== allow) {
335      const reason = answer && answer !== LEAVE ? ` Their note: ${answer}` : ''
336      return { deny: `${$.plugin.name}: the user denied this Linear write (${action}).${reason}` }
337    }
338    const out = await next(e)
339    if (out.deny) return out
340    const failed = failure(out)
341    await $.ui.toast(failed ? `✘ ${action} failed: ${failed}` : `✔ ${action}`)
342    return out
343  })
344
345  on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
346    const questions = e.props.questions as { question?: unknown; header?: unknown }[]
347    const q = questions.length === 1 ? questions[0] : undefined
348    const description = q?.header === HEADER && typeof q.question === 'string' ? (await read($, asks))[q.question] : undefined
349    if (!description) return next(e)
350    const { Box, Text } = $.ui.resolve(e)
351    const dialog = await next(e)
352    let color: string | undefined
353    const rows = bodyOf(description).map(line => {
354      color = diffColor(line, color)
355      return <Text color={color}>{line || ' '}</Text>
356    })
357    return (
358      <Box flexDirection="column">
359        {rows}
360        {dialog}
361      </Box>
362    )
363  })
364}
365
types/index.d.ts 8 lines
1export type Asks = Record<string, string>
2
3declare module 'claude-code' {
4  interface PluginState {
5    'linear-gate': { asks: Asks }
6  }
7}
8