claude-db 0.12.0 → 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 (59) hide show
  1. package/CHANGELOG.md +18 -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/commands/pick.js +4 -2
  17. package/dist/cli/install.js +1 -0
  18. package/dist/facts/handoff.d.ts +2 -0
  19. package/dist/facts/handoff.js +7 -0
  20. package/dist/facts/last-chat.d.ts +13 -0
  21. package/dist/facts/last-chat.js +45 -0
  22. package/dist/facts/start.d.ts +2 -1
  23. package/dist/facts/start.js +44 -5
  24. package/dist/hooks/detached.d.ts +1 -0
  25. package/dist/hooks/detached.js +1 -0
  26. package/dist/hooks/payload.d.ts +5 -0
  27. package/dist/hooks/relevance.js +1 -5
  28. package/dist/hooks/session-end.js +6 -0
  29. package/dist/hooks/session-start.js +9 -6
  30. package/dist/hooks/turn-end.d.ts +2 -0
  31. package/dist/hooks/turn-end.js +26 -0
  32. package/dist/hooks/turn-job.d.ts +10 -0
  33. package/dist/hooks/turn-job.js +30 -0
  34. package/dist/hooks/turn-save.d.ts +2 -0
  35. package/dist/hooks/turn-save.js +25 -0
  36. package/dist/hooks/user-prompt.js +2 -0
  37. package/dist/pick/pending.js +7 -37
  38. package/dist/pick/run.d.ts +6 -0
  39. package/dist/pick/run.js +8 -1
  40. package/dist/store/mongo/filters.d.ts +1 -0
  41. package/dist/store/mongo/filters.js +9 -3
  42. package/dist/store/mongo/observations.js +2 -3
  43. package/dist/store/postgres/filters.d.ts +1 -0
  44. package/dist/store/postgres/filters.js +9 -4
  45. package/dist/store/postgres/observations.js +4 -1
  46. package/dist/store/sqlite/filters.d.ts +1 -0
  47. package/dist/store/sqlite/filters.js +9 -4
  48. package/dist/store/sqlite/observations.js +4 -1
  49. package/dist/store/sqlite/search.js +4 -5
  50. package/dist/types.d.ts +1 -0
  51. package/dist/util/claude-cli.d.ts +1 -0
  52. package/dist/util/claude-cli.js +15 -3
  53. package/dist/util/day.d.ts +1 -0
  54. package/dist/util/day.js +4 -0
  55. package/dist/util/json-file.d.ts +4 -0
  56. package/dist/util/json-file.js +37 -0
  57. package/docs/how-it-works.md +6 -1
  58. package/package.json +6 -6
  59. package/skills/catchup/SKILL.md +6 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
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
+
13
+ ## 0.12.1
14
+
15
+ ### Changed
16
+
17
+ - **Memories shown with a prompt are picked by Haiku 5.5.** When the account or provider cannot use it, the
18
+ pick falls back to `haiku` on its own. `claude-db pick` shows both. Turning chats into facts still uses
19
+ `haiku`.
20
+
3
21
  ## 0.12.0
4
22
 
5
23
  ### Added
@@ -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();
@@ -1,5 +1,5 @@
1
1
  import { loadConfig, setConfigValue } from '../../config/index.js';
2
- import { PICK_BUDGET } from '../../pick/run.js';
2
+ import { PICK_BUDGET, pickModel } from '../../pick/run.js';
3
3
  import { budgetUsage, describePause } from '../../util/daily-budget.js';
4
4
  export function pickStatus(config, now = Date.now()) {
5
5
  const { pick } = config;
@@ -9,7 +9,9 @@ export function pickStatus(config, now = Date.now()) {
9
9
  const usage = budgetUsage(PICK_BUDGET, now);
10
10
  const pause = describePause(usage, now);
11
11
  const paused = pause ? `, paused ${pause}` : '';
12
- return `pick : on (${pick.model}), ${usage.used} of ${pick.dailyLimit} picks used today${paused}`;
12
+ const { model, fallback } = pickModel(config);
13
+ const models = fallback ? `${model}, else ${fallback}` : model;
14
+ return `pick : on (${models}), ${usage.used} of ${pick.dailyLimit} picks used today${paused}`;
13
15
  }
14
16
  export function cmdPick(argv) {
15
17
  const [first] = argv;
@@ -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>;