Commit graph

66 commits

Author SHA1 Message Date
Kent Overstreet
35f231233f clear activity indicator on error paths
"thinking..." was getting stuck in the status bar when a turn
ended with a stream error, context overflow, or model error —
only the success path cleared it. Now all error returns clear
the activity indicator.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 17:53:51 -04:00
Kent Overstreet
91eb9c95cc delete 20 dead public functions across 12 files
Removed functions with zero callers: parse_timestamp_to_epoch,
hash_key, search_weighted_debug, extract_query_terms, format_results,
move_to_neighbor, adjust_edge_strength, update_graph_metrics,
nearest_to_seeds, nystrom_project, chat_completion_stream, cmd_read,
context_message, split_candidates, split_plan_prompt,
split_extract_prompt, log_event_pub, log_verbose, rpc_record_hits,
memory_definitions. -245 lines.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 16:21:01 -04:00
Kent Overstreet
b0e852a05f add unreachable_pub lint, fix all 17 violations
pub → pub(crate) for SseReader methods (used across child modules).
pub → pub(super) for openai::stream_events, tool definitions, store
helpers. pub → private for normalize_link and differentiate_hub_with_graph
(only used within their own files).

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 16:15:32 -04:00
Kent Overstreet
af3929cc65 simplify compaction: Agent owns config, compact() reloads everything
Agent stores AppConfig and prompt_file, so compact() reloads
identity internally — callers no longer pass system_prompt and
personality. restore_from_log() loads entries and calls compact().

Remove soft compaction threshold and pre-compaction nudge (journal
agent handles this). Remove /compact and /context commands (F10
debug screen replaces both). Inline do_compact, emergency_compact,
trim_and_reload into compact(). Rename model_context_window to
context_window, drop unused model parameter.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 16:08:41 -04:00
Kent Overstreet
d419587c1b WIP: trim_entries dedup, context_window rename, compact simplification
Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 15:58:03 -04:00
Kent Overstreet
809679b6ce delete dead flat-file journal tool and ephemeral stripping
Journal entries are written to the memory graph via journal_new/
journal_update, not appended to a flat file. Remove thought/journal.rs
(67 lines), strip_ephemeral_tool_calls (55 lines), default_journal_path,
and all wiring. -141 lines.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 15:35:56 -04:00
Kent Overstreet
aceaf0410e delete dead flat-file journal code from thought/context.rs
Journal entries are loaded from the memory graph store, not from the
flat journal file. Remove build_context_window, plan_context,
render_journal_text, assemble_context, truncate_at_section,
find_journal_cutoff, parse_journal*, ContextPlan, and stale TODOs.
Keep JournalEntry, default_journal_path (write path), and the live
context management functions. -363 lines.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 15:31:12 -04:00
Kent Overstreet
214806cb90 move context functions from agent/context.rs to thought/context.rs
trim_conversation moved to thought/context.rs where model_context_window,
msg_token_count, is_context_overflow, is_stream_error already lived.
Delete the duplicate agent/context.rs (94 lines).

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 15:28:00 -04:00
Kent Overstreet
01bfbc0dad move journal types from agent/journal.rs to thought/context.rs
JournalEntry, parse_journal, parse_journal_text, parse_header_timestamp,
and default_journal_path consolidated into thought/context.rs. Delete
the duplicate agent/journal.rs (235 lines). Update all references.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 15:25:07 -04:00
Kent Overstreet
e0a54a3b43 save request payload on any API error, not just timeouts
Serialize request JSON before send_and_check so it's available
for both HTTP errors and stream errors. Extracted save logic
into save_failed_request helper on SseReader.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 15:19:26 -04:00
Kent Overstreet
64dbcbf061 unify memory tracking: entries are the single source of truth
Memory tool results (memory_render) are now pushed as
ConversationEntry::Memory with the node key, instead of plain
Messages. Remove loaded_nodes from ContextState — the debug
screen reads memory info from Memory entries in the conversation.

Surfaced memories from surface-observe are pushed as separate
Memory entries, reflections as separate system-reminder messages.
User input is no longer polluted with hook output.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 14:56:02 -04:00
Kent Overstreet
a21cf31ad2 unify conversation persistence to append-only jsonl
Log ConversationEntry (with Memory/Message typing) instead of
raw Message. restore_from_log reads typed entries directly,
preserving Memory vs Message distinction across restarts.

Remove current.json snapshot and save_session — the append-only
log is the single source of truth. Remove dead read_all and
message_count methods. Add push_entry for logging typed entries.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 14:31:19 -04:00
Kent Overstreet
1f7b585d41 remove Anthropic backend, add request logging on timeout
Delete anthropic.rs (713 lines) — we only use OpenAI-compatible
endpoints (vLLM, OpenRouter). Simplify ApiClient to store base_url
directly instead of Backend enum.

SseReader now stores the serialized request payload and saves it
to ~/.consciousness/logs/failed-request-{ts}.json on stream timeout,
so failed requests can be replayed with curl for debugging.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 14:13:23 -04:00
Kent Overstreet
078dcf22d0 cleanup: remove model name string matching
model_context_window() now reads from config.api_context_window
instead of guessing from model name strings. is_anthropic_model()
replaced with backend == "anthropic" checks. Dead model field
removed from AgentDef/AgentHeader.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 14:09:54 -04:00
Kent Overstreet
47c6694b10 Remove dead code: old context builder, plan_context, journal parsing
Removed from context.rs: ContextPlan, plan_context,
render_journal_text, assemble_context, truncate_at_section,
find_journal_cutoff, parse_msg_timestamp. All replaced by
trim_conversation + journal from memory graph.

Removed from tui.rs: most_recent_file, format_duration
(filesystem scanning leftovers).

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 03:40:35 -04:00
Kent Overstreet
e9e47eb798 Replace build_context_window with trim_conversation
build_context_window loaded journal from a stale flat file and
assembled the full context. Now journal comes from the memory graph
and context is assembled on the fly. All that's needed is trimming
the conversation to fit the budget.

trim_conversation accounts for identity, journal, and reserve
tokens, then drops oldest conversation messages until it fits.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 03:35:28 -04:00
Kent Overstreet
87add36cdd Fix: don't overwrite journal during restore/compaction
The restore and compaction paths called build_context_window which
reads from the stale flat journal file, overwriting the journal we
loaded from the memory graph. Preserve the graph-loaded journal
across these operations.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 03:33:04 -04:00
Kent Overstreet
b9e3568385 ConversationEntry enum: typed memory vs conversation messages
Replace untyped message list with ConversationEntry enum:
- Message(Message) — regular conversation turn
- Memory { key, message } — memory content with preserved message
  for KV cache round-tripping

Budget counts memory vs conversation by matching on enum variant.
Debug screen labels memory entries with [memory: key]. No heuristic
tool-name scanning.

Custom serde: Memory serializes with a memory_key field alongside
the message fields, deserializes by checking for the field.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 03:26:00 -04:00
Kent Overstreet
eb4dae04cb Compute ContextBudget on demand from typed sources
Remove cached context_budget field and measure_budget(). Budget
is computed on demand via budget() which calls
ContextState::budget(). Each bucket counted from its typed source.
Memory split from conversation by identifying memory tool calls.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 03:07:45 -04:00
Kent Overstreet
acdfbeeac3 Align debug screen and budget with conversation-only messages
context.messages is conversation-only now — remove conv_start
scanning. Memory counted from loaded_nodes (same as debug screen).
No subtraction heuristics.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 02:56:28 -04:00
Kent Overstreet
5e781e9ae4 Fix budget counting: remove stale refresh_context_message
refresh_context_message was injecting personality into conversation
messages (assuming fixed positions that no longer exist). Replaced
with refresh_context_state which just re-measures and publishes.

conv_tokens now subtracts mem_tokens since memory tool results are
in the conversation message list.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 02:52:59 -04:00
Kent Overstreet
a0aacfc552 Move conversation messages into ContextState
ContextState now owns everything in the context window:
system_prompt, personality, journal, working_stack, loaded_nodes,
and conversation messages. No duplication — each piece exists once
in its typed form.

assemble_api_messages() renders the full message list on the fly
from typed sources. measure_budget() counts each bucket from its
source directly. push_context() removed — identity/journal are
never pushed as messages.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 02:47:32 -04:00
Kent Overstreet
4580f5dade measure_budget: count from typed sources, not message scanning
Identity tokens from system_prompt + personality vec. Journal
from journal entries vec. Memory from loaded_nodes. Conversation
is the remainder. No string prefix matching.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 02:32:26 -04:00
Kent Overstreet
4bdc7ae112 Journal budget: count from structured data, not string matching
Count journal tokens directly from Vec<JournalEntry> instead of
scanning message text for prefix strings. Type system, not string
typing.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 02:29:48 -04:00
Kent Overstreet
5526a26d4c Journal: store as structured Vec<JournalEntry>, not String
Keep journal entries as structured data in ContextState. Render
to text only when building the context message. Debug screen reads
the structured entries directly — no parsing ## headers back out.

Compaction paths temporarily parse the string from build_context_window
back to entries (to be cleaned up when compaction is reworked).

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 02:21:45 -04:00
Kent Overstreet
42f1e888c4 Journal: flat 5% context window budget, skip plan_context
Render journal entries directly with ## headers instead of going
through the plan_context/render_journal_text pipeline. 5% of
model context window (~6500 tokens for Qwen 128K). Simpler and
predictable.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 02:00:14 -04:00
Kent Overstreet
7776d87d53 Journal: walk backwards with token budget, not load-all
Iterate journal entries backwards from the conversation cutoff,
accumulating within ~10K token budget (~8% of context window).
Stops when budget is full, keeps at least one entry. Much more
efficient than loading all entries and trimming.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 01:50:36 -04:00
Kent Overstreet
e4285ba75f Load journal from memory graph, not flat file
Replace flat-file journal parser with direct store query for
EpisodicSession nodes. Filter journal entries to only those older
than the oldest conversation message (plus one overlap entry to
avoid gaps). Falls back to 20 recent entries when no conversation
exists yet.

Fixes: poc-agent context window showing 0 journal entries.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 01:48:16 -04:00
Kent Overstreet
c814ed1345 Split hook.rs: core orchestration -> subconscious.rs
subconscious::subconscious — AgentCycleState, AgentInfo, AgentSnapshot,
  SavedAgentState, format_agent_output, cycle methods. Core agent
  lifecycle independent of Claude Code.

subconscious::hook — Claude Code hook: context loading, chunking,
  seen-set management, run_agent_cycles (serialized state entry point).

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 01:37:51 -04:00
Kent Overstreet
9ac50bd999 Track agent child processes, reap on completion
spawn_agent returns Child handle + log_path. AgentCycleState stores
the Child, polls with try_wait() on each trigger to detect completion.
No more filesystem scanning to track agent lifecycle.

AgentSnapshot (Clone) sent to TUI for display. AgentInfo holds the
Child handle and stays in the state.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 01:20:03 -04:00
Kent Overstreet
a90bd4fd47 Agent log screen: show agent output, not hook log
spawn_agent() now returns SpawnResult { pid, log_path } so the
log path is known at spawn time. No more filesystem scanning.
AgentInfo carries log_path, TUI reads it directly.

F2 → Enter shows the actual agent log (stdout/stderr from the
poc-memory agent process), not the hook orchestration log.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 01:04:54 -04:00
Kent Overstreet
1c190a3925 Wire AgentCycleState through runner and TUI
Runner owns AgentCycleState, calls trigger() on each user message
instead of the old run_hook() JSON round-trip. Sends AgentUpdate
messages to TUI after each cycle.

TUI F2 screen reads agent state from messages instead of scanning
the filesystem on every frame. HookSession::from_fields() lets
poc-agent construct sessions without JSON serialization.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 00:52:57 -04:00
Kent Overstreet
a0245c1279 Refactor hook: split agent orchestration from formatting
- Remove POC_AGENT early return (was from old claude -p era)
- Split hook into run_agent_cycles() -> AgentCycleOutput (returns
  memory keys + reflection) and format_agent_output() (renders for
  Claude Code injection). poc-agent can call run_agent_cycles
  directly and handle output its own way.
- Fix UTF-8 panic in runner.rs display_buf slicing (floor_char_boundary)
- Add priority debug label to API requests
- Wire up F2 agents screen: live pid status, output files, hook log
  tail, arrow key navigation, Enter for log detail view

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-02 00:32:23 -04:00
Kent Overstreet
c72eb4d528 vLLM priority scheduling for agents
Thread request priority through the API call chain to vLLM's
priority scheduler. Lower value = higher priority, with preemption.

Priority is set per-agent in the .agent header:
- interactive (runner): 0 (default, highest)
- surface-observe: 1 (near-realtime, watches conversation)
- all other agents: 10 (batch, default if not specified)

Requires vLLM started with --scheduling-policy priority.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-04-01 23:21:39 -04:00
ProofOfConcept
13453606ae refactor: runner owns stream routing, suppress tool call XML from display
Split the streaming pipeline: API backends yield StreamEvents through
a channel, the runner reads them and routes to the appropriate UI pane.

- Add StreamEvent enum (Content, Reasoning, ToolCallDelta, etc.)
- API start_stream() spawns backend as a task, returns event receiver
- Runner loops over events, sends content to conversation pane but
  suppresses <tool_call> XML with a buffered tail for partial tags
- OpenAI backend refactored to stream_events() — no more UI coupling
- Anthropic backend gets a wrapper that synthesizes events from the
  existing stream() (TODO: native event streaming)
- chat_completion_stream() kept for subconscious agents, reimplemented
  on top of the event stream
- Usage derives Clone

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-03-29 21:22:42 -04:00
ProofOfConcept
2a64d8e11f move leaked tool call recovery into build_response_message
Tool call parsing was only in runner.rs, so subconscious agents
(poc-memory agent run) never recovered leaked tool calls from
models that emit <tool_call> as content text (e.g. Qwen via Crane).

Move the recovery into build_response_message where both code paths
share it. Leaked tool calls are promoted to structured tool_calls
and the content is cleaned, so all consumers see them uniformly.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-03-29 20:57:59 -04:00
ProofOfConcept
39b07311e6 logs: consolidate all logging under ~/.consciousness/logs/
All log output was scattered across ~/.consciousness/memory/ (daemon,
task logs, LLM call logs), ~/.consciousness/agent-sessions/ (observe),
and only hook logs were already in the right place.

Move everything to ~/.consciousness/logs/ with agent-specific subdirs:
  - daemon.log, daemon/ (task logs)
  - {agent_name}/ (knowledge agent logs, e.g. surface-observe/, reflect/)
  - llm/{caller}/ (LLM call logs)
  - observe.log (poc-agent observe)
  - hook-{session_id} (already correct)
  - debug.log (already correct)

Also includes the session.rs and hook.rs fixes from the previous
session (sessions dir → ~/.consciousness/sessions/).

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-03-28 20:39:20 -04:00
Kent Overstreet
0d2bf81a50 consciousness: identity files load from ~/.consciousness/identity/
Separate identity files (loaded via source: "file" in context_groups)
from the memory store (data_dir). New identity_dir config field,
defaults to ~/.consciousness/identity/.

Also restrict subconscious agents to memory-only tools — no
filesystem write access. This prevents agents from creating stray
.md files in the memory directory.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
2026-03-28 19:49:13 -04:00
ProofOfConcept
35d925186d consciousness: update hardcoded paths from ~/.claude to ~/.consciousness
- thalamus/src/idle.rs: dream-start.sh path
- src/agent/dmn.rs: telegram/send.sh path

Part of the directory migration to make this an independent project.
2026-03-27 21:32:28 -04:00
ProofOfConcept
c3cd27ec22 move poc-agent session dir from cache to ~/.consciousness/
session_dir() was using dirs::cache_dir() with /tmp fallback.
Move to ~/.consciousness/agent-sessions/ alongside everything else.
2026-03-27 21:29:39 -04:00
ProofOfConcept
ccf13c3cb5 cleanup: remove dead migrate module, fix stale comment
migrate.rs was a one-time markdown→capnp conversion that's long done.
Remove it and update the identity.rs comment to reference the new
~/.consciousness/ path.
2026-03-27 21:08:40 -04:00
ProofOfConcept
6a1660cc9d move data home from ~/.claude/memory to ~/.consciousness
The consciousness project should stand independently of Claude Code.
All data, logs, sessions, and agent state now live under
~/.consciousness/ instead of being scattered across ~/.claude/memory/,
/tmp/claude-memory-search/, ~/.config/poc-memory/, and ~/.cache/.

Layout:
  ~/.consciousness/
    *.capnp, *.bin, *.rkyv  — store files
    sessions/               — per-session state (seen sets, cookies)
    logs/                   — all logs (hook, agent, debug, dream)
    agents/                 — agent runtime state (pid files, output)
    notifications/          — notification state
    cache/                  — transient data

Things that stay in ~/.claude/:
  - projects/    (Claude Code transcripts)
  - hooks/       (Claude Code hook system)
  - telegram/    (shared integration)
  - irc/         (shared integration)
  - settings.json (Claude Code settings)

Debug log moves from /tmp/ to ~/.consciousness/logs/debug.log.
Session state moves from /tmp/claude-memory-search/ to sessions/.
Notifications move from ~/.claude/notifications/ to notifications/.
2026-03-27 21:07:17 -04:00
ProofOfConcept
92ca2bf2c8 provenance: pass directly through thought::dispatch, remove globals
Provenance now flows as a function parameter through the entire tool
dispatch chain: thought::dispatch → memory::dispatch → store methods.

Removed task_local (TASK_AGENT), thread_local (TASK_PHASE), and env
var (POC_PROVENANCE) from the tool dispatch path. The env var remains
only as a fallback for non-tool paths (CLI commands, digest).

Phase names are passed from knowledge.rs → llm.rs → api.rs, and
api.rs updates the provenance string between steps. No globals needed.
2026-03-27 15:44:39 -04:00
ProofOfConcept
36bde60ba0 thought: wire up agent and subconscious to use shared tools
- agent/tools/mod.rs: remove duplicated tool implementations, delegate
  to thought::dispatch for shared tools, keep only agent-specific
  tools (control, vision, working_stack)
- subconscious/api.rs: replace duplicated memory/tool dispatch with
  thought::dispatch, use thought::all_definitions() for tool schemas
- Delete agent/tools/{bash,read,write,edit,grep,glob_tool,journal,memory}.rs
  (now live in thought/)

Both poc-agent and subconscious agents now use the same tool
implementations through the thought layer. Agent-specific behavior
(node tracking in runner.rs, control tools) stays in agent/.
2026-03-27 15:27:33 -04:00
ProofOfConcept
bfc558893a thought: create shared cognitive substrate module
New src/thought/ module containing tools and infrastructure shared
between poc-agent and subconscious agents: memory operations, file
tools, bash, context window management.

Currently coexists with agent/tools/ — next step is to wire up both
agent/ and subconscious/ to use thought::dispatch instead of
duplicating the routing logic.

Move dbglog macro to lib.rs so it's available crate-wide regardless
of module compilation order.
2026-03-27 15:22:48 -04:00
ProofOfConcept
37acb9502d rename agent: fix tool calls and target override
- Add memory_rename tool (in-place rename, preserves content and links)
- Update rename.agent prompt to use memory_rename() instead of text output
- Fix {{rename}} placeholder to respect --target keys when provided
- Add format_rename_targets() for targeted rename runs
2026-03-27 15:10:55 -04:00
ProofOfConcept
27861a44e5 surface: tag recent nodes as (new) instead of hiding them
Links to nodes created after the conversation window start are
tagged with (new) in memory_render output. The surface prompt
tells the agent not to surface these — they're its own recent
output, not prior memories. Observe can still see and update them.

POC_MEMORIES_OLDER_THAN env var set from the oldest message
timestamp in the conversation window.

Co-Authored-By: Kent Overstreet <kent.overstreet@linux.dev>
2026-03-26 21:19:19 -04:00
ProofOfConcept
5647842412 journal_new: separate name from title, dedup keys
- journal_new(name, title, body): name becomes the node key,
  title goes in the ## heading. Agent picks short searchable names.
- Auto-dedup: if the key exists, append -2, -3, etc.
- CLI journal write also requires a name argument now.

Co-Authored-By: Kent Overstreet <kent.overstreet@linux.dev>
2026-03-26 19:24:19 -04:00
ProofOfConcept
eac59b423e journal: remove all stringly-typed key patterns, use NodeType
- journal_new: key is slugified title (agent names things properly)
- journal_tail: sort by created_at (immutable), not timestamp (mutable)
- journal_update: find latest by created_at
- {{latest_journal}}: query by NodeType::EpisodicSession, not "journal" key
- poc-memory journal write: requires a name argument
- Removed all journal#j-{timestamp}-{slug} patterns from:
  - prompts.rs (rename candidates)
  - graph.rs (date extraction, organize skip list)
  - cursor.rs (date extraction)
  - store/mod.rs (doc comment)
- graph.rs organize: filter by NodeType::Semantic instead of key prefix
- cursor.rs: use created_at for date extraction instead of key parsing

Co-Authored-By: Kent Overstreet <kent.overstreet@linux.dev>
2026-03-26 19:11:17 -04:00
ProofOfConcept
85fa54cba9 journal tools: use NodeType instead of string key matching
- journal_new: create EpisodicSession node with auto-generated key
- journal_tail: query by node_type, not by parsing a monolithic node
- journal_update: find latest EpisodicSession by timestamp
- No string key matching anywhere — all typed
- Fixes journal entries not appearing in 'poc-memory journal tail'
- Also: added --provenance/-p filter to 'poc-memory tail'
- Also: fix early return in surface_observe_cycle store load failure
- Also: scale max_turns by number of steps (50 per step)

Co-Authored-By: Kent Overstreet <kent.overstreet@linux.dev>
2026-03-26 18:41:10 -04:00