context-carwash 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.3
4
+
5
+ - A fresh session can now search the old conversation. When a brief is saved, Carwash keeps a text copy of the conversation in `~/.carwash/recall`, without images, and tells the fresh session where it is, so it can look up an exact error message, path or number the brief left out. The copy is deleted after 7 days, or when you discard the brief. Nothing goes in your project.
6
+ - `install` adds one permission to `~/.claude/settings.json` so Claude can search that folder without asking. It allows reading that folder and nothing else, and `uninstall` takes it out. `carwash doctor` checks it. Run `npx context-carwash@latest install` to get it.
7
+ - `carwash stats` now gives the right cached price on Claude: a twentieth of the normal input price on Opus 5.5 and Sonnet 5.5, not a tenth.
8
+
3
9
  ## 0.2.2
4
10
 
5
11
  - `carwash stats` leads with a likelier saving and shows the old figure as the most it could be. It counts only the first part of the prompts after each wash, since you would have cleared the old conversation at some point anyway. That share starts at two-thirds and is learned from how far your own Claude Code conversations go, read on your machine. Output the fresh conversation had to read again, which the old one already had, is taken off.
package/README.md CHANGED
@@ -25,7 +25,7 @@ It shows you what it's going to change and asks before doing anything. Then star
25
25
 
26
26
  When there's a new version, a line under the meter will tell you. To update, run `npx context-carwash@latest install`.
27
27
 
28
- Under the hood, it adds a status line and three hooks to `~/.claude/settings.json` (after whatever you already have there) and a `/wash` command in `~/.claude/skills/wash`. For Codex, it adds three hooks to `~/.codex/hooks.json` and a `$wash` command in `~/.codex/skills/wash`.
28
+ Under the hood, it adds a status line, three hooks and one read-only permission to `~/.claude/settings.json` (after whatever you already have there) and a `/wash` command in `~/.claude/skills/wash`. The permission lets Claude search `~/.carwash/recall` without asking, and nothing else. For Codex, it adds three hooks to `~/.codex/hooks.json` and a `$wash` command in `~/.codex/skills/wash`.
29
29
 
30
30
  ## The Meter
31
31
 
@@ -40,7 +40,7 @@ The number is roughly how many tokens your conversation is using (Claude Code's
40
40
  1. Type `/wash`. Claude writes a short brief: what you're working on, where things stand, and what's next. The status line switches to `Brief ready ✓`.
41
41
  2. Type `/clear`. Your new session starts with the brief already loaded.
42
42
 
43
- Your old conversation isn't gone. You can still find it in `/resume`.
43
+ Your old conversation isn't gone. You can still find it in `/resume`, and the fresh session can search a text copy of it when it needs an exact detail the brief left out, like an error message or a file path. It only searches when it needs to, so otherwise it costs nothing extra.
44
44
 
45
45
  | Command | What it does |
46
46
  |---|---|
@@ -60,7 +60,7 @@ A few things worth knowing:
60
60
  - Writing a brief is a normal Claude reply, so it uses some tokens. `help`, `discard` and `load` are free.
61
61
  - Bigger conversations get bigger briefs. `/wash help` shows the size limit for each level.
62
62
  - Closed the terminal before you got to `/clear`? Run `claude` in the same folder and your brief loads. If there's more than one waiting, it'll list them so you can pick with `/wash load <id>`.
63
- - Briefs expire after 48 hours.
63
+ - Briefs expire after 48 hours. The text copy of the conversation is deleted after 7 days, or as soon as you discard the brief.
64
64
 
65
65
  ## Codex
66
66
 
@@ -96,7 +96,7 @@ Every request to Claude or Codex sends the whole conversation again. After a was
96
96
 
97
97
  You wouldn't have kept going in the old conversation forever, so the main number only counts the first part of the prompts after each wash. That's two-thirds to begin with. Carwash then adjusts it by looking at how far your own past conversations went once they were that big, so if you usually clear around 300k, a wash at 300k counts for less. Anything the fresh conversation had to read again, like a file the old one already had open, is taken off too. "At most" counts every prompt. All of this is worked out on your computer from Claude Code's own history files, and only a few numbers per conversation are kept.
98
98
 
99
- Repeated context is charged at about a tenth of the price, so in dollars you're saving roughly a tenth of these numbers. You can also see this inside Claude Code with `/wash stats`.
99
+ Repeated context is charged at a fraction of the price: a twentieth of the normal input price on Opus 5.5 and Sonnet 5.5, and about a tenth on most older models. So in dollars you're saving that fraction of these numbers. You can also see this inside Claude Code with `/wash stats`.
100
100
 
101
101
  If you run `stats --share`, it shows you exactly what it would send before asking.
102
102
 
@@ -110,7 +110,7 @@ This checks that everything's still installed and working, and shows your versio
110
110
 
111
111
  ## Where things are kept
112
112
 
113
- Your briefs, stats and error logs live in `~/.carwash`, and only you can read them. Nothing about you gets uploaded. Once a day, Carwash checks npm for a newer version. If you'd rather it didn't, set `CARWASH_NO_UPDATE_CHECK=1`.
113
+ Your briefs, stats, error logs and the text copies of old conversations live in `~/.carwash`, and only you can read them. Nothing goes in your project folders. The text copies leave out images, so they're small: usually under a megabyte each. Nothing about you gets uploaded. Once a day, Carwash checks npm for a newer version. If you'd rather it didn't, set `CARWASH_NO_UPDATE_CHECK=1`.
114
114
 
115
115
  ## Uninstall
116
116
 
@@ -118,7 +118,7 @@ Your briefs, stats and error logs live in `~/.carwash`, and only you can read th
118
118
  npx context-carwash uninstall
119
119
  ```
120
120
 
121
- This puts `settings.json` back exactly as it was. If you've edited the file since installing, it only removes Carwash's status line and hooks and leaves your changes alone. Codex's `hooks.json` gets the same treatment. It also removes the `/wash` and `$wash` commands and deletes `~/.carwash`, including any waiting briefs and your stats.
121
+ This puts `settings.json` back exactly as it was. If you've edited the file since installing, it only removes Carwash's status line, hooks and permission and leaves your changes alone. Codex's `hooks.json` gets the same treatment. It also removes the `/wash` and `$wash` commands and deletes `~/.carwash`, including any waiting briefs, text copies and your stats.
122
122
 
123
123
  ## Platforms
124
124
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "context-carwash",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "A quiet context meter and deliberate fresh-session handoff for Claude Code and Codex.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -7,7 +7,7 @@ import { errorLogPath, errorsSeenPath, installRecordPath, settingsPath, skillDir
7
7
  import { refreshLedger, totals } from '../stats/ledger.mjs';
8
8
  import { readyRecords } from '../wash/store.mjs';
9
9
  import { codexDetected, codexHooksCheck, codexSkillInstalled } from './codex.mjs';
10
- import { commandProgram, isCarwashCommand, isCarwashHook } from './install.mjs';
10
+ import { commandProgram, isCarwashCommand, isCarwashHook, recallRule } from './install.mjs';
11
11
  import { UPDATE_COMMAND } from './notice.mjs';
12
12
  import { readSettings, resolveSettingsFile } from './settings.mjs';
13
13
  import { isNewer } from './update.mjs';
@@ -77,7 +77,8 @@ function settingsCheck(env) {
77
77
  const hooks = Object.fromEntries(HOOK_EVENTS.map((event) => [event, groups(event).some((group) => Array.isArray(group?.hooks) && group.hooks.some((hook) => isCarwashHook(hook?.command)))]));
78
78
  const hookCommands = HOOK_EVENTS.flatMap((event) => groups(event).flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks.map((hook) => hook?.command) : [])));
79
79
  const ours = [data?.statusLine?.command, ...hookCommands].filter((command) => isCarwashCommand(command) || isCarwashHook(command));
80
- return { readable: true, statusLine: isCarwashCommand(data?.statusLine?.command), hooks, nodes: [...new Set(ours.map(commandProgram).filter(Boolean))] };
80
+ const allow = data?.permissions?.allow;
81
+ return { readable: true, statusLine: isCarwashCommand(data?.statusLine?.command), hooks, recall: Array.isArray(allow) && allow.includes(recallRule(env)), nodes: [...new Set(ours.map(commandProgram).filter(Boolean))] };
81
82
  }
82
83
 
83
84
  // The Node that Carwash's commands start. Install writes its path into the
@@ -135,6 +136,7 @@ export function doctorReport({ env = process.env, now = Date.now(), running, new
135
136
  } else {
136
137
  out.push(row('Status line', yes(check.statusLine)));
137
138
  out.push(row('Hooks', HOOK_EVENTS.map((event) => `${event} ${yes(check.hooks[event])}`).join(' · ')));
139
+ out.push(row('Session search', check.recall ? 'ok' : `MISSING: Claude will ask before searching an old session · to fix: ${UPDATE_COMMAND}`));
138
140
  nodes.push(...check.nodes);
139
141
  }
140
142
  out.push(row('/wash command', yes(existsSync(join(skillDir(env), 'SKILL.md')))));
@@ -3,7 +3,7 @@ import { homedir } from 'node:os';
3
3
  import { delimiter, dirname, join, resolve, sep } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { privateDir, readJson, writeFileAtomic } from '../files.mjs';
6
- import { carwashHome, claudeConfigDir, installRecordPath, legacyCommandPath, pendingDir, settingsPath, skillDir } from '../paths.mjs';
6
+ import { RECALL_DAYS, carwashHome, claudeConfigDir, installRecordPath, legacyCommandPath, pendingDir, recallDir, settingsPath, skillDir } from '../paths.mjs';
7
7
  import { applyCodexInstall, applyCodexUninstall, codexDetected, describeCodexInstall, describeCodexUninstall, planCodexInstall, planCodexUninstall } from './codex.mjs';
8
8
  import { UserError, readSettings, resolveSettingsFile, serializeSettings, sha256 } from './settings.mjs';
9
9
 
@@ -128,6 +128,37 @@ function withCarwashHooks(hooks, command, file) {
128
128
  return next;
129
129
  }
130
130
 
131
+ // The one permission Carwash adds: reading the saved copies of old sessions, so
132
+ // that a fresh session can search them without asking. A Read rule also covers
133
+ // Grep and read-only shell commands such as grep, and it allows nothing else.
134
+ export function recallRule(env = process.env) {
135
+ const posix = (path) => path.replace(/\\/g, '/').replace(/^([A-Za-z]):/, (_, drive) => `/${drive.toLowerCase()}`);
136
+ const dir = recallDir(env);
137
+ const path = dir.startsWith(homedir() + sep) ? `~/${posix(dir.slice(homedir().length + 1))}` : `/${posix(dir)}`;
138
+ return `Read(${path}/**)`;
139
+ }
140
+
141
+ // The `permissions` setting with that rule taken out. `allow`, or the whole
142
+ // setting, goes too if it only existed to hold ours. Returns the same object
143
+ // when the rule was not there.
144
+ function withoutRecallRule(permissions, rule) {
145
+ if (!isPlainObject(permissions) || !Array.isArray(permissions.allow) || !permissions.allow.includes(rule)) return permissions;
146
+ const { allow, ...others } = permissions;
147
+ const theirs = allow.filter((entry) => entry !== rule);
148
+ const next = theirs.length ? { ...permissions, allow: theirs } : others;
149
+ return Object.keys(next).length ? next : undefined;
150
+ }
151
+
152
+ // The `permissions` setting with the rule added after whatever is there. One
153
+ // Carwash cannot read is left as it is: a fresh session then asks before it
154
+ // searches, which is all that is lost.
155
+ function withRecallRule(permissions, rule) {
156
+ if (permissions !== undefined && !isPlainObject(permissions)) return permissions;
157
+ if (permissions?.allow !== undefined && !Array.isArray(permissions.allow)) return permissions;
158
+ const theirs = withoutRecallRule(permissions, rule);
159
+ return { ...theirs, allow: [...(theirs?.allow ?? []), rule] };
160
+ }
161
+
131
162
  function isOurSkill(file) {
132
163
  try {
133
164
  return readFileSync(file, 'utf8').includes(SKILL_MARK);
@@ -207,14 +238,18 @@ function planClaudeInstall({ env, record, script }) {
207
238
  }
208
239
 
209
240
  const theirHooks = withoutCarwashHooks(settings.data.hooks);
241
+ const rule = recallRule(env);
242
+ const permissions = withRecallRule(settings.data.permissions, rule);
210
243
  const next = {
211
244
  ...settings.data,
212
245
  statusLine: { refreshInterval: REFRESH_SECONDS, ...(original ?? {}), type: 'command', command: commandFor('statusline', script) },
213
246
  hooks: withCarwashHooks(settings.data.hooks, commandFor('hook', script), file),
247
+ ...(permissions === undefined ? {} : { permissions }),
214
248
  };
215
249
  const skill = planSkill(env);
250
+ const recall = Array.isArray(permissions?.allow) && permissions.allow.includes(rule) ? recallDir(env) : null;
216
251
 
217
- return { file, settings, claudeRecord: record, original, alreadyInstalled, next, skill, keepsHooks: isPlainObject(theirHooks) && Object.keys(theirHooks).length > 0 };
252
+ return { file, settings, claudeRecord: record, original, alreadyInstalled, next, skill, recall, keepsHooks: isPlainObject(theirHooks) && Object.keys(theirHooks).length > 0 };
218
253
  }
219
254
 
220
255
  export function describeInstall(plan) {
@@ -224,6 +259,7 @@ export function describeInstall(plan) {
224
259
  if (plan.codex) lines.push(...describeCodexInstall(plan.codex, plan.claude ? 4 : 2, plan.home));
225
260
  const model = plan.claude && plan.codex ? 'Claude or Codex' : plan.codex ? 'Codex' : 'Claude';
226
261
  lines.push('', `Writing a brief is an ordinary ${model} reply, so it uses tokens like any other.`);
262
+ lines.push(`Each brief also saves a text copy of the conversation in ${tilde(join(plan.home, 'recall'))} for ${RECALL_DAYS} days, so the fresh session can search it for exact details.`);
227
263
  // Version managers such as nvm keep a folder per Node version, so removing
228
264
  // an old version takes this path with it, and nothing of Carwash can start.
229
265
  if (plan.node) lines.push(`Carwash runs with the Node at ${tilde(plan.node)}. If you remove that Node later, for example an old version in nvm, run install again.`);
@@ -250,6 +286,7 @@ function describeClaudeInstall(plan) {
250
286
  }
251
287
  lines.push(' Adds three hooks, so /wash can save a brief and a fresh session can');
252
288
  lines.push(` pick it up.${plan.keepsHooks ? ' The hooks you already have are kept as they are.' : ''}`);
289
+ if (plan.recall) lines.push(` Lets Claude read ${tilde(plan.recall)} without asking, and nothing else.`);
253
290
  if (plan.settings.exists && !plan.claudeRecord) {
254
291
  lines.push(` A backup of the file is kept in ${tilde(join(plan.home, 'backup'))}`);
255
292
  }
@@ -362,6 +399,12 @@ export function planUninstall({ env = process.env } = {}) {
362
399
  else data.hooks = hooks;
363
400
  changed = true;
364
401
  }
402
+ const permissions = withoutRecallRule(data.permissions, recallRule(env));
403
+ if (permissions !== data.permissions) {
404
+ if (permissions === undefined) delete data.permissions;
405
+ else data.permissions = permissions;
406
+ changed = true;
407
+ }
365
408
  if (changed) {
366
409
  plan.action = 'edit';
367
410
  plan.bytes = serializeSettings(data, settings);
@@ -395,7 +438,7 @@ export function describeUninstall(plan) {
395
438
  const what = {
396
439
  restore: `Restore ${tilde(plan.file)} to exactly what it was before install`,
397
440
  delete: `Delete ${tilde(plan.file)} (Carwash created it and it has not changed since)`,
398
- edit: `Edit ${tilde(plan.file)}: undo Carwash's status line and hooks; your other changes stay`,
441
+ edit: `Edit ${tilde(plan.file)}: undo Carwash's status line, hooks and read rule; your other changes stay`,
399
442
  none: `Leave ${tilde(plan.file)} alone`,
400
443
  }[plan.action];
401
444
  const steps = [];
package/src/paths.mjs CHANGED
@@ -31,6 +31,12 @@ export const consumedDir = (env = process.env) => join(carwashHome(env), 'consum
31
31
  // Small per-session notes: the last usage reading and a wash in progress.
32
32
  export const sessionsDir = (env = process.env) => join(carwashHome(env), 'sessions');
33
33
 
34
+ // A text copy of the session each brief came from, for the fresh session to
35
+ // search. Kept for a week.
36
+ export const RECALL_DAYS = 7;
37
+ export const recallDir = (env = process.env) => join(carwashHome(env), 'recall');
38
+ export const recallFile = (env, id) => join(recallDir(env), `${id}.log`);
39
+
34
40
  // The savings ledger behind `carwash stats`: one file per brief written.
35
41
  export const statsDir = (env = process.env) => join(carwashHome(env), 'stats');
36
42
 
@@ -7,7 +7,7 @@ metadata:
7
7
  installed-by: context-carwash
8
8
  ---
9
9
 
10
- The user typed /wash. They want to start a fresh session that picks up where this one leaves off. Your whole reply to this message is saved as the handoff brief, and it is the first thing the next session reads. That session cannot see this conversation, so anything the brief leaves out is gone.
10
+ The user typed /wash. They want to start a fresh session that picks up where this one leaves off. Your whole reply to this message is saved as the handoff brief, and it is the first thing the next session reads. That session cannot see this conversation. It can search a saved copy for an exact detail, but only if it knows to look, so the brief has to stand on its own.
11
11
 
12
12
  Arguments: $ARGUMENTS
13
13
 
@@ -9,7 +9,7 @@ The user typed $wash. Context Carwash saves your reply as a handoff brief, but o
9
9
 
10
10
  **First, look for that message.** If this turn has no developer message starting with "Carwash: level", the hooks are not running and a brief would be lost. Then do not write a brief. Reply with only this: "Carwash's hooks aren't running in Codex yet, so no brief was saved. Restart Codex and choose "Trust all and continue" when it asks about hooks, then run $wash again. If that doesn't help, run `npx context-carwash doctor` in a terminal."
11
11
 
12
- When the message is there: the user wants to start a fresh session that picks up where this one leaves off. Your whole reply to this message is saved as the handoff brief, and it is the first thing the next session reads. That session cannot see this conversation, so anything the brief leaves out is gone.
12
+ When the message is there: the user wants to start a fresh session that picks up where this one leaves off. Your whole reply to this message is saved as the handoff brief, and it is the first thing the next session reads. That session cannot see this conversation. It can search a saved copy for an exact detail, but only if it knows to look, so the brief has to stand on its own.
13
13
 
14
14
  The words after $wash in the user's message are the arguments. The first word is the level: `light`, `mid`, or `detailed`. No arguments means `mid`. Anything after the level is the user's note on what to emphasise.
15
15
 
@@ -93,7 +93,7 @@ export const sentOf = (usage) => (usage.input_tokens ?? 0) + (usage.cache_read_i
93
93
 
94
94
  const blocksOf = (line) => (Array.isArray(line.message?.content) ? line.message.content : []);
95
95
 
96
- const resultText = (block) =>
96
+ export const resultText = (block) =>
97
97
  typeof block.content === 'string' ? block.content : Array.isArray(block.content) ? block.content.map((part) => (part?.type === 'text' ? part.text : '')).join('') : '';
98
98
 
99
99
  // Lines shorter than this are too common to say a file was read again.
@@ -51,7 +51,7 @@ export function statsReport(sum, { inClaude = false } = {}) {
51
51
  `How it is worked out: every request to ${model} carries the whole conversation. After a wash, each request in the fresh session starts from the brief instead of the old conversation, and the difference is context that was not sent again. Counting stops where the old session would have compacted on its own.`,
52
52
  `You would not have gone on forever in the old session, so the main figure counts only the first ${percent(sum.share ?? 2 / 3)} of the prompts after each wash. That share starts at two-thirds and is learned from how far your own sessions go (${sum.learnedFrom ?? 0} so far). Files the fresh session had to read again are taken off. "At most" counts every prompt.`,
53
53
  model === 'Claude'
54
- ? 'Claude caches repeated context and charges about a tenth for it, so in money terms the saving is roughly a tenth of these numbers.'
54
+ ? 'Claude caches repeated context and charges far less for it: a twentieth of the normal input price on Opus 5.5 and Sonnet 5.5, a tenth on most older models. In money terms the saving is that share of these numbers.'
55
55
  : 'Repeated context is cached and charged at about a tenth, so in money terms the saving is roughly a tenth of these numbers.',
56
56
  '',
57
57
  inClaude ? 'To share these totals anonymously, run in a terminal: npx context-carwash stats --share' : 'To share these totals anonymously: npx context-carwash stats --share',
@@ -1,4 +1,5 @@
1
1
  import { CHARS_PER_TOKEN, capFor } from '../levels.mjs';
2
+ import { RECALL_DAYS } from '../paths.mjs';
2
3
  import { colorAt, paint } from '../statusline/color.mjs';
3
4
  import { formatTokens } from '../statusline/render.mjs';
4
5
  import { toolInfo, toolOf } from '../tools.mjs';
@@ -183,6 +184,7 @@ export function helpMessage(used, footer = null, tool = 'claude') {
183
184
  ...(meter ? ["The status line shows how many tokens this conversation is using, and the bar shows how close that is to the model's limit."] : []),
184
185
  ...(replyMeter ? ["The line after each reply shows how many tokens this conversation is using, and the bar shows how close that is to the model's limit. It is shown to you only and costs no tokens."] : []),
185
186
  `Writing a brief is an ordinary ${model} reply, so it uses tokens. help, discard and load do not.`,
187
+ `The old conversation is also saved as plain text for ${RECALL_DAYS} days, so the fresh session can search it for an exact detail the brief left out.`,
186
188
  ...(footer ? ['', footer] : []),
187
189
  ].join('\n');
188
190
  }
@@ -202,11 +204,15 @@ export function pointerMessage(records, now, why, tool = 'claude') {
202
204
  // What the fresh session's model is given. The framing is kept short: when the
203
205
  // whole thing is over Claude Code's limit for hook output, only the first 2,000
204
206
  // characters arrive inline, and the brief's Core section has to be among them.
205
- export function composeContext(record, now, stale) {
207
+ // `recall` is the saved copy of the earlier conversation, when there is one.
208
+ export function composeContext(record, now, stale, recall = null) {
209
+ const earlier = recall
210
+ ? `The brief is a summary; the earlier conversation is saved as plain text at ${recall}. When you need an exact detail it leaves out (an error message, path, number, command, or what the user said), search that file with grep instead of guessing, writing its full path in each command rather than in a shell variable. Do not read it whole.`
211
+ : 'The earlier conversation is not available to you.';
206
212
  return [
207
213
  '# Carwash handoff',
208
214
  '',
209
- `The user ran ${toolInfo(toolOf(record)).wash} in an earlier session and started this one to carry on from it. The brief below (${record.level}, written ${ageOf(record, now)}) is what that session handed over. The earlier conversation is not available to you.`,
215
+ `The user ran ${toolInfo(toolOf(record)).wash} in an earlier session and started this one to carry on from it. The brief below (${record.level}, written ${ageOf(record, now)}) is what that session handed over. ${earlier}`,
210
216
  'If the brief is cut off below, or a note says the full text was saved to a file, read that file in full before you reply.',
211
217
  'Check the current state of a file before acting on what the brief says about it.',
212
218
  ...(stale ? [stale] : []),
@@ -11,6 +11,7 @@ import { budgetNote, composeContext, describe, helpMessage, loadedMessage, parse
11
11
  import { isTool, toolInfo, toolOf } from '../tools.mjs';
12
12
  import { repoState, worktreeRoot } from './git.mjs';
13
13
  import { codexProcess, codexUnattended, currentProcess, isRunning, sameProcess } from './process.mjs';
14
+ import { keptRecall, saveRecall } from './recall.mjs';
14
15
  import { readCodexReplyUsage, readCodexUsage, readCodexVersion } from './rollout.mjs';
15
16
  import { currentWash, endWash, loadUsage, startWash } from './session.mjs';
16
17
  import { AUTO_LOAD_MS, addRecord, claim, findRecords, purge, readyRecords, removeRecord, reopen, updateRecord } from './store.mjs';
@@ -236,6 +237,7 @@ function onStop(payload, ctx) {
236
237
  now,
237
238
  );
238
239
  quietly(ctx, () => recordWash(env, record, wash));
240
+ quietly(ctx, () => saveRecall(env, record.id, payload.transcript_path, ctx.tool));
239
241
  // One ready brief per terminal. An earlier wash of this same session is out
240
242
  // of date and goes; anything else this terminal held goes back to waiting.
241
243
  for (const other of readyRecords(env, now)) {
@@ -257,7 +259,7 @@ function deliver(record, payload, ctx) {
257
259
  const stale = stalenessLine(record.source, repoState(cwdOf(payload)));
258
260
  return {
259
261
  systemMessage: loadedMessage(record, now, stale, ctx.tool),
260
- hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: composeContext(record, now, stale) },
262
+ hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: composeContext(record, now, stale, keptRecall(env, record.id)) },
261
263
  };
262
264
  }
263
265
 
@@ -0,0 +1,151 @@
1
+ import { closeSync, existsSync, openSync, readSync } from 'node:fs';
2
+ import { StringDecoder } from 'node:string_decoder';
3
+ import { privateDir, writeFileAtomic } from '../files.mjs';
4
+ import { recallDir, recallFile } from '../paths.mjs';
5
+ import { resultText } from '../stats/ledger.mjs';
6
+ import { toolInfo } from '../tools.mjs';
7
+
8
+ // A brief is a summary, so it leaves things out: the exact error, the path, the
9
+ // one number that matters. When a brief is saved, the session it came from is
10
+ // copied here as plain text, and the fresh session is told where to find it, so
11
+ // it can search for an exact detail instead of guessing.
12
+ //
13
+ // The session files themselves are poor to search. Theirs can run to hundreds
14
+ // of megabytes and one line of an image can be a megabyte or more, which a single
15
+ // search hit would pull into the conversation. This keeps only the words, ends
16
+ // at the wash so the brief is not in it twice, and wraps long lines. One file per
17
+ // brief, deleted after RECALL_DAYS or when the brief is discarded.
18
+
19
+ // Longest line kept whole, so one search hit stays a small one.
20
+ const WRAP = 2000;
21
+ const LONG_LINE = new RegExp(`.{1,${WRAP}}`, 'gsu');
22
+
23
+ // Past this, the oldest part of the session is left out. Real sessions are far
24
+ // smaller once images are gone: a few megabytes at the very most.
25
+ const MAX_BYTES = 16 * 1024 * 1024;
26
+
27
+ const CHUNK = 1024 * 1024;
28
+
29
+ // The lines of a file, without holding the whole of it in memory at once.
30
+ function* linesOf(file) {
31
+ const fd = openSync(file, 'r');
32
+ try {
33
+ const buffer = Buffer.alloc(CHUNK);
34
+ const decoder = new StringDecoder('utf8');
35
+ let rest = '';
36
+ for (;;) {
37
+ const read = readSync(fd, buffer, 0, CHUNK, null);
38
+ if (!read) break;
39
+ const lines = (rest + decoder.write(buffer.subarray(0, read))).split('\n');
40
+ rest = lines.pop();
41
+ yield* lines;
42
+ }
43
+ if (rest) yield rest;
44
+ } finally {
45
+ closeSync(fd);
46
+ }
47
+ }
48
+
49
+ // One transcript line as [who, text] pairs. Images, and anything else that is
50
+ // not words, come out empty and are dropped.
51
+ function claudeEntries(line) {
52
+ if ((line.type !== 'user' && line.type !== 'assistant') || line.isMeta || line.isSidechain) return [];
53
+ const content = line.message?.content;
54
+ if (typeof content === 'string') return [[line.type, content]];
55
+ if (!Array.isArray(content)) return [];
56
+ return content.flatMap((block) => {
57
+ if (block?.type === 'text') return [[line.type, block.text]];
58
+ if (block?.type === 'thinking') return [['assistant thinking', block.thinking]];
59
+ if (block?.type === 'tool_use') return [[`tool call ${block.name}`, JSON.stringify(block.input)]];
60
+ if (block?.type === 'tool_result') return [[block.is_error ? 'tool result (error)' : 'tool result', resultText(block)]];
61
+ return [];
62
+ });
63
+ }
64
+
65
+ const partsText = (parts) => (Array.isArray(parts) ? parts.map((part) => part?.text ?? '').join('') : '');
66
+
67
+ // The same for a Codex rollout line. Codex says the format is not a stable
68
+ // interface, so anything unexpected is simply left out.
69
+ function codexEntries(line) {
70
+ if (line.type !== 'response_item') return [];
71
+ const item = line.payload;
72
+ switch (item?.type) {
73
+ case 'message':
74
+ return item.role === 'user' || item.role === 'assistant' ? [[item.role, partsText(item.content)]] : [];
75
+ case 'reasoning':
76
+ return [['assistant thinking', partsText(item.summary)]];
77
+ case 'function_call':
78
+ return [[`tool call ${item.name}`, item.arguments]];
79
+ case 'custom_tool_call':
80
+ return [[`tool call ${item.name}`, item.input]];
81
+ case 'function_call_output':
82
+ case 'custom_tool_call_output':
83
+ return [['tool result', typeof item.output === 'string' ? item.output : partsText(item.output)]];
84
+ default:
85
+ return [];
86
+ }
87
+ }
88
+
89
+ const READERS = {
90
+ claude: { entries: claudeEntries, isWash: (text) => text.includes('<command-name>/wash</command-name>') || /^\s*\/wash(?![\w-])/.test(text) },
91
+ codex: { entries: codexEntries, isWash: (text) => /^\s*\$wash(?![\w-])/.test(text) },
92
+ };
93
+
94
+ // Everything said in a session, up to the last wash.
95
+ function readEntries(file, tool) {
96
+ const { entries: toEntries, isWash } = READERS[tool] ?? READERS.claude;
97
+ const entries = [];
98
+ let end = null;
99
+ for (const raw of linesOf(file)) {
100
+ let line;
101
+ try {
102
+ line = JSON.parse(raw);
103
+ } catch {
104
+ continue;
105
+ }
106
+ if (!line || typeof line !== 'object') continue;
107
+ for (const [who, text] of toEntries(line)) {
108
+ if (typeof text !== 'string' || !text.trim()) continue;
109
+ if (who === 'user' && isWash(text)) end = entries.length;
110
+ entries.push({ who, time: line.timestamp, text });
111
+ }
112
+ }
113
+ return end === null ? entries : entries.slice(0, end);
114
+ }
115
+
116
+ const wrapped = (text) => text.split('\n').map((line) => (line.length > WRAP ? line.match(LONG_LINE).join('\n') : line)).join('\n');
117
+
118
+ function render(entries, tool) {
119
+ const kept = [];
120
+ let bytes = 0;
121
+ for (let i = entries.length - 1; i >= 0; i--) {
122
+ const { who, time, text } = entries[i];
123
+ const block = `--- #${i + 1} ${who}${time ? ` ${time}` : ''} ---\n${wrapped(text)}\n\n`;
124
+ bytes += Buffer.byteLength(block);
125
+ if (bytes > MAX_BYTES) break;
126
+ kept.push(block);
127
+ }
128
+ const { name, wash } = toolInfo(tool);
129
+ const dropped = entries.length - kept.length;
130
+ const note = dropped ? ` The first ${dropped === 1 ? 'entry is' : `${dropped} entries are`} left out too, to keep this file small.` : '';
131
+ return `A text copy of an earlier ${name} session, saved when ${wash} wrote its brief. Images are left out.${note}\nEach entry starts with a "--- #n who time ---" line.\n\n${kept.reverse().join('')}`;
132
+ }
133
+
134
+ // Copy a session to the file for brief `id`. Returns that file, or null if
135
+ // there was nothing to copy. The brief works without it, so a caller should not
136
+ // let a failure here stop anything.
137
+ export function saveRecall(env, id, transcript, tool = 'claude') {
138
+ if (typeof transcript !== 'string' || !existsSync(transcript)) return null;
139
+ const entries = readEntries(transcript, tool);
140
+ if (!entries.length) return null;
141
+ privateDir(recallDir(env));
142
+ const file = recallFile(env, id);
143
+ writeFileAtomic(file, render(entries, tool), 0o600);
144
+ return file;
145
+ }
146
+
147
+ // The copy for brief `id`, or null if it is gone.
148
+ export function keptRecall(env, id) {
149
+ const file = recallFile(env, id);
150
+ return existsSync(file) ? file : null;
151
+ }
@@ -1,8 +1,8 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { existsSync, readdirSync, renameSync, statSync, unlinkSync } from 'node:fs';
2
+ import { existsSync, readdirSync, renameSync, rmSync, statSync, unlinkSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { privateDir, readJson, writePrivateJson } from '../files.mjs';
5
- import { consumedDir, pendingDir, sessionsDir } from '../paths.mjs';
5
+ import { RECALL_DAYS, consumedDir, pendingDir, recallDir, recallFile, sessionsDir } from '../paths.mjs';
6
6
 
7
7
  // The store of handoff briefs. One JSON file per brief, outside any project:
8
8
  // pending/ holds briefs waiting for a fresh session, consumed/ holds delivered
@@ -62,7 +62,9 @@ export function updateRecord(env, record) {
62
62
  if (existsSync(file)) writePrivateJson(file, record);
63
63
  }
64
64
 
65
+ // Drop a waiting brief, and the copy of its session along with it.
65
66
  export function removeRecord(env, id) {
67
+ rmSync(recallFile(env, id), { force: true });
66
68
  try {
67
69
  unlinkSync(fileIn(pendingDir(env), id));
68
70
  return true;
@@ -132,7 +134,7 @@ function sweep(dir, isDue) {
132
134
  }
133
135
 
134
136
  // Delete what has outlived its use: expired briefs, delivered briefs past
135
- // their retention, old session notes, and stray files.
137
+ // their retention, old session notes and copies, and stray files.
136
138
  export function purge(env, now = Date.now()) {
137
139
  const setting = (env.CARWASH_RETAIN_HOURS ?? '').trim();
138
140
  const retainMs = (setting !== '' && Number(setting) >= 0 ? Number(setting) : RETAIN_HOURS) * HOUR;
@@ -148,4 +150,5 @@ export function purge(env, now = Date.now()) {
148
150
  return Number.isFinite(consumed) ? now - consumed > retainMs : stale(file, HOUR);
149
151
  });
150
152
  sweep(sessionsDir(env), (file) => stale(file, SESSION_NOTE_MS));
153
+ sweep(recallDir(env), (file) => stale(file, RECALL_DAYS * 24 * HOUR));
151
154
  }