Class: ClaudeMemory::Hook::Handler

Inherits:
Object
  • Object
show all
Defined in:
lib/claude_memory/hook/handler.rb

Defined Under Namespace

Classes: PayloadError, SingleStoreFacade

Constant Summary collapse

DEFAULT_SWEEP_BUDGET =
5
MAX_NUDGES =

First-week ROI nudge. Computes per-session metrics (facts contributed via Stop-hook ingest, percentage of those Claude actually used in recall/context-injection) and decides whether to print to the user. Quiets after MAX_NUDGES successful runs or when CLAUDE_MEMORY_NO_NUDGE=1.

The “first ~10 sessions” gate is enforced by counting prior ‘roi_nudge` activity events with status=success across both stores. Once the user has seen the nudge enough times, memory gets out of the way; trust is established or it isn’t.

10
ENV_NUDGE_OPT_OUT =
"CLAUDE_MEMORY_NO_NUDGE"

Instance Method Summary collapse

Constructor Details

#initialize(store, env: ENV, manager: nil) ⇒ Handler

Returns a new instance of Handler.



10
11
12
13
14
15
# File 'lib/claude_memory/hook/handler.rb', line 10

def initialize(store, env: ENV, manager: nil)
  @store = store
  @manager = manager
  @config = Configuration.new(env)
  @env = env
end

Instance Method Details

#context(payload) ⇒ Object



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/claude_memory/hook/handler.rb', line 149

def context(payload)
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  manager = @manager || build_manager(payload)
  manager.ensure_both!

  source = payload["source"]
  injector = ContextInjector.new(manager, source: source)
  context_text = injector.generate_context

  log_activity("hook_context",
    status: context_text ? "success" : "skipped", t0: t0,
    details: {
      context_length: context_text&.length,
      context_tokens: Core::TokenEstimator.estimate(context_text),
      source: source
    })

  {status: :ok, context: context_text}
rescue => e
  log_activity("hook_context", status: "error", t0: t0,
    details: {error: e.message})
  {status: :error, context: nil, message: e.message}
end

#ingest(payload) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/claude_memory/hook/handler.rb', line 17

def ingest(payload)
  session_id = payload["session_id"] || @config.session_id
  transcript_path = payload["transcript_path"] || @config.transcript_path
  project_path = payload["project_path"] || @config.project_dir

  raise PayloadError, "Missing required field: session_id" if session_id.nil? || session_id.empty?
  raise PayloadError, "Missing required field: transcript_path" if transcript_path.nil? || transcript_path.empty?

  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  ingester = Ingest::Ingester.new(@store, env: @env)
  result = ingester.ingest(
    source: "claude_code",
    session_id: session_id,
    transcript_path: transcript_path,
    project_path: project_path
  )

  if result[:status] == :ingested && result[:content_id]
    DistillationRunner.new(@store).distill_item(
      result[:content_id], project_path: project_path
    )
  end

  log_activity("hook_ingest",
    status: (result[:status] == :ingested) ? "success" : "skipped",
    session_id: session_id, t0: t0,
    details: {bytes_read: result[:bytes_read], content_id: result[:content_id],
              reason: result[:reason]}.compact)

  result
rescue Ingest::TranscriptReader::FileNotFoundError => e
  log_activity("hook_ingest", status: "skipped", session_id: session_id, t0: t0,
    details: {reason: "transcript_not_found"})
  {status: :skipped, reason: "transcript_not_found", message: e.message}
end

#nudge(payload) ⇒ Object



109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/claude_memory/hook/handler.rb', line 109

def nudge(payload)
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  session_id = payload["session_id"] || @config.session_id

  # Cleanly silent on opt-out — no activity event, no record of
  # having tried. Users who set the env var don't want a paper
  # trail of suppressed nudges.
  return {status: :silent, reason: "opt_out"} if @env[ENV_NUDGE_OPT_OUT] == "1"
  return {status: :silent, reason: "no_session_id"} if session_id.nil? || session_id.empty?

  prior = prior_nudge_count
  if prior >= MAX_NUDGES
    return {status: :silent, reason: "first_week_complete", prior_count: prior}
  end

  contributed_ids = session_contributed_facts(session_id)
  n = contributed_ids.size

  if n.zero?
    # Don't burn one of the user's 10 nudge slots on an empty
    # session. Memory contributed nothing → no trust signal to
    # surface; come back next session with real data.
    return {status: :silent, reason: "no_contributions", prior_count: prior}
  end

  used = session_used_facts(session_id, contributed_ids)
  pct = (used * 100.0 / n).round
  message = "memory contributed #{n} fact#{"s" unless n == 1} this session, %used = #{pct}%"

  log_activity("roi_nudge", status: "success", session_id: session_id, t0: t0,
    details: {n: n, used: used, pct: pct, prior_count: prior})

  {
    status: :emitted,
    message: message,
    n: n, used: used, pct: pct,
    remaining: MAX_NUDGES - prior - 1
  }
end

#publish(payload) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/claude_memory/hook/handler.rb', line 80

def publish(payload)
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  mode = payload.fetch("mode", "shared").to_sym
  since = payload["since"]
  rules_dir = payload["rules_dir"]

  publisher = Publish.new(@store)
  result = publisher.publish!(mode: mode, since: since, rules_dir: rules_dir)

  log_activity("hook_publish", status: "success", t0: t0,
    details: {mode: mode.to_s, publish_status: result[:status].to_s})

  result
end

#refresh_recall_timestampsObject

Sweep-derived staleness data. Skips silently if the sweep was given a store-only handler (no manager); the cross-DB refresher requires the manager because project events can touch global facts and vice versa.



72
73
74
75
76
77
78
# File 'lib/claude_memory/hook/handler.rb', line 72

def refresh_recall_timestamps
  return {project: 0, global: 0} unless @manager
  Sweep::RecallTimestampRefresher.new(@manager).refresh!
rescue Sequel::DatabaseError => e
  ClaudeMemory.logger.debug("recall timestamp refresh failed: #{e.message}")
  {project: 0, global: 0, error: e.message}
end

#sweep(payload) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/claude_memory/hook/handler.rb', line 54

def sweep(payload)
  t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC)

  budget = payload.fetch("budget", DEFAULT_SWEEP_BUDGET).to_i
  sweeper = Sweep::Sweeper.new(@store)
  stats = sweeper.run!(budget_seconds: budget)
  stats[:recall_timestamps_refreshed] = refresh_recall_timestamps

  log_activity("hook_sweep", status: "success", t0: t0,
    details: {elapsed_seconds: stats[:elapsed_seconds],
              budget_honored: stats[:budget_honored]})

  {stats: stats}
end