picoclaw/pkg
Liu Yuan 15a70ac45c
feat(seahorse): implement short-term memory engine (LCM) (#2285)
* feat(seahorse): implement short-term memory engine of seahorse

Add pkg/seahorse/ module implementing a SQLite-backed DAG-based summary
hierarchy for context management, ported from lossless-claw's LCM design:

- types.go + short_constants.go: core types (Message, Summary, Conversation,
  ContextItem) and configuration constants (fanout, token targets, thresholds)
- migration.go: idempotent DB schema with FTS5 trigram tokenizer for CJK
- store.go: full SQLite CRUD (conversations, messages, summaries DAG,
  context_items with ordinal gap numbering, FTS5 search)
- short_engine.go: Engine lifecycle (NewEngine, Ingest, Assemble, Compact),
  session pattern filtering (ignore/stateless glob→regex compilation),
  per-session mutex via sync.Map
- short_assembler.go: budget-aware context assembly with fresh tail protection
  (32 messages), oldest-first eviction, summary XML formatting, RebuildContextItems
- short_compaction.go: leaf compaction (messages→summary) and condensed
  compaction (summaries→higher-level summary), 3-level LLM escalation,
  CompactUntilUnder for emergency overflow
- short_retrieval.go: lookupByID, FTS5/LIKE search, recursive expand with
  token cap
- context_seahorse.go: agent.ContextManager adapter, registered as "seahorse",
  provider↔seahorse message type conversion (ToolCalls, tool_result)

* fix(seahorse): correct 3 adapter bugs in context management

- TokenCount: use full message (Content+ToolCalls+Media) instead of Content-only
- Empty Content: rebuild Content from tool_result Parts when stored empty
- Duplicate summaries: summaries only in Summary field, not in History messages
- Grep: fix SearchResult.Snippet→Content for summaries
- Schema: fix FTS5 SQL uses VIRTUAL TABLE not TEMP TABLE
- TestFTS5SQLConstants: verify FTS5 SQL syntax correctness
- Test: fix flaky TestCompactLeaf

* fix(agent): ingest steering messages into seahorse SQLite

Steering messages were only persisted to session JSONL but not ingested
into seahorse SQLite, causing them to be missing from context assembly.

Added `ts.ingestMessage(turnCtx, al, pm)` call in the steering message
injection block alongside the existing JSONL persistence.

Test: TestSeahorseSteeringMessageIngested verifies steering messages
appear in seahorse SQLite DB after being processed.

* fix(seahorse): address 3 blocking bugs from code review

- Fix resequenceContextItemsTx scan error handling (store.go:850)
  Changed `return err` to `return scanErr` to properly propagate scan errors
  instead of returning nil (which silently corrupts data)

- Fix sql.NullString for INTEGER column (store.go:847)
  Changed `mid` from sql.NullString to sql.NullInt64 since message_id
  is INTEGER in schema. Removed unnecessary strconv.ParseInt call.

- Fix compactCondensed fallback deleting non-candidate items
  Added ReplaceContextItemsWithSummary method for per-item deletion
  when candidates are not contiguous in ordinal space.
  Optimized to use range deletion when candidates are consecutive.

* fix(seahorse): pass Budget to Compact for correct condensed threshold

Issue #4 from PR review: When Budget was not passed to seahorse.Compact,
it defaulted to `tokensBefore * 0.75`, making `tokensBefore > budget`
always true and causing condensed compaction to trigger unnecessarily.

Changes:
- context_seahorse.go: Forward Budget from CompactRequest to CompactInput
- loop.go: Pass Budget (ContextWindow) in all 3 Compact calls
- Add test verifying condensed is skipped when tokens < threshold
- Fix lint issues in store.go and store_test.go

* fix(seahorse): add mutex for assembler lazy initialization

Issue #5 from PR review: The check-then-create pattern for e.assembler
was a data race when multiple goroutines called Assemble() concurrently:
    if e.assembler == nil {
        e.assembler = &Assembler{...}
    }

Changes:
- Add assemblerMu sync.Mutex to Engine struct
- Add initAssemblerOnce() using double-checked locking (same pattern as initCompactionOnce)
- Add TestAssemblerLazyInitRace to verify thread-safety

* fix(seahorse): handle non-consecutive depths in selectShallowestCondensationCandidate

Issue #8 from PR review: the loop iterated depth 0, 1, 2... assuming
consecutive keys, but break when key was missing caused deeper depths
to never be checked.

Fix: collect all existing depth keys, sort, then iterate in order.

* fix(seahorse): wrap DeleteMessagesAfterID and appendContextItems in transactions

- DeleteMessagesAfterID: wrap all DELETE operations in a transaction for
  atomicity, remove redundant manual FTS delete (handled by trigger)
- appendContextItems: use transaction to fix read-then-write race condition
- Add GetMaxOrdinalTx and resolveItemTokenCountTx for transaction-scoped queries
- Remove unused resolveItemTokenCount function

Fixes PR review issues 6 and 7.

* fix(seahorse): derive readable content from Parts and cap CompactUntilUnder iterations

- Derive readable content from MessageParts in AddMessageWithParts so
  FTS5 indexing and summary formatting can access tool call information
- formatMessagesForSummary and truncateSummary now fall back to Parts
  when Content is empty, fixing blank summaries for Part-based messages
- Add MaxCompactIterations (20) to prevent CompactUntilUnder infinite
  loops; exceeded iterations are logged as warnings
2026-04-05 09:05:16 +08:00
..
agent feat(seahorse): implement short-term memory engine (LCM) (#2285) 2026-04-05 09:05:16 +08:00
audio Refactor/asr tts (#1939) 2026-04-01 12:21:21 +08:00
auth Merge branch 'main' into t3 2026-03-29 01:25:20 +08:00
bus Refactor/asr tts (#1939) 2026-04-01 12:21:21 +08:00
channels feat(web): support image messages in pico chat (#2299) 2026-04-03 14:15:20 +08:00
commands resolve conflicts 2026-03-22 23:36:25 +01:00
config feat(mcp): store oversized text results as artifacts (#2308) 2026-04-04 01:30:36 +08:00
constants refactor: replace bool map with set-style map for internal channels (#472) 2026-02-19 11:48:17 +01:00
credential refactor config and security to simplified the structure (#2068) 2026-03-28 00:03:34 +08:00
cron refactor(cron): remove deliver and type params, unify agent execution path (#2147) 2026-03-29 22:52:34 +08:00
devices refactor: cleanup dead code and turn on dead code detection in CI (#515) 2026-02-24 21:52:25 +08:00
fileutil Merge pull request #1829 from perhapzz/test/add-fileutil-health-tests 2026-03-26 10:42:13 +01:00
gateway feat: add VK channel support (#2276) 2026-04-03 10:56:26 +08:00
health add pid file for gateway running and auth token for /reload and pico channel 2026-03-29 01:14:39 +08:00
heartbeat fix(heartbeat): ignore untouched default template 2026-03-15 21:58:21 +08:00
identity fix(identity): support negative integers in isNumeric for Telegram group IDs 2026-03-21 17:09:02 +07:00
logger unify all panic event to panic log file (#2250) 2026-04-01 23:26:49 +08:00
mcp feat(mcp): support DisableStandaloneSSE for HTTP transport (#2108) 2026-03-29 14:37:22 +08:00
media Fix 1886 media cleanup policy (#1887) 2026-03-23 12:13:59 +08:00
memory feat(seahorse): implement short-term memory engine (LCM) (#2285) 2026-04-05 09:05:16 +08:00
migrate add pid file for gateway running and auth token for /reload and pico channel 2026-03-29 01:14:39 +08:00
pid bug: fix picoToken is empty when gateway started by launcher (#2241) 2026-04-01 14:59:18 +08:00
providers fix(tool): clarify write_file nested-JSON escape semantics and add tests (#2320) 2026-04-04 17:56:49 +08:00
routing refactor Config to add Version and migratable 2026-03-12 13:52:55 +08:00
seahorse feat(seahorse): implement short-term memory engine (LCM) (#2285) 2026-04-05 09:05:16 +08:00
session feat(seahorse): implement short-term memory engine (LCM) (#2285) 2026-04-05 09:05:16 +08:00
skills enhance skill installer (#1252) 2026-03-13 14:04:02 +08:00
state refactor Config to add Version and migratable 2026-03-12 13:52:55 +08:00
tokenizer feat(seahorse): implement short-term memory engine (LCM) (#2285) 2026-04-05 09:05:16 +08:00
tools fix(tool): clarify write_file nested-JSON escape semantics and add tests (#2320) 2026-04-04 17:56:49 +08:00
updater feat(updater): robust self-update selection & extraction (nightly default) (#2201) 2026-04-01 23:41:32 +08:00
utils Merge pull request #2176 from Alix-007/fix/issue-2135-retry-after 2026-03-30 16:27:46 +02:00
env.go Merge branch 'main' into version 2026-03-19 18:04:58 +08:00