Asks before Claude edits a file another chat on this machine changed in the last 30 minutes. Each chat keeps its own small ledger; no model calls, no network.

Make the $20 Claude Pro plan last longer in Claude Code.
Twenty-two small mods that show you exactly where your usage goes and cut the waste. One mod makes a model call: prompt-polish, once each time you press Improve, and never on its own. The others make none. None adds anything to the system prompt (read-cap adds one tool, which Claude Code lists by name only until Claude first uses it; write-guard adds one line to a tool result at most once per conversation; compact-keeper adds a note of at most 4,000 characters after a compaction): every figure on screen is one Claude Code already reports, or a time the mod measured.
| Mod | What it does | Where |
|---|---|---|
| tool-diet | Loads tools you have not used lately on demand instead of with every request | Everywhere |
| skill-diet | Lists skills you have not used lately in this project by name only, without their descriptions | Everywhere |
| agent-diet | Runs Explore subagents on Haiku instead of your main model | Everywhere |
| context-xray | /xray opens the exact breakdown of what fills your context window | Everywhere |
| pro-hud | Live meters above the prompt for your 5-hour session, your week and the context window, plus a per-turn receipt of tokens in, cached and out | Claude desktop app |
| output-diet | Trims long shell output, search results and subagent reports before Claude reads them, keeping the head, the tail and the error lines; the untrimmed text is saved to a file Claude can open without a permission prompt | Everywhere |
| reread-guard | Skips Claude re-reading a file it already read when the file has not changed, with Read or a plain cat, sed -n, head, tail or Get-Content; a deliberate retry still goes through | Everywhere |
| write-guard | Steers Claude to Edit instead of rewriting an existing file in full with Write; a deliberate rewrite still goes through | Everywhere |
| loop-guard | Holds back a shell command that already failed twice in a row, so Claude changes approach | Everywhere |
| cmd-diet | Adds quiet flags to noisy shell commands before they run, so Claude reads short output from the start; errors, failures and warnings stay in full | Everywhere |
| gh-account | Runs each git push, pull, fetch, clone and gh command as the logged-in GitHub account that can see the repository, without switching the active account | Everywhere |
| cache-clock | Counts down until the prompt cache expires; once it has, shows exactly how many tokens your next message will re-send uncached | Everywhere |
| read-cap | Stops Claude reading a file over 1,000 lines whole (with Read, cat or Get-Content) and gives it an outline tool, so it reads only the lines it needs; a retry still reads the whole file | Everywhere |
| session-receipt | /receipt opens a pane with the exact tokens every turn of the session spent, and the costliest turns | Everywhere |
| peek | Typing status while background tasks run opens a pane with each one's exact elapsed time and last output lines, instead of sending the prompt to Claude | Everywhere |
| budget-guard | Holds a prompt back once your 5-hour or weekly usage reaches your limit (90% by default); sending it again goes through | Everywhere |
| turn-budget | When one turn uses more than +5 session points, writes a handoff and continues in a fresh session by itself; /handoff any time | Everywhere |
| compact-keeper | After a compaction, adds a note of exact facts from before it: your latest prompt in full, the todo list, the last failed command, files edited | Everywhere |
| collision-guard | Asks before Claude edits a file another chat on this machine changed in the last 30 minutes | Everywhere |
| answer-pane | Explain, plan and ELI5 pages drawn natively in a side pane; plans have decision buttons and Respond fills the prompt box | Desktop app (no diagrams in the terminal) |
| prompt-polish | An Improve button beside Send (above the prompt in the terminal) rewrites your draft with Opus at low effort and puts it back in the box; Undo restores it. One model call per press | Everywhere |
| kit-updates | Tells you when an installed mod from this kit has a newer version or a new mod joins the kit; /kit-update installs updates and new mods | Everywhere |

In Claude Code:
/plugin marketplace add VedantAndhale/claude-pro-kit
/plugin install tool-diet@claude-pro-kit
/plugin install skill-diet@claude-pro-kit
/plugin install agent-diet@claude-pro-kit
/plugin install context-xray@claude-pro-kit
/plugin install pro-hud@claude-pro-kit
/plugin install output-diet@claude-pro-kit
/plugin install reread-guard@claude-pro-kit
/plugin install write-guard@claude-pro-kit
/plugin install loop-guard@claude-pro-kit
/plugin install cmd-diet@claude-pro-kit
/plugin install gh-account@claude-pro-kit
/plugin install cache-clock@claude-pro-kit
/plugin install read-cap@claude-pro-kit
/plugin install session-receipt@claude-pro-kit
/plugin install peek@claude-pro-kit
/plugin install budget-guard@claude-pro-kit
/plugin install turn-budget@claude-pro-kit
/plugin install compact-keeper@claude-pro-kit
/plugin install collision-guard@claude-pro-kit
/plugin install answer-pane@claude-pro-kit
/plugin install prompt-polish@claude-pro-kit
/plugin install kit-updates@claude-pro-kit
Updates are off by default for marketplaces you add yourself. With kit-updates installed you are told when a fix ships and /kit-update installs it, from the desktop app or the terminal. Without it, turn on auto-update once: in a terminal, run claude, then /plugin → Marketplaces → claude-pro-kit → Enable auto-update; the desktop app has no toggle for it.
Install any one on its own; they do not depend on each other. Mods are not sandboxed, so read the code before installing: each mod is a single file under plugins/<name>/hooks/.
Every tool listed in front sends its whole description and schema with every request. A deferred tool is listed by name only, and Claude loads it through ToolSearch when it needs it; Claude Code already does this for most MCP tools. tool-diet does it for the rest of the tools you are not using: anything outside the core set (Bash, PowerShell, Read, Edit, Write, Glob, Grep, Agent, Skill, ToolSearch, TodoWrite, AskUserQuestion) that you have not used in your last five sessions.
Measured with one prompt, "Reply with just OK.", in a fresh session, as the API reported each request:
| Prompt tokens per request | |
|---|---|
| Without tool-diet | 43,859 |
| With tool-diet | 27,905 |
| Change | −15,954 (−36%) |
On that setup, the largest tool moved was Artifact, whose description alone is 19,870 characters. What moves depends on your tools and your habits; /xray shows yours.
/tool-diet lists what is on demand this session, grouped by where each tool comes from; /tool-diet keep <tool> always loads one, unkeep undoes it, and /tool-diet off|on switches it. Answers are toasts, so they add nothing to the conversation. The status line keeps the count: 38 tools on demand.
Every request carries the skill listing: each installed skill's name and its whole description. With a few plugins installed that is dozens of skills, most of which a given project never uses (video skills in a backend repo, document skills in a game). skill-diet keeps the skills you used lately in this project listed in full and lists the rest on one line by name only. The Skill tool still loads any of them, and typing /name still works.
Measured with one prompt, "Reply with just OK.", in a fresh session with 45 skills installed and the other mods on, as the API reported the request:
| Prompt tokens per request | |
|---|---|
| Without skill-diet | 27,423 |
| With skill-diet | 19,197 |
| Change | −8,226 (−30%) |
In the same setup, asked to fill in a PDF form, Claude found anthropic-skills:pdf from its name alone and loaded it with the Skill tool. What moves depends on your skills; /xray shows yours.
/name or called by Claude through the Skill tool./skill-diet shows what is listed by name only this session and how many characters left the listing; /skill-diet keep <skill> always lists one in full, unkeep undoes it, and /skill-diet off|on switches it. Answers are toasts, so they add nothing to the conversation. The status line keeps the count, in the form <n> skills by name only, <n> characters off./xray shows the skills line before and after, in tokens.A subagent runs on your main model unless its definition or Claude's Agent call names another. Explore only searches and reads, yet in the author's own 85 subagent transcripts, every one of the 2,043 Explore requests ran on Opus or Sonnet, reading 147,298,992 input tokens. agent-diet starts the agent types you list (Explore by default) on Haiku.
/agent-diet shows the setting and how many subagents it moved this session; /agent-diet model haiku|sonnet|opus picks the model, /agent-diet add|remove <agent type> changes the list, and /agent-diet off|on switches it. Answers are toasts, so they add nothing to the conversation. The status line keeps the count, in the form 2 subagents on haiku.Measured with claude -p --model sonnet --output-format json on a task that sends one Explore subagent to find a file, three runs each in alternating order. Every run found the file. Figures are the cost and tokens Claude Code reported per model:
| Run | Without: cost | Without: Sonnet tokens in | With: cost | With: Sonnet tokens in | With: Haiku tokens in |
|---|---|---|---|---|---|
| 1 | $0.05692 | 68,395 | $0.03724 | 40,213 | 27,848 |
| 2 | $0.05577 | 68,111 | $0.03764 | 39,593 | 27,872 |
| 3 | $0.05441 | 68,123 | $0.03736 | 40,184 | 42,770 |
| Average | $0.05570 | $0.03741 |

/xray opens a pane with the exact breakdown /context computes: what is sent with every request (system prompt, tools, MCP tools, memory files, skills, messages), what is loaded on demand, which MCP tools load every time, and each memory file's size. It measures when the pane opens and when you press Refresh (or r), never in the background, because the exact count sends one token-count request per tool and memory file.
Opens by itself when the context crosses 60% and again at 80%, with a toast pointing at /compact and /handoff. /xray auto off keeps it to /xray only.
The recording at the top of this page is the band. In text:
Session ━━━━━━━━━━━━━━────── 69% resets in 32m
Week ━━━━━━━━━━━━━━━───── 74% resets in 4d 17h
Context ━━━━━━━━──────────── 44% 436,034 tokens
This turn 1m 35s · 1 tool · 0 files edited · 436,034 in · 431,260 cached · 580 out
On a wide window the three meters sit side by side on one row; on a narrow one each figure on the turn line wraps whole rather than being cut off.
/compact when it climbs.· session 20%, and finished tool calls draw as one line: status dot, tool, target, time./hud shows what is on; /hud all on|off, or /hud band|spinner|cards on|off. The answer is a toast, so toggling adds nothing to the conversation. It draws in the desktop app only and leaves the terminal as it is. Rows other mods put above the prompt still draw beneath the band.
Weekly toasts at 50%, 75% and 90% of the week, once each, because the weekly limit drains quietly across many sessions.
When a Bash or PowerShell result runs past 120 lines or 8,000 characters, Claude reads:
[output-diet: 82/500 lines shown; all 500 in ~/.claude/projects/<project>/<session>/tool-results/output-diet-<call>.txt]
<first 30 lines>
… [lines 31–450 omitted; error/warning lines from them:]
250│ ERROR: build failed in src/app.ts
300│ Warning: deprecated API
…
<last 50 lines>
3 trimmed · 41,200 chars saved.tool-results folder, beside the transcript, where Claude Code keeps the outputs it saves itself, so Claude can open it without a permission prompt. When that folder cannot be found, it goes under ~/.claude/output-diet/ (or CLAUDE_CONFIG_DIR).Grep result past the same limits keeps its first 100 lines, with a note to narrow the search: [output-diet: first 100/252 lines shown; narrow the search, or read all in …]. In the author's 1,048 past Grep results, 26 went past the limits, and keeping the first 100 lines would have cut 104,052 characters. Glob is left alone: none of 128 went past.When Claude asks to Read the same range of the same file again in the same conversation, and the file's size and modification time have not changed, the read is skipped and Claude is told to use the copy it has. Any edit, a different range, or a subagent (which has its own context) reads freely. Claude Code can clear old tool results from context, so retrying the identical read straight after a skip always goes through. The record resets on /compact and /clear.
What Claude is told in place of the repeat read, kept to one line because the model reads it:
api.ts unchanged since you read it; use that copy. If it's gone from context, retry the same Read.
Shell reads too. Claude often reads a file with the shell instead of Read: in the author's transcripts, 318 sed -n runs went past the guard. A shell command that only prints one file is now treated the same way: cat FILE, sed -n 'A,Bp' FILE, head -n N / tail -n N, and in PowerShell Get-Content, gc, cat or type (with -TotalCount, -Head, -First, -Tail, -Last or -Raw). The same range of the same unchanged file is skipped once, and retrying the same command goes through. A whole cat after a whole Read that showed every line counts as a repeat. A pipe, a chain, a variable, a glob or any other flag runs untouched. A shell read never counts as a Read, since Edit needs a real one first.
The status line counts them: 2 re-reads skipped.
Write sends the whole file as Claude's output, the most expensive kind of token; Edit sends only the lines that change. Claude sometimes rewrites a file it has already read in full to change a few lines. In the author's own 272 session transcripts, 141 writes rewrote a file Claude had already read or written (999,273 characters), and 112 of them followed an earlier rewrite in the same session. Of the 512,847 characters in the rewrites whose previous version was in the transcript, 171,325 had changed.
A hook runs after Claude has written the content, so write-guard cannot save the rewrite it sees; it stops the ones after it:
You rewrote all of api.ts. For changes to an existing file use Edit: it sends only the changed lines.api.ts exists; change it with Edit, not a full Write. If a full rewrite is intended, retry the same Write. Retrying the same Write goes through./clear starts over.1 full rewrite held back.Each retry of a failing command re-sends the whole conversation, and the same command usually fails the same way. In the author's 272 session transcripts, 10 commands failed 3 or more times, 38 runs between them.
Once the exact same Bash or PowerShell command has failed twice in a row, the next try is held back once, and Claude is told:
This exact command failed 2 times in a row. Change the approach instead of rerunning it. If a rerun is intended, retry the same command.
/clear starts over.1 failing retry held back.output-diet trims long output after a command has run; cmd-diet keeps the noise from being printed at all. Before a Bash or PowerShell command runs, a known noisy command gets its own quiet flags, which drop progress lines and keep errors, test failures and warnings:
| Command | Runs as | Output, measured |
|---|---|---|
git status | git status --short --branch | 415 to 58 characters |
pytest | pytest -q | 1,063 to 495 characters, failure details unchanged |
cargo build / test / check / clippy / run | cargo build -q | 197 to 0 characters on success, warnings unchanged |
npm install / ci | npm install --no-audit --no-fund | 62 to 18 characters |
curl (Bash only) | curl -sS | 1,049 to 577 characters, the progress meter removed |
mvn | mvn -B -ntp | not measured: drops download progress |
wget (Bash only) | wget -nv | not measured: one line per file |
docker pull | docker pull -q | not measured: drops layer progress |
In a live headless run (git status && python -m pytest on 41 test files, one failing), the request cost 41,535 tokens without cmd-diet and 40,571 with it, by the API's usage, and both runs named the failing test and its reason correctly. The shorter output stays in context, so every later request in the session sends less too.
&&, || or ; chain is handled on its own. A step that pipes, redirects or substitutes (| grep, > file, $(...)) is left alone, since something else reads its output; 2>&1 is fine.git status --porcelain, pytest -v, curl -fsSL, npm install --silent) is left alone, and a flag already present is not added twice.3 commands quieted.With two GitHub accounts logged in to gh, a push to a repository the other account owns fails, and Claude spends turns on gh auth status and gh auth switch. Before a Bash or PowerShell command runs, gh-account matches each git push, pull, fetch, clone, ls-remote and gh step to the repository's owner, and the owner to a logged-in account. When that account is not gh's active one, that step alone runs with its token:
GH_TOKEN="$(gh auth token --user ACCOUNT)" git push
The token itself never appears in the command or its output, and the active account is not switched. For git it also asks gh for the credential.
-R owner/repo, a gh api repos/<owner>/... path, or the folder's remotes. With no remote named, every remote must point at the same owner.gh auth status, and organizations from gh api user/orgs. What it learns is kept across sessions.gh auth and other gh commands that reach no repository, a command that already sets GH_TOKEN, a token from the environment, git over ssh, hosts other than github.com, and subshells or substitutions./gh-account shows which account each owner uses, and /gh-account forget clears it. Answers are toasts. The status line counts them: 2 commands sent as <account>.Claude's prompt cache keeps your conversation for a fixed time after each request. Reply within it and the context is read from cache; reply after it and the whole context is sent again at full price. That message pays the cache-write price (1.25 times the input price for a 5-minute cache, 2 times for a 1-hour one) on every token instead of the cache-read price (0.1 times): 12.5 to 20 times more for the same context, and nothing on screen says so.
cache-clock puts the countdown in the status line, restarted by every response from the main conversation:
cache warm · 3m left
cache cold · next message re-sends 61,204 tokens
When the cache runs out, a toast says so once (after the lifetime is known, see below). The token figure is the previous response
hooks/register.ts 155 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import {
4 CANCEL,
5 DEFAULTS,
6 EDIT_TOOLS,
7 PROCEED,
8 PROCEED_FILE,
9 cancelNote,
10 choiceOf,
11 describeRecent,
12 findCollision,
13 keyOf,
14 parse,
15 prune,
16 question,
17 recentElsewhere,
18} from './guard'
19import type { Ledger, Settings } from './guard'
20
21// Before Claude edits a file, checks whether another chat on this machine
22// edited the same file within the window, and asks first. Each chat keeps its
23// own ledger file, so two chats never write the same file. No model calls and
24// no network; the only text Claude ever reads is one line after a Cancel.
25
26const join = (...parts: string[]) => parts.map((p, i) => (i === 0 ? p.replace(/[\\/]+$/, '') : p)).join('/')
27
28async function ledgerDir($: EngineInterface): Promise<string | undefined> {
29 const config = await $.env.get('CLAUDE_CONFIG_DIR')
30 const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
31 const base = config ?? (home === undefined ? undefined : join(home, '.claude'))
32 return base === undefined ? undefined : join(base, 'collision-guard')
33}
34
35async function settingsOf($: EngineInterface): Promise<Settings> {
36 return { ...DEFAULTS, ...((await $.store.get('settings')) as Partial<Settings> | undefined) }
37}
38
39// Other chats' ledgers that changed inside the window; older files are skipped
40// unread, so a folder of old ledgers costs one listing.
41async function readOthers($: EngineInterface, dir: string, own: string, settings: Settings, now: number): Promise<Ledger[]> {
42 const entries = await $.fs.list(dir).catch(() => [])
43 const fresh = entries.filter(
44 e => e.kind === 'file' && e.name.endsWith('.json') && e.name !== `${own}.json` && now - e.mtimeMs <= settings.windowMin * 60_000,
45 )
46 const ledgers: Ledger[] = []
47 for (const e of fresh) {
48 const text = await $.fs.read(join(dir, e.name)).catch(() => undefined)
49 if (typeof text !== 'string') continue
50 try {
51 const ledger = JSON.parse(text) as Ledger
52 if (ledger && typeof ledger.files === 'object') ledgers.push(ledger)
53 } catch {
54 // A ledger caught mid-write by the other chat: it is read again on the next edit.
55 }
56 }
57 return ledgers
58}
59
60async function realKey($: EngineInterface, path: string) {
61 const stat = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
62 return { key: keyOf(stat?.realPath ?? path), mtimeMs: stat?.kind === 'file' ? stat.mtimeMs : undefined }
63}
64
65// This chat's own state; a reload starts it over and the next edit rebuilds it.
66const me = {
67 session: '',
68 cwd: '',
69 dir: undefined as string | undefined,
70 ledger: undefined as Ledger | undefined,
71 // Files the person said to go ahead with, and the other chat's edit time then.
72 approved: new Map<string, number>(),
73}
74
75async function ensure($: EngineInterface): Promise<Ledger> {
76 if (me.ledger) return me.ledger
77 me.session = await $.session.id()
78 me.cwd = await $.session.cwd()
79 me.dir = await ledgerDir($)
80 me.ledger = { session: me.session, cwd: me.cwd, files: {} }
81 return me.ledger
82}
83
84export const register: Register = on => {
85
86 on('session.start', async ($, e, next) => {
87 await $.command.register({
88 name: 'collisions',
89 description: 'Collision guard: /collisions · /collisions <minutes> · /collisions off|on',
90 })
91 await ensure($)
92 return next(e)
93 })
94
95 on('tool.call', async ($, e, next) => {
96 if (!EDIT_TOOLS.has(e.tool)) return next(e)
97 const path = (e as { file_path?: unknown; notebook_path?: unknown }).file_path ?? (e as { notebook_path?: unknown }).notebook_path
98 if (typeof path !== 'string') return next(e)
99
100 const own = await ensure($)
101 const settings = await settingsOf($)
102 if (settings.isOff || me.dir === undefined) return next(e)
103
104 const now = await $.clock.now()
105 const { key, mtimeMs } = await realKey($, path)
106 const others = await readOthers($, me.dir, me.session, settings, now)
107 const hit = findCollision(others, key, now, settings)
108
109 if (hit && me.approved.get(key) !== hit.at) {
110 let answer: string | undefined
111 try {
112 answer = await $.ui.ask(question(path, hit, now, mtimeMs), {
113 options: [PROCEED, PROCEED_FILE, CANCEL],
114 header: 'Collision',
115 })
116 } catch {
117 // Nobody to ask (a -p run, a dismissed dialog): the edit goes ahead.
118 $.ui.status('collision not asked: another chat edited a file this chat changed')
119 }
120 if (answer !== undefined) {
121 const choice = choiceOf(answer)
122 if (choice === 'cancel') return { deny: cancelNote(path, hit, now) }
123 if (choice === 'file') me.approved.set(key, hit.at)
124 }
125 }
126
127 const ran = await next(e)
128 if (ran.deny === undefined && ran.isError !== true) {
129 const after = await realKey($, path)
130 own.files[after.key] = { at: await $.clock.now(), mtimeMs: after.mtimeMs ?? 0, path }
131 me.ledger = prune(own, now, settings)
132 await $.fs.write(join(me.dir, `${me.session}.json`), JSON.stringify(me.ledger)).catch(() => undefined)
133 }
134 const chats = new Set(others.filter(l => recentElsewhere([l], me.cwd, now, settings).length > 0).map(l => l.session)).size
135 $.ui.status(chats > 0 ? `${chats} other ${chats === 1 ? 'chat' : 'chats'} active here` : undefined)
136 return ran
137 })
138
139 // Answered with a toast and no text, so the command adds nothing to the conversation.
140 on('command.run', { command: 'collisions' }, async ($, e) => {
141 await ensure($)
142 const current = await settingsOf($)
143 const changed = parse(e.args, current)
144 if (changed) await $.store.set('settings', changed)
145 const settings = changed ?? current
146 const now = await $.clock.now()
147 const others = me.dir ? await readOthers($, me.dir, me.session, settings, now) : []
148 const shown = describeRecent(recentElsewhere(others, me.cwd, now, settings), now, settings)
149 $.ui.toast(changed && !changed.isOff ? `Collision guard: asks about edits from the last ${settings.windowMin} min. ${shown}` : shown, {
150 timeoutMs: 12_000,
151 })
152 return {}
153 })
154}
155hooks/guard.ts 98 lines1// The collision arithmetic: pure, so the tests exercise it directly.
2
3export type Settings = { windowMin: number; isOff: boolean }
4export const DEFAULTS: Settings = { windowMin: 30, isOff: false }
5
6/** One chat's record: the files it edited, when, and the file's mtime right after. */
7export type Ledger = {
8 session: string
9 cwd: string
10 files: Record<string, { at: number; mtimeMs: number; path?: string }>
11}
12
13export type Collision = { session: string; cwd: string; at: number; mtimeMs: number }
14
15export const EDIT_TOOLS = new Set(['Edit', 'MultiEdit', 'Write', 'NotebookEdit'])
16
17/** One key per file however it is spelled: forward slashes, and lower case on Windows drives. */
18export const keyOf = (path: string) => {
19 const slashed = path.replace(/\\/g, '/').replace(/\/+$/, '')
20 return /^[a-z]:\//i.test(slashed) ? slashed.toLowerCase() : slashed
21}
22
23/** The most recent edit of `key` by another chat inside the window, if any. */
24export const findCollision = (others: Ledger[], key: string, now: number, settings: Settings): Collision | undefined => {
25 const windowMs = settings.windowMin * 60_000
26 let best: Collision | undefined
27 for (const ledger of others) {
28 const entry = ledger.files[key]
29 if (!entry || now - entry.at > windowMs) continue
30 if (!best || entry.at > best.at) best = { session: ledger.session, cwd: ledger.cwd, at: entry.at, mtimeMs: entry.mtimeMs }
31 }
32 return best
33}
34
35export const age = (ms: number) => {
36 const m = Math.floor(Math.max(0, ms) / 60_000)
37 return m < 1 ? 'less than a minute ago' : m === 1 ? '1 min ago' : `${m} min ago`
38}
39
40const baseName = (path: string) => path.split(/[\\/]/).pop() ?? path
41const folderOf = (cwd: string) => cwd.replace(/[\\/]+$/, '').split(/[\\/]/).pop() || cwd
42
43/** A file whose mtime moved more than 2s past the other chat's edit was changed since. */
44export const isChangedSince = (hit: Collision, currentMtimeMs: number | undefined) =>
45 currentMtimeMs !== undefined && currentMtimeMs > hit.mtimeMs + 2_000
46
47export const question = (path: string, hit: Collision, now: number, currentMtimeMs: number | undefined) =>
48 `${baseName(path)} was ${isChangedSince(hit, currentMtimeMs) ? 'last changed by another chat' : 'changed by another chat'} ` +
49 `${age(now - hit.at)}${isChangedSince(hit, currentMtimeMs) ? ', and modified since' : ''} ` +
50 `(chat ${hit.session.slice(0, 8)} in ${folderOf(hit.cwd)}). Edit it anyway?`
51
52export const PROCEED = 'Proceed'
53export const PROCEED_FILE = 'Proceed for this file'
54export const CANCEL = 'Cancel'
55
56export type Choice = 'proceed' | 'file' | 'cancel'
57
58/** Anything but a Proceed label cancels: an unclear answer leaves the file alone. */
59export const choiceOf = (answer: string): Choice =>
60 answer === PROCEED ? 'proceed' : answer === PROCEED_FILE ? 'file' : 'cancel'
61
62export const cancelNote = (path: string, hit: Collision, now: number) =>
63 `${baseName(path)} was changed ${age(now - hit.at)} in another chat; the user chose not to edit it. Re-read it, then ask how to proceed.`
64
65/** Drops entries older than the window, so a ledger stays small. */
66export const prune = (ledger: Ledger, now: number, settings: Settings): Ledger => ({
67 ...ledger,
68 files: Object.fromEntries(Object.entries(ledger.files).filter(([, v]) => now - v.at <= settings.windowMin * 60_000)),
69})
70
71/** `/collisions 15`, `/collisions off|on`; undefined for anything else. */
72export const parse = (args: string, settings: Settings): Settings | undefined => {
73 const a = args.trim().toLowerCase()
74 if (a === 'off' || a === 'on') return { ...settings, isOff: a === 'off' }
75 if (/^\d+$/.test(a) && Number(a) >= 1 && Number(a) <= 1440) return { ...settings, windowMin: Number(a) }
76 return undefined
77}
78
79/** The files other chats edited in this folder inside the window, newest first. */
80export const recentElsewhere = (others: Ledger[], cwd: string, now: number, settings: Settings) => {
81 const here = keyOf(cwd)
82 const rows: { file: string; at: number }[] = []
83 for (const ledger of others) {
84 for (const [file, v] of Object.entries(ledger.files)) {
85 if (file.startsWith(`${here}/`) && now - v.at <= settings.windowMin * 60_000) rows.push({ file: v.path ?? file, at: v.at })
86 }
87 }
88 return rows.sort((a, b) => b.at - a.at)
89}
90
91export const describeRecent = (rows: { file: string; at: number }[], now: number, settings: Settings) => {
92 if (settings.isOff) return 'Collision guard is off. /collisions on to turn it back on.'
93 if (rows.length === 0) return `No other chat edited files in this folder in the last ${settings.windowMin} min.`
94 const shown = rows.slice(0, 5).map(r => `${baseName(r.file)} ${age(now - r.at)}`)
95 const more = rows.length > 5 ? ` +${rows.length - 5} more` : ''
96 return `Changed by other chats in the last ${settings.windowMin} min: ${shown.join(' · ')}${more}`
97}
98