claude-db 0.10.1 → 0.10.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,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.10.3
4
+
5
+ ### Fixed
6
+
7
+ - **Picks and facts can now find Claude when `claude` is not on `PATH`.** Both call
8
+ Claude through its binary. Claude Code does not pass that path to its hooks, so
9
+ on a machine where `claude` is not on `PATH`, for example when Claude Code runs
10
+ inside an editor, every call failed with `claude was not found`, and the feature
11
+ paused. Each hook now looks up the Claude process that started it and saves
12
+ its path in `~/.claude-memory/claude-binary`. Background jobs and commands run
13
+ in a terminal use that path when `CLAUDE_CODE_EXECPATH` is not set. A saved path
14
+ that no longer exists, for example after an editor update, is replaced by the
15
+ next hook run. Linux and macOS only.
16
+
17
+ ## 0.10.2
18
+
19
+ ### Changed
20
+
21
+ - **A failed Haiku call now says why, and pauses grow instead of staying fixed.**
22
+ `status`, `pick` and `distill` print the reason, for example `paused until
23
+ ... after a failed call: exited with code 1: error: not logged in`, or `timed
24
+ out after 30 s`, or `claude was not found`. Before, they only said a call
25
+ failed, and the cause could not be found. The first failure pauses the
26
+ feature for an hour, a second in a row for six hours, and later ones for a
27
+ day; a working call resets it. Facts used to lose a whole day to one
28
+ failure. The command line, which holds the prompt, is never part of the
29
+ reason.
30
+
3
31
  ## 0.10.1
4
32
 
5
33
  ### Fixed
@@ -3,6 +3,7 @@ import { createContext } from '../../context.js';
3
3
  import { distillUsage } from '../../facts/budget.js';
4
4
  import { importClaudeMemory } from '../../facts/claude-memory.js';
5
5
  import { FACTS_JOB, backfill, distillSession, factCounts, pendingSessions, } from '../../facts/distill.js';
6
+ import { describePause } from '../../util/daily-budget.js';
6
7
  import { finishJob, releaseJob } from '../../util/job-lock.js';
7
8
  import { resolveProject } from '../../util/project.js';
8
9
  export async function cmdDistill(argv) {
@@ -57,9 +58,9 @@ async function printStatus(ctx, project) {
57
58
  const facts = await factCounts(ctx, project);
58
59
  console.log(`distill : ${distill.enabled ? 'on' : 'off'} (${distill.model})`);
59
60
  console.log(`today : ${usage.used} of ${distill.dailyLimit} calls used`);
60
- if (usage.pausedUntil > Date.now()) {
61
- console.log(`paused : until ${new Date(usage.pausedUntil).toISOString()} after a failed call`);
62
- }
61
+ const pause = describePause(usage);
62
+ if (pause)
63
+ console.log(`paused : ${pause}`);
63
64
  console.log(`facts : ${facts.project} for this project, ${facts.you} about you`);
64
65
  console.log(`waiting : ${(await pendingSessions(ctx, project)).length} chat(s) not yet turned into facts`);
65
66
  if (!distill.enabled)
@@ -1,15 +1,14 @@
1
1
  import { loadConfig, setConfigValue } from '../../config/index.js';
2
2
  import { PICK_BUDGET } from '../../pick/run.js';
3
- import { budgetUsage } from '../../util/daily-budget.js';
3
+ import { budgetUsage, describePause } from '../../util/daily-budget.js';
4
4
  export function pickStatus(config, now = Date.now()) {
5
5
  const { pick } = config;
6
6
  if (!pick.enabled) {
7
7
  return 'pick : off, prompts get memory only on a strong word match (claude-db pick on)';
8
8
  }
9
9
  const usage = budgetUsage(PICK_BUDGET, now);
10
- const paused = usage.pausedUntil > now
11
- ? `, paused until ${new Date(usage.pausedUntil).toISOString()} after a failed call`
12
- : '';
10
+ const pause = describePause(usage, now);
11
+ const paused = pause ? `, paused ${pause}` : '';
13
12
  return `pick : on (${pick.model}), ${usage.used} of ${pick.dailyLimit} picks used today${paused}`;
14
13
  }
15
14
  export function cmdPick(argv) {
@@ -1,4 +1,5 @@
1
1
  import type { BudgetUsage } from '../util/daily-budget.js';
2
2
  export declare function distillUsage(now?: number): BudgetUsage;
3
3
  export declare function takeDistillCalls(limit: number, count: number, now?: number): boolean;
4
- export declare function pauseDistill(now?: number): void;
4
+ export declare function recordDistillFailure(reason: string, now?: number): void;
5
+ export declare function recordDistillSuccess(now?: number): void;
@@ -1,12 +1,15 @@
1
- import { budgetUsage, pauseBudget, takeBudget } from '../util/daily-budget.js';
1
+ import { redact } from '../capture/redact.js';
2
+ import { budgetUsage, recordFailure, recordSuccess, takeBudget } from '../util/daily-budget.js';
2
3
  const BUDGET = 'distill';
3
- const PAUSE_MS = 24 * 60 * 60 * 1000;
4
4
  export function distillUsage(now = Date.now()) {
5
5
  return budgetUsage(BUDGET, now);
6
6
  }
7
7
  export function takeDistillCalls(limit, count, now = Date.now()) {
8
8
  return takeBudget(BUDGET, limit, count, now);
9
9
  }
10
- export function pauseDistill(now = Date.now()) {
11
- pauseBudget(BUDGET, PAUSE_MS, now);
10
+ export function recordDistillFailure(reason, now = Date.now()) {
11
+ recordFailure(BUDGET, redact(reason), now);
12
+ }
13
+ export function recordDistillSuccess(now = Date.now()) {
14
+ recordSuccess(BUDGET, now);
12
15
  }
@@ -1,8 +1,9 @@
1
1
  import type { RecallContext } from '../context.js';
2
2
  import type { Observation } from '../types.js';
3
+ import type { HeadlessResult } from '../util/claude-cli.js';
3
4
  import type { ExistingFact } from './ops.js';
4
5
  export declare const FACTS_JOB = "facts";
5
- export type Runner = (prompt: string, model: string, timeoutMs: number) => Promise<string | null>;
6
+ export type Runner = (prompt: string, model: string, timeoutMs: number) => Promise<HeadlessResult>;
6
7
  export type DistillOutcome = 'distilled' | 'empty' | 'over-budget' | 'failed';
7
8
  export interface DistillResult {
8
9
  outcome: DistillOutcome;
@@ -1,7 +1,7 @@
1
1
  import { embedObservations } from '../capture/flush.js';
2
- import { runHeadless } from '../util/claude-cli.js';
2
+ import { runHeadlessResult } from '../util/claude-cli.js';
3
3
  import { formatDay } from '../util/day.js';
4
- import { pauseDistill, takeDistillCalls } from './budget.js';
4
+ import { recordDistillFailure, recordDistillSuccess, takeDistillCalls } from './budget.js';
5
5
  import { FACT_SESSION, factId, factKey, factToObservation, factType, youScope } from './model.js';
6
6
  import { buildDistillPrompt, parseOps } from './ops.js';
7
7
  export const FACTS_JOB = 'facts';
@@ -13,7 +13,7 @@ const SEPARATOR = '\n\n---\n\n';
13
13
  const EXISTING_LIMIT = 80;
14
14
  const SESSION_ROWS = 1000;
15
15
  const TIMEOUT_MS = 120_000;
16
- export async function distillSession(ctx, project, sessionId, run = runHeadless) {
16
+ export async function distillSession(ctx, project, sessionId, run = runHeadlessResult) {
17
17
  const rows = (await ctx.store.list({ project, sessionId, limit: SESSION_ROWS })).filter((obs) => obs.status !== 'replaced');
18
18
  const last = rows[rows.length - 1];
19
19
  if (!last) {
@@ -31,8 +31,8 @@ export async function distillSession(ctx, project, sessionId, run = runHeadless)
31
31
  let summary = [];
32
32
  for (const window of windows) {
33
33
  const applied = await distillWindow(ctx, project, window, source, last.createdAt, run);
34
- if (!applied) {
35
- pauseDistill();
34
+ if (!applied.ok) {
35
+ recordDistillFailure(applied.reason);
36
36
  return { outcome: 'failed', set, retired };
37
37
  }
38
38
  set += applied.set;
@@ -40,16 +40,17 @@ export async function distillSession(ctx, project, sessionId, run = runHeadless)
40
40
  if (applied.texts.length > 0)
41
41
  summary = applied.texts;
42
42
  }
43
+ recordDistillSuccess();
43
44
  const startedAt = rows[0]?.createdAt ?? last.createdAt;
44
45
  await markDistilled(ctx, project, sessionId, startedAt, summary.slice(0, 3).join(' | '));
45
46
  return { outcome: 'distilled', set, retired };
46
47
  }
47
48
  async function distillWindow(ctx, project, chat, source, at, run) {
48
49
  const existing = await existingFacts(ctx, project);
49
- const stdout = await run(buildDistillPrompt(chat, existing), ctx.config.distill.model, TIMEOUT_MS);
50
- if (stdout === null)
51
- return null;
52
- const ops = parseOps(stdout);
50
+ const reply = await run(buildDistillPrompt(chat, existing), ctx.config.distill.model, TIMEOUT_MS);
51
+ if (!reply.ok)
52
+ return { ok: false, reason: reply.reason };
53
+ const ops = parseOps(reply.stdout);
53
54
  const sets = ops
54
55
  .filter((op) => op.op === 'set')
55
56
  .map((op) => (op.type === 'rule' ? op : { ...op, scope: 'project' }));
@@ -62,7 +63,7 @@ async function distillWindow(ctx, project, chat, source, at, run) {
62
63
  .flatMap((op) => existing.filter((fact) => fact.key === op.key))
63
64
  .map((fact) => factId(fact.scope === 'you' ? youScope() : project, fact.key));
64
65
  const retired = await ctx.store.markReplaced(retiring);
65
- return { set: facts.length, retired, texts: sets.map((op) => op.text) };
66
+ return { ok: true, set: facts.length, retired, texts: sets.map((op) => op.text) };
66
67
  }
67
68
  export async function pendingSessions(ctx, project, now = Date.now()) {
68
69
  const cutoff = now - ctx.config.distill.backfillDays * DAY_MS;
@@ -70,7 +71,7 @@ export async function pendingSessions(ctx, project, now = Date.now()) {
70
71
  .filter((session) => session.distilledAt === undefined && session.startedAt >= cutoff)
71
72
  .map((session) => session.id);
72
73
  }
73
- export async function backfill(ctx, project, run = runHeadless) {
74
+ export async function backfill(ctx, project, run = runHeadlessResult) {
74
75
  const pending = await pendingSessions(ctx, project);
75
76
  let distilled = 0;
76
77
  for (const [index, sessionId] of pending.entries()) {
@@ -1,3 +1,4 @@
1
+ import { rememberClaudeBinary } from '../util/claude-binary.js';
1
2
  export function capturingDisabled(scripted) {
2
3
  if (process.env['CLAUDE_DB_CAPTURE'] === 'off')
3
4
  return true;
@@ -19,6 +20,7 @@ export async function readPayload() {
19
20
  }
20
21
  export async function runHook(fn) {
21
22
  try {
23
+ rememberClaudeBinary();
22
24
  await fn();
23
25
  }
24
26
  catch (error) {
@@ -1,8 +1,8 @@
1
1
  import type { Config } from '../config/index.js';
2
2
  import type { RecallContext } from '../context.js';
3
+ import type { HeadlessResult } from '../util/claude-cli.js';
3
4
  export declare const PICK_BUDGET = "pick";
4
- export declare const PICK_PAUSE_MS: number;
5
- export type PickRunner = (prompt: string) => Promise<string | null>;
5
+ export type PickRunner = (prompt: string) => Promise<HeadlessResult>;
6
6
  export type PickOutcome = {
7
7
  kind: 'picked';
8
8
  block: string;
@@ -11,6 +11,7 @@ export type PickOutcome = {
11
11
  kind: 'none';
12
12
  } | {
13
13
  kind: 'failed';
14
+ reason: string;
14
15
  };
15
16
  export interface PickRequest {
16
17
  prompt: string;
@@ -18,5 +19,7 @@ export interface PickRequest {
18
19
  ids: string[];
19
20
  }
20
21
  export declare function takePick(config: Config, now?: number): boolean;
22
+ export declare function recordPickFailure(reason: string, now?: number): void;
23
+ export declare function recordPickSuccess(now?: number): void;
21
24
  export declare function headlessPicker(config: Config): PickRunner;
22
25
  export declare function pickMemories(ctx: RecallContext, request: PickRequest, run: PickRunner): Promise<PickOutcome>;
package/dist/pick/run.js CHANGED
@@ -1,15 +1,21 @@
1
+ import { redact } from '../capture/redact.js';
1
2
  import { renderPicked } from '../hooks/relevance.js';
2
- import { runHeadless } from '../util/claude-cli.js';
3
- import { takeBudget } from '../util/daily-budget.js';
3
+ import { runHeadlessResult } from '../util/claude-cli.js';
4
+ import { recordFailure, recordSuccess, takeBudget } from '../util/daily-budget.js';
4
5
  import { PICK_SYSTEM_PROMPT, buildPickPrompt, parsePicks } from './prompt.js';
5
6
  export const PICK_BUDGET = 'pick';
6
- export const PICK_PAUSE_MS = 60 * 60 * 1000;
7
7
  const TIMEOUT_MS = 30_000;
8
8
  export function takePick(config, now = Date.now()) {
9
9
  return config.pick.enabled && takeBudget(PICK_BUDGET, config.pick.dailyLimit, 1, now);
10
10
  }
11
+ export function recordPickFailure(reason, now = Date.now()) {
12
+ recordFailure(PICK_BUDGET, redact(reason), now);
13
+ }
14
+ export function recordPickSuccess(now = Date.now()) {
15
+ recordSuccess(PICK_BUDGET, now);
16
+ }
11
17
  export function headlessPicker(config) {
12
- return (prompt) => runHeadless(prompt, config.pick.model, TIMEOUT_MS, {
18
+ return (prompt) => runHeadlessResult(prompt, config.pick.model, TIMEOUT_MS, {
13
19
  flags: [['--system-prompt', PICK_SYSTEM_PROMPT], ['--tools', ''], ['--strict-mcp-config']],
14
20
  env: { MAX_THINKING_TOKENS: '0' },
15
21
  });
@@ -22,15 +28,15 @@ export async function pickMemories(ctx, request, run) {
22
28
  if (memories.length === 0)
23
29
  return { kind: 'none' };
24
30
  const { promptResults: limit, promptMaxChars } = ctx.config.inject;
25
- const stdout = await run(buildPickPrompt({
31
+ const reply = await run(buildPickPrompt({
26
32
  prompt: request.prompt,
27
33
  previousReply: request.previousReply,
28
34
  memories,
29
35
  limit,
30
36
  }));
31
- if (stdout === null)
32
- return { kind: 'failed' };
37
+ if (!reply.ok)
38
+ return { kind: 'failed', reason: reply.reason };
33
39
  const ids = [];
34
- const block = renderPicked(parsePicks(stdout, memories, limit) ?? [], promptMaxChars, ids);
40
+ const block = renderPicked(parsePicks(reply.stdout, memories, limit) ?? [], promptMaxChars, ids);
35
41
  return block ? { kind: 'picked', block, ids } : { kind: 'none' };
36
42
  }
@@ -2,10 +2,9 @@
2
2
  import { createContext } from '../context.js';
3
3
  import { runHook } from '../hooks/payload.js';
4
4
  import { withCost } from '../hooks/prompt-recall.js';
5
- import { pauseBudget } from '../util/daily-budget.js';
6
5
  import { silenceSqliteWarning } from '../util/warnings.js';
7
6
  import { finishPick, takeJob } from './pending.js';
8
- import { PICK_BUDGET, PICK_PAUSE_MS, headlessPicker, pickMemories } from './run.js';
7
+ import { headlessPicker, pickMemories, recordPickFailure, recordPickSuccess } from './run.js';
9
8
  silenceSqliteWarning();
10
9
  await runHook(async () => {
11
10
  const [sessionId, token] = process.argv.slice(2);
@@ -17,13 +16,15 @@ await runHook(async () => {
17
16
  const ctx = await createContext();
18
17
  try {
19
18
  const outcome = await pickMemories(ctx, job, headlessPicker(ctx.config));
20
- if (outcome.kind === 'picked') {
21
- finishPick(sessionId, token, { text: withCost(outcome.block), ids: outcome.ids });
22
- }
23
- else if (outcome.kind === 'failed') {
24
- pauseBudget(PICK_BUDGET, PICK_PAUSE_MS);
19
+ if (outcome.kind === 'failed') {
20
+ recordPickFailure(outcome.reason);
25
21
  if (job.fallback)
26
22
  finishPick(sessionId, token, job.fallback);
23
+ return;
24
+ }
25
+ recordPickSuccess();
26
+ if (outcome.kind === 'picked') {
27
+ finishPick(sessionId, token, { text: withCost(outcome.block), ids: outcome.ids });
27
28
  }
28
29
  }
29
30
  finally {
@@ -0,0 +1,9 @@
1
+ export interface ProcessInfo {
2
+ parent: number;
3
+ exe: string;
4
+ }
5
+ export type InspectProcess = (pid: number) => ProcessInfo | null;
6
+ export declare function findClaudeAncestor(start?: number, inspect?: InspectProcess): string | null;
7
+ export declare function rememberedBinary(file?: string): string | null;
8
+ export declare function rememberClaudeBinary(env?: NodeJS.ProcessEnv, file?: string, find?: () => string | null): void;
9
+ export declare function claudeBinary(env?: NodeJS.ProcessEnv, remembered?: () => string | null): string;
@@ -0,0 +1,74 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { mkdirSync, readFileSync, readlinkSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, join } from 'node:path';
4
+ import { CONFIG_DIR } from '../config/dir.js';
5
+ const REMEMBERED_FILE = join(CONFIG_DIR, 'claude-binary');
6
+ const MAX_ANCESTORS = 8;
7
+ function inspectOnLinux(pid) {
8
+ try {
9
+ const exe = readlinkSync(`/proc/${pid}/exe`);
10
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
11
+ const parent = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
12
+ return Number.isInteger(parent) ? { parent, exe } : null;
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ function inspectWithPs(pid) {
19
+ try {
20
+ const line = execFileSync('ps', ['-o', 'ppid=,comm=', '-p', String(pid)], {
21
+ encoding: 'utf8',
22
+ stdio: ['ignore', 'pipe', 'ignore'],
23
+ timeout: 1000,
24
+ }).trim();
25
+ const match = /^(\d+)\s+(.+)$/.exec(line);
26
+ return match?.[1] && match[2] ? { parent: Number(match[1]), exe: match[2] } : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ function inspectProcess(pid) {
33
+ if (process.platform === 'win32')
34
+ return null;
35
+ return process.platform === 'linux' ? inspectOnLinux(pid) : inspectWithPs(pid);
36
+ }
37
+ function isClaude(exe) {
38
+ return basename(exe) === 'claude';
39
+ }
40
+ export function findClaudeAncestor(start = process.ppid, inspect = inspectProcess) {
41
+ let pid = start;
42
+ for (let depth = 0; depth < MAX_ANCESTORS && pid > 1; depth++) {
43
+ const info = inspect(pid);
44
+ if (!info)
45
+ return null;
46
+ if (isClaude(info.exe))
47
+ return info.exe;
48
+ pid = info.parent;
49
+ }
50
+ return null;
51
+ }
52
+ export function rememberedBinary(file = REMEMBERED_FILE) {
53
+ try {
54
+ const path = readFileSync(file, 'utf8').trim();
55
+ return path !== '' && statSync(path, { throwIfNoEntry: false })?.isFile() ? path : null;
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ }
61
+ export function rememberClaudeBinary(env = process.env, file = REMEMBERED_FILE, find = findClaudeAncestor) {
62
+ const known = rememberedBinary(file);
63
+ const path = env['CLAUDE_CODE_EXECPATH'] || (known === null ? find() : null);
64
+ if (!path || path === known)
65
+ return;
66
+ try {
67
+ mkdirSync(CONFIG_DIR, { recursive: true });
68
+ writeFileSync(file, `${path}\n`, 'utf8');
69
+ }
70
+ catch { }
71
+ }
72
+ export function claudeBinary(env = process.env, remembered = rememberedBinary) {
73
+ return env['CLAUDE_CODE_EXECPATH'] || remembered() || 'claude';
74
+ }
@@ -2,5 +2,13 @@ export interface HeadlessOptions {
2
2
  flags?: readonly (readonly string[])[];
3
3
  env?: Readonly<Record<string, string>>;
4
4
  }
5
- export declare function claudeBinary(env?: NodeJS.ProcessEnv): string;
5
+ export type HeadlessResult = {
6
+ ok: true;
7
+ stdout: string;
8
+ } | {
9
+ ok: false;
10
+ reason: string;
11
+ };
12
+ export declare function runHeadlessResult(prompt: string, model: string, timeoutMs: number, options?: HeadlessOptions): Promise<HeadlessResult>;
6
13
  export declare function runHeadless(prompt: string, model: string, timeoutMs: number, options?: HeadlessOptions): Promise<string | null>;
14
+ export declare function describeFailure(error: unknown, stderr: string, timeoutMs: number): string;
@@ -1,26 +1,61 @@
1
1
  import { execFile } from 'node:child_process';
2
+ import { claudeBinary } from './claude-binary.js';
2
3
  const MAX_BUFFER = 1024 * 1024;
4
+ const REASON_CHARS = 120;
3
5
  const OPTIONAL_FLAGS = [
4
6
  ['--effort', 'low'],
5
7
  ['--no-session-persistence'],
6
8
  ];
7
9
  const UNKNOWN_OPTION = /unknown option '(--[\w-]+)'/i;
8
- export function claudeBinary(env = process.env) {
9
- return env['CLAUDE_CODE_EXECPATH'] || 'claude';
10
- }
11
- export async function runHeadless(prompt, model, timeoutMs, options = {}) {
10
+ export async function runHeadlessResult(prompt, model, timeoutMs, options = {}) {
12
11
  let optional = [...OPTIONAL_FLAGS, ...(options.flags ?? [])];
13
12
  for (;;) {
14
13
  const result = await call(['-p', prompt, '--model', model, ...optional.flat()], timeoutMs, options.env ?? {});
15
- if (result.stdout !== null)
16
- return result.stdout;
14
+ if (result.ok)
15
+ return { ok: true, stdout: result.stdout };
17
16
  const rejected = UNKNOWN_OPTION.exec(result.stderr)?.[1];
18
17
  const remaining = optional.filter((flags) => flags[0] !== rejected);
19
18
  if (remaining.length === optional.length)
20
- return null;
19
+ return { ok: false, reason: result.reason };
21
20
  optional = remaining;
22
21
  }
23
22
  }
23
+ export async function runHeadless(prompt, model, timeoutMs, options = {}) {
24
+ const result = await runHeadlessResult(prompt, model, timeoutMs, options);
25
+ return result.ok ? result.stdout : null;
26
+ }
27
+ export function describeFailure(error, stderr, timeoutMs) {
28
+ const failure = typeof error === 'object' && error !== null ? error : {};
29
+ if (failure.code === 'ENOENT') {
30
+ return 'claude was not found: put it on PATH, or set CLAUDE_CODE_EXECPATH';
31
+ }
32
+ if (failure.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
33
+ return 'the reply was larger than the 1 MB buffer';
34
+ }
35
+ if (failure.killed === true)
36
+ return `timed out after ${formatDuration(timeoutMs)}`;
37
+ const detail = firstLine(stderr);
38
+ if (typeof failure.code === 'number') {
39
+ return detail
40
+ ? `exited with code ${failure.code}: ${detail}`
41
+ : `exited with code ${failure.code}`;
42
+ }
43
+ if (typeof failure.signal === 'string')
44
+ return `stopped by ${failure.signal}`;
45
+ return detail || 'could not run claude';
46
+ }
47
+ function formatDuration(ms) {
48
+ return ms < 1000 ? `${ms} ms` : `${Math.round(ms / 1000)} s`;
49
+ }
50
+ function firstLine(text) {
51
+ const line = text
52
+ .split('\n')
53
+ .map((part) => part.trim())
54
+ .find((part) => part.length > 0);
55
+ if (!line)
56
+ return '';
57
+ return line.length > REASON_CHARS ? `${line.slice(0, REASON_CHARS - 1)}…` : line;
58
+ }
24
59
  function call(args, timeoutMs, env) {
25
60
  return new Promise((done) => {
26
61
  try {
@@ -28,11 +63,18 @@ function call(args, timeoutMs, env) {
28
63
  timeout: timeoutMs,
29
64
  maxBuffer: MAX_BUFFER,
30
65
  env: { ...process.env, ...env, CLAUDE_DB_CAPTURE: 'off' },
31
- }, (error, stdout, stderr) => done({ stdout: error ? null : stdout, stderr: String(stderr) }));
66
+ }, (error, stdout, stderr) => {
67
+ if (!error) {
68
+ done({ ok: true, stdout });
69
+ return;
70
+ }
71
+ const text = String(stderr);
72
+ done({ ok: false, stderr: text, reason: describeFailure(error, text, timeoutMs) });
73
+ });
32
74
  child.stdin?.end();
33
75
  }
34
- catch {
35
- done({ stdout: null, stderr: '' });
76
+ catch (error) {
77
+ done({ ok: false, stderr: '', reason: describeFailure(error, '', timeoutMs) });
36
78
  }
37
79
  });
38
80
  }
@@ -1,7 +1,17 @@
1
+ export declare const BACKOFF_MS: readonly number[];
2
+ export interface BudgetFailure {
3
+ at: number;
4
+ reason: string;
5
+ }
1
6
  export interface BudgetUsage {
2
7
  used: number;
3
8
  pausedUntil: number;
9
+ failures: number;
10
+ lastFailure: BudgetFailure | null;
4
11
  }
12
+ export declare function pauseFor(failures: number): number;
5
13
  export declare function budgetUsage(name: string, now?: number): BudgetUsage;
6
14
  export declare function takeBudget(name: string, limit: number, count: number, now?: number): boolean;
7
- export declare function pauseBudget(name: string, ms: number, now?: number): void;
15
+ export declare function recordFailure(name: string, reason: string, now?: number): void;
16
+ export declare function recordSuccess(name: string, now?: number): void;
17
+ export declare function describePause(usage: BudgetUsage, now?: number): string | null;
@@ -1,30 +1,52 @@
1
- import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
- import { join } from 'node:path';
1
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
3
  import { CONFIG_DIR } from '../config/dir.js';
4
+ const HOUR_MS = 60 * 60 * 1000;
5
+ const REASON_CHARS = 160;
6
+ export const BACKOFF_MS = [HOUR_MS, 6 * HOUR_MS, 24 * HOUR_MS];
4
7
  function budgetPath(name) {
5
8
  return join(CONFIG_DIR, name, 'budget.json');
6
9
  }
7
10
  function today(now) {
8
11
  return new Date(now).toISOString().slice(0, 10);
9
12
  }
13
+ function readFailure(value) {
14
+ if (typeof value !== 'object' || value === null)
15
+ return null;
16
+ const { at, reason } = value;
17
+ return typeof at === 'number' && typeof reason === 'string' ? { at, reason } : null;
18
+ }
10
19
  function read(name, now) {
11
20
  let saved = {};
12
21
  try {
13
22
  saved = JSON.parse(readFileSync(budgetPath(name), 'utf8'));
14
23
  }
15
24
  catch { }
16
- const pausedUntil = Number(saved.pausedUntil) || 0;
17
- if (saved.day !== today(now))
18
- return { day: today(now), used: 0, pausedUntil };
19
- return { day: saved.day, used: Number(saved.used) || 0, pausedUntil };
25
+ return {
26
+ day: today(now),
27
+ used: saved.day === today(now) ? Number(saved.used) || 0 : 0,
28
+ pausedUntil: Number(saved.pausedUntil) || 0,
29
+ failures: Number(saved.failures) || 0,
30
+ lastFailure: readFailure(saved.lastFailure),
31
+ };
20
32
  }
21
33
  function write(name, budget) {
22
- mkdirSync(join(CONFIG_DIR, name), { recursive: true });
23
- writeFileSync(budgetPath(name), `${JSON.stringify(budget)}\n`, 'utf8');
34
+ const path = budgetPath(name);
35
+ mkdirSync(dirname(path), { recursive: true });
36
+ const staging = `${path}.${process.pid}.tmp`;
37
+ writeFileSync(staging, `${JSON.stringify(budget)}\n`, 'utf8');
38
+ renameSync(staging, path);
39
+ }
40
+ function oneLine(text) {
41
+ return text.replace(/\s+/g, ' ').trim().slice(0, REASON_CHARS);
42
+ }
43
+ export function pauseFor(failures) {
44
+ const step = Math.min(Math.max(failures, 1), BACKOFF_MS.length);
45
+ return BACKOFF_MS[step - 1] ?? HOUR_MS;
24
46
  }
25
47
  export function budgetUsage(name, now = Date.now()) {
26
- const budget = read(name, now);
27
- return { used: budget.used, pausedUntil: budget.pausedUntil };
48
+ const { used, pausedUntil, failures, lastFailure } = read(name, now);
49
+ return { used, pausedUntil, failures, lastFailure };
28
50
  }
29
51
  export function takeBudget(name, limit, count, now = Date.now()) {
30
52
  const budget = read(name, now);
@@ -33,6 +55,27 @@ export function takeBudget(name, limit, count, now = Date.now()) {
33
55
  write(name, { ...budget, used: budget.used + count });
34
56
  return true;
35
57
  }
36
- export function pauseBudget(name, ms, now = Date.now()) {
37
- write(name, { ...read(name, now), pausedUntil: now + ms });
58
+ export function recordFailure(name, reason, now = Date.now()) {
59
+ const budget = read(name, now);
60
+ const failures = budget.failures + 1;
61
+ write(name, {
62
+ ...budget,
63
+ failures,
64
+ pausedUntil: now + pauseFor(failures),
65
+ lastFailure: { at: now, reason: oneLine(reason) },
66
+ });
67
+ }
68
+ export function recordSuccess(name, now = Date.now()) {
69
+ const budget = read(name, now);
70
+ if (budget.failures === 0 && budget.lastFailure === null)
71
+ return;
72
+ write(name, { ...budget, failures: 0, lastFailure: null });
73
+ }
74
+ export function describePause(usage, now = Date.now()) {
75
+ if (usage.pausedUntil <= now)
76
+ return null;
77
+ const until = new Date(usage.pausedUntil).toISOString();
78
+ const after = usage.failures > 1 ? `${usage.failures} failed calls in a row` : 'a failed call';
79
+ const reason = usage.lastFailure ? `: ${usage.lastFailure.reason}` : '';
80
+ return `until ${until} after ${after}${reason}`;
38
81
  }
@@ -60,7 +60,8 @@ it. Subagent reports, task notifications and slash commands are not prompts, so
60
60
  they get nothing.
61
61
 
62
62
  At most 150 picks a day (`pick.dailyLimit`), and a failed call pauses picking
63
- for an hour. Without Haiku (off, over the limit, or paused), only a strong word
63
+ for an hour, then six hours, then a day if calls keep failing, and `claude-db status`
64
+ shows why. Without Haiku (off, over the limit, or paused), only a strong word
64
65
  match is shown: the closest memory, if it shares four content words with the
65
66
  prompt. `claude-db pick off` turns Haiku off; `claude-db pick` shows today's
66
67
  count.
@@ -111,7 +112,8 @@ on a shared database. Everything else stays in its project.
111
112
 
112
113
  The call goes through your own Claude Code login and runs in the background, so
113
114
  closing a chat stays instant. At most 30 calls a day; a failed call pauses it
114
- for a day while capture carries on; a long chat is read in windows of about
115
+ (an hour, then six hours, then a day, with the reason in `claude-db distill`)
116
+ while capture carries on; a long chat is read in windows of about
115
117
  40,000 characters, one call each. `claude-db distill off` turns it off, and
116
118
  `claude-db distill` shows what it has done.
117
119
 
@@ -236,7 +236,8 @@ Nothing leaves your machine except the things below, and each can be turned off.
236
236
 
237
237
  Both Haiku features go through your own Claude Code login, so they count against your plan like any
238
238
  other use. Haiku is the lightest model, and a pick is small next to an ordinary chat turn. A failed
239
- call pauses that feature, for an hour for picking and a day for facts, while recording carries on.
239
+ call pauses that feature for an hour, then six hours, then a day if calls keep failing, while recording
240
+ carries on. `claude-db status` shows the reason.
240
241
 
241
242
  What is never stored: `.env` files, anything under `secrets/`, `node_modules` and `.git/`. Text in
242
243
  `<private>...</private>` is stripped. API keys, tokens, private keys, connection-string passwords and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-db",
3
- "version": "0.10.1",
3
+ "version": "0.10.3",
4
4
  "description": "Persistent memory for Claude Code. Captures why decisions were made, not just which files changed. Bring your own database: SQLite, MongoDB or Postgres. No cloud, no subscription.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",