SLOPSHOPPER

allan

Allan's workflow mods, built from his own session logs. Every feature has its own on/off row in /config and is switched with /mods on|off <feature>…

panebandguardcommandtoaststatus
v0.1.0no licenseupdated 2026-10-14lua-erissatallan/claude-mods/allan
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · allan
│ ┃ allan-pulse ✕ › fix the failing auth test and add an audit log call │ ┃ Press p (parked), h (handoffs) or i (inbox) │ ┃ in the band to see them here. ⏺ 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 │ │ › /mods │ ⎿ allan: Allan's mods │ ⎿ allan: on voice voiceStyle=normal │ ⎿ allan: on commit commitIdentity=block commitEmail=allan@l │ ⎿ allan: on pulse pulseStaleDays=7 │ ⎿ allan: on handover handoverThresholds=60,70,80,90 handoverL │ ⎿ allan: on relay │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · allan-pulse
Press p (parked), h (handoffs) or i (inbox) in the band to see them here.
Pane · allan-release
Promote (each button runs lua version promote with LUA_DEPLOY_CONFIRMED=1) [ Close ]
Pane · allan-outbox
Outbox: 0 drafts. Re-read the live systems behind every claim before you send this. [ Close ]
README

claude-mods

Allan's Claude Code mods, built from his own session logs (see M-Kopa/MODS-PLAN-2026-10-04.md). One plugin, allan, with one feature per mod. Every feature can be switched on or off.

Switching

Want toDo
See every feature and its state/mods
Turn one off or on/mods off <feature> · /mods on <feature>
Change a setting/mods set <field> <value> (for example /mods set commitIdentity warn)
Same, by menu/config, rows named allan.<field>
Turn the whole plugin off/plugin disable allan@allan-mods
Emergency: start with nothing loadedALLAN_MODS_OFF=1 claude
Ask Claude"turn off watch": it runs /mods off watch or sets pluginConfigs.allan.watch to false in ~/.claude/settings.json

Guards fail open: if a mod's own code breaks, the call it was checking goes ahead.

Features

FeatureStatusWhat it doesFields
modsbuilt/mods lists and switches everything
voicebuiltKeeps Allan's reply rules in the system prompt (survives compaction); `/style normal \plain \visual` per sessionvoice, voiceStyle
commitbuiltStrips Claude attribution from commits and PRs; refuses a push that would leave through a non github.com-lua remote or a non work email; flags internal ids (D12, H22, Claude_Memory) in PR text and in files under docs/ or Business_Documents/commit, commitIdentity (off/warn/block), commitEmail, commitInternalIds (off/warn/block)
pulsebuiltBand above the prompt: session name, project, baton, parked count and oldest age (yellow when any is stale), handoffs addressed to this session's surface. The band is one line: p opens the parked list in a pane (a digit opens one item, with Unpark and b back), h opens the handoffs (n and p page). Press the key, or ctrl+x tab to the band first. /pending answers from INDEX and HANDOFFS with no model call; /park "what" "next step" and /unpark <n> write INDEXpulse, pulseStaleDays
handoverbuiltStatus line ctx 64% from the first threshold up (quiet below it); a toast the first time context crosses each threshold (the last says hand over now). Sessions named Orchestrator, Lead… or Code… skip auto compaction (manual /compact still works). /handover <successor> asks the model, with Allan's own handover prompt, to draft Claude_Memory/HANDOVER_<successor>.md from this session's transcript (work, learnings and gotchas, pending items with what is recorded nowhere else, how to start), tells you what to finish here before closing, never overwrites without --force, and copies the START/END kickoff prompt. /close checks git is clean, INDEX and HANDOFFS were updated today, nothing of yours is parked too long, and asks the model Allan's closing question: what lives only in this conversationhandover, handoverThresholds, handoverLeadPattern, handoverBlockAutoCompact
relaybuilt/sessions lists every open Claude Code session (read from Claude Code's own list in ~/.claude/sessions, so names are the ones you gave with /rename), this project first, then the others by project. `/relay <name> <text\last> sends text, or the last START/END block of my last reply, headed [relay from <me> · <project>]; a bare name looks in this project first, <Project>/<name> reaches another, an unnamed session goes by the id /sessions shows, an ambiguous name is refused with the choices. Delivery is by session id; if it fails the message is copied to the clipboard. Relayed messages show in the pulse band (i` opens them, with Clear)relay
askmodebuiltWhen a message only asks something (ends with ?, starts with why/what/how/quick question, or says "no code change" / "just a question"), that turn cannot Edit, Write or run changing commands (lua push/deploy/promote, lua env … -k, lua version create, git commit/push, vercel, rm, sed -i); each hold shows a toast. A request ("can you fix X?", "go …") is never held. Reply go or /build to allow; the mark ends with the turn. Optional Haiku call for messages the rules cannot placeaskmode, askmodeUseModel
releasebuilt, unverified live/promote reads the version list of this agent and its paired agents (.claude-mods.json: agent, pairs, versionCap), refuses on a dirty git tree, and opens a pane with one Promote button per agent. Nothing runs until you press it. The press runs the promote (with LUA_DEPLOY_CONFIRMED=1, so the lua-agent-builder deploy hook stays out of the way), deletes the oldest superseded versions past the cap (lua version delete <n> --force, never the active one), and adds a dated line under ## Releases in Claude_Memory/TECH.md. Built against the version list JSON of a real agent; the promote press itself has only run against mocksrelease
watchbuilt, unverified liveIn a project with a lua agent (the folder with lua.skill.yaml, or agent in .claude-mods.json), one session per project (a lease in the plugin store) reads one page of lua logs --ci --json --limit 100 every 10 minutes since its last mark, counts errors, preprocessor blocks and fail open or gate bypassed lines, compares errors to the week's median, and runs the checks commands from .claude-mods.json (non zero exit = red). A green, amber or red dot leads the pulse band; a toast fires when the level changes to amber or red. /logs prints what it saw since you last asked. Chosen defaults: the first look is 15 s after start, no second page is ever fetched, a lua logs failure shows amber with the errorwatch, watchIntervalMin
testguardbuilt, unverified live/testmode on (or ALLAN_TESTMODE=1): a Bash command naming an address from protected in .claude-mods.json, a script it runs that names one, or lua env … -k on a key ending in CC, ALLOWLIST, RECIPIENT or TO is refused with a toast until /testmode off. /secret set NAME reads the value from the clipboard, keeps it in this session only, prefixes Bash commands that use $NAME with an export, and redacts the value from every transcript row (/secret list, /secret clear). A prompt carrying a key shaped string (sk_, am_, lua_ plus 16 characters) gets a warning toasttestguard
outboxbuilt, unverified liveWhen a finished reply holds a message for a contact named in contacts in .claude-mods.json (a START/END block whose START line names them, or a > quoted block introduced within three lines as a draft, message or email for them), it is appended to Claude_Memory/MESSAGES.md as ## M<n> · DRAFT <date> · to <contact> · <first line> (the format Lee's MESSAGES.md already uses), newest first, with a toast. /outbox lists the drafts and opens a pane: Copy, Copy for Slack (markdown tables become aligned text, bold becomes Slack bold) and Mark sent (DRAFT becomes SENT <date>). Drafts older than a day are mentioned once at session start. Every copy reminds you to re-read the live systems firstoutbox

Install (all sessions)

claude plugin marketplace add ~/Desktop/Desktop/Work/claude-mods claude plugin install allan@allan-mods

Edits to this folder reach every session on /reload-plugins.

Develop

claude plugin validate allan claude plugin test allan

Source 24 files
hooks/register.ts 70 lines
1import { atom, read } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import { askmode, askmodeCommands } from './features/askmode'
5import { commit } from './features/commit'
6import { handover, handoverCommands } from './features/handover'
7import { mods, modsCommand } from './features/mods'
8import { outbox, outboxCommands } from './features/outbox'
9import { pulse, pulseCommands } from './features/pulse'
10import { release, releaseCommands } from './features/release'
11import { relay, relayCommands } from './features/relay'
12import { testguard, testguardCommands } from './features/testguard'
13import { asStyle, styleCommand, voice, voiceText } from './features/voice'
14import { watch, watchCommands } from './features/watch'
15import { thresholdsOf } from './lib/handover'
16import { isOn, kill, textOf } from './lib/switch'
17
18// The same session value voice.ts writes from /style.
19const style = atom({ plugin: 'allan', key: 'style' } as const, null)
20
21// One plugin, many features. Events with no matcher (session start, the system prompt) are
22// hooked once here, with pure helpers from the features. Matched events (a tool, a command)
23// are hooked inside each feature.
24export const register: Register = (on, options) => {
25  on('session.start', async ($, e, next) => {
26    kill.isOn = (await $.env.get('ALLAN_MODS_OFF')) === '1'
27    if (kill.isOn) {
28      $.ui.toast("Allan's mods are off for this session (ALLAN_MODS_OFF=1).")
29      return next(e)
30    }
31    await $.command.register(modsCommand)
32    await $.command.register(styleCommand)
33    for (const spec of pulseCommands) await $.command.register(spec)
34    for (const spec of handoverCommands) await $.command.register(spec)
35    for (const spec of relayCommands) await $.command.register(spec)
36    for (const spec of askmodeCommands) await $.command.register(spec)
37    for (const spec of releaseCommands) await $.command.register(spec)
38    for (const spec of watchCommands) await $.command.register(spec)
39    for (const spec of testguardCommands) await $.command.register(spec)
40    for (const spec of outboxCommands) await $.command.register(spec)
41    // A reload keeps the old status line until the next measurement: set it now (handover's meter).
42    try {
43      const percent = (await $.session.usage()).context.percent
44      const lowest = thresholdsOf(textOf(options, 'handoverThresholds', '60,70,80,90'))[0] ?? 0
45      $.ui.status(isOn(options, 'handover') && percent !== undefined && percent >= lowest ? `ctx ${percent}%` : undefined)
46    } catch { /* the meter is a convenience */ }
47    return next(e)
48  })
49
50  on('prompt.compose', async ($, e, next) => {
51    const composed = await next(e)
52    if (!isOn(options, 'voice')) return composed
53    const chosen = (await read($, style)) ?? asStyle(textOf(options, 'voiceStyle', 'normal'))
54    return { sections: [...composed.sections, { id: 'allan:voice', text: voiceText(chosen), scope: 'session' as const }] }
55  })
56
57  // Each feature registers on its own, so one failing never takes the others down.
58  try { mods(on, options) } catch { /* reported by the engine */ }
59  try { voice(on, options) } catch { /* reported by the engine */ }
60  try { commit(on, options) } catch { /* reported by the engine */ }
61  try { pulse(on, options) } catch { /* reported by the engine */ }
62  try { handover(on, options) } catch { /* reported by the engine */ }
63  try { relay(on, options) } catch { /* reported by the engine */ }
64  try { askmode(on, options) } catch { /* reported by the engine */ }
65  try { release(on, options) } catch { /* reported by the engine */ }
66  try { watch(on, options) } catch { /* reported by the engine */ }
67  try { testguard(on, options) } catch { /* reported by the engine */ }
68  try { outbox(on, options) } catch { /* reported by the engine */ }
69}
70
hooks/features/askmode.ts 67 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import { HELD, intentOf, isMutatingBash } from '../lib/askmode'
5import { looksLikeKey } from '../lib/testguard'
6import { isOn, type Options } from '../lib/switch'
7
8// Whether the turn running now answers a question; pulse clears it when the turn completes.
9const askTurn = atom({ plugin: 'allan', key: 'askTurn' } as const, false)
10
11export const askmodeCommands = [
12  { name: 'build', description: 'This turn may change files and production after all (askmode marked it a question).' },
13]
14
15function usesModel(options: Options): boolean {
16  return (options as Record<string, unknown>)['askmodeUseModel'] === true
17}
18
19async function hold($: EngineInterface, what: string): Promise<{ deny: string }> {
20  $.ui.toast(`askmode held back ${what}: this turn is a question. Reply 'go' or /build to allow it.`)
21  return { deny: HELD }
22}
23
24export function askmode(on: On, options: Options): void {
25  on('prompt.submit', async ($, e, next) => {
26    // testguard's warning lives here because prompt.submit has one owner per plugin.
27    if (isOn(options, 'testguard') && looksLikeKey(e.text)) $.ui.toast('That message carries something shaped like an API key. Rotate it if it is real; prefer /secret set NAME.')
28    if (!isOn(options, 'askmode')) return next(e)
29    let intent = intentOf(e.text)
30    if (intent === 'unclear' && usesModel(options)) {
31      try {
32        const label = await $.model.classify(e.text, ['question', 'request for changes'], { model: 'haiku' })
33        if (label === 'question') intent = 'question'
34      } catch { /* unclear stays unmarked */ }
35    }
36    await update($, askTurn, () => intent === 'question')
37    return next(e)
38  }).catch(($, e, next) => next(e))
39
40  on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
41    if (!isOn(options, 'askmode') || !(await read($, askTurn))) return next(e)
42    return hold($, 'Edit')
43  }).catch(($, e, next) => next(e))
44
45  on('tool.call', { tool: 'Write' }, async ($, e, next) => {
46    if (!isOn(options, 'askmode') || !(await read($, askTurn))) return next(e)
47    return hold($, 'Write')
48  }).catch(($, e, next) => next(e))
49
50  on('tool.call', { tool: 'NotebookEdit' }, async ($, e, next) => {
51    if (!isOn(options, 'askmode') || !(await read($, askTurn))) return next(e)
52    return hold($, 'NotebookEdit')
53  }).catch(($, e, next) => next(e))
54
55  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
56    if (!isOn(options, 'askmode') || !(await read($, askTurn))) return next(e)
57    const command = String(e.command ?? '')
58    return isMutatingBash(command) ? hold($, `\`${command.slice(0, 60)}\``) : next(e)
59  }).catch(($, e, next) => next(e))
60
61  on('command.run', { command: 'build' }, async $ => {
62    const was = await read($, askTurn)
63    await update($, askTurn, () => false)
64    return { text: was ? 'Changes allowed for the rest of this turn.' : 'Nothing was held: this turn was not marked a question.' }
65  })
66}
67
hooks/features/commit.ts 80 lines
1import type { EngineInterface, On } from 'claude-code'
2
3import { isOn, modeOf, textOf, type Options } from '../lib/switch'
4
5const PUSH = /(^|[;&|]\s*|\s)git\b(?:\s+-C\s+\S+)?[^;&|\n]*?\bpush\b/
6const PR_TEXT = /\bgh\s+pr\s+(create|comment|review|edit)\b/
7const INTERNAL = /\b(?:D|H|CC|CR|O)\d{1,3}\b|Claude_Memory|HANDOFFS(?:\.md)?\b/
8const OUTWARD_PATH = /\/(docs|Business_Documents)\//
9
10/** The folder a git command runs in: `git -C <dir>`, a leading `cd <dir> &&`, else the session cwd. */
11async function dirOf($: EngineInterface, command: string): Promise<string> {
12  const c = command.match(/\bgit\s+-C\s+("[^"]+"|'[^']+'|\S+)/)
13  if (c?.[1] !== undefined) return c[1].replace(/^["']|["']$/g, '')
14  const cd = command.match(/^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*&&/)
15  if (cd?.[1] !== undefined) return cd[1].replace(/^["']|["']$/g, '').replace(/^~/, (await $.env.get('HOME')) ?? '~')
16  return $.session.cwd()
17}
18
19function remoteOf(command: string): string {
20  const after = command.slice(command.search(/\bpush\b/) + 4).trim().split(/\s+/)
21  return after.find(t => t !== '' && !t.startsWith('-')) ?? 'origin'
22}
23
24async function git($: EngineInterface, dir: string, args: string[]): Promise<string> {
25  const r = await $.process.run(['git', '-C', dir, ...args])
26  return r.exitCode === 0 ? r.stdout.trim() : ''
27}
28
29export function commit(on: On, options: Options): void {
30  on('attribution.text', ($, e, next) => {
31    if (!isOn(options, 'commit')) return next(e)
32    return e.kind === 'commit' || e.kind === 'pr' ? { text: '' } : next(e)
33  })
34
35  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
36    if (!isOn(options, 'commit')) return next(e)
37    const command = String(e.command ?? '')
38
39    const identity = modeOf(options, 'commitIdentity', 'block')
40    if (identity !== 'off' && PUSH.test(command)) {
41      const dir = await dirOf($, command)
42      const url = await git($, dir, ['remote', 'get-url', remoteOf(command)])
43      const email = await git($, dir, ['config', 'user.email'])
44      const wantEmail = textOf(options, 'commitEmail', 'allan@luaimplementation.ai')
45      const problems = [
46        url !== '' && !url.includes('github.com-lua') ? `remote is ${url} (not github.com-lua)` : '',
47        email !== '' && email !== wantEmail ? `user.email is ${email} (not ${wantEmail})` : '',
48      ].filter(Boolean)
49      if (problems.length > 0) {
50        const why = `allan/commit: this push would leave under the wrong identity: ${problems.join('; ')}.`
51        if (identity === 'block') {
52          return { deny: `${why} Fix the remote or user.email in ${dir}, or allow it with /mods set commitIdentity warn.` }
53        }
54        $.ui.toast(why)
55      }
56    }
57
58    const ids = modeOf(options, 'commitInternalIds', 'warn')
59    if (ids !== 'off' && PR_TEXT.test(command) && INTERNAL.test(command)) {
60      const why = `allan/commit: this PR text carries an internal memory reference (${command.match(INTERNAL)?.[0] ?? ''}). Clients and reviewers should not see those.`
61      if (ids === 'block') return { deny: `${why} Rewrite it, or /mods set commitInternalIds warn.` }
62      $.ui.toast(why)
63    }
64    return next(e)
65  }).catch(($, e, next) => next(e))
66
67  on('tool.call', { tool: 'Write' }, async ($, e, next) => {
68    if (!isOn(options, 'commit')) return next(e)
69    const ids = modeOf(options, 'commitInternalIds', 'warn')
70    const path = String(e.file_path ?? '')
71    const text = String(e.content ?? '')
72    if (ids !== 'off' && OUTWARD_PATH.test(path) && INTERNAL.test(text)) {
73      const why = `allan/commit: ${path} is client facing and carries an internal reference (${text.match(INTERNAL)?.[0] ?? ''}).`
74      if (ids === 'block') return { deny: `${why} Rewrite it, or /mods set commitInternalIds warn.` }
75      $.ui.toast(why)
76    }
77    return next(e)
78  }).catch(($, e, next) => next(e))
79}
80
hooks/features/handover.ts 164 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import { alertFor, alertText, CLOSING, closeChecks, closePrompt, emptySections, forkPrompt, handoverDoc, isLead, kickoff, localDate, sectionsFrom, splitSection, thresholdsOf } from '../lib/handover'
5import { parentOf, parkedOf, type Project } from '../lib/project'
6import { isOn, textOf, type Options } from '../lib/switch'
7
8// The session name pulse records from the classic hooks; the thresholds already alerted.
9const sessionName = atom({ plugin: 'allan', key: 'session' } as const, null)
10const fired = atom({ plugin: 'allan', key: 'handoverFired' } as const, [])
11
12export const handoverCommands = [
13  { name: 'handover', description: 'Write Claude_Memory/HANDOVER_<successor>.md from this session and copy the kickoff prompt: /handover Code-4', argumentHint: '<successor> [--force]' },
14  { name: 'close', description: 'Before closing this session: git clean, INDEX and HANDOFFS updated today, nothing of yours parked too long.' },
15]
16
17function blocksAutoCompact(options: Options): boolean {
18  return (options as Record<string, unknown>)['handoverBlockAutoCompact'] !== false
19}
20
21/** Walks up from the cwd to the nearest folder holding Claude_Memory/INDEX.md or lua.skill.yaml. */
22async function findProject($: EngineInterface): Promise<Project | null> {
23  let dir: string | null = await $.session.cwd()
24  while (dir !== null) {
25    const hasMemory = await $.fs.exists(`${dir}/Claude_Memory/INDEX.md`)
26    const hasAgent = await $.fs.exists(`${dir}/lua.skill.yaml`)
27    if (hasMemory || hasAgent) {
28      return { root: dir, name: dir.slice(dir.lastIndexOf('/') + 1), memoryDir: hasMemory ? `${dir}/Claude_Memory` : null, hasAgent }
29    }
30    dir = parentOf(dir)
31  }
32  return null
33}
34
35async function today($: EngineInterface): Promise<string> {
36  const now = await $.clock.now()
37  return localDate(now, new Date(now).getTimezoneOffset())
38}
39
40async function writeHandover($: EngineInterface, args: string): Promise<string> {
41  const words = args.trim().split(/\s+/).filter(Boolean)
42  const force = words.includes('--force')
43  const successor = words.find(w => w !== '--force')
44  if (successor === undefined || !/^[A-Za-z0-9_.]+(?:-[A-Za-z0-9_.]+)*$/.test(successor)) {
45    return 'Usage: /handover <successor>, for example /handover Code-4'
46  }
47
48  const cwd = await $.session.cwd()
49  const project = await findProject($)
50  const root = project?.root ?? cwd
51  const dir = project?.memoryDir ?? root
52  const file = `${dir}/HANDOVER_${successor}.md`
53  const shown = file.startsWith(`${root}/`) ? file.slice(root.length + 1) : file
54  if (!force && (await $.fs.exists(file))) return `${shown} already exists. /handover ${successor} --force replaces it.`
55
56  const me = (await read($, sessionName)) ?? 'this session'
57  const reply = await $.model.fork({ prompt: forkPrompt(successor, me) })
58  const whole = reply.isAnswered ? sectionsFrom(reply.text) : null
59  // The closing advice is for Allan now, not for the successor's file.
60  const split = whole === null ? null : splitSection(whole, CLOSING)
61  const drafted = split?.rest ?? null
62  const closing = split?.section ?? null
63  const usage = await $.session.usage()
64  await $.fs.write(file, handoverDoc({
65    me,
66    successor,
67    date: await today($),
68    sessionId: await $.session.id(),
69    percent: usage.context.percent ?? null,
70    sections: drafted ?? emptySections(),
71  }))
72
73  const prompt = kickoff({ me, successor, project: project?.name ?? root.slice(root.lastIndexOf('/') + 1), root, file: shown })
74  const copied = (await $.ui.copy({ text: prompt })).isCopied
75  const how = drafted !== null
76    ? 'Sections drafted from this session; read it and fix anything wrong before you close.'
77    : `The model did not draft it (${reply.isAnswered ? 'its reply lacked the four headings' : reply.reason}): the file has empty headings to fill.`
78  return [
79    `Wrote ${shown}. ${how}`,
80    ...(closing === null || /^-\s*none\b/i.test(closing) ? [] : ['', 'Recommended to finish here, with the remaining context, rather than hand over:', closing]),
81    '',
82    copied ? 'Kickoff prompt copied to the clipboard:' : 'Kickoff prompt (copy it by hand):',
83    '',
84    prompt,
85    '',
86    `Start ${successor} with /rename ${successor}, paste the prompt, then /close here.`,
87  ].join('\n')
88}
89
90async function gitPorcelain($: EngineInterface, dir: string): Promise<string | null> {
91  const r = await $.process.run(['git', '-C', dir, 'status', '--porcelain'])
92  return r.exitCode === 0 ? r.stdout : null
93}
94
95async function close($: EngineInterface, options: Options): Promise<string> {
96  const project = await findProject($)
97  const root = project?.root ?? (await $.session.cwd())
98  const day = await today($)
99  const modified: Record<string, string | null> = {}
100  let index = ''
101  for (const name of ['INDEX.md', 'HANDOFFS.md']) {
102    const path = project?.memoryDir == null ? null : `${project.memoryDir}/${name}`
103    if (path === null || !(await $.fs.exists(path))) {
104      modified[name] = null
105      continue
106    }
107    const stat = await $.fs.stat(path)
108    modified[name] = localDate(stat.mtimeMs, new Date(stat.mtimeMs).getTimezoneOffset())
109    if (name === 'INDEX.md') index = await $.fs.read(path)
110  }
111  const stale = (options as Record<string, unknown>)['pulseStaleDays']
112  const checks = closeChecks({
113    porcelain: await gitPorcelain($, root),
114    today: day,
115    modified,
116    parked: parkedOf(index, await $.clock.now()),
117    session: await read($, sessionName),
118    staleDays: typeof stale === 'number' && stale > 0 ? stale : 7,
119  })
120  const missing = checks.filter(c => !c.ok).length
121  // Allan's closing question, answered over this session's own transcript.
122  let only = 'Could not ask the model what lives only in this conversation.'
123  try {
124    const reply = await $.model.fork({ prompt: closePrompt() })
125    only = reply.isAnswered ? reply.text.trim() : `Could not ask the model what lives only in this conversation (${reply.reason}).`
126  } catch { /* the checklist still stands */ }
127  const clean = /^nothing\b/i.test(only)
128  return [
129    ...checks.map(c => `${c.ok ? '✔' : '✘'} ${c.line}`),
130    `${clean ? '✔' : '✘'} Only in this conversation: ${only}`,
131    '',
132    missing === 0 && clean ? 'Safe to close.' : `Not yet: ${missing + (clean ? 0 : 1)} item${missing + (clean ? 0 : 1) === 1 ? '' : 's'} above.`,
133  ].join('\n')
134}
135
136export function handover(on: On, options: Options): void {
137  on('session.measure', async ($, e, next) => {
138    const done = await next(e)
139    if (!isOn(options, 'handover') || !e.changed.includes('context')) return done
140    const percent = e.context.percent
141    if (percent === undefined) return done
142    const thresholds = thresholdsOf(textOf(options, 'handoverThresholds', '60,70,80,90'))
143    // Quiet until the first threshold; cleared again after a compaction brings it back under.
144    $.ui.status(percent >= (thresholds[0] ?? 0) ? `ctx ${percent}%` : undefined)
145    const result = alertFor(percent, thresholds, await read($, fired))
146    await update($, fired, () => result.fired)
147    if (result.alert !== null) $.ui.toast(alertText(percent, result.alert, thresholds))
148    return done
149  })
150
151  // Lead sessions hand over instead of compacting away what they know. Manual /compact still runs.
152  on('session.compact', { trigger: 'auto' }, async ($, e, next) => {
153    if (!isOn(options, 'handover') || !blocksAutoCompact(options) || e.agentId !== undefined) return next(e)
154    const name = await read($, sessionName)
155    if (!isLead(name, textOf(options, 'handoverLeadPattern', '^(Orchestrator|Lead|Code)'))) return next(e)
156    $.ui.toast('Auto compaction skipped for a lead session: /handover <successor>, or /compact to compact anyway.')
157    return { skip: `${name} is a lead session: hand over (/handover <successor>) or run /compact yourself.` }
158  }).catch(($, e, next) => next(e))
159
160  on('command.run', { command: 'handover' }, async ($, e) => ({ text: await writeHandover($, e.args) }))
161
162  on('command.run', { command: 'close' }, async $ => ({ text: await close($, options) }))
163}
164
hooks/features/mods.ts 63 lines
1import type { On } from 'claude-code'
2
3import { FEATURES, type Options } from '../lib/switch'
4
5const FIELDS = new Set(Object.values(FEATURES).flat())
6
7function listing(options: Options): string {
8  const o = options as Record<string, unknown>
9  const lines = Object.entries(FEATURES).map(([name, fields]) => {
10    const state = o[name] === false ? 'off' : 'on '
11    const extra = fields
12      .filter(f => f !== name)
13      .map(f => `${f}=${String(o[f] ?? 'default')}`)
14      .join('  ')
15    return `${state}  ${name.padEnd(10)} ${extra}`
16  })
17  return [
18    "Allan's mods",
19    ...lines,
20    '',
21    '/mods off <feature>  ·  /mods on <feature>  ·  /mods set <field> <value>',
22    'Everything off at once: start Claude with ALLAN_MODS_OFF=1, or /plugin disable allan@allan-mods.',
23  ].join('\n')
24}
25
26export const modsCommand = {
27  name: 'mods',
28  description: "List Allan's mods, or switch one: /mods off watch · /mods on watch · /mods set commitIdentity warn",
29  argumentHint: '[on|off|set] [feature|field] [value]',
30}
31
32export function mods(on: On, options: Options): void {
33  on('command.run', { command: 'mods' }, async ($, e) => {
34    const [verb, target, ...rest] = e.args.trim().split(/\s+/).filter(Boolean)
35    if (verb === undefined) return { text: listing(options) }
36
37    if ((verb === 'on' || verb === 'off') && target === undefined) {
38      return { text: `Which feature? For example /mods ${verb} voice. Features: ${Object.keys(FEATURES).join(', ')}.` }
39    }
40
41    if ((verb === 'on' || verb === 'off') && target !== undefined) {
42      if (!(target in FEATURES)) return { text: `No feature named "${target}". /mods lists them.` }
43      const wanted = verb === 'on'
44      const current = (options as Record<string, unknown>)[target] !== false
45      if (current === wanted) return { text: `${target} is already ${verb}.` }
46      // Changing a row reloads this plugin, so reply first and let the change land after.
47      void $.config.set({ key: `allan.${target}`, value: wanted })
48      return { text: `${target} is now ${verb}.` }
49    }
50
51    if (verb === 'set' && target !== undefined && rest.length > 0) {
52      if (!FIELDS.has(target)) return { text: `No field named "${target}". /mods lists them.` }
53      const raw = rest.join(' ')
54      const value = raw === 'true' ? true : raw === 'false' ? false : raw
55      if ((options as Record<string, unknown>)[target] === value) return { text: `${target} is already ${raw}.` }
56      void $.config.set({ key: `allan.${target}`, value })
57      return { text: `${target} = ${raw}.` }
58    }
59
60    return { text: `Not understood: /mods ${e.args}\n\n${listing(options)}` }
61  })
62}
63
hooks/features/outbox.tsx 152 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import { parseModsConfig } from '../lib/config'
5import { addDraft, ageDays, draftsIn, markSent, parseDrafts, slackify, type Draft } from '../lib/outbox'
6import { parentOf, type Project } from '../lib/project'
7import { isOn, type Options } from '../lib/switch'
8
9const PANE = 'allan-outbox'
10const sessionName = atom({ plugin: 'allan', key: 'session' } as const, null)
11const shown = atom({ plugin: 'allan', key: 'outboxDrafts' } as const, [])
12const note = atom({ plugin: 'allan', key: 'outboxNote' } as const, null)
13
14export const outboxCommands = [
15  { name: 'outbox', description: 'Drafts for your contacts kept in Claude_Memory/MESSAGES.md, in a pane with Copy, Copy for Slack and Mark sent.' },
16]
17
18const REMINDER = 'Re-read the live systems behind every claim before you send this.'
19
20/** Walks up from the cwd to the nearest folder holding Claude_Memory/INDEX.md or lua.skill.yaml. */
21async function findProject($: EngineInterface): Promise<Project | null> {
22  let dir: string | null = await $.session.cwd()
23  while (dir !== null) {
24    const hasMemory = await $.fs.exists(`${dir}/Claude_Memory/INDEX.md`)
25    const hasAgent = await $.fs.exists(`${dir}/lua.skill.yaml`)
26    if (hasMemory || hasAgent) {
27      return { root: dir, name: dir.slice(dir.lastIndexOf('/') + 1), memoryDir: hasMemory ? `${dir}/Claude_Memory` : null, hasAgent }
28    }
29    dir = parentOf(dir)
30  }
31  return null
32}
33
34async function readOr($: EngineInterface, path: string): Promise<string | null> {
35  return (await $.fs.exists(path)) ? $.fs.read(path) : null
36}
37
38async function messagesPath($: EngineInterface): Promise<{ path: string; contacts: string[] } | null> {
39  const project = await findProject($)
40  if (project === null || project.memoryDir === null) return null
41  const config = parseModsConfig(await readOr($, `${project.root}/.claude-mods.json`))
42  return { path: `${project.memoryDir}/MESSAGES.md`, contacts: config.contacts }
43}
44
45async function today($: EngineInterface): Promise<string> {
46  return new Date(await $.clock.now()).toISOString().slice(0, 10)
47}
48
49/** Keeps every message for a contact found in the reply. */
50async function capture($: EngineInterface, answer: string): Promise<void> {
51  const where = await messagesPath($)
52  if (where === null || where.contacts.length === 0) return
53  const found = draftsIn(answer, where.contacts)
54  if (found.length === 0) return
55  let text = await readOr($, where.path)
56  const date = await today($)
57  const by = (await read($, sessionName)) ?? 'unnamed session'
58  const added: number[] = []
59  for (const d of found) {
60    const next = addDraft(text, d.to, d.body, date, by)
61    if (next === null) continue
62    text = next.text
63    added.push(next.id)
64  }
65  if (added.length === 0 || text === null) return
66  await $.fs.write(where.path, text)
67  $.ui.toast(`outbox kept draft${added.length === 1 ? '' : 's'} M${added.join(', M')} in Claude_Memory/MESSAGES.md (/outbox).`)
68}
69
70async function refresh($: EngineInterface): Promise<Draft[]> {
71  const where = await messagesPath($)
72  const drafts = where === null ? [] : parseDrafts((await readOr($, where.path)) ?? '').filter(d => d.status === 'DRAFT')
73  await update($, shown, () => drafts)
74  return drafts
75}
76
77async function open($: EngineInterface): Promise<string> {
78  const where = await messagesPath($)
79  if (where === null) return 'No Claude_Memory above this folder, so no MESSAGES.md.'
80  const drafts = await refresh($)
81  await update($, note, () => null)
82  if (drafts.length === 0) return `No drafts in ${where.path.replace(/^.*\/Claude_Memory/, 'Claude_Memory')}.${where.contacts.length === 0 ? ' Add "contacts" to .claude-mods.json for drafts to be kept.' : ''}`
83  void $.ui.open({ id: PANE, title: 'Outbox', focus: true })
84  return [`${drafts.length} draft${drafts.length === 1 ? '' : 's'} (pane opened):`, ...drafts.map(d => `  M${d.id} · ${d.date} · to ${d.to} · ${d.title}`)].join('\n')
85}
86
87export function outbox(on: On, options: Options): void {
88  // One line per finished turn: any message for a contact in the reply is kept.
89  on('turn.complete', { reason: 'answer' }, async ($, e, next) => {
90    const done = await next(e)
91    if (!isOn(options, 'outbox') || e.agentId !== undefined) return done
92    try { await capture($, e.answer) } catch { /* a draft not kept is a draft still in the reply */ }
93    return done
94  })
95
96  // Drafts left over a day are mentioned once, at the start of a session in that project.
97  on('session.start', { cwd: /./ }, async ($, e, next) => {
98    if (!isOn(options, 'outbox') || !e.isInteractive) return next(e)
99    try {
100      const where = await messagesPath($)
101      if (where !== null) {
102        const now = await $.clock.now()
103        const old = parseDrafts((await readOr($, where.path)) ?? '').filter(d => d.status === 'DRAFT' && ageDays(d.date, now) >= 1)
104        if (old.length > 0) $.ui.toast(`outbox: ${old.length} draft${old.length === 1 ? '' : 's'} older than a day (M${old.map(d => d.id).join(', M')}). /outbox to send or drop them.`)
105      }
106    } catch { /* the reminder is a convenience */ }
107    return next(e)
108  })
109
110  on('command.run', { command: 'outbox' }, async $ => {
111    if (!isOn(options, 'outbox')) return { text: 'outbox is off (/mods on outbox).' }
112    return { text: await open($) }
113  })
114
115  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
116    const { Box, Text, Button } = $.ui.resolve(e)
117    const drafts = await read($, shown)
118    const last = await read($, note)
119    const copy = (text: string, what: string) => async (press: { surface?: 'terminal' | 'desktop' | 'vscode' | 'mobile' }) => {
120      const copied = (await $.ui.copy({ text, surface: press.surface })).isCopied
121      await update($, note, () => (copied ? `${what} copied. ${REMINDER}` : `Could not reach a clipboard for ${what}.`))
122      $.ui.toast(copied ? `${what} copied. ${REMINDER}` : 'No clipboard reached.')
123    }
124    const sent = (id: number) => async () => {
125      const where = await messagesPath($)
126      if (where === null) return
127      const text = await readOr($, where.path)
128      const done = text === null ? null : markSent(text, id, await today($))
129      if (done !== null) await $.fs.write(where.path, done)
130      await update($, note, () => (done === null ? `M${id} not found as a draft.` : `M${id} marked sent.`))
131      await refresh($)
132    }
133    return (
134      <Box flexDirection="column">
135        <Text bold>Outbox: {drafts.length} draft{drafts.length === 1 ? '' : 's'}. {REMINDER}</Text>
136        {drafts.map(d => (
137          <Box key={`d${d.id}`} flexDirection="column">
138            <Text>M{d.id} · {d.date} · to {d.to} · {d.title}</Text>
139            <Box>
140              <Button key={`copy${d.id}`} onPress={copy(d.body, `M${d.id}`)}>Copy</Button>
141              <Button key={`slack${d.id}`} onPress={copy(slackify(d.body), `M${d.id} for Slack`)}>Copy for Slack</Button>
142              <Button key={`sent${d.id}`} variant="primary" onPress={sent(d.id)}>Mark sent</Button>
143            </Box>
144          </Box>
145        ))}
146        {last !== null && <Text dimColor>{last}</Text>}
147        <Button role="dismiss" onPress={async () => { await update($, note, () => null) }}>Close</Button>
148      </Box>
149    )
150  })
151}
152
hooks/features/pulse.tsx 316 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import type { PulseHandoffItem, PulseParkedItem, PulseSelection, PulseView } from '../../types'
5import { addParked, isForSurface, openHandoffs, parseParkArgs, removeParked, surfaceOf } from '../lib/memory'
6import { batonOf, parentOf, parkedOf, type Project } from '../lib/project'
7import { isOn, type Options } from '../lib/switch'
8
9const PANE = 'allan-pulse'
10const view = atom({ plugin: 'allan', key: 'pulse' } as const, null)
11const sessionName = atom({ plugin: 'allan', key: 'session' } as const, null)
12const parkedItems = atom({ plugin: 'allan', key: 'parkedItems' } as const, [])
13const handoffItems = atom({ plugin: 'allan', key: 'handoffItems' } as const, [])
14const selected = atom({ plugin: 'allan', key: 'selected' } as const, null)
15// Messages other sessions relayed here (relay.ts records them).
16const inbox = atom({ plugin: 'allan', key: 'inbox' } as const, [])
17// watch's light (watch.ts writes it).
18const watchLight = atom({ plugin: 'allan', key: 'watchLight' } as const, null)
19// askmode's mark on a question turn lasts until the turn completes.
20const askTurn = atom({ plugin: 'allan', key: 'askTurn' } as const, false)
21
22const PARKED_HOTKEYS = '123456789'
23const LIST: PulseSelection = { kind: 'parkedList', index: 0 }
24
25export const pulseCommands = [
26  { name: 'pending', description: 'What is pending here: baton, parked items with ages, open handoffs for this session. Reads the files, no model call.' },
27  { name: 'park', description: 'Park a thread before you pivot: /park "what" "next step"', argumentHint: '"what" "next step"' },
28  { name: 'unpark', description: 'Remove parked item n (as numbered by /pending): /unpark 2', argumentHint: '<n>' },
29]
30
31function staleDaysOf(options: Options): number {
32  const v = (options as Record<string, unknown>)['pulseStaleDays']
33  return typeof v === 'number' && v > 0 ? v : 7
34}
35
36/** Walks up from the cwd to the nearest folder holding Claude_Memory/INDEX.md or lua.skill.yaml. */
37async function findProject($: EngineInterface): Promise<Project | null> {
38  let dir: string | null = await $.session.cwd()
39  while (dir !== null) {
40    const hasMemory = await $.fs.exists(`${dir}/Claude_Memory/INDEX.md`)
41    const hasAgent = await $.fs.exists(`${dir}/lua.skill.yaml`)
42    if (hasMemory || hasAgent) {
43      return { root: dir, name: dir.slice(dir.lastIndexOf('/') + 1), memoryDir: hasMemory ? `${dir}/Claude_Memory` : null, hasAgent }
44    }
45    dir = parentOf(dir)
46  }
47  return null
48}
49
50async function readOr($: EngineInterface, path: string): Promise<string> {
51  return (await $.fs.exists(path)) ? $.fs.read(path) : ''
52}
53
54async function refresh($: EngineInterface, options: Options): Promise<void> {
55  if (!isOn(options, 'pulse')) {
56    await update($, view, () => null)
57    await update($, parkedItems, () => [])
58    await update($, handoffItems, () => [])
59    return
60  }
61  const project = await findProject($)
62  if (project === null || project.memoryDir === null) {
63    await update($, view, () => null)
64    await update($, parkedItems, () => [])
65    await update($, handoffItems, () => [])
66    return
67  }
68  const index = await readOr($, `${project.memoryDir}/INDEX.md`)
69  const handoffs = await readOr($, `${project.memoryDir}/HANDOFFS.md`)
70  const session = await read($, sessionName)
71  const parked = parkedOf(index, await $.clock.now())
72  const surface = session === null ? '' : surfaceOf(session)
73  const mine = openHandoffs(handoffs).filter(r => isForSurface(r, surface))
74
75  const nextView: PulseView = {
76    session,
77    project: project.name,
78    baton: batonOf(index),
79    parked: parked.length,
80    oldestDays: parked.reduce((m, p) => Math.max(m, p.ageDays), 0),
81    staleCount: parked.filter(p => p.ageDays > staleDaysOf(options)).length,
82    handoffs: mine.length,
83  }
84  const nextParked: PulseParkedItem[] = parked.map((p, i) => ({ index: i + 1, ...p }))
85  const nextHandoffs: PulseHandoffItem[] = mine.map((r, i) => ({ index: i + 1, ...r }))
86
87  await update($, view, () => nextView)
88  await update($, parkedItems, () => nextParked)
89  await update($, handoffItems, () => nextHandoffs)
90
91  // A selection pointing at an item that no longer exists (unparked, or the list shrank) is dropped.
92  const current = await read($, selected)
93  if (current?.kind === 'parked' && current.index > nextParked.length) await update($, selected, () => null)
94  if (current?.kind === 'handoff' && current.index > nextHandoffs.length) await update($, selected, () => null)
95}
96
97async function doUnpark($: EngineInterface, options: Options, n: number): Promise<string> {
98  const project = await findProject($)
99  if (project === null || project.memoryDir === null) return 'No Claude_Memory/INDEX.md above this folder.'
100  const path = `${project.memoryDir}/INDEX.md`
101  const done = removeParked(await $.fs.read(path), n)
102  if (done === null) return `There is no parked item ${n}. /pending lists them.`
103  await $.fs.write(path, done.text)
104  await refresh($, options)
105  if ((await read($, selected))?.kind === 'parked') await update($, selected, () => LIST)
106  return `Unparked: ${done.removed}`
107}
108
109export function pulse(on: On, options: Options): void {
110  // Also fires after each reload of this plugin, so the band is filled without waiting for a prompt.
111  on('session.start', { isInteractive: true }, async ($, e, next) => {
112    await refresh($, options)
113    return next(e)
114  })
115
116  on('classic.SessionStart', async ($, e, next) => {
117    if (typeof e.session_title === 'string' && e.session_title !== '') await update($, sessionName, () => e.session_title ?? null)
118    await refresh($, options)
119    return next(e)
120  })
121
122  on('classic.UserPromptSubmit', async ($, e, next) => {
123    if (typeof e.session_title === 'string' && e.session_title !== '') await update($, sessionName, () => e.session_title ?? null)
124    await refresh($, options)
125    return next(e)
126  })
127
128  on('turn.complete', async ($, e, next) => {
129    const done = await next(e)
130    await update($, askTurn, () => false)
131    await refresh($, options)
132    return done
133  })
134
135  on('command.run', { command: 'pending' }, async $ => {
136    const project = await findProject($)
137    if (project === null || project.memoryDir === null) return { text: 'No Claude_Memory/INDEX.md above this folder.' }
138    const index = await readOr($, `${project.memoryDir}/INDEX.md`)
139    const handoffs = await readOr($, `${project.memoryDir}/HANDOFFS.md`)
140    const session = await read($, sessionName)
141    const parked = parkedOf(index, await $.clock.now())
142    const mine = openHandoffs(handoffs).filter(r => isForSurface(r, session === null ? '' : surfaceOf(session)))
143    const lines = [
144      `${project.name}${session === null ? '' : ` · ${session}`}`,
145      `▶ ${batonOf(index) ?? 'no baton line in INDEX.md'}`,
146      '',
147      parked.length === 0 ? '⏳ Nothing parked.' : `⏳ Parked (${parked.length}):`,
148      ...parked.map((p, i) => `  ${i + 1}. ${p.ageDays}d · ${p.text}`),
149      '',
150      session === null
151        ? 'Handoffs: session has no name yet (/rename it to see its handoffs).'
152        : mine.length === 0 ? `No open handoffs addressed to ${surfaceOf(session)}.` : `Open handoffs for ${surfaceOf(session)} (${mine.length}):`,
153      ...mine.slice(0, 15).map(r => `  ${r.id} · from ${r.from} · ${r.title}`),
154    ]
155    return { text: lines.join('\n') }
156  })
157
158  on('command.run', { command: 'park' }, async ($, e) => {
159    const parsed = parseParkArgs(e.args)
160    if (parsed === null) return { text: 'Usage: /park "what" "next step"' }
161    const project = await findProject($)
162    if (project === null || project.memoryDir === null) return { text: 'No Claude_Memory/INDEX.md above this folder.' }
163    const path = `${project.memoryDir}/INDEX.md`
164    const date = new Date(await $.clock.now()).toISOString().slice(0, 10)
165    const who = (await read($, sessionName)) ?? 'unnamed session'
166    const line = `- ${date} · ${parsed.what}${parsed.next === '' ? '' : ` · next step: ${parsed.next}`} · (${who})`
167    await $.fs.write(path, addParked(await $.fs.read(path), line))
168    await refresh($, options)
169    return { text: `Parked in ${project.name}/Claude_Memory/INDEX.md:\n${line}` }
170  })
171
172  on('command.run', { command: 'unpark' }, async ($, e) => {
173    const n = Number.parseInt(e.args.trim(), 10)
174    if (!Number.isFinite(n) || n < 1) return { text: 'Usage: /unpark <n>, numbered as /pending lists them.' }
175    return { text: await doUnpark($, options, n) }
176  })
177
178  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
179    const v = await read($, view)
180    if (v === null || e.props.hasSurvey || !isOn(options, 'pulse')) return next(e)
181    const { Box, Text, Button } = $.ui.resolve(e)
182    const handoffs = await read($, handoffItems)
183    const received = await read($, inbox)
184    const lightNow = await read($, watchLight)
185
186    const parts = [
187      v.session ?? 'unnamed',
188      v.project,
189      v.baton === null ? null : `▶ ${v.baton.slice(0, 40)}`,
190    ].filter((p): p is string => p !== null)
191
192    const openOn = (target: PulseSelection) => async () => {
193      await update($, selected, () => target)
194      void $.ui.open({ id: PANE, title: 'Pulse' })
195    }
196
197    // One line: the details live in the pane, opened with p (parked) or h (handoffs).
198    const stale = v.staleCount > 0
199    return (
200      <Box>
201        {lightNow !== null && (
202          <Text color={lightNow.level === 'green' ? 'green' : lightNow.level === 'amber' ? 'yellow' : 'red'}>● </Text>
203        )}
204        <Text dimColor>{parts.join('  ·  ')}</Text>
205        {v.parked > 0 && <Text dimColor>  ·  </Text>}
206        {v.parked > 0 && (
207          <Button key="parked" hotkey="p" dimColor={!stale} onPress={openOn(LIST)}>
208            <Text color={stale ? 'yellow' : undefined}>p:⏳ {v.parked} parked (oldest {v.oldestDays}d)</Text>
209          </Button>
210        )}
211        {handoffs.length > 0 && <Text dimColor>  ·  </Text>}
212        {handoffs.length > 0 && (
213          <Button key="handoffs" hotkey="h" dimColor onPress={openOn({ kind: 'handoff', index: 1 })}>
214            h:{handoffs.length === 1 ? handoffs[0]?.id : `${handoffs.length} handoffs`}
215          </Button>
216        )}
217        {received.length > 0 && <Text dimColor>  ·  </Text>}
218        {received.length > 0 && (
219          <Button key="inbox" hotkey="i" onPress={openOn({ kind: 'inbox', index: 0 })}>
220            <Text color="cyan">i:✉ {received.length} from {received[received.length - 1]?.from}</Text>
221          </Button>
222        )}
223      </Box>
224    )
225  })
226
227  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
228    const { Box, Text, Button } = $.ui.resolve(e)
229    const sel = await read($, selected)
230    const parked = await read($, parkedItems)
231    const handoffs = await read($, handoffItems)
232    const close = async () => { await update($, selected, () => null) }
233
234    if (sel === null) {
235      return (
236        <Box flexDirection="column">
237          <Text dimColor>Press p (parked), h (handoffs) or i (inbox) in the band to see them here.</Text>
238        </Box>
239      )
240    }
241
242    if (sel.kind === 'inbox') {
243      const received = await read($, inbox)
244      if (received.length === 0) return <Text dimColor>Inbox empty.</Text>
245      return (
246        <Box flexDirection="column">
247          <Text bold>✉ Relayed to this session ({received.length})</Text>
248          {received.map((m, i) => (
249            <Text key={`m${i}`}>{new Date(m.at).toISOString().slice(11, 16)} · {m.from} · {m.preview}</Text>
250          ))}
251          <Box>
252            <Button key="clear" variant="primary" onPress={async () => { await update($, inbox, () => []); await close() }}>Clear</Button>
253            <Button role="dismiss" onPress={close}>Close</Button>
254          </Box>
255        </Box>
256      )
257    }
258
259    if (sel.kind === 'parkedList') {
260      if (parked.length === 0) return <Text dimColor>Nothing parked.</Text>
261      return (
262        <Box flexDirection="column">
263          <Text bold>⏳ Parked ({parked.length}): press a number</Text>
264          {parked.map(p => (
265            <Button key={`p${p.index}`} hotkey={PARKED_HOTKEYS[p.index - 1]} onPress={async () => { await update($, selected, () => ({ kind: 'parked' as const, index: p.index })) }}>
266              {p.index}. {p.ageDays}d · {p.text.slice(0, 70)}
267            </Button>
268          ))}
269          <Button role="dismiss" onPress={close}>Close</Button>
270        </Box>
271      )
272    }
273
274    if (sel.kind === 'parked') {
275      const item = parked.find(p => p.index === sel.index)
276      if (item === undefined) return <Text dimColor>That parked item is gone.</Text>
277      return (
278        <Box flexDirection="column">
279          <Text bold>Parked, {item.ageDays} days ago ({item.date})</Text>
280          <Text>{item.text}</Text>
281          <Box>
282            <Button key="back" hotkey="b" onPress={async () => { await update($, selected, () => LIST) }}>b:Back</Button>
283            <Button variant="primary" onPress={async () => { await doUnpark($, options, item.index) }}>
284              Unpark
285            </Button>
286            <Button role="dismiss" onPress={close}>Close</Button>
287          </Box>
288        </Box>
289      )
290    }
291
292    const item = handoffs.find(row => row.index === sel.index)
293    if (item === undefined) return <Text dimColor>That handoff is gone.</Text>
294    const step = (by: number) => async () => {
295      const n = ((item.index - 1 + by + handoffs.length) % handoffs.length) + 1
296      await update($, selected, () => ({ kind: 'handoff' as const, index: n }))
297    }
298    return (
299      <Box flexDirection="column">
300        <Text bold>{item.id}</Text>
301        <Text dimColor>from {item.from} → {item.to}  ·  {item.index} of {handoffs.length}</Text>
302        <Text>{item.title}</Text>
303        <Box>
304          {handoffs.length > 1 && (
305            <Button key="prev" hotkey="p" onPress={step(-1)}>p:Prev</Button>
306          )}
307          {handoffs.length > 1 && (
308            <Button key="next" hotkey="n" onPress={step(1)}>n:Next</Button>
309          )}
310          <Button role="dismiss" onPress={close}>Close</Button>
311        </Box>
312      </Box>
313    )
314  })
315}
316
hooks/features/release.tsx 154 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import type { ReleaseAgent } from '../../types'
5import { joinPath, parseModsConfig } from '../lib/config'
6import { parentOf, type Project } from '../lib/project'
7import { addTechLine, parseVersions, planFor, techLine } from '../lib/release'
8import { isOn, type Options } from '../lib/switch'
9
10const PANE = 'allan-release'
11const plan = atom({ plugin: 'allan', key: 'releasePlan' } as const, null)
12const log = atom({ plugin: 'allan', key: 'releaseLog' } as const, [])
13const sessionName = atom({ plugin: 'allan', key: 'session' } as const, null)
14
15export const releaseCommands = [
16  { name: 'promote', description: 'Promote the newest staged version of this agent and its paired agents, from a pane with one Promote button per agent. Refuses on a dirty git tree.' },
17]
18
19/** Walks up from the cwd to the nearest folder holding Claude_Memory/INDEX.md or lua.skill.yaml. */
20async function findProject($: EngineInterface): Promise<Project | null> {
21  let dir: string | null = await $.session.cwd()
22  while (dir !== null) {
23    const hasMemory = await $.fs.exists(`${dir}/Claude_Memory/INDEX.md`)
24    const hasAgent = await $.fs.exists(`${dir}/lua.skill.yaml`)
25    if (hasMemory || hasAgent) {
26      return { root: dir, name: dir.slice(dir.lastIndexOf('/') + 1), memoryDir: hasMemory ? `${dir}/Claude_Memory` : null, hasAgent }
27    }
28    dir = parentOf(dir)
29  }
30  return null
31}
32
33/** The Claude_Memory folder at or above `dir`, if any. */
34async function memoryAbove($: EngineInterface, dir: string): Promise<string | null> {
35  let at: string | null = dir
36  while (at !== null) {
37    if (await $.fs.exists(`${at}/Claude_Memory/INDEX.md`)) return `${at}/Claude_Memory`
38    at = parentOf(at)
39  }
40  return null
41}
42
43async function readOr($: EngineInterface, path: string): Promise<string | null> {
44  return (await $.fs.exists(path)) ? $.fs.read(path) : null
45}
46
47async function lua($: EngineInterface, dir: string, args: string[], confirmed = false): Promise<{ ok: boolean; out: string }> {
48  const r = await $.process.run(['lua', ...args], { cwd: dir, timeoutMs: 120_000, env: confirmed ? { LUA_DEPLOY_CONFIRMED: '1' } : {} })
49  const out = `${r.stdout}\n${r.stderr}`.trim()
50  return { ok: r.exitCode === 0, out }
51}
52
53async function prepare($: EngineInterface): Promise<string> {
54  const project = await findProject($)
55  if (project === null) return 'No lua.skill.yaml or Claude_Memory above this folder.'
56  const config = parseModsConfig(await readOr($, `${project.root}/.claude-mods.json`))
57  const agentDir = config.agent === null ? project.root : joinPath(project.root, config.agent)
58  if (!(await $.fs.exists(`${agentDir}/lua.skill.yaml`))) return `No lua.skill.yaml in ${agentDir}. Set "agent" in ${project.root}/.claude-mods.json to the agent folder.`
59
60  const status = await $.process.run(['git', '-C', project.root, 'status', '--porcelain'])
61  if (status.exitCode === 0 && status.stdout.trim() !== '') {
62    const n = status.stdout.trim().split('\n').length
63    return `Refused: ${n} uncommitted path${n === 1 ? '' : 's'} in ${project.root}. Commit first; the promote should match a commit.`
64  }
65
66  const dirs = [agentDir, ...config.pairs.map(p => joinPath(agentDir, p))]
67  const agents: ReleaseAgent[] = []
68  for (const dir of dirs) {
69    if (!(await $.fs.exists(`${dir}/lua.skill.yaml`))) {
70      agents.push({ dir, name: dir.slice(dir.lastIndexOf('/') + 1), active: null, next: null, nextMessage: '', count: 0, prune: [], error: 'no lua.skill.yaml here', done: false })
71      continue
72    }
73    const listed = await lua($, dir, ['version', 'list', '--json', '--all'])
74    const versions = listed.ok ? parseVersions(listed.out) : null
75    if (versions === null) {
76      agents.push({ dir, name: dir.slice(dir.lastIndexOf('/') + 1), active: null, next: null, nextMessage: '', count: 0, prune: [], error: `lua version list failed: ${listed.out.slice(0, 120)}`, done: false })
77      continue
78    }
79    agents.push({ ...planFor(dir, versions, config.versionCap), error: null, done: false })
80  }
81  await update($, plan, () => agents)
82  await update($, log, () => [])
83  void $.ui.open({ id: PANE, title: 'Promote', focus: true })
84  const lines = agents.map(a => a.error !== null ? `  ${a.name}: ${a.error}` : a.next === null ? `  ${a.name}: nothing staged above v${a.active ?? '?'}` : `  ${a.name}: v${a.active ?? '?'} → v${a.next}${a.prune.length > 0 ? ` (then prune v${a.prune.join(', v')})` : ''}`)
85  return ['Promote plan (press the button in the pane; nothing runs until you do):', ...lines].join('\n')
86}
87
88async function promoteOne($: EngineInterface, index: number): Promise<void> {
89  const agents = (await read($, plan)) ?? []
90  const agent = agents[index]
91  if (agent === undefined || agent.next === null || agent.done) return
92  const say = async (line: string) => { await update($, log, l => [...l, line].slice(-30)) }
93  await say(`${agent.name}: promoting v${agent.next}…`)
94  const promoted = await lua($, agent.dir, ['version', 'promote', String(agent.next)], true)
95  if (!promoted.ok) {
96    await say(`${agent.name}: promote FAILED: ${promoted.out.slice(0, 200)}`)
97    $.ui.toast(`${agent.name}: promote failed. See the Promote pane.`)
98    return
99  }
100  await say(`${agent.name}: v${agent.next} is live.`)
101  const pruned: number[] = []
102  for (const v of agent.prune) {
103    const gone = await lua($, agent.dir, ['version', 'delete', String(v), '--force'], true)
104    if (gone.ok) pruned.push(v)
105    else await say(`${agent.name}: could not delete v${v}: ${gone.out.slice(0, 120)}`)
106  }
107  if (pruned.length > 0) await say(`${agent.name}: pruned v${pruned.join(', v')}.`)
108  try {
109    const memory = await memoryAbove($, agent.dir)
110    if (memory !== null) {
111      const path = `${memory}/TECH.md`
112      const tech = (await readOr($, path)) ?? ''
113      const date = new Date(await $.clock.now()).toISOString().slice(0, 10)
114      await $.fs.write(path, addTechLine(tech, techLine(date, agent, pruned, (await read($, sessionName)) ?? 'unnamed session')))
115      await say(`${agent.name}: noted in ${path.replace(/^.*\/Claude_Memory/, 'Claude_Memory')}.`)
116    }
117  } catch { await say(`${agent.name}: could not write TECH.md (promote stands).`) }
118  await update($, plan, list => (list ?? []).map((a, i) => (i === index ? { ...a, done: true, active: a.next, next: null } : a)))
119  $.ui.toast(`${agent.name}: v${agent.next} promoted. Run lua version list to confirm.`)
120}
121
122export function release(on: On, options: Options): void {
123  on('command.run', { command: 'promote' }, async $ => {
124    if (!isOn(options, 'release')) return { text: 'release is off (/mods on release).' }
125    return { text: await prepare($) }
126  })
127
128  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
129    const { Box, Text, Button } = $.ui.resolve(e)
130    const agents = (await read($, plan)) ?? []
131    const lines = await read($, log)
132    return (
133      <Box flexDirection="column">
134        <Text bold>Promote (each button runs lua version promote with LUA_DEPLOY_CONFIRMED=1)</Text>
135        {agents.map((a, i) => (
136          <Box key={`a${i}`}>
137            {a.error !== null && <Text color="red">{a.name}: {a.error}</Text>}
138            {a.error === null && a.done && <Text color="green">{a.name}: v{a.active} live ✔</Text>}
139            {a.error === null && !a.done && a.next === null && <Text dimColor>{a.name}: nothing staged above v{a.active ?? '?'}</Text>}
140            {a.error === null && !a.done && a.next !== null && (
141              <Button key={`promote${i}`} variant="primary" onPress={async () => { await promoteOne($, i) }}>
142                Promote {a.name} v{a.active ?? '?'} → v{a.next}{a.prune.length > 0 ? ` (prune ${a.prune.length})` : ''}
143              </Button>
144            )}
145            {a.error === null && !a.done && a.next !== null && <Text dimColor>  {a.nextMessage}</Text>}
146          </Box>
147        ))}
148        {lines.map((l, i) => <Text key={`l${i}`} dimColor>{l}</Text>)}
149        <Button role="dismiss" onPress={async () => { await update($, plan, () => null) }}>Close</Button>
150      </Box>
151    )
152  })
153}
154
hooks/features/relay.ts 127 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import { alivePids, inboxItem, label, lastBlock, listing, parseSessionFile, resolve, wrap, type SessionEntry } from '../lib/relay'
5import { parentOf } from '../lib/project'
6import { isOn, type Options } from '../lib/switch'
7
8// The session name pulse records; the messages other sessions relayed here (pulse draws them).
9const sessionName = atom({ plugin: 'allan', key: 'session' } as const, null)
10const inbox = atom({ plugin: 'allan', key: 'inbox' } as const, [])
11
12export const relayCommands = [
13  { name: 'sessions', description: 'Your open Claude Code sessions, this project first, then the others by project.' },
14  { name: 'relay', description: 'Send text, or the last START/END block of my last reply, to another session: /relay Code-4 last · /relay Jackfruit/Code-QC <text>', argumentHint: '<name|Project/name> <text|last>' },
15]
16
17/** The nearest folder at or above `dir` holding Claude_Memory/INDEX.md or lua.skill.yaml, by name; else `dir`'s own name. */
18async function projectOf($: EngineInterface, dir: string): Promise<string> {
19  let at: string | null = dir
20  while (at !== null) {
21    if ((await $.fs.exists(`${at}/Claude_Memory/INDEX.md`)) || (await $.fs.exists(`${at}/lua.skill.yaml`))) return at.slice(at.lastIndexOf('/') + 1)
22    at = parentOf(at)
23  }
24  return dir.slice(dir.lastIndexOf('/') + 1)
25}
26
27/** Every file of Claude Code's own list of sessions (~/.claude/sessions), parsed. */
28async function sessionFiles($: EngineInterface): Promise<Array<Omit<SessionEntry, 'project'>>> {
29  const dir = `${(await $.env.get('HOME')) ?? ''}/.claude/sessions`
30  if (!(await $.fs.exists(dir))) return []
31  const found: Array<Omit<SessionEntry, 'project'>> = []
32  for (const f of await $.fs.list(dir)) {
33    if (f.kind !== 'file' || !f.name.endsWith('.json')) continue
34    const entry = parseSessionFile(await $.fs.read(`${dir}/${f.name}`))
35    if (entry !== null) found.push(entry)
36  }
37  return found
38}
39
40/** This session's name as /rename set it (Claude Code's list), else as pulse saw it, else its id. */
41async function selfName($: EngineInterface): Promise<string> {
42  const id = await $.session.id()
43  return (await sessionFiles($)).find(s => s.id === id)?.name ?? (await read($, sessionName)) ?? id.slice(0, 8)
44}
45
46/** Claude Code's own list of running sessions, each with its project. */
47async function registry($: EngineInterface): Promise<SessionEntry[]> {
48  const found = await sessionFiles($)
49  if (found.length === 0) return []
50  // A file left behind by a session that crashed names a pid no longer running.
51  const ps = await $.process.run(['ps', '-o', 'pid=', '-p', found.map(s => s.pid).join(',')])
52  const alive = alivePids(ps.stdout)
53  const projects = new Map<string, string>()
54  const out: SessionEntry[] = []
55  for (const s of found) {
56    if (!alive.has(s.pid)) continue
57    const project = projects.get(s.cwd) ?? (await projectOf($, s.cwd))
58    projects.set(s.cwd, project)
59    out.push({ ...s, project })
60  }
61  return out
62}
63
64async function send($: EngineInterface, args: string): Promise<string> {
65  const m = args.trim().match(/^(\S+)\s+([\s\S]+)$/)
66  if (m === null) return 'Usage: /relay <name> <text|last>, for example /relay Code-4 last'
67  const target = m[1] ?? ''
68  const rest = (m[2] ?? '').trim()
69
70  const selfId = await $.session.id()
71  const project = await projectOf($, await $.session.cwd())
72  const all = await registry($)
73  const found = resolve(target, all, selfId, project)
74  if (!found.ok) return found.why
75
76  let body = rest
77  if (rest === 'last') {
78    const replies = (await $.session.messages()).filter(x => x.role === 'assistant').map(x => x.text)
79    const block = lastBlock(replies.slice(-10))
80    if (block === null) return 'No START/END block in my recent replies. /relay <name> <text> sends text as typed.'
81    body = block
82  }
83
84  const me = all.find(s => s.id === selfId)?.name ?? (await read($, sessionName)) ?? selfId.slice(0, 8)
85  const text = wrap(body, me, project)
86  const to = `${found.to.project}/${label(found.to)}`
87  const sent = await $.session.send({ to: { sessionId: found.to.id }, text })
88  if (sent.isDelivered) return `Relayed to ${to}${rest === 'last' ? ' (the last START/END block)' : ''}.`
89  const copied = (await $.ui.copy({ text })).isCopied
90  return `Not delivered to ${to}: ${sent.reason}. ${copied ? 'Copied to the clipboard; paste it there.' : 'Copy it by hand:'}\n\n${copied ? '' : text}`.trimEnd()
91}
92
93export function relay(on: On, options: Options): void {
94  on('command.run', { command: 'sessions' }, async $ => {
95    if (!isOn(options, 'relay')) return { text: 'relay is off (/mods on relay).' }
96    const text = listing(await registry($), await $.session.id(), await projectOf($, await $.session.cwd()), await $.clock.now())
97    return { text }
98  })
99
100  on('command.run', { command: 'relay' }, async ($, e) => {
101    if (!isOn(options, 'relay')) return { text: 'relay is off (/mods on relay).' }
102    return { text: await send($, e.args) }
103  })
104
105  // Everything this session's model sends another session (SendMessage) carries the sender too.
106  on('session.send', async ($, e, next) => {
107    if (!isOn(options, 'relay') || e.origin?.kind !== 'model' || e.agentId !== undefined || e.text.startsWith('[relay from ')) return next(e)
108    let text = e.text
109    try {
110      text = wrap(e.text, await selfName($), await projectOf($, await $.session.cwd()))
111    } catch { /* send it unheaded rather than not at all */ }
112    return next({ ...e, text })
113  })
114
115  // A message from another session goes on to the model as usual; the band shows it arrived.
116  on('session.receive', async ($, e, next) => {
117    const done = await next(e)
118    if (!isOn(options, 'relay') || e.agentId !== undefined) return done
119    if (e.origin.kind !== 'peer-send-message' && !e.text.startsWith('[relay from ')) return done
120    try {
121      const item = inboxItem(e.text, await $.clock.now())
122      await update($, inbox, items => [...items, item].slice(-20))
123    } catch { /* the inbox row is a convenience; the message itself is already delivered */ }
124    return done
125  })
126}
127
hooks/features/testguard.ts 118 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On } from 'claude-code'
3
4import { parseModsConfig } from '../lib/config'
5import { parentOf } from '../lib/project'
6import { isOn, type Options } from '../lib/switch'
7import { protectedIn, recipientKey, redactBlocks, scriptsIn, secretsUsed, TESTMODE_HELD, withSecrets } from '../lib/testguard'
8
9// Whether /testmode is on, and the secrets /secret set holds for this session only.
10const testMode = atom({ plugin: 'allan', key: 'testMode' } as const, false)
11const secrets = atom({ plugin: 'allan', key: 'secrets' } as const, {})
12
13export const testguardCommands = [
14  { name: 'testmode', description: 'Protect real recipients while you test: /testmode on | off | status. Bash naming a protected address, or lua env setting a recipient key, is refused while on.', argumentHint: 'on|off|status' },
15  { name: 'secret', description: 'Hold a secret for this session from the clipboard, never in the transcript: /secret set NAME, then use $NAME in commands. /secret list · /secret clear', argumentHint: 'set <NAME> | list | clear' },
16]
17
18/** The nearest folder above the cwd with a .claude-mods.json, read; else empty config. */
19async function config($: EngineInterface) {
20  let dir: string | null = await $.session.cwd()
21  while (dir !== null) {
22    const path = `${dir}/.claude-mods.json`
23    if (await $.fs.exists(path)) return parseModsConfig(await $.fs.read(path))
24    if ((await $.fs.exists(`${dir}/Claude_Memory/INDEX.md`)) || (await $.fs.exists(`${dir}/lua.skill.yaml`))) break
25    dir = parentOf(dir)
26  }
27  return parseModsConfig(null)
28}
29
30async function isTesting($: EngineInterface): Promise<boolean> {
31  if (await read($, testMode)) return true
32  return (await $.env.get('ALLAN_TESTMODE')) === '1'
33}
34
35async function testmode($: EngineInterface, args: string): Promise<string> {
36  const verb = args.trim().toLowerCase()
37  if (verb === 'on') {
38    await update($, testMode, () => true)
39    const list = (await config($)).protected
40    return list.length === 0
41      ? 'Test mode on, but .claude-mods.json names no "protected" addresses above this folder, so only recipient env keys are guarded.'
42      : `Test mode on. Protected: ${list.join(', ')}. Bash naming them and lua env -k *CC/*ALLOWLIST/*RECIPIENT/*TO are refused until /testmode off.`
43  }
44  if (verb === 'off') {
45    await update($, testMode, () => false)
46    return (await $.env.get('ALLAN_TESTMODE')) === '1' ? 'Test mode off here, but ALLAN_TESTMODE=1 is set in the environment, so the guard stays on.' : 'Test mode off.'
47  }
48  const on = await isTesting($)
49  const list = (await config($)).protected
50  return `Test mode is ${on ? 'on' : 'off'}. Protected: ${list.length === 0 ? '(none in .claude-mods.json)' : list.join(', ')}.`
51}
52
53async function secret($: EngineInterface, args: string): Promise<string> {
54  const [verb, name] = args.trim().split(/\s+/)
55  if (verb === 'list') {
56    const names = Object.keys(await read($, secrets))
57    return names.length === 0 ? 'No secrets held this session.' : `Held this session: ${names.join(', ')}. Use $NAME in Bash; the value never shows.`
58  }
59  if (verb === 'clear') {
60    await update($, secrets, () => ({}))
61    return 'Secrets cleared.'
62  }
63  if (verb !== 'set' || name === undefined || !/^[A-Z_][A-Z0-9_]*$/.test(name)) return 'Usage: /secret set NAME (the value is read from the clipboard) · /secret list · /secret clear'
64  const paste = await $.process.run(['pbpaste'])
65  const value = paste.stdout.trim()
66  if (paste.exitCode !== 0 || value === '') return 'The clipboard is empty. Copy the value first, then /secret set NAME.'
67  await update($, secrets, s => ({ ...s, [name]: value }))
68  return `${name} held for this session (${value.length} characters, never shown). Use $${name} in Bash commands; tool results are redacted.`
69}
70
71export function testguard(on: On, options: Options): void {
72  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
73    if (!isOn(options, 'testguard')) return next(e)
74    let command = String(e.command ?? '')
75
76    if (await isTesting($)) {
77      const list = (await config($)).protected
78      const named = protectedIn(command, list)
79      if (named.length > 0) {
80        $.ui.toast(`testguard held a command naming ${named[0]}`)
81        return { deny: TESTMODE_HELD(`this command names a protected address (${named.join(', ')})`) }
82      }
83      const cwd = await $.session.cwd()
84      for (const script of scriptsIn(command)) {
85        const path = script.startsWith('/') ? script : `${cwd}/${script}`
86        if (!(await $.fs.exists(path))) continue
87        const inside = protectedIn(await $.fs.read(path), list)
88        if (inside.length > 0) {
89          $.ui.toast(`testguard held ${script}: it names ${inside[0]}`)
90          return { deny: TESTMODE_HELD(`${script} names a protected address (${inside.join(', ')})`) }
91        }
92      }
93      const key = recipientKey(command)
94      if (key !== null) {
95        $.ui.toast(`testguard held lua env -k ${key}`)
96        return { deny: TESTMODE_HELD(`${key} names recipients; changing it`) }
97      }
98    }
99
100    const held = await read($, secrets)
101    const used = secretsUsed(command, Object.keys(held))
102    if (used.length > 0) command = withSecrets(command, held, used)
103    return command === e.command ? next(e) : next({ ...e, command })
104  }).catch(($, e, next) => next(e))
105
106  // Every row kept in the transcript: a secret's value is replaced before it is stored or read by the model.
107  on('session.append', async ($, e, next) => {
108    if (!isOn(options, 'testguard')) return next(e)
109    const held = await read($, secrets)
110    if (Object.keys(held).length === 0) return next(e)
111    const content = redactBlocks(e.message.content as Array<Record<string, unknown>>, held)
112    return content === null ? next(e) : next({ ...e, message: { ...e.message, content: content as typeof e.message.content } })
113  }).catch(($, e, next) => next(e))
114
115  on('command.run', { command: 'testmode' }, async ($, e) => ({ text: await testmode($, e.args) }))
116  on('command.run', { command: 'secret' }, async ($, e) => ({ text: await secret($, e.args) }))
117}
118
hooks/features/voice.ts 59 lines
1import { atom, read, update } from 'claude-code'
2import type { On } from 'claude-code'
3
4import type { VoiceStyle } from '../../types'
5import { isOn, textOf, type Options } from '../lib/switch'
6
7const style = atom({ plugin: 'allan', key: 'style' } as const, null)
8
9const BASE = [
10  "How to write replies for Allan (his standing preferences, kept here so they survive compaction):",
11  '- Lead with the answer or the outcome. Then only the detail he needs to act. Aim for half the length you would naturally write.',
12  '- Plain words, short sentences. He juggles several client projects and often reads on his phone.',
13  '- When a task is non-trivial to implement, walk through the build steps; he knows the terms but has not built much end to end.',
14  '- Minimize em dashes and hyphens in prose, code identifiers and anything sent outward.',
15  '- Never put internal memory references (decision or handoff ids like D12, H22, Claude_Memory paths) into anything a client or another company will read.',
16  '- Any message he must paste into another session goes between a START line and an END line that name the target session.',
17].join('\n')
18
19const EXTRA: Record<VoiceStyle, string> = {
20  normal: '',
21  plain:
22    '- Style for this session: explain as if to a bright high school student. Keep every crucial detail; drop jargon or explain it in one clause.',
23  visual:
24    '- Style for this session: where a flow, sequence or structure is involved, add one small ASCII diagram (under 12 lines) before the prose.',
25}
26
27function asStyle(value: string): VoiceStyle {
28  return value === 'plain' || value === 'visual' ? value : 'normal'
29}
30
31export const styleCommand = {
32  name: 'style',
33  description: 'Reply style for this session: /style normal · /style plain (high school tone) · /style visual (ASCII diagrams)',
34  argumentHint: '[normal|plain|visual]',
35}
36
37/** The voice section's text for a style (pure: register.ts reads the state and options). */
38export function voiceText(chosen: VoiceStyle): string {
39  return [BASE, EXTRA[chosen]].filter(Boolean).join('\n')
40}
41
42export { asStyle }
43
44export function voice(on: On, options: Options): void {
45  on('command.run', { command: 'style' }, async ($, e) => {
46    const wanted = e.args.trim()
47    if (wanted === '') {
48      const now = (await read($, style)) ?? asStyle(textOf(options, 'voiceStyle', 'normal'))
49      return { text: `Reply style: ${now}${isOn(options, 'voice') ? '' : ' (voice is off: /mods on voice)'}` }
50    }
51    if (wanted !== 'normal' && wanted !== 'plain' && wanted !== 'visual') {
52      return { text: 'Styles: normal, plain, visual.' }
53    }
54    await update($, style, () => wanted)
55    return { text: `Reply style for this session: ${wanted}.` }
56  })
57
58}
59
hooks/features/watch.ts 142 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, On, Timer } from 'claude-code'
3
4import type { WatchLight } from '../../types'
5import { joinPath, parseModsConfig } from '../lib/config'
6import { parentOf, type Project } from '../lib/project'
7import { count, describe, keepWeek, levelOf, median, parseLogs, takeLease, WATCH_PREFIX, type Sample } from '../lib/watch'
8import { isOn, type Options } from '../lib/switch'
9
10// The light pulse draws in the band, and what /logs reports since it was last run.
11const light = atom({ plugin: 'allan', key: 'watchLight' } as const, null)
12const unseen = atom({ plugin: 'allan', key: 'watchUnseen' } as const, { errors: 0, blocks: 0, bypass: 0, since: null })
13const recent = atom({ plugin: 'allan', key: 'watchRecent' } as const, [])
14
15export const watchCommands = [
16  { name: 'logs', description: 'What watch saw in the agent logs since you last asked: errors, preprocessor blocks, gate bypasses, failing checks.' },
17]
18
19let timer: Timer | null = null
20let first: Timer | null = null
21
22function intervalMs(options: Options): number {
23  const v = (options as Record<string, unknown>)['watchIntervalMin']
24  return (typeof v === 'number' && v >= 1 ? v : 10) * 60_000
25}
26
27/** Walks up from the cwd to the nearest folder holding Claude_Memory/INDEX.md or lua.skill.yaml. */
28async function findProject($: EngineInterface): Promise<Project | null> {
29  let dir: string | null = await $.session.cwd()
30  while (dir !== null) {
31    const hasMemory = await $.fs.exists(`${dir}/Claude_Memory/INDEX.md`)
32    const hasAgent = await $.fs.exists(`${dir}/lua.skill.yaml`)
33    if (hasMemory || hasAgent) {
34      return { root: dir, name: dir.slice(dir.lastIndexOf('/') + 1), memoryDir: hasMemory ? `${dir}/Claude_Memory` : null, hasAgent }
35    }
36    dir = parentOf(dir)
37  }
38  return null
39}
40
41async function readOr($: EngineInterface, path: string): Promise<string | null> {
42  return (await $.fs.exists(path)) ? $.fs.read(path) : null
43}
44
45/** One look at the logs and checks. Cheap: one page of 100 lines, one process per check. */
46async function tick($: EngineInterface, options: Options): Promise<void> {
47  if (!isOn(options, 'watch')) return
48  const project = await findProject($)
49  if (project === null) return
50  const config = parseModsConfig(await readOr($, `${project.root}/.claude-mods.json`))
51  const agentDir = config.agent === null ? project.root : joinPath(project.root, config.agent)
52  if (!(await $.fs.exists(`${agentDir}/lua.skill.yaml`))) return
53
54  const now = await $.clock.now()
55  const selfId = await $.session.id()
56  const leaseKey = `${WATCH_PREFIX}${project.root}`
57  const lease = takeLease(await $.store.get(leaseKey), selfId, now, intervalMs(options))
58  if (lease === null) return
59  await $.store.set(leaseKey, lease)
60
61  const markKey = `${WATCH_PREFIX}mark:${project.root}`
62  const seenKey = `${WATCH_PREFIX}seen:${project.root}`
63  const historyKey = `${WATCH_PREFIX}history:${project.root}`
64  const mark = await $.store.get(markKey)
65  const since = typeof mark === 'string' && mark !== '' ? mark : '1h'
66  const r = await $.process.run(['lua', 'logs', '--ci', '--json', '--limit', '100', '--since', since], { cwd: agentDir, timeoutMs: 60_000 })
67  const entries = r.exitCode === 0 ? parseLogs(r.stdout) : null
68  if (entries === null) {
69    await update($, light, () => ({ level: 'amber', text: `lua logs failed: ${(r.stderr || r.stdout).trim().slice(0, 80)}`, at: now, project: project.name }))
70    return
71  }
72  const seenRaw = await $.store.get(seenKey)
73  const seen = new Set(Array.isArray(seenRaw) ? (seenRaw as string[]) : [])
74  const fresh = entries.filter(e => !seen.has(e.id))
75  await $.store.set(seenKey, [...seen, ...fresh.map(e => e.id)].slice(-400))
76  const newest = entries.map(e => e.at).filter(a => a !== '').sort().pop()
77  if (newest !== undefined) await $.store.set(markKey, newest)
78
79  const c = count(fresh)
80  const historyRaw = await $.store.get(historyKey)
81  const history = keepWeek(Array.isArray(historyRaw) ? (historyRaw as Sample[]) : [], now)
82  const usual = median(history.map(s => s.errors))
83  await $.store.set(historyKey, [...history, { at: now, ...c }])
84
85  const failed: string[] = []
86  for (const check of config.checks) {
87    try {
88      const run = await $.process.run(['sh', '-c', check.command], { cwd: project.root, timeoutMs: 60_000 })
89      if (run.exitCode !== 0) failed.push(check.name)
90    } catch {
91      failed.push(check.name)
92    }
93  }
94
95  const level = levelOf(c, usual, failed)
96  const text = describe(c, level, failed)
97  const before = await read($, light)
98  await update($, light, () => ({ level, text, at: now, project: project.name }))
99  await update($, unseen, u => ({ errors: u.errors + c.errors, blocks: u.blocks + c.blocks, bypass: u.bypass + c.bypass, since: u.since ?? now }))
100  const lines = fresh.filter(e => e.isError || e.isBypass || e.isBlock).map(e => `${e.at.slice(11, 19)} ${e.message.slice(0, 160)}`)
101  if (lines.length > 0) await update($, recent, l => [...l, ...lines].slice(-10))
102  if (level !== 'green' && before?.level !== level) $.ui.toast(`watch ${level === 'red' ? '🔴' : '🟡'} ${project.name}: ${text}. /logs for the lines.`)
103}
104
105async function report($: EngineInterface, options: Options): Promise<string> {
106  const l = await read($, light)
107  if (l === null) {
108    return isOn(options, 'watch')
109      ? 'watch has not looked yet (it runs every ' + String(intervalMs(options) / 60_000) + ' min in a folder with lua.skill.yaml, or set "agent" in .claude-mods.json).'
110      : 'watch is off (/mods on watch).'
111  }
112  const u = await read($, unseen)
113  const lines = await read($, recent)
114  const dot = l.level === 'green' ? '🟢' : l.level === 'amber' ? '🟡' : '🔴'
115  const out = [
116    `${dot} ${l.project}: ${l.text} (last look ${new Date(l.at).toISOString().slice(11, 16)} UTC)`,
117    u.since === null ? 'Nothing new since you last asked.' : `Since ${new Date(u.since).toISOString().slice(11, 16)} UTC: ${u.errors} errors, ${u.blocks} blocks, ${u.bypass} bypass lines.`,
118    ...(lines.length > 0 ? ['', 'Recent lines:', ...lines.map(x => `  ${x}`)] : []),
119  ]
120  await update($, unseen, () => ({ errors: 0, blocks: 0, bypass: 0, since: null }))
121  await update($, recent, () => [])
122  return out.join('\n')
123}
124
125export function watch(on: On, options: Options): void {
126  // Starts (or restarts, after a reload) the timer; a surface is set on every session a person sits at.
127  on('session.start', { surface: /terminal|desktop|vscode|mobile/ }, async ($, e, next) => {
128    timer?.cancel()
129    first?.cancel()
130    timer = null
131    first = null
132    if (isOn(options, 'watch') && e.isInteractive) {
133      const safely = () => { tick($, options).catch(() => { /* the light is a convenience; the next tick tries again */ }) }
134      first = $.clock.after(15_000, safely)
135      timer = $.clock.every(intervalMs(options), safely)
136    }
137    return next(e)
138  })
139
140  on('command.run', { command: 'logs' }, async $ => ({ text: await report($, options) }))
141}
142