Trims long xcodebuild and swift build/test output to the errors, failing tests and summary, keeping the full log on disk

A small collection of Claude Code mods (plugins that hook into the session). Install only the ones you want.
| Mod | What it does |
|---|---|
| agent-dashboard | One Dashboard pane with usage and context bars, tasks, tests, sessions and subagents |
| auto-handover | /handover writes a handover note and starts (or proposes) a fresh session |
| auto-compact | Compacts past 250k tokens and saves the full transcript before every compaction |
| build-trimmer | Trims long xcodebuild / swift build output so it does not fill your context |
| prompt-upgrade | /improve rewrites a rough prompt into a clear one |
| keep-going | Stops Claude ending a turn on a vague "want me to…?": it keeps working or asks with options |
| memdb | A searchable memory database Claude can query and add to |
| cache-tax | Keeps the prompt cache warm during breaks and stops a cold send once with its price (third-party, MIT) |
| reflect-mod | Turns your corrections into CLAUDE.md rules, saved with one press (third-party, MIT) |
memdb (it also needs SQLite with FTS5, which most Python builds have) and for build-trimmer's xctrim.py.build-trimmer is for Apple development (Xcode / SwiftPM). agent-dashboard and auto-handover work best in the desktop app, where panes and new sessions are available.To get every mod and the settings this repo is used with (auto-compact at 200k, the built-in auto-compact at the same size), clone it and run the setup script:
git clone https://github.com/flyingpurplepizzaeater/claude-mods.git
cd claude-mods && ./setup.sh
It copies each mod to ~/.claude/mods/<mod> and adds three keys to the env of ~/.claude/settings.json: CLAUDE_CODE_PLUGIN_DIRS (the mods, kept alongside any plugin folders already listed), AUTO_COMPACT_THRESHOLD and CLAUDE_CODE_AUTO_COMPACT_WINDOW. Nothing else in the file changes, and the old one is kept as settings.json.bak. Name mods to install only those (./setup.sh memdb cache-tax), set AUTO_COMPACT_THRESHOLD=300k before it for another size, and run it again after git pull to update. New sessions load the mods. It needs rsync and python3, and follows CLAUDE_CONFIG_DIR if you set it.
Use either this or the marketplace install below for a mod, not both, or its hooks run twice.
At the prompt of a terminal session (swap memdb for any mod name above):
/plugin install memdb --marketplace flyingpurplepizzaeater/claude-mods
Claude asks Add marketplace?: answer y, then pick a scope (user scope is the first one). If the mod has options, a screen lets you set them. You then see Installed memdb. Plugin is now active., and its hooks run from then on, with no reload needed.
From a shell:
claude plugin install memdb --marketplace flyingpurplepizzaeater/claude-mods
In the desktop app, where /plugin does not run: click + next to the prompt box, then Plugins, Add marketplace with flyingpurplepizzaeater/claude-mods, then Add plugin.
If you have already added the marketplace, claude plugin install <mod>@claude-mods is enough.
Opens one Dashboard pane at session start and stacks everything in it:
/dashboard brings the pane to the front. The pane refreshes every 5 seconds.
Options (all can be changed later in /config):
| Option | Default | Meaning |
|---|---|---|
planNote | on | Tell Claude to write long or multi-part requests into its task list first |
queueMessages | on | A message sent while Claude is working goes to the end of its task list instead of derailing it. Start the message with !now to act on it immediately |
buildReminder | off | After a long build or test run in the foreground, remind Claude to use the background next time |
/handover asks Claude to write a short handover note (goal, state, done, next steps, key files, gotchas) to ~/.claude/handovers/ and then starts a fresh session that continues from it. In the desktop app it starts the session directly (or proposes it as a card); elsewhere it leaves the "continue" prompt in the prompt box for you to send after /clear.
/handover write the note and hand over now
/handover status show whether auto mode is on, the threshold and this session's size
/handover on | off automatic handover past a context threshold (off by default)
/handover threshold 200k set the threshold (at least 1k; never above 80% of the window)
The threshold can also be set with the environment variable AUTO_HANDOVER_THRESHOLD or per project in .claude/auto-handover.json ({ "threshold": "120k" }). Notes go to $CLAUDE_CONFIG_DIR/handovers if that variable is set. No plugin options.
After each answer, if the context is past 250k tokens, it compacts the conversation, telling the summary to keep the goal, decisions, files changed and next steps. Before every compaction (your /compact, the built-in auto-compact, or its own) it saves the full conversation as markdown to ~/.claude/compact-saves/: every message and each tool call with its result, long ones clipped. Common secrets (API keys, tokens, JWTs, private keys, password: …) are redacted, and the folder is owner-only (700, files 600). A failed save never blocks the compaction. With memdb installed, the saves become searchable there.
/autocompact status on or off, the threshold, this session's size and the last save
/autocompact on | off automatic compaction (on by default; saves happen either way)
/autocompact threshold 250k set the threshold (at least 10k)
/autocompact now save and compact now
The threshold can also be set with the environment variable AUTO_COMPACT_THRESHOLD. Saves go to $CLAUDE_CONFIG_DIR/compact-saves if that variable is set. If the model's context window is no larger than the threshold, the built-in auto-compact fires first (the transcript is still saved). No plugin options.
Its own compaction runs between turns, so after one it sends a short prompt telling the session to carry on where it left off (or say in one line that it was done or waiting for you); /autocompact now doesn't. Long autonomous runs are smoother if the built-in auto-compact, which compacts mid-turn and keeps going, fires at the same size: set CLAUDE_CODE_AUTO_COMPACT_WINDOW to the threshold plus 13000 (e.g. 213000 for 200k). The mod then stays as a backup and still saves the transcript before every compaction.
Wraps xcodebuild, swift build and swift test commands that Claude runs in Bash. The full output goes to a log file and Claude sees only the errors, failing tests, the summary and the tail, plus the log path. The exit code is preserved. Logs are in ~/.claude/build-trimmer/logs and are deleted after 7 days. Add # no-trim to a command to leave it alone.
Options:
| Option | Default | Meaning |
|---|---|---|
developerDir | empty (off) | DEVELOPER_DIR to build with, e.g. /Applications/Xcode-beta.app/Contents/Developer |
developerDirPathMatch | empty | Use developerDir only when the command or working folder contains this text, e.g. /MyApp. Empty means every build |
extraBuildScripts | empty | Comma-separated script names that run xcodebuild or swift test themselves, e.g. test.sh,ci.sh |
A command that already sets DEVELOPER_DIR is never changed. If python3 is missing the full log is shown instead.
/improve <rough prompt> rewrites a rough prompt into a clear, specific one, using what the session already knows about your project, and puts it in the prompt box so you can review and edit it. Run /improve send to submit the last one. It keeps your intent and does not add goals you did not ask for. No options.
When Claude ends a turn by handing the next move back in plain text ("Want me to…?", "Should I…?", "Let me know if…"), the mod blocks that stop once and tells Claude to either keep working, routing around anything blocked, or ask properly with AskUserQuestion (2–4 options, recommendation first). A turn that already asked with AskUserQuestion, plan approval or the desktop app's wrap-up buttons is let through, and so is the second stop in a row, so it never loops. Safety confirmations (push, send, delete) still get asked, as options. The phrases it looks for are in hooks/check.ts. No options.
A searchable memory database (SQLite full-text search, ranked and stemmed) for Claude. It indexes your Claude memory files (~/.claude/projects/*/memory/*.md) automatically, and also holds:
memdb_add)memdb_index)~/.claude/compact-saves/ is indexed automatically, one entry per exchange (your prompt and the work that answered it), titled with the date and the prompt's first line and filed under the folder the session ran in. Search ranks memories and notes above docs and docs above transcripts, shows at most two old conversations by default (the best exchange of each) and says how many more matched; search with kind transcript for all of them. Deleting a save removes it; the database file is owner-only (600).Claude gets these tools: memdb_search, memdb_add, memdb_get, memdb_index and memdb_forget, and a short note in the system prompt telling it to search before rereading long notes. You get /memdb <words> to search, plus /memdb stats, /memdb list, /memdb get <name> and /memdb sync.
If Python is missing, older than 3.8, or lacks FTS5, the tools answer with a clear message instead of failing.
Options:
| Option | Default | Meaning |
|---|---|---|
python | python3 | Python command to run the script |
dbPath | empty | Database file. Empty means ~/.claude/memdb/memory.db (or under $CLAUDE_CONFIG_DIR) |
promptNote | on | Add the short "memdb is available" note to the system prompt |
The script also works on its own, with no Claude involved. After installing, find it under the plugin folder (or clone this repo):
python3 plugins/memdb/bin/memdb.py --help
python3 plugins/memdb/bin/memdb.py search "database port"
python3 plugins/memdb/bin/memdb.py add staging-port "It is 5433" -d "staging DB port"
MEMDB_PATH overrides the database location.
cache-tax by Karan Bansal (MIT), copied here at upstream commit 432a08d (2.3.0) so it installs with the rest. /keepwarm keeps the one-hour prompt cache warm through a break by sending a tiny ping 50 minutes after the last request; /keepwarm always does that for every session, for up to six hours after each turn. When the cache has gone cold, it stops the first send once and shows what the rewrite will cost. /cache-tax shows the cache state and prices. See its README.
One change from upstream: after a compaction in the middle of a turn (the built-in auto-compact), it starts pinging again as soon as the next request comes back, rather than when the turn ends. Without it, a long autonomous turn that compacted and then sat at a permission prompt or a question went cold. Two tests at the end of tests/register.test.ts cover it.
reflect-mod from claude-reflect by Bayram Annakov (MIT), copied unchanged at upstream commit b6c4232 (3.3.0). After a short prompt that corrects Claude, a model check decides whether it is a reusable rule; if so, a band above the prompt offers to save it to CLAUDE.md with one press. See its README.
/config in a terminal session (each mod's options are rows there), or reinstall and answer the options screen.claude plugin update <mod> (or claude plugin marketplace update claude-mods first).claude plugin disable <mod>; turn back on with claude plugin enable <mod>.claude plugin uninstall <mod>. To drop the marketplace too: claude plugin marketplace remove claude-mods.~/.claude/memdb/; delete that folder if you want the data gone. auto-handover notes stay in ~/.claude/handovers/, auto-compact saves in ~/.claude/compact-saves/ and build-trimmer logs in ~/.claude/build-trimmer/logs/.Each mod is a folder under plugins/. Check one with:
claude plugin validate plugins/<mod>
claude plugin test plugins/<mod>
claude plugin validate . # the marketplace file
MIT licensed, see LICENSE.
hooks/register.ts 64 lines1import type { Engine, PluginOptions, Register } from 'claude-code'
2
3import { isBuild, segments } from './shell'
4
5const KEEP_DAYS = 7
6
7const q = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
8const str = (v: unknown) => (typeof v === 'string' ? v.trim() : '')
9
10/** Full logs live in <config dir>/build-trimmer/logs: CLAUDE_CONFIG_DIR when set, else ~/.claude. */
11async function logsDir($: Engine): Promise<string> {
12 const home = ((await $.env.get('HOME').catch(() => undefined)) ?? '').replace(/\/+$/, '')
13 const configDir = ((await $.env.get('CLAUDE_CONFIG_DIR').catch(() => undefined)) ?? '').replace(/\/+$/, '')
14 return `${configDir || `${home}/.claude`}/build-trimmer/logs`
15}
16
17export function wrap(
18 command: string,
19 opts: { root: string; logs: string; logName: string; developerDir?: string },
20): string {
21 const log = `${opts.logs}/${opts.logName}.log`
22 return [
23 `mkdir -p ${q(opts.logs)} && find ${q(opts.logs)} -name '*.log' -mtime +${KEEP_DAYS} -delete 2>/dev/null`,
24 ...(opts.developerDir ? [`export DEVELOPER_DIR=${q(opts.developerDir)}`] : []),
25 `__trim_log=${q(log)}`,
26 '{',
27 command,
28 '} > "$__trim_log" 2>&1',
29 '__trim_rc=$?',
30 // Without python3 the log is shown whole rather than lost.
31 `if command -v python3 >/dev/null 2>&1; then python3 -I ${q(`${opts.root}/bin/xctrim.py`)} "$__trim_log" "$__trim_rc"; else cat "$__trim_log"; fi`,
32 '(exit $__trim_rc)',
33 ].join('\n')
34}
35
36export const register: Register = (on, options: PluginOptions) => {
37 // Optional: run builds with a particular Xcode (DEVELOPER_DIR), everywhere or only where a path matches.
38 const developerDir = str(options.developerDir)
39 const pathMatch = str(options.developerDirPathMatch)
40 // Extra scripts (comma-separated names) that run xcodebuild or swift test themselves.
41 const extraScripts = str(options.extraBuildScripts)
42 .split(',')
43 .map(s => s.trim())
44 .filter(Boolean)
45
46 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
47 // `# no-trim` in a command opts it out; a wrapped command is never wrapped again.
48 if (/no-trim|__trim_log/.test(e.command) || !segments(e.command).some(seg => isBuild(seg, extraScripts))) return next(e)
49
50 const stamp = new Date(await $.clock.now()).toISOString().replace(/[:.]/g, '-').slice(0, 19)
51 const useDeveloperDir =
52 developerDir !== '' &&
53 !e.command.includes('DEVELOPER_DIR') &&
54 (pathMatch === '' || e.command.includes(pathMatch) || (await $.session.cwd()).includes(pathMatch))
55 const command = wrap(e.command, {
56 root: $.plugin.root,
57 logs: await logsDir($),
58 logName: `${stamp}-${e.tool_use_id.slice(-6)}`,
59 developerDir: useDeveloperDir ? developerDir : undefined,
60 })
61 return next({ ...e, command })
62 }).catch(($, e, next) => next(e)) // if the wrapper can't be built, run the command as it was
63}
64hooks/shell.ts 146 lines1// A small shell splitter: enough to find the commands a Bash call runs,
2// not a full shell parser. Quotes are honoured; $(...) and backticks are not.
3
4export type Segment = { argv: string[]; cwd?: string }
5
6const WRAPPERS = new Set(['env', 'time', 'nohup', 'caffeinate', 'xcrun', 'command', 'exec', 'sudo'])
7const SHELLS = new Set(['bash', 'sh', 'zsh'])
8
9function tokenize(cmd: string): string[][] {
10 const groups: string[][] = [[]]
11 let word = ''
12 let hasWord = false
13 let quote: '"' | "'" | null = null
14
15 const endWord = () => {
16 if (hasWord) groups[groups.length - 1]!.push(word)
17 word = ''
18 hasWord = false
19 }
20 const endGroup = () => {
21 endWord()
22 if (groups[groups.length - 1]!.length > 0) groups.push([])
23 }
24
25 for (let i = 0; i < cmd.length; i++) {
26 const c = cmd[i]!
27 if (quote) {
28 if (c === quote) quote = null
29 else if (c === '\\' && quote === '"' && i + 1 < cmd.length) word += cmd[++i]
30 else word += c
31 continue
32 }
33 if (c === '"' || c === "'") {
34 quote = c
35 hasWord = true
36 } else if (c === '\\' && i + 1 < cmd.length) {
37 if (cmd[i + 1] === '\n') i++
38 else {
39 word += cmd[++i]
40 hasWord = true
41 }
42 } else if (c === ' ' || c === '\t') {
43 endWord()
44 } else if (c === '>' || c === '<') {
45 // a redirection is a word of its own: an fd before it, the operator, an &fd after it (2>&1)
46 if (hasWord && !/^\d+$/.test(word)) endWord()
47 word += c
48 hasWord = true
49 if (cmd[i + 1] === c) word += cmd[++i]
50 if (cmd[i + 1] === '&') {
51 word += cmd[++i]
52 while (/[\d-]/.test(cmd[i + 1] ?? '')) word += cmd[++i]
53 }
54 endWord()
55 } else if (c === '\n' || c === ';' || c === '&' || c === '|' || c === '(' || c === ')') {
56 endGroup()
57 } else if (c === '#' && !hasWord) {
58 while (i < cmd.length && cmd[i] !== '\n') i++
59 endGroup()
60 } else {
61 word += c
62 hasWord = true
63 }
64 }
65 endGroup()
66 return groups.filter(g => g.length > 0)
67}
68
69function basename(path: string): string {
70 return path.slice(path.lastIndexOf('/') + 1)
71}
72
73const REDIRECT = /^\d*(>>?|<<?)(&[\d-]*)?$/
74
75/** The words of a command without its redirections (`2>&1`, `> out.log`, `<<'EOF'`). */
76function dropRedirects(words: string[]): string[] {
77 const out: string[] = []
78 for (let i = 0; i < words.length; i++) {
79 const w = words[i]!
80 if (!REDIRECT.test(w)) out.push(w)
81 else if (!w.includes('&')) i++ // its target is the next word
82 }
83 return out
84}
85
86function unwrap(argv: string[]): string[] {
87 let i = 0
88 for (;;) {
89 while (i < argv.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[i]!)) i++
90 const head = argv[i]
91 if (head === undefined || !WRAPPERS.has(basename(head))) break
92 i++
93 while (i < argv.length && argv[i]!.startsWith('-')) i++
94 }
95 return argv.slice(i)
96}
97
98/** The commands a Bash call runs, each with the directory a preceding `cd` set. */
99export function segments(cmd: string, depth = 0): Segment[] {
100 const out: Segment[] = []
101 let cwd: string | undefined
102 for (const raw of tokenize(cmd)) {
103 const argv = unwrap(dropRedirects(raw))
104 const head = argv[0]
105 if (head === undefined) continue
106 if (head === 'cd' || head === 'pushd') {
107 const dir = argv[1]
108 if (dir !== undefined) cwd = /^[/~]/.test(dir) || cwd === undefined ? dir : `${cwd}/${dir}`
109 continue
110 }
111 const shellArg = argv.indexOf('-c')
112 if (SHELLS.has(basename(head)) && shellArg > 0 && argv[shellArg + 1] !== undefined && depth < 3) {
113 for (const inner of segments(argv[shellArg + 1]!, depth + 1)) {
114 out.push({ argv: inner.argv, cwd: inner.cwd ?? cwd })
115 }
116 continue
117 }
118 out.push({ argv: [basename(head), ...argv.slice(1)], cwd })
119 }
120 return out
121}
122
123export function expandHome(path: string, home: string): string {
124 return path === '~' || path.startsWith('~/') ? home + path.slice(1) : path
125}
126
127const XCODEBUILD_INFO = new Set([
128 '-version', '-showsdks', '-list', '-showBuildSettings', '-showdestinations',
129 '-help', '-usage', '-checkFirstLaunchStatus', '-showTestPlans', '-license',
130])
131
132/** True when the segment runs a real xcodebuild (a build, test, archive...). */
133export function isXcodebuild(seg: Segment): boolean {
134 return seg.argv[0] === 'xcodebuild' && !seg.argv.some(a => XCODEBUILD_INFO.has(a))
135}
136
137/** Any command that builds or tests: xcodebuild, swift build/test, or a script named in the `extraBuildScripts` option. */
138export function isBuild(seg: Segment, extraScripts: readonly string[] = []): boolean {
139 const [head = '', sub] = seg.argv
140 return (
141 isXcodebuild(seg) ||
142 (head === 'swift' && (sub === 'build' || sub === 'test')) ||
143 extraScripts.some(name => head === name || head.endsWith(`/${name}`))
144 )
145}
146