claude-db 0.12.1 → 0.12.2

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/capture/active.d.ts +12 -0
  3. package/dist/capture/active.js +74 -0
  4. package/dist/capture/flush.d.ts +1 -1
  5. package/dist/capture/flush.js +12 -2
  6. package/dist/capture/git.d.ts +1 -0
  7. package/dist/capture/git.js +3 -2
  8. package/dist/capture/transcript.d.ts +1 -0
  9. package/dist/capture/transcript.js +3 -2
  10. package/dist/capture/turn-extractor.d.ts +3 -0
  11. package/dist/capture/turn-extractor.js +12 -2
  12. package/dist/catchup/gather.d.ts +9 -4
  13. package/dist/catchup/gather.js +22 -15
  14. package/dist/catchup/render.js +17 -8
  15. package/dist/cli/commands/catchup.js +2 -1
  16. package/dist/cli/install.js +1 -0
  17. package/dist/facts/handoff.d.ts +2 -0
  18. package/dist/facts/handoff.js +7 -0
  19. package/dist/facts/last-chat.d.ts +13 -0
  20. package/dist/facts/last-chat.js +45 -0
  21. package/dist/facts/start.d.ts +2 -1
  22. package/dist/facts/start.js +44 -5
  23. package/dist/hooks/detached.d.ts +1 -0
  24. package/dist/hooks/detached.js +1 -0
  25. package/dist/hooks/payload.d.ts +5 -0
  26. package/dist/hooks/relevance.js +1 -5
  27. package/dist/hooks/session-end.js +6 -0
  28. package/dist/hooks/session-start.js +9 -6
  29. package/dist/hooks/turn-end.d.ts +2 -0
  30. package/dist/hooks/turn-end.js +26 -0
  31. package/dist/hooks/turn-job.d.ts +10 -0
  32. package/dist/hooks/turn-job.js +30 -0
  33. package/dist/hooks/turn-save.d.ts +2 -0
  34. package/dist/hooks/turn-save.js +25 -0
  35. package/dist/hooks/user-prompt.js +2 -0
  36. package/dist/pick/pending.js +7 -37
  37. package/dist/store/mongo/filters.d.ts +1 -0
  38. package/dist/store/mongo/filters.js +9 -3
  39. package/dist/store/mongo/observations.js +2 -3
  40. package/dist/store/postgres/filters.d.ts +1 -0
  41. package/dist/store/postgres/filters.js +9 -4
  42. package/dist/store/postgres/observations.js +4 -1
  43. package/dist/store/sqlite/filters.d.ts +1 -0
  44. package/dist/store/sqlite/filters.js +9 -4
  45. package/dist/store/sqlite/observations.js +4 -1
  46. package/dist/store/sqlite/search.js +4 -5
  47. package/dist/types.d.ts +1 -0
  48. package/dist/util/day.d.ts +1 -0
  49. package/dist/util/day.js +4 -0
  50. package/dist/util/json-file.d.ts +4 -0
  51. package/dist/util/json-file.js +37 -0
  52. package/docs/how-it-works.md +6 -1
  53. package/package.json +6 -6
  54. package/skills/catchup/SKILL.md +6 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.2
4
+
5
+ ### Fixed
6
+
7
+ - **A new chat knows what the other chats did, even while they are still open.** The start of each chat shows
8
+ the newest 5 requests from other chats, grouped by chat, with a chat's summary once it has ended. A request is
9
+ saved as soon as Claude finishes the reply, and one that another chat is still working on, also in a
10
+ background task, is shown as not finished yet. A handoff note stays, marked `older than the last chat` once a
11
+ later request has moved past it. `/catchup` shows the same and leaves out the chat it runs in.
12
+
3
13
  ## 0.12.1
4
14
 
5
15
  ### Changed
@@ -0,0 +1,12 @@
1
+ export interface ActiveRequest {
2
+ sessionId: string;
3
+ project: string;
4
+ request: string;
5
+ askedAt: number;
6
+ token: string;
7
+ }
8
+ export declare function recordActive(sessionId: string, project: string, prompt: string, now?: number): void;
9
+ export declare function activeToken(sessionId: string): string | null;
10
+ export declare function clearActive(sessionId: string, token?: string): void;
11
+ export declare function activeRequests(projects: readonly string[], current: string | undefined, now?: number): ActiveRequest[];
12
+ export declare function sweepActive(now?: number): void;
@@ -0,0 +1,74 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readdirSync, rmSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { CONFIG_DIR } from '../config/dir.js';
5
+ import { readJson, safeName, sweepOlderThan, writeJsonAtomic } from '../util/json-file.js';
6
+ import { isSearchable, readablePrompt } from '../util/prompt.js';
7
+ import { redact } from './redact.js';
8
+ import { isSyntheticPrompt } from './transcript.js';
9
+ import { clipAsked, stripPrivate } from './turn-extractor.js';
10
+ const SHOWN_FOR_MS = 2 * 60 * 60 * 1000;
11
+ const KEPT_FOR_MS = 24 * 60 * 60 * 1000;
12
+ const SHOWN_AT_MOST = 2;
13
+ function folder() {
14
+ return join(CONFIG_DIR, 'active');
15
+ }
16
+ function fileFor(sessionId) {
17
+ return join(folder(), `${safeName(sessionId)}.json`);
18
+ }
19
+ function readActive(file) {
20
+ const value = readJson(file);
21
+ const valid = typeof value?.sessionId === 'string' &&
22
+ typeof value.project === 'string' &&
23
+ typeof value.request === 'string' &&
24
+ typeof value.askedAt === 'number' &&
25
+ typeof value.token === 'string';
26
+ return valid ? value : null;
27
+ }
28
+ export function recordActive(sessionId, project, prompt, now = Date.now()) {
29
+ if (isSyntheticPrompt(prompt))
30
+ return;
31
+ const text = readablePrompt(stripPrivate(prompt));
32
+ if (!isSearchable(text)) {
33
+ clearActive(sessionId);
34
+ return;
35
+ }
36
+ const request = clipAsked(redact(text));
37
+ writeJsonAtomic(fileFor(sessionId), {
38
+ sessionId,
39
+ project,
40
+ request,
41
+ askedAt: now,
42
+ token: randomUUID(),
43
+ });
44
+ }
45
+ export function activeToken(sessionId) {
46
+ return readActive(fileFor(sessionId))?.token ?? null;
47
+ }
48
+ export function clearActive(sessionId, token) {
49
+ const file = fileFor(sessionId);
50
+ if (token !== undefined && readActive(file)?.token !== token)
51
+ return;
52
+ rmSync(file, { force: true });
53
+ }
54
+ export function activeRequests(projects, current, now = Date.now()) {
55
+ let names;
56
+ try {
57
+ names = readdirSync(folder());
58
+ }
59
+ catch {
60
+ return [];
61
+ }
62
+ return names
63
+ .filter((name) => name.endsWith('.json'))
64
+ .map((name) => readActive(join(folder(), name)))
65
+ .filter((entry) => entry !== null &&
66
+ projects.includes(entry.project) &&
67
+ entry.sessionId !== current &&
68
+ now - entry.askedAt <= SHOWN_FOR_MS)
69
+ .sort((a, b) => b.askedAt - a.askedAt)
70
+ .slice(0, SHOWN_AT_MOST);
71
+ }
72
+ export function sweepActive(now = Date.now()) {
73
+ sweepOlderThan(folder(), KEPT_FOR_MS, now);
74
+ }
@@ -5,7 +5,7 @@ export interface FlushResult {
5
5
  summary: string | null;
6
6
  lastReply: string;
7
7
  }
8
- export declare function flushSession(ctx: RecallContext, sessionId: string, project: string, transcriptPath?: string, rebuild?: boolean): Promise<FlushResult>;
8
+ export declare function flushSession(ctx: RecallContext, sessionId: string, project: string, transcriptPath?: string, rebuild?: boolean, finalReply?: string): Promise<FlushResult>;
9
9
  export declare function embedObservations(ctx: RecallContext, observations: Observation[]): Promise<void>;
10
10
  export declare function summarize(observations: Observation[], previous?: string): string;
11
11
  export declare function resetCursor(sessionId: string): void;
@@ -4,10 +4,12 @@ import { CONFIG_DIR } from '../config/index.js';
4
4
  import { readTranscript, sessionIdsOnDisk, transcriptPathFor } from './transcript.js';
5
5
  import { observationsFromTurns } from './turn-extractor.js';
6
6
  import { closeLandedWork } from './progress.js';
7
- export async function flushSession(ctx, sessionId, project, transcriptPath, rebuild = false) {
7
+ export async function flushSession(ctx, sessionId, project, transcriptPath, rebuild = false, finalReply = '') {
8
8
  const path = transcriptPath ?? transcriptPathFor(project, sessionId);
9
9
  const cursor = readCursor(sessionId);
10
- const { turns, nextOffset } = readTranscript(path, cursor);
10
+ const read = readTranscript(path, cursor);
11
+ const { nextOffset } = read;
12
+ const turns = withFinalReply(read.turns, finalReply);
11
13
  const lastReply = turns.at(-1)?.reasoning ?? '';
12
14
  if (turns.length === 0) {
13
15
  await closeLandedWork(ctx.store, project);
@@ -65,6 +67,14 @@ const KIND_RANK = {
65
67
  pattern: 4,
66
68
  context: 5,
67
69
  };
70
+ function withFinalReply(turns, finalReply) {
71
+ const reply = finalReply.trim();
72
+ const last = turns.at(-1);
73
+ if (!last || !reply || last.reasoning.includes(reply))
74
+ return turns;
75
+ const reasoning = last.reasoning ? `${last.reasoning}\n${reply}` : reply;
76
+ return [...turns.slice(0, -1), { ...last, reasoning }];
77
+ }
68
78
  export function summarize(observations, previous) {
69
79
  const kept = previous ? previous.split(' | ').filter(Boolean) : [];
70
80
  for (const obs of [...observations].sort((a, b) => KIND_RANK[a.kind] - KIND_RANK[b.kind])) {
@@ -1,2 +1,3 @@
1
1
  import type { Observation } from '../types.js';
2
+ export declare const GIT_SESSION = "git";
2
3
  export declare function observationsFromGit(project: string, limit: number): Observation[];
@@ -3,6 +3,7 @@ import { join } from 'node:path';
3
3
  import { observationId } from './identity.js';
4
4
  import { redact } from './redact.js';
5
5
  import { classifyTurn, topLevelDirs } from './turn-extractor.js';
6
+ export const GIT_SESSION = 'git';
6
7
  const RECORD = '';
7
8
  const FIELD = '';
8
9
  const NOT_WORTH_KEEPING = /^(v?\d+\.\d+\.\d+|merge |revert "|bump |release |chore\(release\)|\d+\.\d+\.\d+$)/i;
@@ -44,8 +45,8 @@ function toObservation(record, project) {
44
45
  return null;
45
46
  const timestamp = createdAt;
46
47
  return {
47
- id: observationId('git', 0, sha),
48
- sessionId: 'git',
48
+ id: observationId(GIT_SESSION, 0, sha),
49
+ sessionId: GIT_SESSION,
49
50
  project,
50
51
  ...(author ? { author } : {}),
51
52
  kind: classifyTurn({
@@ -12,6 +12,7 @@ export interface TranscriptRead {
12
12
  lastTimestamp: number;
13
13
  }
14
14
  export declare function readTranscript(path: string, fromOffset?: number): TranscriptRead;
15
+ export declare function isSyntheticPrompt(text: string): boolean;
15
16
  export declare function transcriptPathFor(project: string, sessionId: string): string;
16
17
  export declare function transcriptsFor(project: string): string[];
17
18
  export declare function sessionIdsOnDisk(): string[];
@@ -117,7 +117,7 @@ function extractToolCalls(content) {
117
117
  }
118
118
  return calls;
119
119
  }
120
- function isSyntheticPrompt(text) {
120
+ export function isSyntheticPrompt(text) {
121
121
  return (text.includes('<system-reminder>') ||
122
122
  text.includes('<project-memory>') ||
123
123
  text.includes('<recalled-memory>') ||
@@ -125,7 +125,8 @@ function isSyntheticPrompt(text) {
125
125
  isRelayedMessage(text) ||
126
126
  text.startsWith('Caveat:') ||
127
127
  text.startsWith('[Request interrupted') ||
128
- text.startsWith('<local-command'));
128
+ text.startsWith('<local-command') ||
129
+ text.startsWith('<task-notification>'));
129
130
  }
130
131
  function projectSlug(project) {
131
132
  return project.replace(/[^a-zA-Z0-9]/g, '-');
@@ -1,6 +1,9 @@
1
1
  import type { Config } from '../config/index.js';
2
2
  import type { Observation, ObservationKind } from '../types.js';
3
3
  import type { Turn } from './transcript.js';
4
+ export declare function clipAsked(text: string): string;
5
+ export declare function askedIn(body: string): string;
6
+ export declare function stripPrivate(text: string): string;
4
7
  export declare function observationsFromTurns(turns: Turn[], sessionId: string, project: string, config: Config): Observation[];
5
8
  export declare function topLevelDirs(files: string[], project: string): string[];
6
9
  export declare function classifyTurn(turn: Turn): ObservationKind;
@@ -2,6 +2,17 @@ import { classifyCommand } from './command.js';
2
2
  import { isSearchable, readablePrompt } from '../util/prompt.js';
3
3
  import { currentAuthor, observationId } from './identity.js';
4
4
  import { redact } from './redact.js';
5
+ const ASKED_CHARS = 120;
6
+ export function clipAsked(text) {
7
+ const asked = text.replace(/\s+/g, ' ').trim();
8
+ return asked.length > ASKED_CHARS ? `${asked.slice(0, ASKED_CHARS)}…` : asked;
9
+ }
10
+ export function askedIn(body) {
11
+ return clipAsked(/^Asked: (.*)$/m.exec(body)?.[1] ?? '');
12
+ }
13
+ export function stripPrivate(text) {
14
+ return text.replace(/<private>[\s\S]*?(?:<\/private>|$)/gi, '[private]');
15
+ }
5
16
  export function observationsFromTurns(turns, sessionId, project, config) {
6
17
  return turns
7
18
  .map(withoutPrivate)
@@ -13,8 +24,7 @@ export function observationsFromTurns(turns, sessionId, project, config) {
13
24
  .map(({ id, turn }) => buildObservation(turn, id, sessionId, project, config));
14
25
  }
15
26
  function withoutPrivate(turn) {
16
- const strip = (text) => text.replace(/<private>[\s\S]*?(?:<\/private>|$)/gi, '[private]');
17
- return { ...turn, prompt: strip(turn.prompt), reasoning: strip(turn.reasoning) };
27
+ return { ...turn, prompt: stripPrivate(turn.prompt), reasoning: stripPrivate(turn.reasoning) };
18
28
  }
19
29
  function isSubstantive(turn, config) {
20
30
  const files = turn.files.filter((file) => !isExcluded(file, config.capture.exclude));
@@ -4,15 +4,20 @@ export interface CatchupData {
4
4
  handoff: {
5
5
  at: number;
6
6
  lines: string[];
7
+ passed: boolean;
7
8
  } | null;
8
- lastChat: {
9
+ unfinished: {
9
10
  at: number;
10
- summary: string;
11
+ request: string;
12
+ }[];
13
+ chats: {
14
+ at: number;
15
+ summary: string | null;
11
16
  work: string[];
12
- } | null;
17
+ }[];
13
18
  todos: string[];
14
19
  decisions: string[];
15
20
  uncommitted: string[];
16
21
  git: GitState | null;
17
22
  }
18
- export declare function gatherCatchup(ctx: RecallContext, project: string, now?: number): Promise<CatchupData>;
23
+ export declare function gatherCatchup(ctx: RecallContext, project: string, current?: string, now?: number): Promise<CatchupData>;
@@ -1,32 +1,30 @@
1
1
  import { openWork } from '../capture/progress.js';
2
2
  import { FACT_SESSION, factLabel, factType, onePerKey } from '../facts/model.js';
3
- import { handoffBodyLines, newestHandoff } from '../facts/handoff.js';
3
+ import { activeRequests } from '../capture/active.js';
4
+ import { handoffBodyLines, newestHandoff, passedNote } from '../facts/handoff.js';
5
+ import { latestRequestAt, recentChats, turnLine } from '../facts/last-chat.js';
4
6
  import { readGitState } from './git-state.js';
5
- const CHAT_TITLES = 6;
6
7
  const TODOS = 5;
7
8
  const UNCOMMITTED = 5;
8
9
  const DECISIONS = 5;
9
10
  const FACTS_SCANNED = 100;
10
- export async function gatherCatchup(ctx, project, now = Date.now()) {
11
+ export async function gatherCatchup(ctx, project, current, now = Date.now()) {
11
12
  const handoff = await newestHandoff(ctx, project, now);
12
- const [latest] = await ctx.store.recentSessions(project, 1);
13
- const chatWork = latest
14
- ? (await ctx.store.list({ project, sessionId: latest.id, newest: true, limit: CHAT_TITLES }))
15
- .filter((obs) => obs.status !== 'replaced')
16
- .map((obs) => obs.title)
17
- : [];
13
+ const unfinished = activeRequests(await ctx.store.projectScope(project), current, now);
14
+ const chats = await recentChats(ctx, project, current);
15
+ const latest = latestRequestAt(chats, unfinished);
18
16
  const facts = await ctx.store.list({
19
17
  project,
20
18
  sessionId: FACT_SESSION,
21
19
  newest: true,
22
20
  limit: FACTS_SCANNED,
23
21
  });
24
- const current = onePerKey(facts.filter((obs) => obs.status !== 'replaced'));
25
- const todos = current
22
+ const kept = onePerKey(facts.filter((obs) => obs.status !== 'replaced'));
23
+ const todos = kept
26
24
  .filter((obs) => factType(obs) === 'todo')
27
25
  .slice(0, TODOS)
28
26
  .map((obs) => obs.title);
29
- const decisions = current
27
+ const decisions = kept
30
28
  .filter((obs) => ['decision', 'deadend'].includes(factType(obs) ?? ''))
31
29
  .slice(0, DECISIONS)
32
30
  .map((obs) => `${factLabel(obs)}: ${obs.title}`);
@@ -34,10 +32,19 @@ export async function gatherCatchup(ctx, project, now = Date.now()) {
34
32
  .slice(0, UNCOMMITTED)
35
33
  .map((obs) => obs.title);
36
34
  return {
37
- handoff: handoff ? { at: handoff.createdAt, lines: handoffBodyLines(handoff) } : null,
38
- lastChat: latest
39
- ? { at: latest.startedAt, summary: latest.summary ?? '', work: chatWork }
35
+ handoff: handoff
36
+ ? {
37
+ at: handoff.createdAt,
38
+ lines: handoffBodyLines(handoff),
39
+ passed: passedNote(handoff.createdAt, latest),
40
+ }
40
41
  : null,
42
+ unfinished: unfinished.map((entry) => ({ at: entry.askedAt, request: entry.request })),
43
+ chats: chats.map((chat) => ({
44
+ at: chat.at,
45
+ summary: chat.summary,
46
+ work: chat.turns.map(turnLine),
47
+ })),
41
48
  todos,
42
49
  decisions,
43
50
  uncommitted,
@@ -1,4 +1,5 @@
1
- import { formatDay } from '../util/day.js';
1
+ import { handoffHeading } from '../facts/handoff.js';
2
+ import { formatDay, formatDayTime } from '../util/day.js';
2
3
  export const NOTHING_RECORDED = 'Nothing recorded for this project yet.';
3
4
  function section(heading, lines) {
4
5
  return lines.length === 0 ? [] : [heading, ...lines, ''];
@@ -22,22 +23,30 @@ function branchLine(git) {
22
23
  const state = git.changed === 0 ? 'clean' : `${git.changed} file${git.changed === 1 ? '' : 's'} uncommitted`;
23
24
  return [`Branch: ${git.branch ?? 'detached HEAD'}, ${state}`, ''];
24
25
  }
25
- function chatBlock(chat, now) {
26
- if (!chat)
27
- return [];
28
- const heading = `Last chat (${formatDay(chat.at, now)}): ${chat.summary || 'no summary'}`;
29
- return [heading, ...bullets(chat.work), ''];
26
+ function chatBlocks(chats, now) {
27
+ return chats.flatMap((chat, index) => {
28
+ if (!chat.summary && chat.work.length === 0)
29
+ return [];
30
+ const heading = `${index === 0 ? 'Last chat' : 'Chat before'} (${formatDay(chat.at, now)}):`;
31
+ return [chat.summary ? `${heading} ${chat.summary}` : heading, ...bullets(chat.work), ''];
32
+ });
33
+ }
34
+ function unfinishedBlocks(unfinished, now) {
35
+ return unfinished.flatMap((entry) => section(`Not finished yet in another chat (${formatDayTime(entry.at, now)}):`, [
36
+ ` - asked "${entry.request}"`,
37
+ ]));
30
38
  }
31
39
  function handoffBlock(handoff, now) {
32
40
  if (!handoff)
33
41
  return [];
34
- return section(`Last handoff (${formatDay(handoff.at, now)}):`, handoff.lines.map((line) => ` ${line}`));
42
+ return section(handoffHeading(handoff.at, handoff.passed, now), handoff.lines.map((line) => ` ${line}`));
35
43
  }
36
44
  export function renderCatchup(data, now = Date.now()) {
37
45
  const { status, commits } = gitLines(data);
38
46
  const blocks = [
39
47
  ...handoffBlock(data.handoff, now),
40
- ...chatBlock(data.lastChat, now),
48
+ ...unfinishedBlocks(data.unfinished, now),
49
+ ...chatBlocks(data.chats, now),
41
50
  ...section('Still to do (from facts):', bullets(data.todos)),
42
51
  ...section('Decisions and dead ends (from facts):', bullets(data.decisions)),
43
52
  ...section('Not committed yet (recorded work):', bullets(data.uncommitted)),
@@ -6,7 +6,8 @@ export async function cmdCatchup() {
6
6
  const project = resolveProject(undefined);
7
7
  const ctx = await createContext();
8
8
  try {
9
- console.log(renderCatchup(await gatherCatchup(ctx, project)));
9
+ const current = process.env['CLAUDE_CODE_SESSION_ID'] || undefined;
10
+ console.log(renderCatchup(await gatherCatchup(ctx, project, current)));
10
11
  }
11
12
  finally {
12
13
  await ctx.close();
@@ -9,6 +9,7 @@ const HOOKS = [
9
9
  ['SessionStart', 'session-start.js'],
10
10
  ['UserPromptSubmit', 'user-prompt.js'],
11
11
  ['SessionEnd', 'session-end.js'],
12
+ ['Stop', 'turn-end.js'],
12
13
  ['PreToolUse', 'prefer-usages.js', 'Bash|Grep', 10],
13
14
  ['PreToolUse', 'pick-deliver.js', undefined, 5],
14
15
  ];
@@ -2,5 +2,7 @@ import type { RecallContext } from '../context.js';
2
2
  import type { Observation } from '../types.js';
3
3
  export declare const HANDOFF_TAG = "handoff";
4
4
  export declare const HANDOFF_KEY = "handoff";
5
+ export declare function passedNote(noteAt: number, latestRequest: number | null): boolean;
6
+ export declare function handoffHeading(at: number, passed: boolean, now?: number): string;
5
7
  export declare function newestHandoff(ctx: RecallContext, project: string, now?: number): Promise<Observation | null>;
6
8
  export declare function handoffBodyLines(obs: Observation): string[];
@@ -1,3 +1,4 @@
1
+ import { formatDay } from '../util/day.js';
1
2
  import { MANUAL_SESSION } from './render.js';
2
3
  export const HANDOFF_TAG = 'handoff';
3
4
  export const HANDOFF_KEY = 'handoff';
@@ -6,6 +7,12 @@ const HANDOFF_MAX_AGE_MS = 14 * DAY_MS;
6
7
  const MANUAL_NOTES_SCANNED = 50;
7
8
  const HANDOFF_MAX_LINES = 8;
8
9
  const HANDOFF_LINE_CHARS = 220;
10
+ export function passedNote(noteAt, latestRequest) {
11
+ return latestRequest !== null && latestRequest > noteAt;
12
+ }
13
+ export function handoffHeading(at, passed, now = Date.now()) {
14
+ return `Last handoff (${formatDay(at, now)}${passed ? ', older than the last chat' : ''}):`;
15
+ }
9
16
  export async function newestHandoff(ctx, project, now = Date.now()) {
10
17
  const notes = await ctx.store.list({
11
18
  project,
@@ -0,0 +1,13 @@
1
+ import type { RecallContext } from '../context.js';
2
+ import type { Observation } from '../types.js';
3
+ export interface RecentChat {
4
+ sessionId: string;
5
+ at: number;
6
+ summary: string | null;
7
+ turns: Observation[];
8
+ }
9
+ export declare function recentChats(ctx: RecallContext, project: string, current?: string): Promise<RecentChat[]>;
10
+ export declare function latestRequestAt(chats: RecentChat[], unfinished: {
11
+ askedAt: number;
12
+ }[]): number | null;
13
+ export declare function turnLine(turn: Observation): string;
@@ -0,0 +1,45 @@
1
+ import { GIT_SESSION } from '../capture/git.js';
2
+ import { askedIn } from '../capture/turn-extractor.js';
3
+ import { toSnippet } from '../util/snippet.js';
4
+ import { FACT_SESSION } from './model.js';
5
+ import { MANUAL_SESSION } from './render.js';
6
+ const NOT_CHATS = [FACT_SESSION, MANUAL_SESSION, GIT_SESSION];
7
+ const ROWS_READ = 10;
8
+ const TURNS_SHOWN = 5;
9
+ const SUMMARY_CHARS = 300;
10
+ const SUMMARY_PARTS = ' | ';
11
+ export async function recentChats(ctx, project, current) {
12
+ const rows = (await ctx.store.list({
13
+ project,
14
+ excludeSessions: current ? [...NOT_CHATS, current] : NOT_CHATS,
15
+ newest: true,
16
+ limit: ROWS_READ,
17
+ }))
18
+ .filter((row) => row.status !== 'replaced')
19
+ .slice(0, TURNS_SHOWN);
20
+ const byChat = new Map();
21
+ for (const row of rows)
22
+ byChat.set(row.sessionId, [...(byChat.get(row.sessionId) ?? []), row]);
23
+ return Promise.all([...byChat].map(async ([sessionId, newestFirst]) => toChat(sessionId, newestFirst, await ctx.store.getSession(sessionId))));
24
+ }
25
+ function toChat(sessionId, newestFirst, session) {
26
+ const turns = [...newestFirst].reverse();
27
+ const at = newestFirst[0]?.createdAt ?? 0;
28
+ return { sessionId, at, summary: chatSummary(session, at, turns), turns };
29
+ }
30
+ function chatSummary(session, at, turns) {
31
+ if (!session?.summary || session.endedAt === undefined || session.endedAt < at)
32
+ return null;
33
+ const shown = new Set(turns.map((turn) => turn.title));
34
+ if (session.summary.split(SUMMARY_PARTS).every((part) => shown.has(part)))
35
+ return null;
36
+ return toSnippet(session.summary, SUMMARY_CHARS) ?? null;
37
+ }
38
+ export function latestRequestAt(chats, unfinished) {
39
+ const times = [...chats.map((chat) => chat.at), ...unfinished.map((entry) => entry.askedAt)];
40
+ return times.length === 0 ? null : Math.max(...times);
41
+ }
42
+ export function turnLine(turn) {
43
+ const asked = askedIn(turn.body);
44
+ return asked ? `asked "${asked}": ${turn.title}` : turn.title;
45
+ }
@@ -3,4 +3,5 @@ export interface StartFacts {
3
3
  block: string;
4
4
  ids: Set<string>;
5
5
  }
6
- export declare function startFacts(ctx: RecallContext, project: string, hidden?: ReadonlySet<string>): Promise<StartFacts | null>;
6
+ export declare function startFacts(ctx: RecallContext, project: string, hidden?: ReadonlySet<string>, current?: string): Promise<StartFacts | null>;
7
+ export declare function recentWorkBlock(ctx: RecallContext, project: string, current?: string, hidden?: ReadonlySet<string>): Promise<StartFacts | null>;
@@ -1,15 +1,17 @@
1
1
  import { openWork } from '../capture/progress.js';
2
2
  import { FACT_SESSION, factType, onePerKey, youScope } from './model.js';
3
- import { newestHandoff, handoffBodyLines } from './handoff.js';
3
+ import { activeRequests } from '../capture/active.js';
4
+ import { handoffBodyLines, handoffHeading, newestHandoff, passedNote } from './handoff.js';
5
+ import { latestRequestAt, recentChats, turnLine } from './last-chat.js';
4
6
  import { MANUAL_SESSION, factLine, seenByClaude } from './render.js';
5
- import { formatDay } from '../util/day.js';
7
+ import { formatDay, formatDayTime } from '../util/day.js';
6
8
  import { toShortId } from '../util/shortid.js';
7
9
  const ABOUT_YOU = 6;
8
10
  const THIS_PROJECT = 10;
9
11
  const TODOS = 4;
10
12
  const UNCOMMITTED = 3;
11
13
  const ORDER = ['rule', 'decision', 'deadend', 'fact'];
12
- export async function startFacts(ctx, project, hidden = new Set()) {
14
+ export async function startFacts(ctx, project, hidden = new Set(), current) {
13
15
  const visible = (obs) => obs.status !== 'replaced' && !hidden.has(obs.id) && !seenByClaude(obs, project);
14
16
  const list = async (owner, sessionId, limit) => (await ctx.store.list({ project: owner, sessionId, newest: true, limit })).filter(visible);
15
17
  const you = onePerKey(await list(youScope(), FACT_SESSION, 50));
@@ -28,11 +30,15 @@ export async function startFacts(ctx, project, hidden = new Set()) {
28
30
  const uncommitted = (await openWork(ctx.store, project))
29
31
  .filter((obs) => !hidden.has(obs.id))
30
32
  .slice(0, UNCOMMITTED);
33
+ const recent = await recentWork(ctx, project, current);
31
34
  const sections = [
32
35
  ['About you:', you.slice(0, ABOUT_YOU).map((obs) => [factLine(obs), obs.id])],
33
36
  ['This project:', known.slice(0, THIS_PROJECT).map((obs) => [factLine(obs), obs.id])],
37
+ ...recentSections(recent, hidden),
34
38
  [
35
- shownHandoff ? `Last handoff (${formatDay(shownHandoff.createdAt)}):` : '',
39
+ shownHandoff
40
+ ? handoffHeading(shownHandoff.createdAt, passedNote(shownHandoff.createdAt, recent.latest))
41
+ : '',
36
42
  shownHandoff ? handoffEntries(shownHandoff) : [],
37
43
  ],
38
44
  [
@@ -43,9 +49,29 @@ export async function startFacts(ctx, project, hidden = new Set()) {
43
49
  ],
44
50
  ],
45
51
  ];
52
+ return render(sections, ctx.config.inject.maxChars);
53
+ }
54
+ async function recentWork(ctx, project, current) {
55
+ const unfinished = activeRequests(await ctx.store.projectScope(project), current);
56
+ const chats = await recentChats(ctx, project, current);
57
+ return { unfinished, chats, latest: latestRequestAt(chats, unfinished) };
58
+ }
59
+ function recentSections(recent, hidden) {
60
+ return [
61
+ ...recent.unfinished.map(unfinishedSection),
62
+ ...recent.chats.map((chat, index) => chatSection(chat, index, hidden)),
63
+ ];
64
+ }
65
+ export async function recentWorkBlock(ctx, project, current, hidden = new Set()) {
66
+ const sections = recentSections(await recentWork(ctx, project, current), hidden);
67
+ return sections.some(([, entries]) => entries.length > 0)
68
+ ? render(sections, ctx.config.inject.maxChars)
69
+ : null;
70
+ }
71
+ function render(sections, maxChars) {
46
72
  const lines = ['<memory>'];
47
73
  const ids = new Set();
48
- let budget = ctx.config.inject.maxChars;
74
+ let budget = maxChars;
49
75
  for (const [heading, entries] of sections) {
50
76
  if (entries.length === 0)
51
77
  continue;
@@ -64,6 +90,19 @@ export async function startFacts(ctx, project, hidden = new Set()) {
64
90
  lines.push('</memory>');
65
91
  return { block: lines.join('\n'), ids };
66
92
  }
93
+ function unfinishedSection(entry) {
94
+ return [
95
+ `Not finished yet in another chat (${formatDayTime(entry.askedAt)}):`,
96
+ [[`- asked "${entry.request}"`, null]],
97
+ ];
98
+ }
99
+ function chatSection(chat, index, hidden) {
100
+ const heading = `${index === 0 ? 'Last chat' : 'Chat before'} (${formatDay(chat.at)}):`;
101
+ const turns = chat.turns
102
+ .filter((turn) => !hidden.has(turn.id))
103
+ .map((turn) => [`- ${turnLine(turn)} (${toShortId(turn.id)})`, turn.id]);
104
+ return [heading, chat.summary ? [[`- Summary: ${chat.summary}`, null], ...turns] : turns];
105
+ }
67
106
  function handoffEntries(handoff) {
68
107
  return handoffBodyLines(handoff).map((line, index) => [
69
108
  index === 0 ? `${line} (${toShortId(handoff.id)})` : line,
@@ -1,3 +1,4 @@
1
1
  export declare const CLI: string;
2
2
  export declare const PICK_WORKER: string;
3
+ export declare const TURN_WORKER: string;
3
4
  export declare function runDetached(script: string, args: string[], cwd: string, release: () => void): void;
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url';
4
4
  const DIST = resolve(dirname(fileURLToPath(import.meta.url)), '..');
5
5
  export const CLI = resolve(DIST, 'cli', 'index.js');
6
6
  export const PICK_WORKER = resolve(DIST, 'pick', 'worker.js');
7
+ export const TURN_WORKER = resolve(DIST, 'hooks', 'turn-save.js');
7
8
  export function runDetached(script, args, cwd, release) {
8
9
  try {
9
10
  spawn(process.execPath, [script, ...args], { cwd, detached: true, stdio: 'ignore' })
@@ -8,6 +8,11 @@ export interface HookPayload {
8
8
  tool_input?: Record<string, unknown>;
9
9
  tool_response?: unknown;
10
10
  prompt?: string;
11
+ last_assistant_message?: string;
12
+ background_tasks?: {
13
+ status?: string;
14
+ }[];
15
+ session_crons?: unknown[];
11
16
  }
12
17
  export declare function capturingDisabled(scripted: boolean): boolean;
13
18
  export declare function readPayload(): Promise<HookPayload>;
@@ -1,4 +1,5 @@
1
1
  import { redact } from '../capture/redact.js';
2
+ import { askedIn } from '../capture/turn-extractor.js';
2
3
  import { meaningfulTokens } from '../search/stopwords.js';
3
4
  import { formatDay } from '../util/day.js';
4
5
  import { toShortId } from '../util/shortid.js';
@@ -46,11 +47,6 @@ export function renderPromptContext(entries, maxChars, expanded = [], expandMaxC
46
47
  return null;
47
48
  return ['<memory>', ...lines, '</memory>'].join('\n');
48
49
  }
49
- const ASKED_CHARS = 120;
50
- function askedIn(body) {
51
- const asked = /^Asked: (.*)$/m.exec(body)?.[1]?.replace(/\s+/g, ' ').trim() ?? '';
52
- return asked.length > ASKED_CHARS ? `${asked.slice(0, ASKED_CHARS)}…` : asked;
53
- }
54
50
  export function renderPicked(picks, maxChars, shown = [], now = Date.now()) {
55
51
  const lines = [];
56
52
  let budget = maxChars;
@@ -11,6 +11,8 @@ import { resolveProject } from '../util/project.js';
11
11
  import { silenceSqliteWarning } from '../util/warnings.js';
12
12
  import { distillInBackground } from './background.js';
13
13
  import { clearPick, sweepPicks } from '../pick/pending.js';
14
+ import { clearActive, sweepActive } from '../capture/active.js';
15
+ import { dropTurnSave, sweepTurnSaves } from './turn-job.js';
14
16
  silenceSqliteWarning();
15
17
  await runHook(async () => {
16
18
  if (capturingDisabled(loadConfig().capture.scripted))
@@ -42,6 +44,10 @@ await runHook(async () => {
42
44
  clearCursor(sessionId);
43
45
  clearPick(sessionId);
44
46
  sweepPicks();
47
+ dropTurnSave(sessionId);
48
+ sweepTurnSaves();
49
+ clearActive(sessionId);
50
+ sweepActive();
45
51
  if (ctx.config.distill.enabled)
46
52
  distillInBackground(project, sessionId);
47
53
  if (ctx.config.updates !== 'off' && isDue(readState())) {
@@ -5,7 +5,7 @@ import { dirname, join, resolve } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { createContext } from '../context.js';
7
7
  import { distillNotice } from '../facts/notice.js';
8
- import { startFacts } from '../facts/start.js';
8
+ import { recentWorkBlock, startFacts } from '../facts/start.js';
9
9
  import { startBackgroundWork } from './background.js';
10
10
  import { refreshGraphInBackground } from './graph-refresh.js';
11
11
  import { recoverAfterCompact } from './compact.js';
@@ -61,12 +61,15 @@ await runHook(async () => {
61
61
  ? await recoverAfterCompact(ctx, project, payload.session_id, payload.transcript_path)
62
62
  : null;
63
63
  const restored = earlier?.ids ?? new Set();
64
- const facts = await startFacts(ctx, project, restored);
64
+ const facts = await startFacts(ctx, project, restored, payload.session_id);
65
+ const recent = facts ? null : await recentWorkBlock(ctx, project, payload.session_id, restored);
65
66
  const legacy = facts ? null : await legacyBlock(ctx, project, restored);
66
- if (facts && payload.session_id)
67
- markShown(payload.session_id, [...facts.ids]);
68
- const parts = [earlier?.block, facts?.block ?? legacy?.text].filter((part) => Boolean(part));
69
- if ((facts || legacy?.hasMemory) && mcpRegistered(project)) {
67
+ const shown = [...(facts?.ids ?? []), ...(recent?.ids ?? [])];
68
+ if (shown.length > 0 && payload.session_id)
69
+ markShown(payload.session_id, shown);
70
+ const fallback = legacy?.hasMemory || !recent ? legacy?.text : undefined;
71
+ const parts = [earlier?.block, facts?.block ?? fallback, recent?.block].filter((part) => Boolean(part));
72
+ if ((facts || recent || legacy?.hasMemory) && mcpRegistered(project)) {
70
73
  parts.push("Search this project's full history with the memory MCP tools before " +
71
74
  'asking the user to re-explain prior decisions.');
72
75
  }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import { activeToken } from '../capture/active.js';
3
+ import { loadConfig } from '../config/index.js';
4
+ import { resolveProject } from '../util/project.js';
5
+ import { TURN_WORKER, runDetached } from './detached.js';
6
+ import { capturingDisabled, readPayload, runHook } from './payload.js';
7
+ import { queueTurnSave } from './turn-job.js';
8
+ await runHook(async () => {
9
+ if (capturingDisabled(loadConfig().capture.scripted))
10
+ return;
11
+ const payload = await readPayload();
12
+ const sessionId = payload.session_id;
13
+ if (!sessionId)
14
+ return;
15
+ const project = resolveProject(payload.cwd);
16
+ const tasks = Array.isArray(payload.background_tasks) ? payload.background_tasks : [];
17
+ const crons = Array.isArray(payload.session_crons) ? payload.session_crons : [];
18
+ const stillWorking = crons.length > 0 || tasks.some((task) => task?.status === 'running');
19
+ queueTurnSave(sessionId, {
20
+ project,
21
+ ...(payload.transcript_path ? { transcriptPath: payload.transcript_path } : {}),
22
+ finalReply: payload.last_assistant_message ?? '',
23
+ activeToken: stillWorking ? null : activeToken(sessionId),
24
+ });
25
+ runDetached(TURN_WORKER, [sessionId], project, () => { });
26
+ });
@@ -0,0 +1,10 @@
1
+ export interface TurnJob {
2
+ project: string;
3
+ transcriptPath?: string;
4
+ finalReply: string;
5
+ activeToken: string | null;
6
+ }
7
+ export declare function queueTurnSave(sessionId: string, job: TurnJob): void;
8
+ export declare function takeTurnSave(sessionId: string): TurnJob | null;
9
+ export declare function dropTurnSave(sessionId: string): void;
10
+ export declare function sweepTurnSaves(now?: number): void;
@@ -0,0 +1,30 @@
1
+ import { rmSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { CONFIG_DIR } from '../config/dir.js';
4
+ import { readJson, safeName, sweepOlderThan, writeJsonAtomic } from '../util/json-file.js';
5
+ const KEPT_FOR_MS = 24 * 60 * 60 * 1000;
6
+ function folder() {
7
+ return join(CONFIG_DIR, 'turns');
8
+ }
9
+ function fileFor(sessionId) {
10
+ return join(folder(), `${safeName(sessionId)}.json`);
11
+ }
12
+ export function queueTurnSave(sessionId, job) {
13
+ writeJsonAtomic(fileFor(sessionId), job);
14
+ }
15
+ export function takeTurnSave(sessionId) {
16
+ const file = fileFor(sessionId);
17
+ const job = readJson(file);
18
+ rmSync(file, { force: true });
19
+ const valid = typeof job?.project === 'string' &&
20
+ typeof job.finalReply === 'string' &&
21
+ (job.transcriptPath === undefined || typeof job.transcriptPath === 'string') &&
22
+ (job.activeToken === null || typeof job.activeToken === 'string');
23
+ return valid ? job : null;
24
+ }
25
+ export function dropTurnSave(sessionId) {
26
+ rmSync(fileFor(sessionId), { force: true });
27
+ }
28
+ export function sweepTurnSaves(now = Date.now()) {
29
+ sweepOlderThan(folder(), KEPT_FOR_MS, now);
30
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import { clearActive } from '../capture/active.js';
3
+ import { flushSession } from '../capture/index.js';
4
+ import { createContext } from '../context.js';
5
+ import { silenceSqliteWarning } from '../util/warnings.js';
6
+ import { runHook } from './payload.js';
7
+ import { takeTurnSave } from './turn-job.js';
8
+ silenceSqliteWarning();
9
+ await runHook(async () => {
10
+ const [sessionId] = process.argv.slice(2);
11
+ if (!sessionId)
12
+ return;
13
+ const job = takeTurnSave(sessionId);
14
+ if (!job)
15
+ return;
16
+ const ctx = await createContext();
17
+ try {
18
+ await flushSession(ctx, sessionId, job.project, job.transcriptPath, false, job.finalReply);
19
+ }
20
+ finally {
21
+ await ctx.close();
22
+ }
23
+ if (job.activeToken)
24
+ clearActive(sessionId, job.activeToken);
25
+ });
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { recordActive } from '../capture/active.js';
2
3
  import { flushSession, redact } from '../capture/index.js';
3
4
  import { createContext } from '../context.js';
4
5
  import { capturingDisabled, emitContext, readPayload, runHook } from './payload.js';
@@ -22,6 +23,7 @@ await runHook(async () => {
22
23
  const ctx = await createContext();
23
24
  try {
24
25
  await ctx.store.upsertSession({ id: sessionId, project, startedAt: Date.now() });
26
+ recordActive(sessionId, project, payload.prompt ?? '');
25
27
  const { lastReply } = await flushSession(ctx, sessionId, project, payload.transcript_path);
26
28
  const candidates = await promptCandidates(ctx, {
27
29
  prompt: payload.prompt ?? '',
@@ -1,32 +1,16 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
2
+ import { renameSync, rmSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { CONFIG_DIR } from '../config/dir.js';
5
+ import { readJson, safeName, sweepOlderThan, writeJsonAtomic } from '../util/json-file.js';
5
6
  const STALE_MS = 10 * 60 * 1000;
6
7
  const ORPHAN_MS = 24 * 60 * 60 * 1000;
7
8
  const TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
8
9
  function folder() {
9
10
  return join(CONFIG_DIR, 'pick', 'pending');
10
11
  }
11
- function safe(sessionId) {
12
- return sessionId.replace(/[^\w-]/g, '_');
13
- }
14
12
  function path(sessionId, suffix) {
15
- return join(folder(), `${safe(sessionId)}${suffix}`);
16
- }
17
- function readJson(file) {
18
- try {
19
- return JSON.parse(readFileSync(file, 'utf8'));
20
- }
21
- catch {
22
- return null;
23
- }
24
- }
25
- function writeAtomic(file, value) {
26
- mkdirSync(folder(), { recursive: true });
27
- const temp = `${file}.${randomUUID()}.tmp`;
28
- writeFileSync(temp, JSON.stringify(value), 'utf8');
29
- renameSync(temp, file);
13
+ return join(folder(), `${safeName(sessionId)}${suffix}`);
30
14
  }
31
15
  function isToken(value) {
32
16
  return typeof value === 'string' && TOKEN.test(value);
@@ -40,27 +24,13 @@ export function clearPick(sessionId) {
40
24
  rmSync(path(sessionId, '.json'), { force: true });
41
25
  }
42
26
  export function sweepPicks(now = Date.now()) {
43
- let names;
44
- try {
45
- names = readdirSync(folder());
46
- }
47
- catch {
48
- return;
49
- }
50
- for (const name of names) {
51
- const file = join(folder(), name);
52
- try {
53
- if (now - statSync(file).mtimeMs > ORPHAN_MS)
54
- rmSync(file, { force: true });
55
- }
56
- catch { }
57
- }
27
+ sweepOlderThan(folder(), ORPHAN_MS, now);
58
28
  }
59
29
  export function startPick(sessionId, job, now = Date.now()) {
60
30
  clearPick(sessionId);
61
31
  const token = randomUUID();
62
- writeAtomic(path(sessionId, `.${token}.job.json`), job);
63
- writeAtomic(path(sessionId, '.json'), { token, startedAt: now });
32
+ writeJsonAtomic(path(sessionId, `.${token}.job.json`), job);
33
+ writeJsonAtomic(path(sessionId, '.json'), { token, startedAt: now });
64
34
  return token;
65
35
  }
66
36
  export function takeJob(sessionId, token) {
@@ -85,7 +55,7 @@ function current(sessionId, now) {
85
55
  export function finishPick(sessionId, token, ready, now = Date.now()) {
86
56
  if (current(sessionId, now)?.token !== token)
87
57
  return false;
88
- writeAtomic(path(sessionId, `.${token}.ready.json`), ready);
58
+ writeJsonAtomic(path(sessionId, `.${token}.ready.json`), ready);
89
59
  return true;
90
60
  }
91
61
  export function takeReady(sessionId, now = Date.now()) {
@@ -5,4 +5,5 @@ export interface VectorCache {
5
5
  atlasVectorIndex: boolean | null;
6
6
  }
7
7
  export declare function scopeFilter(query: SearchQuery): Doc;
8
+ export declare function sessionMatch(only: string | undefined, exclude: string[] | undefined): Doc;
8
9
  export declare function visibleFilter(query: SearchQuery): Doc;
@@ -23,11 +23,17 @@ export function scopeFilter(query) {
23
23
  }
24
24
  return filter;
25
25
  }
26
+ export function sessionMatch(only, exclude) {
27
+ const match = {};
28
+ if (only)
29
+ match['$eq'] = only;
30
+ if (exclude && exclude.length > 0)
31
+ match['$nin'] = exclude;
32
+ return Object.keys(match).length === 0 ? {} : { sessionId: match };
33
+ }
26
34
  export function visibleFilter(query) {
27
35
  return {
28
36
  status: { $ne: 'replaced' },
29
- ...(query.excludeSessions && query.excludeSessions.length > 0
30
- ? { sessionId: { $nin: query.excludeSessions } }
31
- : {}),
37
+ ...sessionMatch(undefined, query.excludeSessions),
32
38
  };
33
39
  }
@@ -1,6 +1,6 @@
1
1
  import { isWholeScope } from '../adapter.js';
2
2
  import { toDoc, toObservation } from './docs.js';
3
- import { projectMatch } from './filters.js';
3
+ import { projectMatch, sessionMatch } from './filters.js';
4
4
  import { escapeRegex } from './helpers.js';
5
5
  import { partitionIds } from '../../util/shortid.js';
6
6
  import { noProjects } from '../project-scope.js';
@@ -65,8 +65,7 @@ export async function list(observations, sessions, symbols, edges, scanned, filt
65
65
  return [];
66
66
  const query = {};
67
67
  Object.assign(query, projectMatch(filter.project));
68
- if (filter.sessionId)
69
- query['sessionId'] = filter.sessionId;
68
+ Object.assign(query, sessionMatch(filter.sessionId, filter.excludeSessions));
70
69
  if (filter.kind)
71
70
  query['kind'] = filter.kind;
72
71
  if (filter.status)
@@ -1,3 +1,4 @@
1
1
  import type { ProjectFilter, SearchQuery } from '../../types.js';
2
2
  export declare function projectClause(filter: ProjectFilter | undefined, values: unknown[], column?: string): string | null;
3
+ export declare function excludeSessionsClause(sessions: string[] | undefined, values: unknown[]): string | null;
3
4
  export declare function appendScope(query: SearchQuery, conditions: string[], values: unknown[]): void;
@@ -6,6 +6,12 @@ export function projectClause(filter, values, column = 'project') {
6
6
  values.push(projects);
7
7
  return `${column} = ANY($${values.length}::text[])`;
8
8
  }
9
+ export function excludeSessionsClause(sessions, values) {
10
+ if (!sessions || sessions.length === 0)
11
+ return null;
12
+ values.push(sessions);
13
+ return `session_id <> ALL($${values.length}::text[])`;
14
+ }
9
15
  export function appendScope(query, conditions, values) {
10
16
  conditions.push("status <> 'replaced'");
11
17
  const project = projectClause(query.project, values);
@@ -27,8 +33,7 @@ export function appendScope(query, conditions, values) {
27
33
  values.push(query.until);
28
34
  conditions.push(`created_at <= $${values.length}`);
29
35
  }
30
- if (query.excludeSessions && query.excludeSessions.length > 0) {
31
- values.push(query.excludeSessions);
32
- conditions.push(`session_id <> ALL($${values.length}::text[])`);
33
- }
36
+ const excluded = excludeSessionsClause(query.excludeSessions, values);
37
+ if (excluded)
38
+ conditions.push(excluded);
34
39
  }
@@ -1,6 +1,6 @@
1
1
  import { foreignNames, isWholeScope } from '../adapter.js';
2
2
  import { partitionIds } from '../../util/shortid.js';
3
- import { projectClause } from './filters.js';
3
+ import { excludeSessionsClause, projectClause } from './filters.js';
4
4
  import { toIndexEntry, toObservation } from './rows.js';
5
5
  import { noProjects } from '../project-scope.js';
6
6
  export async function getObservations(pool, ids) {
@@ -88,6 +88,9 @@ export async function list(pool, filter) {
88
88
  values.push(filter.sessionId);
89
89
  conditions.push(`session_id = $${values.length}`);
90
90
  }
91
+ const excluded = excludeSessionsClause(filter.excludeSessions, values);
92
+ if (excluded)
93
+ conditions.push(excluded);
91
94
  if (filter.kind) {
92
95
  values.push(filter.kind);
93
96
  conditions.push(`kind = $${values.length}`);
@@ -1,5 +1,6 @@
1
1
  import type { ProjectFilter, RemoveFilter, SearchQuery } from '../../types.js';
2
2
  export declare function projectClause(column: string, filter: ProjectFilter | undefined, params: unknown[]): string | null;
3
+ export declare function excludeSessionsClause(column: string, sessions: string[] | undefined, params: unknown[]): string | null;
3
4
  export declare function removeWhere(filter: RemoveFilter): {
4
5
  where: string;
5
6
  params: unknown[];
@@ -12,6 +12,12 @@ export function projectClause(column, filter, params) {
12
12
  ? `${column} = ?`
13
13
  : `${column} IN (${projects.map(() => '?').join(',')})`;
14
14
  }
15
+ export function excludeSessionsClause(column, sessions, params) {
16
+ if (!sessions || sessions.length === 0)
17
+ return null;
18
+ params.push(...sessions);
19
+ return `${column} NOT IN (${sessions.map(() => '?').join(',')})`;
20
+ }
15
21
  export function removeWhere(filter) {
16
22
  const conditions = [];
17
23
  const params = [];
@@ -66,10 +72,9 @@ export function appendScope(query, conditions, params, prefix) {
66
72
  conditions.push(`${prefix}created_at <= ?`);
67
73
  params.push(query.until);
68
74
  }
69
- if (query.excludeSessions && query.excludeSessions.length > 0) {
70
- conditions.push(`${prefix}session_id NOT IN (${query.excludeSessions.map(() => '?').join(',')})`);
71
- params.push(...query.excludeSessions);
72
- }
75
+ const excluded = excludeSessionsClause(`${prefix}session_id`, query.excludeSessions, params);
76
+ if (excluded)
77
+ conditions.push(excluded);
73
78
  }
74
79
  function scopeExpression(filter) {
75
80
  const tokens = projectsOf(filter).map(scopeToken);
@@ -1,6 +1,6 @@
1
1
  import { foreignNames, isWholeScope } from '../adapter.js';
2
2
  import { toObservation } from './rows.js';
3
- import { projectClause, removeWhere } from './filters.js';
3
+ import { excludeSessionsClause, projectClause, removeWhere } from './filters.js';
4
4
  import { partitionIds } from '../../util/shortid.js';
5
5
  import { packVector } from '../../util/vector.js';
6
6
  import { scopeToken } from '../../util/scope.js';
@@ -88,6 +88,9 @@ export async function list(db, filter) {
88
88
  conditions.push('session_id = ?');
89
89
  params.push(filter.sessionId);
90
90
  }
91
+ const excluded = excludeSessionsClause('session_id', filter.excludeSessions, params);
92
+ if (excluded)
93
+ conditions.push(excluded);
91
94
  if (filter.kind) {
92
95
  conditions.push('kind = ?');
93
96
  params.push(filter.kind);
@@ -1,5 +1,5 @@
1
1
  import { toBuffer, toIndexEntry } from './rows.js';
2
- import { TAG_PREDICATE, appendScope, toMatchExpression } from './filters.js';
2
+ import { TAG_PREDICATE, appendScope, excludeSessionsClause, toMatchExpression } from './filters.js';
3
3
  import { cosine, unpackVector } from '../../util/vector.js';
4
4
  import { noProjects } from '../project-scope.js';
5
5
  export async function searchKeyword(db, query) {
@@ -26,10 +26,9 @@ export async function searchKeyword(db, query) {
26
26
  conditions.push('o.created_at <= ?');
27
27
  params.push(query.until);
28
28
  }
29
- if (query.excludeSessions && query.excludeSessions.length > 0) {
30
- conditions.push(`o.session_id NOT IN (${query.excludeSessions.map(() => '?').join(',')})`);
31
- params.push(...query.excludeSessions);
32
- }
29
+ const excluded = excludeSessionsClause('o.session_id', query.excludeSessions, params);
30
+ if (excluded)
31
+ conditions.push(excluded);
33
32
  params.push(query.limit);
34
33
  const rows = db
35
34
  .prepare(`SELECT o.id, o.kind, o.title, o.project, o.created_at,
package/dist/types.d.ts CHANGED
@@ -55,6 +55,7 @@ export interface RemoveFilter {
55
55
  export interface ListFilter {
56
56
  project?: ProjectFilter;
57
57
  sessionId?: string;
58
+ excludeSessions?: string[];
58
59
  kind?: ObservationKind;
59
60
  status?: ObservationStatus;
60
61
  after?: number;
@@ -1 +1,2 @@
1
+ export declare function formatDayTime(at: number, now?: number): string;
1
2
  export declare function formatDay(at: number, now?: number): string;
package/dist/util/day.js CHANGED
@@ -4,6 +4,10 @@ const OTHER_YEAR = new Intl.DateTimeFormat('en-US', {
4
4
  day: 'numeric',
5
5
  year: 'numeric',
6
6
  });
7
+ const CLOCK = new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit' });
8
+ export function formatDayTime(at, now = Date.now()) {
9
+ return `${formatDay(at, now)}, ${CLOCK.format(new Date(at))}`;
10
+ }
7
11
  export function formatDay(at, now = Date.now()) {
8
12
  const date = new Date(at);
9
13
  const format = date.getFullYear() === new Date(now).getFullYear() ? THIS_YEAR : OTHER_YEAR;
@@ -0,0 +1,4 @@
1
+ export declare function safeName(id: string): string;
2
+ export declare function readJson<T>(file: string): T | null;
3
+ export declare function writeJsonAtomic(file: string, value: unknown): void;
4
+ export declare function sweepOlderThan(folder: string, maxAgeMs: number, now?: number): void;
@@ -0,0 +1,37 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ export function safeName(id) {
5
+ return id.replace(/[^\w-]/g, '_');
6
+ }
7
+ export function readJson(file) {
8
+ try {
9
+ return JSON.parse(readFileSync(file, 'utf8'));
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ }
15
+ export function writeJsonAtomic(file, value) {
16
+ mkdirSync(dirname(file), { recursive: true });
17
+ const temp = `${file}.${randomUUID()}.tmp`;
18
+ writeFileSync(temp, JSON.stringify(value), 'utf8');
19
+ renameSync(temp, file);
20
+ }
21
+ export function sweepOlderThan(folder, maxAgeMs, now = Date.now()) {
22
+ let names;
23
+ try {
24
+ names = readdirSync(folder);
25
+ }
26
+ catch {
27
+ return;
28
+ }
29
+ for (const name of names) {
30
+ const file = join(folder, name);
31
+ try {
32
+ if (now - statSync(file).mtimeMs > maxAgeMs)
33
+ rmSync(file, { force: true });
34
+ }
35
+ catch { }
36
+ }
37
+ }
@@ -25,6 +25,10 @@ you send a prompt
25
25
  Both steps are hooks, so they always run. Nothing depends on Claude deciding to
26
26
  look something up.
27
27
 
28
+ A turn is also saved as soon as Claude finishes the reply, in the background, so
29
+ another chat sees it without waiting for your next prompt. The save at the next
30
+ prompt stays as the backup, for a reply you interrupted.
31
+
28
32
  Install also writes a short standing instruction into `CLAUDE.local.md` (or
29
33
  `~/.claude/CLAUDE.md` for a machine-wide install), telling Claude to search
30
34
  memory before asking you to re-explain something. Hook output is context the
@@ -36,7 +40,8 @@ for. `claude-db uninstall` takes the block back out.
36
40
  file or ran a real command. Questions, `grep`, and "ok" are skipped. A busy day
37
41
  produces 10 to 20 rows, not hundreds.
38
42
 
39
- **What gets injected.** Recent session summaries at startup. Above a prompt, at
43
+ **What gets injected.** At startup: facts, the newest 5 requests from other
44
+ chats, any request another chat has not finished, and the handoff note. Above a prompt, at
40
45
  most two memories from earlier chats, picked by Claude Haiku:
41
46
 
42
47
  1. Search finds the ten closest memories from other chats. If none shares at
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-db",
3
- "version": "0.12.1",
3
+ "version": "0.12.2",
4
4
  "description": "Free, open-source memory for Claude Code. Remembers why decisions were made and maps your code. Your own database (SQLite, Postgres or MongoDB), no cloud, no subscription.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -130,10 +130,10 @@
130
130
  "access": "public"
131
131
  },
132
132
  "optionalDependencies": {
133
- "claude-db-grammars-linux-x64": "0.12.1",
134
- "claude-db-grammars-linux-arm64": "0.12.1",
135
- "claude-db-grammars-darwin-x64": "0.12.1",
136
- "claude-db-grammars-darwin-arm64": "0.12.1",
137
- "claude-db-grammars-win32-x64": "0.12.1"
133
+ "claude-db-grammars-linux-x64": "0.12.2",
134
+ "claude-db-grammars-linux-arm64": "0.12.2",
135
+ "claude-db-grammars-darwin-x64": "0.12.2",
136
+ "claude-db-grammars-darwin-arm64": "0.12.2",
137
+ "claude-db-grammars-win32-x64": "0.12.2"
138
138
  }
139
139
  }
@@ -14,8 +14,12 @@ claude-db catchup
14
14
  It prints what memory and git know about this project, in plain text. Some parts may be missing. A part
15
15
  with nothing in it is left out.
16
16
 
17
- - `Last handoff` is a note the user or a teammate saved on purpose. Trust it most.
18
- - `Last chat` is the newest recorded chat, with a few lines of the work done in it.
17
+ - `Last handoff` is a note the user or a teammate saved on purpose. Trust it most, unless its heading says
18
+ `older than the last chat`. Then the last chat is newer, and wins where they differ.
19
+ - `Not finished yet in another chat` is a request another chat is still working on, or that was stopped.
20
+ Say so under **Open**.
21
+ - `Last chat` and `Chat before` are the other chats with the newest recorded requests, open or ended, newest
22
+ first: the 5 newest requests in all.
19
23
  - `Still to do` are to-dos found in earlier chats.
20
24
  - `Not committed yet` is recorded work that no commit has covered.
21
25
  - `Decisions and dead ends` are what was chosen or ruled out, with the reason.