brainiac 0.0.33 → 0.1.0

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: aa14f181c9965192fcc2507837be14e29cc9bce6a0273d806dd556eb2bfb72e2
4
- data.tar.gz: c1d2fcbed4ce125a150d442e4cc3a1d68dfa856c424addf981904b4b88393b70
3
+ metadata.gz: 82f144b517fd0197684d1912858134c0a6b440263cf2e6bb43d1c4e2651aec3a
4
+ data.tar.gz: 415ae3b9fad9b4d407e13147ce0c28286b8292897175f45c37d39b4dfbf2cccd
5
5
  SHA512:
6
- metadata.gz: beaf113fb5acf361c73df0da4d93dd65a7a7159397c0b1c559e4b84df9396376148a95a7e09824744ca1d272ef51c6008da334bc906a3bd6ce8d940d0568f43a
7
- data.tar.gz: 5382b695151def7319fcadfbb51ae84f6f4401b43b9de92ecd51e5c17b20a8e05723cd9943dfba4229ca70a7097f317c70f44b973e9d815f9815ee994b8414c9
6
+ metadata.gz: 567146d407026c606a08a9c3d592059a43f195f9785318d3763ad368aab002d16153a2b442cf778a06513b231327552201f71b1d7bb2680036214f0cf842e5cc
7
+ data.tar.gz: a41c6857915e2e9493f45fa0d49755e4958d6c4de6175a7171d7e25a8013ac3b3f498a7ab1933021c09b0bf3a5768bd1542176d59a0e4ad680e186ce7af74545
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- brainiac (0.0.33)
4
+ brainiac (0.1.0)
5
5
  puma (~> 7.2)
6
6
  rackup (~> 2.3)
7
7
  sinatra (~> 4.1)
@@ -11,22 +11,22 @@ GEM
11
11
  specs:
12
12
  ast (2.4.3)
13
13
  base64 (0.3.0)
14
- json (2.19.9)
15
- language_server-protocol (3.17.0.5)
14
+ json (2.21.2)
15
+ language_server-protocol (3.17.0.6)
16
16
  lint_roller (1.1.0)
17
17
  logger (1.7.0)
18
18
  minitest (5.27.0)
19
19
  mustermann (3.1.1)
20
20
  nio4r (2.7.5)
21
- parallel (2.1.0)
22
- parser (3.3.11.1)
21
+ parallel (2.2.0)
22
+ parser (3.3.12.0)
23
23
  ast (~> 2.4.1)
24
24
  racc
25
25
  prism (1.9.0)
26
26
  puma (7.2.1)
27
27
  nio4r (~> 2.0)
28
28
  racc (1.8.1)
29
- rack (3.2.6)
29
+ rack (3.2.7)
30
30
  rack-protection (4.2.1)
31
31
  base64 (>= 0.1.0)
32
32
  logger (>= 1.6.0)
@@ -50,7 +50,7 @@ GEM
50
50
  rubocop-ast (>= 1.49.0, < 2.0)
51
51
  ruby-progressbar (~> 1.7)
52
52
  unicode-display_width (>= 2.4.0, < 4.0)
53
- rubocop-ast (1.49.1)
53
+ rubocop-ast (1.50.0)
54
54
  parser (>= 3.3.7.2)
55
55
  prism (~> 1.7)
56
56
  rubocop-performance (1.26.1)
@@ -65,7 +65,7 @@ GEM
65
65
  rack-protection (= 4.2.1)
66
66
  rack-session (>= 2.0.0, < 3)
67
67
  tilt (~> 2.0)
68
- tilt (2.7.0)
68
+ tilt (2.9.0)
69
69
  unicode-display_width (3.2.0)
70
70
  unicode-emoji (~> 4.1)
71
71
  unicode-emoji (4.2.0)
@@ -84,20 +84,20 @@ DEPENDENCIES
84
84
  CHECKSUMS
85
85
  ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383
86
86
  base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
87
- brainiac (0.0.33)
88
- json (2.19.9) sha256=9b9025b7cdddafa38d316eca0b2358488e42d417045c1b90d216a9fefe46b79a
89
- language_server-protocol (3.17.0.5) sha256=fd1e39a51a28bf3eec959379985a72e296e9f9acfce46f6a79d31ca8760803cc
87
+ brainiac (0.1.0)
88
+ json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a
89
+ language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0
90
90
  lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87
91
91
  logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
92
92
  minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
93
93
  mustermann (3.1.1) sha256=4c6170c7234d5499c345562ba7c7dfe73e1754286dcc1abb053064d66a127198
94
94
  nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1
95
- parallel (2.1.0) sha256=b35258865c2e31134c5ecb708beaaf6772adf9d5efae28e93e99260877b09356
96
- parser (3.3.11.1) sha256=d17ace7aabe3e72c3cc94043714be27cc6f852f104d81aa284c2281aecc65d54
95
+ parallel (2.2.0) sha256=e1059c5fd7b649558a0aec38a769f06a42942bdb40503d005a59c352fe011cd8
96
+ parser (3.3.12.0) sha256=21a6d7f755d5a24dfbdc6e6b772e4e879a52e7631a88bc5a3a134606052c9828
97
97
  prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85
98
98
  puma (7.2.1) sha256=d7bf0e9cabd532e0d401e142cd94e3ac531e993610e2d80e6fbf9c26961414b0
99
99
  racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f
100
- rack (3.2.6) sha256=5ed78e1f73b2e25679bec7d45ee2d4483cc4146eb1be0264fc4d94cb5ef212c2
100
+ rack (3.2.7) sha256=93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7
101
101
  rack-protection (4.2.1) sha256=cf6e2842df8c55f5e4d1a4be015e603e19e9bc3a7178bae58949ccbb58558bac
102
102
  rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8
103
103
  rackup (2.3.1) sha256=6c79c26753778e90983761d677a48937ee3192b3ffef6bc963c0950f94688868
@@ -105,11 +105,11 @@ CHECKSUMS
105
105
  rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701
106
106
  regexp_parser (2.12.0) sha256=35a916a1d63190ab5c9009457136ae5f3c0c7512d60291d0d1378ba18ce08ebb
107
107
  rubocop (1.88.0) sha256=e420ddf1662d0ef34bc8a2910ac4b396a7ddda0b51a708264405241734b08e0b
108
- rubocop-ast (1.49.1) sha256=4412f3ee70f6fe4546cc489548e0f6fcf76cafcfa80fa03af67098ffed755035
108
+ rubocop-ast (1.50.0) sha256=b9ca88300da0803ee222ad20cdb30494c0a784eed06fdc35d254b06d662788db
109
109
  rubocop-performance (1.26.1) sha256=cd19b936ff196df85829d264b522fd4f98b6c89ad271fa52744a8c11b8f71834
110
110
  ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33
111
111
  sinatra (4.2.1) sha256=b7aeb9b11d046b552972ade834f1f9be98b185fa8444480688e3627625377080
112
- tilt (2.7.0) sha256=0d5b9ba69f6a36490c64b0eee9f6e9aad517e20dcc848800a06eb116f08c6ab3
112
+ tilt (2.9.0) sha256=da5735d0280bba96e9a91041bb14aee435ccad5c17b0fa519249ae543d9aa3a5
113
113
  unicode-display_width (3.2.0) sha256=0cdd96b5681a5949cdbc2c55e7b420facae74c4aaf9a9815eee1087cb1853c42
114
114
  unicode-emoji (4.2.0) sha256=519e69150f75652e40bf736106cfbc8f0f73aa3fb6a65afe62fefa7f80b0f80f
115
115
 
data/README.md CHANGED
@@ -1270,6 +1270,32 @@ curl "http://localhost:4567/api/gif?q=excited" # Search for GIFs (r
1270
1270
  curl http://localhost:4567/api/cron # Cron jobs and thread status
1271
1271
  curl http://localhost:4567/api/logs # Read log files
1272
1272
  curl http://localhost:4567/api/status # Active agent sessions (used by monitor)
1273
+ curl "http://localhost:4567/api/sessions/history?limit=25" # Durable session history (survives restarts)
1274
+ ```
1275
+
1276
+ ### Session History
1277
+
1278
+ `/api/status` returns only *live* sessions plus the last 10 finished ones held in memory
1279
+ (wiped on every restart). For durable, restart-surviving history use
1280
+ `GET /api/sessions/history?limit=N`, backed by an append-only JSONL log at
1281
+ `~/.brainiac/session-history.jsonl`.
1282
+
1283
+ Every finished agent session is recorded with timing, identity (agent, CLI, model, source),
1284
+ exit status, and — where the provider exposes it — **session heaviness**: context window
1285
+ usage and credits spent. Heaviness is captured at completion time via a provider-specific
1286
+ probe that is **declared in the provider config**, not hardcoded in brainiac. Add a
1287
+ `heaviness_probe` block to `~/.brainiac/cli-providers/<name>.json`:
1288
+
1289
+ ```json
1290
+ "heaviness_probe": { "type": "kiro_sqlite", "db_path": "~/.local/share/kiro-cli/data.sqlite3" }
1291
+ ```
1292
+
1293
+ `type` selects the probe strategy and `db_path` points at the provider's local usage store,
1294
+ so enabling/disabling a provider or moving its data store is pure JSON. kiro-cli ships with a
1295
+ `kiro_sqlite` probe (reads its local conversation sqlite, read-only). A genuinely new storage
1296
+ mechanism needs a small probe implementation in `lib/brainiac/session_history.rb`; providers
1297
+ with no `heaviness_probe` simply record timing + identity. The file is trimmed to the most
1298
+ recent 500 records.
1273
1299
  ```
1274
1300
 
1275
1301
  ## Development
@@ -35,7 +35,7 @@ def load_cli_provider(provider_name)
35
35
  %w[prompt_flag list_models_command resume_flag resume_args resume_id_flag new_session_id_flag
36
36
  session_list_command session_id_field session_directory_field session_updated_field
37
37
  session_list_path session_dir output_last_message_flag cwd_flag config_override_flag
38
- effort_config_key effort_map title_flag].each do |key|
38
+ effort_config_key effort_map title_flag heaviness_probe].each do |key|
39
39
  next unless raw[key]
40
40
  next if raw[key].respond_to?(:empty?) && raw[key].empty?
41
41
 
@@ -507,6 +507,74 @@ rescue StandardError => e
507
507
  nil
508
508
  end
509
509
 
510
+ # Detect when an agent exited cleanly (exit 0) but produced no usable response.
511
+ # This covers cases the crash path misses because the exit code is 0 — most notably a
512
+ # CLI that prints a request/usage-limit notice and exits without doing any work.
513
+ #
514
+ # Returns a short human-readable reason string when the session yielded no response,
515
+ # or nil when the session did produce output (i.e. nothing to surface).
516
+ #
517
+ # @param log_file [String, nil] Path to the agent's log file
518
+ # @param output_content [String, nil] Structured output captured via --output-last-message, if any
519
+ NO_OUTPUT_LIMIT_PATTERNS = [
520
+ /\bmonthly request limit reached\b/i,
521
+ /\brequest limit reached\b/i,
522
+ /\busage limit\b/i,
523
+ /\brate limit(?:ed|ing)?\b/i,
524
+ /\bquota (?:exceeded|reached)\b/i,
525
+ /\btoo many requests\b/i
526
+ ].freeze
527
+
528
+ def detect_no_output_reason(log_file, output_content)
529
+ # If we captured a structured response, the session clearly produced output.
530
+ return nil if output_content && !output_content.strip.empty?
531
+
532
+ tail = extract_crash_snippet(log_file, max_lines: 40)
533
+ return nil if tail.nil?
534
+
535
+ limit_line = tail.lines.map(&:strip).reverse.find do |line|
536
+ NO_OUTPUT_LIMIT_PATTERNS.any? { |re| line.match?(re) }
537
+ end
538
+ return "hit a request/usage limit: #{limit_line}" if limit_line
539
+
540
+ # No structured output and no recognizable limit notice. Treat a log that carries no
541
+ # assistant text as "produced no response" so the channel isn't left silent. We can't
542
+ # parse every CLI's transcript here, so this is best-effort: only flag when the log is
543
+ # effectively empty of content beyond startup/boilerplate lines.
544
+ meaningful = tail.lines.map(&:strip).reject do |line|
545
+ line.empty? ||
546
+ line.start_with?("---", "▸") ||
547
+ line.match?(/all tools are now trusted/i) ||
548
+ line.match?(/mcp server did not load/i) ||
549
+ line.match?(/agents can sometimes do unexpected things/i) ||
550
+ line.match?(%r{learn more at https?://}i)
551
+ end
552
+ return "produced no response (log contained no agent output)" if meaningful.empty?
553
+
554
+ nil
555
+ end
556
+
557
+ # Surface a clean-exit-but-no-response session to the originating channel. Reuses the
558
+ # crash notification delivery path (the :agent_crashed hook) so plugins deliver it the
559
+ # same way they deliver failures, but frames it as "no response" rather than a crash.
560
+ def notify_agent_no_output(reason:, log_file:, agent_name:, source:, source_context:, project_config:)
561
+ agent_display = agent_name || "Agent"
562
+ snippet = extract_crash_snippet(log_file)
563
+
564
+ handled = Brainiac.emit(:agent_crashed,
565
+ exit_status: 0, log_file: log_file, agent_name: agent_display,
566
+ source: source, source_context: source_context, project_config: project_config,
567
+ snippet: snippet, no_output: true, no_output_reason: reason)
568
+
569
+ if handled.any?
570
+ LOG.info "[NoOutput] #{agent_display} #{reason} — notified via #{source}"
571
+ else
572
+ LOG.warn "[NoOutput] #{agent_display} #{reason} but no plugin handled notification (source: #{source})"
573
+ end
574
+ rescue StandardError => e
575
+ LOG.error "[NoOutput] Unexpected error: #{e.message}"
576
+ end
577
+
510
578
  # Notify the originating channel that an agent crashed.
511
579
  # source: :github, :discord, or plugin-registered sources
512
580
  # source_context: hash with channel-specific info needed to post the notification
@@ -737,8 +805,6 @@ def run_agent(prompt, project_config:, chdir: nil, log_name: "agent", model: nil
737
805
  prompt_file: prompt_file, resume: should_resume,
738
806
  output_file: output_file, chdir: chdir, title: work_item_id,
739
807
  new_session_id: minted_session_id)
740
- prompt_mode = resolved["prompt_mode"] || "stdin"
741
-
742
808
  spawn_env = agent_env_for(agent_name).merge(env)
743
809
 
744
810
  log_agent_launch(resolved: resolved, chdir: chdir, log_file: log_file, prompt_file: prompt_file,
@@ -748,11 +814,9 @@ def run_agent(prompt, project_config:, chdir: nil, log_name: "agent", model: nil
748
814
  project_key_for_restart = PROJECTS.find { |_k, v| v == project_config }&.first
749
815
  head_before, status_before = capture_git_state(chdir) if project_key_for_restart == "brainiac"
750
816
 
751
- pid = spawn(spawn_env, *cmd,
752
- chdir: chdir,
753
- **(prompt_mode == "stdin" ? { in: prompt_file } : {}),
754
- out: [log_file, "w"],
755
- err: %i[child out])
817
+ started_at = Time.now
818
+ stdin_redirect = (resolved["prompt_mode"] || "stdin") == "stdin" ? { in: prompt_file } : {}
819
+ pid = spawn(spawn_env, *cmd, chdir: chdir, **stdin_redirect, out: [log_file, "w"], err: %i[child out])
756
820
 
757
821
  spawn_completion_watcher(
758
822
  pid: pid, agent_cli: resolved["agent_cli"], agent_config_name: agent_config_name,
@@ -762,7 +826,7 @@ def run_agent(prompt, project_config:, chdir: nil, log_name: "agent", model: nil
762
826
  card_number: card_number, skip_column_move: skip_column_move,
763
827
  output_file: output_file, resolved: resolved, minted_session_id: minted_session_id,
764
828
  head_before: head_before, status_before: status_before,
765
- project_key_for_restart: project_key_for_restart
829
+ project_key_for_restart: project_key_for_restart, model: model, started_at: started_at
766
830
  )
767
831
 
768
832
  LOG.info "#{resolved["agent_cli"]} started (pid: #{pid}, agent: #{agent_config_name || "default"}, " \
@@ -773,10 +837,15 @@ end
773
837
 
774
838
  # Spawn a background thread that waits for the agent process to finish and runs completion handling.
775
839
  def spawn_completion_watcher(**ctx)
776
- Thread.new do
840
+ thread = Thread.new do
777
841
  Process.wait(ctx[:pid])
778
842
  handle_agent_completion(**ctx)
779
843
  end
844
+ # Without this, an unrescued exception anywhere in handle_agent_completion silently
845
+ # kills the thread and is never logged — which previously hid completion-path failures
846
+ # (e.g. a step raising before session history was archived).
847
+ thread.report_on_exception = true
848
+ thread
780
849
  end
781
850
 
782
851
  # Log the details of an agent launch (command, prompt/output files, injected env).
@@ -1056,13 +1125,60 @@ def handle_agent_completion(**ctx)
1056
1125
  # Clean up the output file after hook emission (content already captured above).
1057
1126
  FileUtils.rm_f(ctx[:output_file]) if ctx[:output_file]
1058
1127
 
1059
- run_qmd_update(ctx[:agent_config_name])
1060
- log_skill_candidate(ctx[:log_file])
1128
+ run_post_completion_steps(ctx, exit_status: agent_exit_status, signaled: agent_signaled, output_content: output_content)
1129
+ end
1061
1130
 
1062
- brain_push(message: "#{ctx[:agent_config_name] || "agent"}: #{ctx[:log_name]}")
1131
+ # Independent, best-effort steps that run after the lifecycle hook. Each is isolated via
1132
+ # completion_step so a failure in one (e.g. a raising notify path) can't abort the rest —
1133
+ # notably session-history archival, which must always run regardless of earlier steps.
1134
+ def run_post_completion_steps(ctx, exit_status:, signaled:, output_content:)
1135
+ # Clean exit (0) but no usable response — e.g. the CLI hit a request/usage limit and
1136
+ # bailed without doing work. The crash path only fires on non-zero exits, so this would
1137
+ # otherwise be silent. Surface it to the originating channel.
1138
+ completion_step("notify_no_output") do
1139
+ notify_no_output_if_needed(ctx, exit_status: exit_status, signaled: signaled, output_content: output_content)
1140
+ end
1141
+
1142
+ # Durable session history — record every finished session to disk (survives restarts),
1143
+ # including provider-specific "heaviness" (context window usage + credits). Best-effort.
1144
+ completion_step("archive_session_history") do
1145
+ archive_session_history(ctx: ctx, exit_status: exit_status, signaled: signaled)
1146
+ end
1147
+
1148
+ completion_step("qmd_update") { run_qmd_update(ctx[:agent_config_name]) }
1149
+ completion_step("skill_candidate") { log_skill_candidate(ctx[:log_file]) }
1150
+ completion_step("brain_push") { brain_push(message: "#{ctx[:agent_config_name] || "agent"}: #{ctx[:log_name]}") }
1063
1151
  # check_brainiac_restart(ctx[:head_before], ctx[:status_before], ctx[:chdir], ctx[:project_key_for_restart], ctx[:agent_config_name])
1064
1152
  end
1065
1153
 
1154
+ # Run an independent post-completion step, logging and swallowing any failure so one
1155
+ # broken step (e.g. a plugin-facing call raising) can't abort the remaining steps —
1156
+ # notably session-history archival, which must not depend on earlier steps succeeding.
1157
+ def completion_step(name)
1158
+ yield
1159
+ rescue StandardError => e
1160
+ LOG.error "[Completion] step '#{name}' failed: #{e.class}: #{e.message}"
1161
+ LOG.error "[Completion] #{e.backtrace.first(3).join("\n ")}" if e.backtrace
1162
+ nil
1163
+ end
1164
+
1165
+ # Surface a clean-exit session that produced no response, pulling fields from the
1166
+ # completion context. Only fires for exit 0 (non-zero already goes through the crash
1167
+ # path) with a source to notify. Extracted from handle_agent_completion.
1168
+ def notify_no_output_if_needed(ctx, exit_status:, signaled:, output_content:)
1169
+ return unless ctx[:source]
1170
+ return if signaled
1171
+ return unless exit_status&.zero?
1172
+
1173
+ reason = detect_no_output_reason(ctx[:log_file], output_content)
1174
+ return unless reason
1175
+
1176
+ notify_agent_no_output(
1177
+ reason: reason, log_file: ctx[:log_file], agent_name: ctx[:agent_name],
1178
+ source: ctx[:source], source_context: ctx[:source_context], project_config: ctx[:project_config]
1179
+ )
1180
+ end
1181
+
1066
1182
  # Capture the CLI session id after a run, if the provider and working dir are known.
1067
1183
  def capture_session_id_if_possible(ctx)
1068
1184
  return unless ctx[:resolved] && ctx[:chdir]
@@ -265,6 +265,13 @@ get "/api/status" do
265
265
  end
266
266
  end
267
267
 
268
+ get "/api/sessions/history" do
269
+ content_type :json
270
+ limit = (params["limit"] || 50).to_i.clamp(1, SESSION_HISTORY_MAX)
271
+ history = read_session_history(limit: limit)
272
+ { history: history, count: history.size }.to_json
273
+ end
274
+
268
275
  post "/api/sessions/kill/:card_key" do
269
276
  content_type :json
270
277
  card_key = params[:card_key]
@@ -0,0 +1,202 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "timeout"
4
+
5
+ # Durable session history + "session heaviness" tracking.
6
+ #
7
+ # The in-memory RECENT_SESSIONS (see sessions.rb) only holds the last 10 finished
8
+ # sessions and is wiped on every brainiac restart. This module persists a durable,
9
+ # append-only record of every completed agent session to disk so the monitor (and
10
+ # anything else) can review real history: how long a session ran, which CLI/model it
11
+ # used, where it came from, and — where the provider exposes it — how "heavy" the
12
+ # session was (context window usage + credits spent).
13
+ #
14
+ # Storage: append-only JSONL at ~/.brainiac/session-history.jsonl (one record per line).
15
+ # JSONL is chosen deliberately: appends are atomic-ish and cheap, the file survives
16
+ # restarts, it's trivially tailable, and a corrupt line never poisons the whole file.
17
+ # The file is trimmed to SESSION_HISTORY_MAX records to bound growth.
18
+
19
+ SESSION_HISTORY_FILE = File.join(BRAINIAC_DIR, "session-history.jsonl")
20
+ SESSION_HISTORY_MAX = 500
21
+ SESSION_HISTORY_MUTEX = Mutex.new
22
+
23
+ # Append a completed-session record to the durable history file.
24
+ # `record` is a plain Hash; symbol keys are fine (serialized to JSON).
25
+ # Best-effort: any failure is logged and swallowed — history is never allowed to
26
+ # break the completion path.
27
+ def record_session_history(record)
28
+ SESSION_HISTORY_MUTEX.synchronize do
29
+ FileUtils.mkdir_p(File.dirname(SESSION_HISTORY_FILE))
30
+ File.open(SESSION_HISTORY_FILE, "a") { |f| f.puts(JSON.generate(record)) }
31
+ trim_session_history!
32
+ end
33
+ LOG.info "[SessionHistory] Recorded session for #{record["agent"] || "?"} → #{SESSION_HISTORY_FILE}"
34
+ true
35
+ rescue StandardError => e
36
+ LOG.warn "[SessionHistory] Failed to record session: #{e.class}: #{e.message}"
37
+ false
38
+ end
39
+
40
+ # Read the most recent `limit` session records, newest first.
41
+ def read_session_history(limit: 50)
42
+ return [] unless File.exist?(SESSION_HISTORY_FILE)
43
+
44
+ lines = SESSION_HISTORY_MUTEX.synchronize { File.readlines(SESSION_HISTORY_FILE) }
45
+ records = lines.filter_map do |line|
46
+ line = line.strip
47
+ next if line.empty?
48
+
49
+ begin
50
+ JSON.parse(line)
51
+ rescue JSON::ParserError
52
+ nil
53
+ end
54
+ end
55
+ records.last(limit).reverse
56
+ rescue StandardError => e
57
+ LOG.warn "[SessionHistory] Failed to read history: #{e.message}"
58
+ []
59
+ end
60
+
61
+ # Keep the history file bounded. Call inside SESSION_HISTORY_MUTEX.
62
+ def trim_session_history!
63
+ lines = File.readlines(SESSION_HISTORY_FILE)
64
+ return if lines.size <= SESSION_HISTORY_MAX
65
+
66
+ File.write(SESSION_HISTORY_FILE, lines.last(SESSION_HISTORY_MAX).join)
67
+ rescue StandardError => e
68
+ LOG.warn "[SessionHistory] Failed to trim history: #{e.message}"
69
+ end
70
+
71
+ # Build the durable history record for a finished session and append it.
72
+ # Called from handle_agent_completion. Gathers timing, identity, and — via the
73
+ # provider-specific heaviness probe — context/credit usage. Never raises.
74
+ def archive_session_history(ctx:, exit_status:, signaled:)
75
+ started_at = ctx[:started_at]
76
+ finished_at = Time.now
77
+ heaviness = session_heaviness(resolved: ctx[:resolved], chdir: ctx[:chdir])
78
+ source_context = ctx[:source_context] || {}
79
+ card_key = ctx[:card_key] || source_context[:card_key]
80
+ channel_id = ctx[:channel_id] || source_context[:channel_id]
81
+
82
+ record = {
83
+ "recorded_at" => finished_at.utc.iso8601,
84
+ "agent" => ctx[:agent_name] || ctx[:agent_config_name] || "Unknown",
85
+ "card_key" => card_key,
86
+ "card_number" => ctx[:card_number] || source_context[:card_number],
87
+ "source" => ctx[:source]&.to_s,
88
+ "channel_id" => channel_id,
89
+ "log_file" => ctx[:log_file],
90
+ "cli" => ctx[:agent_cli],
91
+ "model" => ctx[:model],
92
+ "started_at" => started_at&.utc&.iso8601,
93
+ "finished_at" => finished_at.utc.iso8601,
94
+ "duration_seconds" => started_at ? (finished_at - started_at).to_i : nil,
95
+ "exit_status" => exit_status,
96
+ "signaled" => signaled
97
+ }
98
+ record.merge!(heaviness) if heaviness
99
+ record.compact!
100
+
101
+ record_session_history(record)
102
+ end
103
+
104
+ # --- Provider-generic session heaviness probe ---
105
+ #
106
+ # "How heavy was this session?" — context window usage + credits spent.
107
+ # This is inherently provider-specific: each CLI stores (or doesn't store) usage
108
+ # differently. Rather than hardcode any one CLI in this file, brainiac reads a
109
+ # `heaviness_probe` block from the provider's cli-providers/<name>.json. That config
110
+ # declares WHICH probe strategy to use and WHERE its data lives, e.g.:
111
+ #
112
+ # "heaviness_probe": { "type": "kiro_sqlite", "db_path": "~/.local/share/kiro-cli/data.sqlite3" }
113
+ #
114
+ # The config controls the "what and where" (enable/disable a provider, point it at a
115
+ # moved db) with zero code changes. The "how" for each probe TYPE lives here in Ruby —
116
+ # a genuinely new storage mechanism (a provider that logs usage to JSON, an HTTP
117
+ # endpoint, etc.) still needs a small probe implementation, but pointing kiro at a new
118
+ # path or turning a provider's probe on/off is pure JSON.
119
+ #
120
+ # Providers with no `heaviness_probe` (or an unknown type) simply yield nil and the
121
+ # history record carries timing/identity only.
122
+ #
123
+ # Returns a Hash of string-keyed heaviness fields, or nil if unavailable:
124
+ # context_window_tokens, context_usage_pct, context_used_tokens, credits_used
125
+ def session_heaviness(resolved:, chdir:)
126
+ return nil unless resolved && chdir
127
+
128
+ probe = resolved["heaviness_probe"]
129
+ return nil unless probe.is_a?(Hash)
130
+
131
+ case probe["type"]
132
+ when "kiro_sqlite"
133
+ kiro_session_heaviness(chdir, db_path: probe["db_path"])
134
+ end
135
+ rescue StandardError => e
136
+ LOG.warn "[SessionHistory] Heaviness probe failed for #{chdir}: #{e.message}"
137
+ nil
138
+ end
139
+
140
+ # kiro-cli persists every conversation in a local sqlite keyed by working directory.
141
+ # Each conversation's JSON carries the model's context window, the latest request's
142
+ # context-usage percentage, and per-request credit usage. We read it read-only via the
143
+ # sqlite3 CLI (no gem dependency) and derive the heaviness fields. Best-effort: any
144
+ # problem (missing db, no row for this cwd, malformed json) yields nil.
145
+ #
146
+ # The db location comes from the provider's heaviness_probe.db_path so it's not baked
147
+ # into brainiac; KIRO_DEFAULT_DB_PATH is only the fallback.
148
+ KIRO_DEFAULT_DB_PATH = File.join(Dir.home, ".local", "share", "kiro-cli", "data.sqlite3")
149
+
150
+ def kiro_session_heaviness(chdir, db_path: nil)
151
+ db = File.expand_path(db_path || KIRO_DEFAULT_DB_PATH)
152
+ return nil unless File.exist?(db)
153
+
154
+ key = File.expand_path(chdir)
155
+ # The CTE picks the most recently updated conversation for this working directory,
156
+ # then we pull the model's context window, the latest request's context-usage %, and
157
+ # the summed credit spend. `.timeout` (via -cmd, so it doesn't emit output) keeps us
158
+ # from hanging if kiro-cli is mid-write.
159
+ sql = <<~SQL.gsub(/\s+/, " ").strip
160
+ WITH latest AS (
161
+ SELECT value FROM conversations_v2
162
+ WHERE key = #{sqlite_quote(key)} ORDER BY updated_at DESC LIMIT 1
163
+ )
164
+ SELECT
165
+ json_extract(value, '$.model_info.context_window_tokens'),
166
+ (SELECT r.value ->> 'context_usage_percentage'
167
+ FROM latest, json_each(json_extract(latest.value, '$.user_turn_metadata.requests')) r
168
+ ORDER BY CAST(r.key AS INTEGER) DESC LIMIT 1),
169
+ (SELECT ROUND(SUM(CAST(u.value ->> 'value' AS REAL)), 4)
170
+ FROM latest, json_each(json_extract(latest.value, '$.user_turn_metadata.usage_info')) u
171
+ WHERE (u.value ->> 'unit') = 'credit')
172
+ FROM latest;
173
+ SQL
174
+
175
+ out = ""
176
+ status = nil
177
+ Timeout.timeout(6) do
178
+ out, status = Open3.capture2(
179
+ "sqlite3", "-separator", "\t", "-cmd", ".timeout 3000",
180
+ "file:#{db}?mode=ro", sql
181
+ )
182
+ end
183
+ return nil unless status&.success?
184
+
185
+ row = out.strip
186
+ return nil if row.empty?
187
+
188
+ window, pct, credits = row.split("\t", 3)
189
+ window = window.to_i
190
+ return nil if window.zero?
191
+
192
+ pct = pct.to_f
193
+ fields = { "context_window_tokens" => window, "context_usage_pct" => pct.round(2) }
194
+ fields["context_used_tokens"] = (window * pct / 100.0).round if pct.positive?
195
+ fields["credits_used"] = credits.to_f.round(4) if credits && !credits.empty?
196
+ fields
197
+ end
198
+
199
+ # Single-quote a string for safe literal interpolation into SQLite SQL.
200
+ def sqlite_quote(str)
201
+ "'#{str.to_s.gsub("'", "''")}'"
202
+ end
@@ -2,5 +2,5 @@
2
2
 
3
3
  module Brainiac
4
4
  # @return [String] the current gem version
5
- VERSION = "0.0.33"
5
+ VERSION = "0.1.0"
6
6
  end
data/lib/brainiac.rb CHANGED
@@ -5,6 +5,7 @@ require_relative "brainiac/agents"
5
5
  require_relative "brainiac/brain"
6
6
  require_relative "brainiac/skills"
7
7
  require_relative "brainiac/sessions"
8
+ require_relative "brainiac/session_history"
8
9
  require_relative "brainiac/prompts"
9
10
  require_relative "brainiac/helpers"
10
11
  require_relative "brainiac/intent"
data/receiver.rb CHANGED
@@ -19,6 +19,7 @@ require_relative "lib/brainiac/agents"
19
19
  require_relative "lib/brainiac/brain"
20
20
  require_relative "lib/brainiac/skills"
21
21
  require_relative "lib/brainiac/sessions"
22
+ require_relative "lib/brainiac/session_history"
22
23
  require_relative "lib/brainiac/prompts"
23
24
  require_relative "lib/brainiac/helpers"
24
25
  require_relative "lib/brainiac/notifications"
@@ -100,6 +101,16 @@ configure do
100
101
  end
101
102
 
102
103
  LOG.info "[Brainiac] Starting v#{BRAINIAC_VERSION} on port #{settings.port} (#{settings.environment})"
104
+ LOG.info "[Brainiac] Server root: #{SERVER_ROOT} (pid #{Process.pid})"
105
+
106
+ # Warn loudly when the server is running from an installed gem rather than a git
107
+ # checkout. During development this is almost always a mistake: `brainiac` on PATH
108
+ # resolves to the gem's bin, so edits to a working checkout never take effect. Surfacing
109
+ # it here turns a long "why won't my change apply" hunt into a one-line startup notice.
110
+ if SERVER_ROOT.include?("/gems/")
111
+ LOG.warn "[Brainiac] Running from an installed GEM (#{SERVER_ROOT}) — not a git checkout. " \
112
+ "Local code changes will NOT be loaded. Run `ruby ./bin/brainiac server` from your checkout to test edits."
113
+ end
103
114
  if intent_config["enabled"]
104
115
  LOG.info "[Intent] Enabled — model: #{intent_config["model"]}, endpoint: #{intent_config["endpoint"]}"
105
116
  begin
@@ -18,5 +18,10 @@
18
18
  "qwen": "qwen3-coder-next",
19
19
  "auto": "auto"
20
20
  },
21
- "efforts": ["low", "medium", "high", "xhigh", "max"]
21
+ "efforts": ["low", "medium", "high", "xhigh", "max"],
22
+ "heaviness_probe": {
23
+ "comment": "Optional. Lets brainiac record how 'heavy' a finished session was (context window usage + credits) in the durable session history. type selects the probe strategy; db_path points at the provider's local usage store. Omit this block to record timing/identity only.",
24
+ "type": "kiro_sqlite",
25
+ "db_path": "~/.local/share/kiro-cli/data.sqlite3"
26
+ }
22
27
  }
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: brainiac
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.33
4
+ version: 0.1.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andy Davis
@@ -142,6 +142,7 @@ files:
142
142
  - lib/brainiac/prompts.rb
143
143
  - lib/brainiac/restart.rb
144
144
  - lib/brainiac/routes/api.rb
145
+ - lib/brainiac/session_history.rb
145
146
  - lib/brainiac/sessions.rb
146
147
  - lib/brainiac/skills.rb
147
148
  - lib/brainiac/users.rb