SLOPSHOPPER

learning-gate

Enforces the opt-in learning-guardrails skill: keeps Claude from loading it unasked, refuses code edits before triage or when the risk rules flag an edit the…

bandguardcommandtoaststatusprompt
★ 39v0.7.0no licenseupdated 2026-10-162Steaks/skills/plugins/learning-gate
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · learning-gate
› fix the failing auth test and add an audit log call ⏺ 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 › /learned ⎿ learning-gate: Nothing recorded yet. The record fills in as concepts come up. ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

learning-gate

Enforcement for the opt-in learning-guardrails skill.

/plugin install learning-gate --marketplace 2Steaks/skills
  • Claude can't load the skill unless you run /learning-guardrails or name it.
  • While a GATE checkpoint (a high-risk change) is open, code edits are refused and the question is pinned above the prompt. A quick CHECK question never locks.
  • A GATE question Claude forgot to lock, asked in the question dialog or as a 👉 Your move: line, locks anyway.
  • Triage comes first: a code edit with no Guardrail · triage line since your last message is refused, so Claude rates the change before writing it.
  • A tripwire on the skill's rule packs: an edit they flag (a migration, a transaction, an auth path) that the triage didn't GATE is refused. Claude then judges it: a GATE if it changes how that behaves, or a reason on the triage line if not (· not data: test-fixture). The skill writes the rules to .learning/floor.json each session; without that file, only the triage check runs.
  • Prose and files the packs ignore pass. Shell commands aren't edits, so the tripwire doesn't see them.
  • Each session is held only by its own checkpoint, so sessions in the same project never block each other.
  • Every question offers a pause, and a task with a plan is tracked as it goes. Work you paused, checkpoints left open in other sessions, and tasks a session was tracking when it ended are counted in the band: ⏸ 2 paused or unfinished · /pickup to carry on.
  • /pickup loads the skill and, when there's more than one, offers a menu. It recaps the one you pick: a checkpoint's question is re-asked and the gate holds again; a paused task carries on from its next step.
  • /learned shows what your record says you've demonstrated. /audit runs the skill's self-evaluation, tripwire counts included.

The record lives in .learning/ and is kept out of git via .git/info/exclude.

Source 3 files
hooks/register.tsx 774 lines
1// learning-gate: the enforcement half of the learning-guardrails skill.
2// The skill is opt-in: Claude may load it only when the user's latest message runs
3// /learning-guardrails or names it (/pickup and /audit do); any other attempt is refused.
4// The skill writes .learning/locks/<session id>.lock (first line: `TIER · category ·
5// question`) right before it asks a GATE question, and deletes it when the user passes,
6// drops the task, or gives a valid override; a pause keeps it under another name for
7// /pickup. A task with a plan is tracked in <session>.task, which never locks, so a session
8// that ends mid-task can be picked up. Each session is held only by its own lock, so sessions
9// never block each other; the band counts what's paused, open or tracked elsewhere. While this session's lock exists:
10// - code edits are refused, with the open question as the reason;
11// - the question is pinned above the prompt;
12// - every prompt carries it to the model, so it survives a compacted context.
13// Edits inside any .learning/ folder always pass, so the record can update.
14// A project's .learning/ is kept out of git via the repo's local exclude list.
15// Only a GATE locks. A GATE question asked with no lock open (a `👉 Your move:`
16// line, or the question dialog headed with the GATE's category) opens one, so a
17// checkpoint Claude forgot to lock still holds. It never overwrites a lock.
18// It logs the mechanical events (triage, gate open/close, refusals) to
19// .learning/events.jsonl as "by":"mod"; the skill logs the judgement calls.
20// Until the skill is in play this session, its lock is parked, not enforced: the band
21// says so and /pickup resumes it (loading the skill), or picks another from a menu.
22// The tripwire, while the skill is in play: a code edit is refused when no triage line
23// has come since the user's last message, or when the skill's rule packs flag it
24// (.learning/floor.json, which the skill writes each session) and no triage line since
25// then GATEs that category or rates it lower with a reason (`· not data: test-fixture`).
26// An open checkpoint counts as triage. Prose and files the packs ignore always pass.
27// A hook that fails is skipped: the gate fails open, never locking you out.
28import { atom, read, update } from 'claude-code'
29import type { EngineInterface, Register } from 'claude-code'
30
31import type { Cover, GateLock } from '../types'
32import { CATS, changedLines, compileFloor, floorMatches } from './floor.mjs'
33import type { Floor, FloorMatch } from './floor.mjs'
34
35type Engine = EngineInterface
36
37const UNCOVERED: Cover = { triaged: false, gated: [], waived: [] }
38const lockState = atom({ plugin: 'learning-gate', key: 'lock' } as const, null)
39const triageState = atom({ plugin: 'learning-gate', key: 'triage' } as const, null)
40const activeState = atom({ plugin: 'learning-gate', key: 'active' } as const, false)
41const namedState = atom({ plugin: 'learning-gate', key: 'named' } as const, false)
42const unfinishedState = atom({ plugin: 'learning-gate', key: 'unfinished' } as const, 0)
43const coverState = atom({ plugin: 'learning-gate', key: 'cover' } as const, UNCOVERED)
44const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
45const TRIAGE = /Guardrail · (GO|CHECK|GATE) · ([^\n`]+)/g
46const SKILL = 'learning-guardrails'
47const NAMES_SKILL = /learning[\s_-]*guardrails/i
48const isThisSkill = (name: unknown) => typeof name === 'string' && (name === SKILL || name.endsWith(`:${SKILL}`))
49const OPT_IN = `${SKILL} is opt-in: it loads only when the user runs /${SKILL} or names it. Carry on without it.`
50
51const RULES = {
52  id: 'learning-gate:rules',
53  scope: 'session',
54  text: [
55    'The learning-gate plugin is installed. It enforces the checkpoints the learning-guardrails skill opens, and nothing else.',
56    'The learning-guardrails skill is opt-in: load it only when the user runs /learning-guardrails or names it in their latest message. Never load it on your own, even for coding tasks.',
57    "While this session's lock (.learning/locks/<session id>.lock) exists, the plugin refuses code edits and pins the open question above the prompt. Other sessions' locks never hold this one. Close a checkpoint only as the skill allows, and never offer the user a way around one.",
58    "While the skill is in play, it also refuses a code edit made before any triage line since the user's last message, or one the skill's rule packs flag that no triage line since then GATEs or gives a reason for (`· not <category>: <reason-code>`). Write the line, then edit again. Judge the change, not the words: never GATE just to get past it.",
59    "The plugin replaces the skill's hook script: do not install learning-gate.mjs.",
60  ].join('\n'),
61} as const
62
63const PICKUP =
64  'Pick up paused or unfinished work, per the learning-guardrails skill: list it, ask me which if there is more than one, then a three-line recap, and the checkpoint\'s question in full or the next step.'
65const AUDIT = 'Audit the learning guardrails, per section 10 of the learning-guardrails skill.'
66
67export const register: Register = on => {
68  on('session.start', async ($, e, next) => {
69    await tellShells($)
70    await Promise.all([
71      $.command.register({ name: 'learned', description: 'Show what your learning record says you have demonstrated' }),
72      $.command.register({ name: 'pickup', description: 'Pick up paused or unfinished work, from a menu when there are several' }),
73      $.command.register({ name: 'audit', description: 'Audit the learning guardrails against their own logs' }),
74    ])
75    await refresh($)
76
77    return next(e)
78  })
79
80  // Opt-in: the skill is in play once its prompt is expanded (/name, or an allowed Skill call).
81  // Where an organization manages Claude Code this hook never runs for an installed plugin,
82  // so prompt.submit (the slash command) and tool.call (the Skill call) turn it on as well.
83  on('skill.prompt', async ($, e, next) => {
84    if (isThisSkill(e.skill)) await update($, activeState, () => true)
85
86    return next(e)
87  })
88
89  // The gate: refuse Claude loading the skill unasked, and code edits while a checkpoint is open.
90  on('tool.call', async ($, e, next) => {
91    const tool = String(e.tool)
92    let touchesRecord = false
93
94    if (tool === 'Skill' && isThisSkill((e as { skill?: unknown }).skill) && !(await read($, namedState))) {
95      return { deny: OPT_IN }
96    }
97
98    // Every shell, lock.mjs's included, knows which session it runs in: the id this mod enforces.
99    if (tool === 'Bash') await tellShells($)
100
101    // A GATE question in the dialog: lock first, so the gate holds while it's open.
102    if (tool === 'AskUserQuestion' && (await read($, activeState))) {
103      const asked = askedInDialog(e, await read($, triageState))
104      if (asked !== null) await lockIfOpen($, asked)
105    }
106
107    if (EDIT_TOOLS.has(tool)) {
108      const cwd = await $.session.cwd()
109      const target = editTarget(e)
110      const file = target === undefined ? undefined : resolvePath(cwd, target)
111      touchesRecord = file !== undefined && isInRecord(file)
112
113      // Opt-in: a lock only blocks once the skill is in play this session.
114      if (!touchesRecord && (await read($, activeState))) {
115        const lock = await readLock($, file === undefined ? [cwd] : [parentOf(file), cwd])
116        if (lock !== null) {
117          await setLock($, lock)
118          await logEvent($, { e: 'edit_refused', tier: lock.tier.toLowerCase(), label: lock.category, tool })
119
120          return { deny: blockMessage(lock) }
121        }
122        // The tripwire: triage before building, and nothing the rule packs flag slips past it.
123        const refused = file === undefined ? null : await tripwire($, e, tool, file)
124        if (refused !== null) {
125          await logEvent($, refused.event)
126
127          return { deny: refused.message }
128        }
129      }
130    }
131
132    const ran = await next(e)
133    if (tool === 'Skill' && isThisSkill((e as { skill?: unknown }).skill) && ran.deny === undefined) await update($, activeState, () => true)
134    if (touchesRecord) {
135      const target = editTarget(e)
136      if (target !== undefined) await keepPrivate($, resolvePath(await $.session.cwd(), target))
137    }
138    // The lock is written with Write and deleted with Bash: look again after either.
139    if (touchesRecord || tool === 'Bash') await refresh($)
140
141    return ran
142  }).catch(($, e, next) => next(e))
143
144  // Keep the open question in front of the model on every prompt.
145  on('prompt.submit', async ($, e, next) => {
146    const named = NAMES_SKILL.test(e.text)
147    await update($, namedState, () => named)
148    if (isThisSkill(e.command?.name)) await update($, activeState, () => true)
149    const lock = await refresh($)
150    // A new message starts new work, to triage before building. An answer to the open checkpoint doesn't.
151    if (lock === null || !(await read($, activeState))) await uncover($)
152    // Parked checkpoints stay quiet until the user opts back in.
153    if (lock === null || !(named || (await read($, activeState)))) return next(e)
154    const note =
155      `Learning checkpoint open (${label(lock)}): "${lock.question}" ` +
156      'Read this message as the answer unless it plainly is not one (a pickup request is not: re-ask the question in full), and judge it by the learning-guardrails evidence bar. ' +
157      `Code edits stay refused until the checkpoint closes, only as the learning-guardrails skill allows (lock.mjs).`
158
159    return next({ ...e, context: [...(e.context ?? []), note] })
160  }).catch(($, e, next) => next(e))
161
162  // Always on: the rule rides in the system prompt, not on a skill match.
163  on('prompt.compose', async ($, e, next) => {
164    const composed = await next(e)
165
166    return { sections: [...composed.sections, RULES] }
167  })
168
169  // The status line: the open checkpoint, else the last triage line.
170  on('session.append', { door: 'response' }, async ($, e, next) => {
171    if (e.agentId === undefined) {
172      const text = e.message.content.flatMap(block => (block.type === 'text' ? [block.text] : [])).join('\n')
173      const found = [...text.matchAll(TRIAGE)]
174      const last = found.at(-1)?.[0].trim()
175      if (last !== undefined) {
176        await update($, triageState, () => last)
177        showStatus($, await read($, lockState), last, await read($, activeState))
178      }
179      const triaged = triageLines(text)
180      for (const t of triaged) {
181        const lowered = t.waived.length > 0 ? { waived: t.waived.map(w => w.cat), why: t.waived[0]?.why } : {}
182        await logEvent($, { e: 'triage', tier: t.tier.toLowerCase(), what: t.what.slice(0, 80), ...lowered })
183      }
184      if (triaged.length > 0) await cover($, triaged)
185      const asked = (await read($, activeState)) ? askedCheckpoint(text, await read($, triageState)) : null
186      if (asked !== null) await lockIfOpen($, asked)
187    }
188
189    return next(e)
190  })
191
192  // The band above the prompt: the open question, pinned until answered.
193  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
194    const lock = await read($, lockState)
195    if (e.props.hasSurvey) return next(e)
196    const { Box, Text } = $.ui.resolve(e)
197
198    if (lock === null) {
199      const others = await read($, unfinishedState)
200      if (others === 0) return next(e)
201
202      return (
203        <Text dimColor wrap="wrap">
204          ⏸ {others} paused or unfinished · /pickup to carry on
205        </Text>
206      )
207    }
208
209    if (!(await read($, activeState))) {
210      return (
211        <Text dimColor wrap="wrap">
212          ⏸ Paused checkpoint · {label(lock)} · /pickup to carry on
213        </Text>
214      )
215    }
216
217    return (
218      <Box flexDirection="column">
219        <Text color="warning" bold>
220          🛑 Checkpoint open · {label(lock)}
221        </Text>
222        <Text wrap="wrap">{lock.question}</Text>
223        <Text dimColor>Answer below, or type pause to come back later. You can stop; you can't skip.</Text>
224      </Box>
225    )
226  })
227
228  on('command.run', { command: 'learned' }, async $ => ({ text: await learnedSummary($) }))
229
230  on('command.run', { command: 'pickup' }, async $ => {
231    await optIn($)
232    void runSkill($, PICKUP)
233
234    return {}
235  })
236
237  on('command.run', { command: 'audit' }, async $ => {
238    await optIn($)
239    void runSkill($, AUDIT)
240
241    return {}
242  })
243}
244
245// ---- opting in ----
246
247// /pickup and /audit are the user asking for the skill: let it load and enforce.
248async function optIn($: Engine): Promise<void> {
249  await update($, namedState, () => true)
250  await update($, activeState, () => true)
251  await refresh($)
252}
253
254// Load the skill the way the user would (/learning-guardrails <ask>), else ask in words.
255async function runSkill($: Engine, ask: string): Promise<void> {
256  try {
257    const found = (await $.command.list()).find(c => isThisSkill(c.name))
258    if (found !== undefined) {
259      await $.command.run({ command: found.name, args: ask })
260
261      return
262    }
263  } catch {
264    // fall through to a plain prompt
265  }
266  await $.prompt.submit({ text: ask, asUser: true })
267}
268
269// ---- the lock ----
270
271async function refresh($: Engine): Promise<GateLock | null> {
272  const lock = await readLock($, [await $.session.cwd()])
273  await setLock($, lock)
274  if (lock !== null) await keepPrivate($, lock.path)
275  const others = await countUnfinished($)
276  if ((await read($, unfinishedState)) !== others) await update($, unfinishedState, () => others)
277
278  return lock
279}
280
281// This session, as the engine names it: the same id the CLI gives the shell, so
282// lock.mjs and the mod agree on whose lock is whose.
283async function sessionId($: Engine): Promise<string> {
284  try {
285    return String(await $.session.id()).replace(/[^\w-]/g, '') || 'local'
286  } catch {
287    return 'local'
288  }
289}
290
291const ownLock = async ($: Engine) => `locks/${await sessionId($)}.lock`
292
293// lock.mjs names its lock from LEARNING_GATE_SESSION, so the mod and the skill always agree on whose
294// lock is whose, even where Claude Code gives the shell no session id of its own.
295async function tellShells($: Engine): Promise<void> {
296  try {
297    await $.env.set('LEARNING_GATE_SESSION', await sessionId($))
298  } catch {
299    // lock.mjs falls back to CLAUDE_CODE_SESSION_ID
300  }
301}
302
303// Work paused in this project, checkpoints open in other sessions, and tasks other sessions
304// were tracking (one that ended mid-task leaves its .task): /pickup's menu.
305async function countUnfinished($: Engine): Promise<number> {
306  try {
307    const root = await projectRecord($)
308    if (root === null) return 0
309    const id = await sessionId($)
310    const mine = new Set([`${id}.lock`, `${id}.task`])
311    const dir = join(root, 'locks')
312    const locks = (await $.fs.exists(dir))
313      ? (await $.fs.list(dir)).filter(f => f.kind === 'file' && /\.(lock|task)$/.test(f.name) && !mine.has(f.name)).length
314      : 0
315
316    return locks + ((await $.fs.exists(join(root, 'gate.lock'))) ? 1 : 0)
317  } catch {
318    return 0
319  }
320}
321
322async function readLock($: Engine, starts: readonly string[]): Promise<GateLock | null> {
323  const path = await findUp($, starts, `.learning/${await ownLock($)}`)
324  if (path === null) return null
325  try {
326    return parseLock(path, await $.fs.read(path))
327  } catch {
328    return null // deleted between the look and the read
329  }
330}
331
332async function setLock($: Engine, lock: GateLock | null): Promise<void> {
333  const before = await read($, lockState)
334  if (JSON.stringify(before) !== JSON.stringify(lock)) {
335    await update($, lockState, () => lock)
336    if (before !== null && lock === null) $.ui.toast('Gate lifted. Carry on.')
337  }
338  await trackGate($, lock)
339  const active = await read($, activeState)
340  if (lock !== null && active) await coverLock($, lock)
341  showStatus($, lock, await read($, triageState), active)
342}
343
344// Which gates are open, by lock path, kept across sessions: a lock seen again
345// in a new session is not a new gate, and a rewritten question is the same one.
346type OpenGate = { at: number; tier: string; label: string }
347const GATES = 'gates'
348
349async function trackGate($: Engine, lock: GateLock | null): Promise<void> {
350  try {
351    const gates = { ...(((await $.store.get(GATES)) ?? {}) as Record<string, OpenGate>) }
352    // A record deleted outright takes its open gate with it (nowhere left to log).
353    let pruned = false
354    for (const stored of Object.keys(gates)) {
355      if (!(await $.fs.exists(recordOf(stored)))) {
356        delete gates[stored]
357        pruned = true
358      }
359    }
360    if (pruned) await $.store.set(GATES, gates)
361    const root = await projectRecord($)
362    if (root === null) return
363    const path = join(root, await ownLock($))
364    const open = gates[path]
365    if (lock !== null && lock.path === path && open === undefined) {
366      const at = await $.clock.now()
367      await $.store.set(GATES, { ...gates, [path]: { at, tier: lock.tier, label: lock.category } })
368      await logEvent($, { e: 'gate_open', tier: lock.tier.toLowerCase(), label: lock.category })
369    } else if ((lock === null || lock.path !== path) && open !== undefined) {
370      const rest = { ...gates }
371      delete rest[path]
372      await $.store.set(GATES, rest)
373      const ms = (await $.clock.now()) - open.at
374      await logEvent($, { e: 'gate_close', tier: open.tier.toLowerCase(), label: open.label, ms })
375    }
376  } catch {
377    // tracking must never get in the way of the gate
378  }
379}
380
381function showStatus($: Engine, lock: GateLock | null, triage: string | null, active: boolean): void {
382  if (lock !== null) $.ui.status(active ? `🛑 Checkpoint open · ${label(lock)}` : `⏸ Paused checkpoint · ${label(lock)}`)
383  else $.ui.status(triage ?? undefined)
384}
385
386// The first line is the checkpoint; any `key: value` lines after it are lock.mjs's own.
387export function parseLock(path: string, text: string): GateLock {
388  const first = text.trim().split('\n')[0]?.trim() ?? ''
389  const [tier, category, ...rest] = first.split(' · ')
390  if (tier !== undefined && category !== undefined && rest.length > 0 && /^(GO|CHECK|GATE)$/i.test(tier.trim())) {
391    return { path, tier: tier.trim().toUpperCase(), category: category.trim(), question: rest.join(' · ').trim() }
392  }
393  const line = text.trim().replace(/\s*\n\s*/g, ' ')
394
395  return { path, tier: 'CHECKPOINT', category: '', question: line || 'See lock.mjs show' }
396}
397
398const label = (lock: GateLock) => [lock.tier, lock.category].filter(Boolean).join(' · ')
399
400const blockMessage = (lock: GateLock) =>
401  [
402    'Learning checkpoint open: code edits are refused until the user shows they understand.',
403    `Open question: ${lock.question}`,
404    'Re-ask the question, options and all, and wait for the answer.',
405    'Close the checkpoint only as the learning-guardrails skill allows (lock.mjs). Never offer the user a way around it.',
406  ].join('\n')
407
408function editTarget(e: unknown): string | undefined {
409  const input = e as { file_path?: unknown; notebook_path?: unknown }
410  if (typeof input.file_path === 'string') return input.file_path
411  if (typeof input.notebook_path === 'string') return input.notebook_path
412
413  return undefined
414}
415
416// ---- a question asked without a lock ----
417
418type Asked = { tier: string; label: string; question: string }
419
420const MOVE = /👉\s*(?:\*\*)?Your move(?::\*\*|\*\*:|:)\s*(.+)/g
421
422// The last triage line's category, when it was a GATE: only a GATE locks.
423function gateCategory(triage: string | null): string | null {
424  const triaged = triage === null ? null : /Guardrail · (GO|CHECK|GATE) · ([^:\n]+)/.exec(triage)
425  if (triaged?.[1] !== 'GATE') return null
426  const label = triaged[2]?.trim() ?? ''
427
428  return label.split(JOIN)[0]?.trim() || label
429}
430
431// Between the categories a GATE line names: `concurrency + data: a double removal`.
432const JOIN = /\s*(?:\+|,|&|\/|\band\b)\s*/
433
434// The last `👉 Your move:` question in a reply after a GATE triage line, labelled
435// from the checkpoint header or that line. A CHECK question never locks.
436export function askedCheckpoint(text: string, triage: string | null): Asked | null {
437  const question = [...text.matchAll(MOVE)].at(-1)?.[1]?.replace(/\*\*/g, '').trim()
438  const category = gateCategory(triage)
439  if (!question || category === null) return null
440  const header = text.split('\n').find(line => /^\s*Checkpoint \d+\/\d+ · /.test(line))
441  const fromHeader = header?.split(' · ').at(-1)?.trim()
442
443  return { tier: 'GATE', label: fromHeader || category || 'checkpoint', question }
444}
445
446// A GATE question asked in the AskUserQuestion dialog: its header is the category
447// from the last GATE triage line. Any other question (a clarifying one) isn't a checkpoint.
448export function askedInDialog(input: unknown, triage: string | null): Asked | null {
449  const first = (input as { questions?: readonly { question?: unknown; header?: unknown }[] }).questions?.[0]
450  const question = typeof first?.question === 'string' ? first.question.trim() : ''
451  const category = gateCategory(triage)
452  if (question === '' || !category || String(first?.header ?? '').trim().toLowerCase() !== category.toLowerCase()) return null
453
454  return { tier: 'GATE', label: category, question }
455}
456
457async function lockIfOpen($: Engine, asked: Asked): Promise<void> {
458  try {
459    const cwd = await $.session.cwd()
460    if ((await readLock($, [cwd])) !== null) return // Claude's own lock stands
461    const root = (await projectRecord($)) ?? join(cwd, '.learning')
462    await $.fs.write(join(root, await ownLock($)), `${asked.tier} · ${asked.label} · ${asked.question}\n`)
463    await refresh($)
464  } catch {
465    // the skill still holds the line if this fails
466  }
467}
468
469// ---- the tripwire ----
470
471type Triaged = { tier: string; what: string; gated: readonly string[]; waived: readonly { cat: string; why: string }[] }
472
473const WAIVER = /·\s*not\s+(data|concurrency|security|performance|state|contracts)\s*:\s*([a-z0-9][a-z0-9-]*)/gi
474
475// Each triage line in a reply: the categories a GATE covers (one, or two joined: `concurrency +
476// data: …`), and each one rated lower with a reason (`Guardrail · GO · token rename · not security: rename`).
477export function triageLines(text: string): Triaged[] {
478  return [...text.matchAll(TRIAGE)].map(m => {
479    const tier = m[1] ?? ''
480    const what = (m[2] ?? '').trim()
481    const at = m.index ?? 0
482    const end = text.indexOf('\n', at)
483    const line = text.slice(at, end < 0 ? undefined : end).replace(/`/g, '')
484    const cats = (what.split(':')[0] ?? '').split(JOIN).map(c => c.trim().toLowerCase())
485    const waived = [...line.matchAll(WAIVER)].map(w => ({ cat: (w[1] ?? '').toLowerCase(), why: (w[2] ?? '').toLowerCase() }))
486
487    return { tier, what, gated: tier === 'GATE' ? cats.filter(c => CATS.includes(c)) : [], waived }
488  })
489}
490
491async function cover($: Engine, lines: readonly Triaged[]): Promise<void> {
492  await update($, coverState, c => ({
493    triaged: true,
494    gated: [...new Set([...c.gated, ...lines.flatMap(t => t.gated)])],
495    waived: [...new Set([...c.waived, ...lines.flatMap(t => t.waived.map(w => w.cat))])],
496  }))
497}
498
499// An open checkpoint is triage: its category stays covered once it closes, until the next message.
500async function coverLock($: Engine, lock: GateLock): Promise<void> {
501  const cat = lock.category.trim().toLowerCase()
502  const known = CATS.includes(cat)
503  const c = await read($, coverState)
504  if (c.triaged && (!known || c.gated.includes(cat))) return
505  await update($, coverState, now => ({ ...now, triaged: true, gated: known && !now.gated.includes(cat) ? [...now.gated, cat] : now.gated }))
506}
507
508async function uncover($: Engine): Promise<void> {
509  const c = await read($, coverState)
510  if (c.triaged || c.gated.length > 0 || c.waived.length > 0) await update($, coverState, () => UNCOVERED)
511}
512
513const PROSE = /\.(md|mdx|markdown|rst|adoc|txt)$/i
514
515const TRIAGE_FIRST = [
516  "Learning guardrails: triage before building. No triage line has come since the user's last message.",
517  'Write it first (`Guardrail · GO|CHECK|GATE · <label>`, learning-guardrails §1), then make the edit.',
518].join('\n')
519
520type Refusal = { message: string; event: Record<string, unknown> }
521
522// Null lets the edit through. Anything unexpected fails open, like the gate.
523async function tripwire($: Engine, e: unknown, tool: string, file: string): Promise<Refusal | null> {
524  try {
525    const record = await projectRecord($)
526    if (record === null) return null // not set up here: nothing to check against
527    const rel = relativeTo(parentOf(record), file)
528    if (rel === null) return null // outside this project
529    const floor = await loadFloor($, join(record, 'floor.json'))
530    if (floor === null ? PROSE.test(rel) : floor.ignore.some(re => re.test(rel))) return null // not building
531    const covered = await read($, coverState)
532    if (!covered.triaged) return { message: TRIAGE_FIRST, event: { e: 'triage_refused', tool } }
533    if (floor === null) return null
534    const lines = await editedLines($, e, file)
535    const found = floorMatches(floor, [rel], lines.map(text => ({ file: rel, text })))
536    const missing = CATS.filter(cat => found.some(m => m.cat === cat) && !covered.gated.includes(cat) && !covered.waived.includes(cat))
537    if (missing.length === 0) return null
538
539    return { message: floorMessage(rel, missing, found), event: { e: 'floor_refused', cats: missing, tool } }
540  } catch {
541    return null
542  }
543}
544
545function relativeTo(root: string, file: string): string | null {
546  const path = clean(file)
547  const prefix = root === '/' ? '/' : `${root}/`
548
549  return path.startsWith(prefix) ? path.slice(prefix.length) : null
550}
551
552// The lines this edit adds or removes, whichever tool makes it.
553async function editedLines($: Engine, e: unknown, file: string): Promise<string[]> {
554  const input = e as { old_string?: unknown; new_string?: unknown; content?: unknown; edits?: unknown; new_source?: unknown }
555  const str = (v: unknown) => (typeof v === 'string' ? v : '')
556  if (Array.isArray(input.edits)) {
557    return input.edits.flatMap((one: { old_string?: unknown; new_string?: unknown } | null) => changedLines(str(one?.old_string), str(one?.new_string)))
558  }
559  if (typeof input.content === 'string') {
560    let before = ''
561    try {
562      if (await $.fs.exists(file)) before = await $.fs.read(file)
563    } catch {
564      before = '' // unreadable: every line counts
565    }
566    return changedLines(before, input.content)
567  }
568  if (typeof input.new_source === 'string') return changedLines('', input.new_source)
569
570  return changedLines(str(input.old_string), str(input.new_string))
571}
572
573let floorCache: { text: string; floor: Floor | null } | undefined
574
575async function loadFloor($: Engine, path: string): Promise<Floor | null> {
576  if (!(await $.fs.exists(path))) return null
577  const text = await $.fs.read(path)
578  if (floorCache === undefined || floorCache.text !== text) {
579    let raw: unknown = null
580    try {
581      raw = JSON.parse(text)
582    } catch {
583      raw = null
584    }
585    floorCache = { text, floor: compileFloor(raw) }
586  }
587
588  return floorCache.floor
589}
590
591function floorMessage(rel: string, cats: readonly string[], found: readonly FloorMatch[]): string {
592  const why = cats.map(cat => {
593    const hits = found.filter(m => m.cat === cat)
594    const shown = [...new Set(hits.map(m => (m.text === undefined ? `its path matches ${m.pattern.replace(/\\\//g, '/')}` : `"${m.text.trim().slice(0, 60)}"`)))]
595
596    return `${cat} (${shown.slice(0, 2).join('; ')})`
597  })
598  const first = cats[0] ?? 'data'
599
600  return [
601    `Learning guardrails: the rule packs flag this edit to ${rel} as ${why.join(', ')}, and no triage line since the user's last message covers ${cats.length === 1 ? 'it' : 'them'}.`,
602    `Judge the change, not the words. If it changes how that behaves, it's a GATE: \`Guardrail · GATE · ${first}: <label>\`, then the checkpoint the skill asks for.`,
603    `If it doesn't, add the reason to your triage line, one per category: \`· not ${first}: <reason-code>\` (non-functional-edit, test-fixture, rename…). Then edit again.`,
604  ].join('\n')
605}
606
607// ---- the log ----
608
609// Best effort: a failure here never touches the gate. Writes go one at a
610// time, so two hooks logging at once can't drop each other's lines.
611let logQueue: Promise<void> = Promise.resolve()
612
613function logEvent($: Engine, event: Record<string, unknown>): Promise<void> {
614  logQueue = logQueue.then(() => writeEvent($, event))
615
616  return logQueue
617}
618
619async function writeEvent($: Engine, event: Record<string, unknown>): Promise<void> {
620  try {
621    const root = await projectRecord($)
622    if (root === null) return
623    const path = join(root, 'events.jsonl')
624    const line = JSON.stringify({ d: new Date(await $.clock.now()).toISOString(), by: 'mod', ...event })
625    const before = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
626    await $.fs.write(path, `${before}${before === '' || before.endsWith('\n') ? '' : '\n'}${line}\n`)
627  } catch {
628    // logging must never get in the way
629  }
630}
631
632// This project's .learning/ folder: never the general one under HOME.
633async function projectRecord($: Engine): Promise<string | null> {
634  const found = await findUp($, [await $.session.cwd()], '.learning')
635  const home = await $.env.get('HOME')
636  if (found === null || (home !== undefined && found === join(clean(home), '.learning'))) return null
637
638  return found
639}
640
641// ---- privacy ----
642
643const privateRoots = new Set<string>()
644
645// Keeps a project's .learning/ out of git with one line in the repo's own
646// .git/info/exclude: local to this machine, never the team's .gitignore.
647async function keepPrivate($: Engine, file: string): Promise<void> {
648  const parts = clean(file).split('/')
649  const at = parts.lastIndexOf('.learning')
650  if (at < 1) return
651  const root = parts.slice(0, at).join('/') || '/'
652  if (privateRoots.has(root)) return
653  const exclude = join(root, '.git/info/exclude')
654  if (!(await $.fs.exists(exclude))) return
655  const text = await $.fs.read(exclude)
656  if (!/^\/?\.learning\/?$/m.test(text)) {
657    await $.fs.write(exclude, `${text}${text === '' || text.endsWith('\n') ? '' : '\n'}.learning/\n`)
658    $.ui.toast('Kept .learning/ out of git (local exclude only).')
659  }
660  privateRoots.add(root)
661}
662
663// ---- /learned ----
664
665type Concept = { name: string; status: string; gaps: number }
666
667const GROUPS: readonly (readonly [string, string])[] = [
668  ['demonstrated', 'Demonstrated'],
669  ['learning', 'Learning'],
670  ['needs-reinforcement', 'Worth a refresh'],
671  ['unfamiliar', 'Unfamiliar'],
672]
673
674async function learnedSummary($: Engine): Promise<string> {
675  const home = await $.env.get('HOME')
676  const dirs: string[] = []
677  if (home !== undefined) dirs.push(join(clean(home), '.learning/general'))
678  const project = await findUp($, [await $.session.cwd()], '.learning/project')
679  if (project !== null && !dirs.includes(project)) dirs.push(project)
680
681  const concepts: Concept[] = []
682  for (const dir of dirs) {
683    if (!(await $.fs.exists(dir))) continue
684    for (const entry of await $.fs.list(dir)) {
685      if (entry.kind !== 'file' || !entry.name.endsWith('.md')) continue
686      concepts.push(parseConcept(entry.name, await $.fs.read(join(dir, entry.name))))
687    }
688  }
689
690  return summarise(concepts)
691}
692
693export function parseConcept(file: string, text: string): Concept {
694  const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)?.[1] ?? ''
695  const field = (key: string) => new RegExp(`^${key}:[ \\t]*([^#\\n]*)`, 'm').exec(front)?.[1]?.trim()
696  const gaps = /^## Known gaps[ \t]*\r?\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(text)?.[1] ?? ''
697
698  return {
699    name: field('concept') || file.replace(/\.md$/, ''),
700    status: field('status') || 'unknown',
701    gaps: gaps.split('\n').filter(line => /^\s*- /.test(line)).length,
702  }
703}
704
705export function summarise(concepts: readonly Concept[]): string {
706  if (concepts.length === 0) return 'Nothing recorded yet. The record fills in as concepts come up.'
707  const names = (list: readonly Concept[]) => {
708    const shown = list.slice(0, 8).map(c => c.name)
709    return list.length > 8 ? `${shown.join(', ')}, +${list.length - 8} more` : shown.join(', ')
710  }
711  const known = new Set(GROUPS.map(([status]) => status))
712  const lines = [`Learning record: ${concepts.length} concept${concepts.length === 1 ? '' : 's'}`]
713  for (const [status, title] of GROUPS) {
714    const list = concepts.filter(c => c.status === status)
715    if (list.length > 0) lines.push(`${title} (${list.length}): ${names(list)}`)
716  }
717  const other = concepts.filter(c => !known.has(c.status))
718  if (other.length > 0) lines.push(`Other (${other.length}): ${names(other)}`)
719  // No gap count: gaps are notes for when a concept comes up again, not a to-do list.
720
721  return lines.join('\n')
722}
723
724// ---- paths (POSIX) ----
725
726export function clean(path: string): string {
727  const parts: string[] = []
728  for (const part of path.replace(/\\/g, '/').split('/')) {
729    if (part === '' || part === '.') continue
730    if (part === '..') parts.pop()
731    else parts.push(part)
732  }
733
734  return '/' + parts.join('/')
735}
736
737export const resolvePath = (cwd: string, path: string) => clean(path.startsWith('/') ? path : `${cwd}/${path}`)
738
739export const isInRecord = (file: string) => clean(file).split('/').includes('.learning')
740
741function ancestors(dir: string): string[] {
742  const parts = clean(dir).split('/').filter(Boolean)
743  const out: string[] = []
744  for (let i = parts.length; i >= 0; i--) out.push('/' + parts.slice(0, i).join('/'))
745
746  return out
747}
748
749const parentOf = (file: string) => ancestors(file)[1] ?? '/'
750
751// The .learning folder a lock belongs to: the record, which outlives its locks folder.
752function recordOf(lock: string): string {
753  const parts = clean(lock).split('/')
754  const at = parts.lastIndexOf('.learning')
755
756  return at < 1 ? parentOf(lock) : parts.slice(0, at + 1).join('/')
757}
758
759const join = (dir: string, rest: string) => `${dir === '/' ? '' : dir}/${rest}`
760
761async function findUp($: Engine, starts: readonly string[], rest: string): Promise<string | null> {
762  const seen = new Set<string>()
763  for (const start of starts) {
764    for (const dir of ancestors(start)) {
765      if (seen.has(dir)) continue
766      seen.add(dir)
767      const path = join(dir, rest)
768      if (await $.fs.exists(path)) return path
769    }
770  }
771
772  return null
773}
774
hooks/floor.mjs 82 lines
1// floor.mjs: the rule packs' deterministic floor, as the learning-guardrails skill writes it to
2// .learning/floor.json (rules.mjs floorOf). Plain JavaScript with no engine or Node APIs, so the
3// skill's tests can hold floorMatches() to the skill's own matches(), case by case.
4
5export const CATS = ['data', 'concurrency', 'security', 'performance', 'state', 'contracts']
6
7// The JSON compiled to patterns, or null when it isn't a floor this version reads.
8export function compileFloor(raw) {
9  try {
10    if (raw === null || typeof raw !== 'object' || raw.version !== 1 || !Array.isArray(raw.packs)) return null
11    const re = (list, flags) => (Array.isArray(list) ? list : []).map(p => new RegExp(p, flags))
12    return {
13      commentOnly: raw.commentOnly !== false,
14      comment: new RegExp(typeof raw.comment === 'string' ? raw.comment : '^\\s*$'),
15      ignore: re(raw.ignore, 'i'),
16      packs: raw.packs.map(p => ({
17        name: String(p.name),
18        scope: Array.isArray(p.files) ? re(p.files, 'i') : null,
19        categories: Object.fromEntries(
20          CATS.map(cat => {
21            const c = p.categories?.[cat] ?? {}
22            return [cat, { paths: re(c.paths, 'i'), diff: [...re(c.diff, 'i'), ...re(c.diffExact, '')] }]
23          }),
24        ),
25      })),
26    }
27  } catch {
28    return null
29  }
30}
31
32// Every pattern a change matches, as rules.mjs matches() finds them. A line is { file, text }, or a
33// bare string that belongs to every changed file.
34export function floorMatches(floor, allFiles = [], lines = []) {
35  const seen = new Map()
36  const ignored = f => {
37    if (!seen.has(f)) seen.set(f, floor.ignore.some(re => re.test(f)))
38    return seen.get(f)
39  }
40  const files = allFiles.filter(f => !ignored(f))
41  const counts = text => floor.commentOnly === false || !floor.comment.test(text)
42  const rows = lines
43    .map(l => (typeof l === 'string' ? { file: null, text: l } : l))
44    .filter(r => counts(r.text) && (r.file === null ? files.length > 0 || allFiles.length === 0 : !ignored(r.file)))
45  const inScope = (pack, file) => pack.scope === null || (file === null ? files : [file]).some(f => pack.scope.some(re => re.test(f)))
46  const found = []
47  for (const pack of floor.packs) {
48    const scoped = rows.filter(r => inScope(pack, r.file))
49    for (const cat of CATS) {
50      const { paths, diff } = pack.categories[cat]
51      for (const re of paths) for (const f of files) if (re.test(f)) found.push({ cat, pack: pack.name, pattern: re.source, file: f })
52      for (const re of diff) for (const r of scoped) if (re.test(r.text)) found.push({ cat, pack: pack.name, pattern: re.source, file: r.file, text: r.text })
53    }
54  }
55  return found
56}
57
58// The risk categories a change points at, in the usual order.
59export function floorSignals(floor, files = [], lines = []) {
60  const cats = new Set(floorMatches(floor, files, lines).map(m => m.cat))
61  return CATS.filter(cat => cats.has(cat))
62}
63
64// The lines an edit changes: those in `after` that `before` lacks, then those `before` had that
65// `after` lacks, as a diff counts them. Order kept; a line repeated counts each time.
66export function changedLines(before = '', after = '') {
67  const split = text => (text === '' ? [] : String(text).replace(/\r\n/g, '\n').split('\n'))
68  const minus = (a, b) => {
69    const left = new Map()
70    for (const line of b) left.set(line, (left.get(line) ?? 0) + 1)
71    return a.filter(line => {
72      const n = left.get(line) ?? 0
73      if (n === 0) return true
74      left.set(line, n - 1)
75      return false
76    })
77  }
78  const was = split(before)
79  const now = split(after)
80  return [...minus(now, was), ...minus(was, now)]
81}
82
types/index.d.ts 41 lines
1/** This session's open checkpoint, as read from `.learning/locks/<session id>.lock`. */
2export type GateLock = {
3  /** Absolute path of the lock file. */
4  path: string
5  /** GO, CHECK or GATE as the skill wrote it; `CHECKPOINT` when unparsed. */
6  tier: string
7  /** The risk category (`concurrency`, `data`, ...); may be empty. */
8  category: string
9  /** The open question, on one line. */
10  question: string
11}
12
13/** What triage since the user's last message covers, for the tripwire. */
14export type Cover = {
15  /** A triage line, or an open checkpoint, has come since the user's last message. */
16  triaged: boolean
17  /** Risk categories a GATE line or an open checkpoint covers. */
18  gated: readonly string[]
19  /** Risk categories a triage line rated lower with a reason (`· not security: rename`). */
20  waived: readonly string[]
21}
22
23declare module 'claude-code' {
24  interface PluginState {
25    'learning-gate': {
26      /** The open checkpoint, or null when none is open. */
27      lock: GateLock | null
28      /** The last `Guardrail · TIER · ...` line the model wrote. */
29      triage: string | null
30      /** Whether the learning-guardrails skill was expanded this session. */
31      active: boolean
32      /** Whether the user's latest prompt named the skill (lets Claude load it). */
33      named: boolean
34      /** Checkpoints left in the project by other sessions, or paused: /pickup's menu. */
35      unfinished: number
36      /** What triage since the user's last message covers: the tripwire reads it. */
37      cover: Cover
38    }
39  }
40}
41