{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package sessionlog\n\nPackage sessionlog is memcode's episodic memory: a local, append-only record of the high-level causal trail of a session — user messages, assistant messages, meaningful actions (commands, edits, commits), and approvals — written to disk as it happens, independent of the LLM context window. It is NOT a stdout landfill: internal reads/greps and raw tool output stay out (raw mechanics belong in an optional debug trace, not canonical memory).\n\nThe doctrine it serves:\n\n\tworking context → fast but lossy\n\tsession log     → episodic truth (why/when/under whose approval/side effects)\n\tgit             → code-diff truth\n\tclaims/memories → distilled doctrine\n\nevents.jsonl is the append-only source of truth (replayable); transcript.md is a human-readable rendering written alongside. Readers are deterministic scans — no model, no index — so the agent can self-recall before acting on fuzzy memory.\n\n## Constants\n\n```go\nconst (\n\tKindSessionStarted   = \"session_started\"\n\tKindUserMessage      = \"user_message\"\n\tKindAssistantMessage = \"assistant_message\"\n\tKindToolCall         = \"tool_call\"      // a meaningful action: command, edit, commit — NOT internal reads\n\tKindApproval         = \"approval\"       // a user allow/deny decision\n\tKindToolResult       = \"tool_result\"    // reserved for an optional debug trace; not written to the canonical log\n\tKindCompaction       = \"compaction\"     // older turns summarized in-session (the warm layer's durable record)\n\tKindPlanPresented    = \"plan_presented\" // a plan was presented for approval — full text + slug (recoverable via RecentPlans)\n\tKindPlanCancelled    = \"plan_cancelled\" // planning was ABANDONED before execution — the ask is still open work\n\tKindSessionFinished  = \"session_finished\"\n\tKindPreferenceSignal = \"preference_signal\" // a captured user directive — the CANONICAL copy for the prefs reducer\n\tKindLessonSignal     = \"lesson_signal\"     // a distilled lesson — the CANONICAL copy for the lessons reducer\n\tKindContextInlined   = \"context_inlined\"   // which promoted rules (lesson/pref ids) rode this session's system prompt\n\tKindAdherence        = \"adherence\"         // a rule-adherence verdict about TargetSession — the CANONICAL copy for reducer weighting\n\tKindFacts            = \"facts\"             // one atomic extracted fact about THIS session (post-session cognition) — indexed by ranked search\n)\n```\nRecord kinds. Keep these stable — they're the on-disk contract.\n\n## Variables\n\n```go\nvar Ranking = RankingOptions{}\n```\nRanking is the live configuration. The bench mutates it between adapter runs; the product path only ever reads it.\n\n## Functions\n\n```go\nfunc HasActions(threads []Thread) bool\n```\nHasActions reports whether any thread carries a recorded action (command, edit, approval) — i.e. the session actually did something rather than just exchanging messages. A brand-new session that has only said \"hi\" has none; that's the cue to recap the previous distinct session instead of this near-empty one.\n\n```go\nfunc IsGitCommitPush(input string) bool\n```\nIsGitCommitPush reports whether a tool-call input is an actual \\`git commit\\`/\\`git push\\` INVOCATION — parsed with the shell AST, never a substring match. \\`rg \"git commit\"\\` (the phrase inside a quoted search arg) is NOT a commit; the old substring check flagged it, marking a strand Completed and logging a phantom commit. The input may be a raw command or a bash tool's JSON ({\"command\":\"…\"}); both are handled.\n\n```go\nfunc RenderRecap(threads []Thread) string\n```\nRenderRecap formats threads as a numbered checklist with a drill-deeper hint.\n\n## Types\n\n```go\ntype Digest struct {\n\tRequests []string // user asks in order — the session's sidequests\n\tCommits  []string // git commit/push commands run\n\tTests    int      // verification runs (test/vet/build/lint)\n\tEdits    int      // file-edit tool calls\n}\n```\nDigest is a compact, reduced projection of a session's raw events — the form orientation/prediction should consume (NOT raw events.jsonl, which is noisy and private). It answers \"where did we leave off\": what was asked, what was committed/pushed, how much was tested/edited.\n\n```go\nfunc Reduce(recs []Record) Digest\n```\nReduce projects raw records into a Digest. This is the \"session reducer\" seam: raw log → compact facts → orientation. Keep it deterministic and lossy.\n\n```go\nfunc (d Digest) Lines() []string\n```\nLines renders the digest as compact one-liners for an orientation prompt.\n\n```go\ntype PlanRec struct {\n\tSlug    string\n\tTitle   string\n\tText    string\n\tSession string\n\tTS      time.Time\n}\n```\nPlanRec is a presented plan recovered from a session log — the full markdown plus its slug and where/when it was presented. The canonical, project-scoped record of a plan (independent of the user-level ~/.memcode/plans store), so a plan is recoverable even if that store is empty.\n\n```go\nfunc RecentPlans(root string, limit int) ([]PlanRec, error)\n```\nRecentPlans scans every session's log for presented-plan records, newest first, deduped by slug (the most recent revision of each plan wins). limit ≤ 0 means no limit. Records with no slug (legacy) are kept individually. This is the recovery path recall reaches for when the user-level store doesn't have a plan — e.g. a plan from a prior session, a wiped store, or a new machine.\n\n```go\ntype RankingOptions struct {\n\tFieldWeights bool // per-kind multipliers: facts \u003e compaction \u003e user \u003e assistant \u003e tool\n\tRM3          bool // pseudo-relevance feedback query expansion (skipped on exact-tier hits)\n\tAdjacency    bool // a strong turn credits its immediate neighbors — evidence sits next door\n\tEntityPPR    bool // personalized PageRank over the facts entity graph, RRF-fused at session level\n}\n```\nRankingOptions toggles the retrieval features layered on the BM25 core so membench can isolate each one's lift. Defaults are the measured winners (membench ablation, 2026-07-25): ALL OFF. Facts indexing — the data layer, not a knob here — delivered the lift on both benchmarks (LoCoMo R@5 0.502→0.612, LME R@5 held 0.93+); every global reranking layer measured neutral-to-harmful on at least one dataset (field weights flip sign across granularities, RM3 and adjacency trade R@1 for tail recall, session-level PPR+RRF scrambles good lexical orderings). They remain as options for ablation and for callers with a matching corpus shape.\n\n```go\ntype Record struct {\n\tTS        time.Time `json:\"ts\"`\n\tKind      string    `json:\"kind\"`\n\tText      string    `json:\"text,omitempty\"`        // user/assistant message text\n\tTool      string    `json:\"tool,omitempty\"`        // tool_call/result tool name\n\tInput     string    `json:\"input,omitempty\"`       // tool_call input (redacted JSON)\n\tDecision  string    `json:\"decision,omitempty\"`    // approval: approved | denied | …\n\tToolUseID string    `json:\"tool_use_id,omitempty\"` // links a result to its call (debug trace)\n\tContent   string    `json:\"content,omitempty\"`     // tool_result output (debug trace) / $ shell output\n\tIsError   bool      `json:\"is_error,omitempty\"`    // tool_result / $ shell failed\n\tExit      int       `json:\"exit,omitempty\"`        // $ shell command exit code\n\tModel     string    `json:\"model,omitempty\"`       // session_started\n\tMode      string    `json:\"mode,omitempty\"`        // session_started\n\tHeadSHA   string    `json:\"head_sha,omitempty\"`    // session_started\n\tSlug      string    `json:\"slug,omitempty\"`        // plan_presented: the saved-plan slug (~/.memcode/plans/\u003cslug\u003e.md)\n\tAxis      string    `json:\"axis,omitempty\"`        // preference_signal: which axis (workflow/gating/…)\n\tScope     string    `json:\"scope,omitempty\"`       // preference_signal: this-repo vs global\n\tStrength  float64   `json:\"strength,omitempty\"`    // preference_signal / lesson_signal: evidence weight\n\tTrigger   string    `json:\"trigger,omitempty\"`     // lesson_signal: the recurring failure condition\n\tStrategy  string    `json:\"strategy,omitempty\"`    // lesson_signal: what to do when the trigger holds\n\tEntities  []string  `json:\"entities,omitempty\"`    // facts: lowercase entity keys the fact is about (feeds the session entity graph)\n\n\t// Post-session learning loop fields.\n\tLessonIDs     []string `json:\"lesson_ids,omitempty\"`     // context_inlined: promoted lesson ids in this session's prompt\n\tPrefIDs       []string `json:\"pref_ids,omitempty\"`       // context_inlined: confirmed pref ids in this session's prompt\n\tRuleKind      string   `json:\"rule_kind,omitempty\"`      // adherence: \"lesson\" | \"pref\"\n\tRuleID        string   `json:\"rule_id,omitempty\"`        // adherence: the rule's stable id\n\tVerdict       string   `json:\"verdict,omitempty\"`        // adherence: followed | violated | not_applicable\n\tOutcome       string   `json:\"outcome,omitempty\"`        // adherence: the target session's git outcome (accepted/corrected/rejected)\n\tTargetSession string   `json:\"target_session,omitempty\"` // adherence / lesson_signal: the session the verdict/lesson is ABOUT (the record lives in the judging session's log)\n\n\t// SessionID is stamped IN MEMORY by the multi-session readers (RecentBurstExcluding,\n\t// Recent) so a merged record knows which session it came from — used to name a\n\t// thread's source session in orientation. json:\"-\": never written to disk (the dir\n\t// name IS the id; persisting it would be redundant and could drift).\n\tSessionID string `json:\"-\"`\n}\n```\nRecord is one append-only line in events.jsonl. Fields are sparse (omitempty); which ones are set depends on Kind.\n\n```go\nfunc Commits(root string) ([]Record, error)\n```\nCommits returns the git commit/push tool calls across all sessions (newest first) — the accountability trail of \"did we already commit/push this?\".\n\n```go\nfunc LastShell(root string) (Record, bool)\n```\nLastShell returns the most recent \\`$\\` direct-shell command (Tool \"shell\"), across all sessions newest-first — its command (Input), output (Content), and exit (Exit/IsError). This is the data behind explain/fix-last: \"why did that fail?\" / \"fix it\" consult it. Empty (false) when no \\`$\\` command has run.\n\n```go\nfunc LatestRecent(root string, n int) ([]Record, error)\n```\nLatestRecent returns the last n records of the most recently active session (by directory mtime) — the signal orientation/prediction pulls from to know \"where you left off.\" Empty (nil, nil) if no sessions exist yet.\n\n```go\nfunc LatestRecentExcluding(root, excludeID string, n int) ([]Record, error)\n```\nLatestRecentExcluding returns the last n records of the most recently active session whose id differs from excludeID — i.e. \"the previous distinct session\" when excludeID is the current one. This is what answers \"what was the last session about?\" from a brand-new session, which is already non-empty (it holds the user's opening message) and would otherwise shadow the prior one. Empty (nil, nil) if there is no other session.\n\n```go\nfunc LessonSignals(root string) ([]Record, error)\n```\nLessonSignals returns every lesson\\_signal record across all sessions, oldest first, each stamped with its session id. The lessons reducer's backfill path — same contract as PreferenceSignals (files canonical, SQLite derived).\n\n```go\nfunc PreferenceSignals(root string) ([]Record, error)\n```\nPreferenceSignals returns every preference\\_signal record across ALL sessions on disk, oldest-first, each stamped with its source session id. This is the CANONICAL read for the prefs reducer's backfill: the SQLite events table is a derived index, so after a state.db wipe the signals are recovered from the append-only files here.\n\n```go\nfunc Recent(root, sessionID string, n int) ([]Record, error)\n```\nRecent returns the last n records of one session (n\\\u003c=0 = all).\n\n```go\nfunc RecentBurstExcluding(root, excludeID string, maxSessions int, burstGap time.Duration, perSession int) ([]Record, error)\n```\nRecentBurstExcluding returns the merged records of the current WORK BURST of prior sessions (excludeID skipped), in CHRONOLOGICAL order — oldest session first, so a reducer sees one continuous stream and later work supersedes earlier work naturally. perSession caps each session's tail (0 = all).\n\nThe burst rule replaces both bad windows. A flat \"last session\" baked in amnesia (the thread from two sessions ago — minutes older — vanished); a flat \"last K sessions\" hauls year-old work into today's orientation just to fill a quota. Instead: ALWAYS take the most recent prior session, however old — that is \"where you left off\" — then keep walking older only while the gap between CONSECUTIVE sessions stays within burstGap, capped at maxSessions. Sessions clustered in one stretch of work arrive together; a long break ends the window.\n\n```go\nfunc Search(root, query string, n int) ([]Record, error)\n```\nSearch scans every session (newest first) for records whose text/content/input /tool contains query (case-insensitive). An empty query matches everything. Returns at most n hits (n\\\u003c=0 = unlimited).\n\n```go\nfunc SessionRecords(root, id string) ([]Record, error)\n```\nSessionRecords returns the full record list of ONE session by id, oldest first — the post-session learning loop reads a finished session's trail to build the adherence digest. (nil, nil) when the session has no log.\n\n```go\nfunc Sidequests(root, sessionID string) ([]Record, error)\n```\nSidequests returns the user messages of one session — the sequence of things the user actually asked for, in order.\n\n```go\ntype SessionSummary struct {\n\tID       string\n\tStarted  time.Time\n\tHeadline string\n\tActions  int // meaningful tool calls (commands/edits) — a sense of how much happened\n}\n```\nSessionSummary is a one-line digest of a past session for \"what were the last couple sessions about?\" — the headline is the session's first user request.\n\n```go\nfunc RecentSessions(root, excludeID string, n int) ([]SessionSummary, error)\n```\nRecentSessions returns the most recent sessions newest-first, EXCLUDING excludeID (the current one). n\\\u003c=0 means all. This is the \"recent sessions\" affordance the agent needs to answer about session history — distinct from Recent(), which reads a SINGLE session's records.\n\n```go\ntype Thread struct {\n\tRequest string\n\tActions []string\n}\n```\nThread is one strand of work in a session: a user request and the meaningful actions taken under it. A session's Threads read like a checklist of \"what we did,\" each with a line of detail — the right grain for recall (signal, not the raw event firehose; drill into events.jsonl when you need 100%).\n\n```go\nfunc Recap(recs []Record) []Thread\n```\nRecap groups records into Threads: each user message starts a strand, and the commands/edits/approvals that follow attach to it. This is the \"we built these N things, with a bit about each\" view.\n\n```go\ntype Writer struct {\n\t// contains filtered or unexported fields\n}\n```\nWriter appends records for one session to .memcode/sessions/\\\u003cid\u003e/.\n\n```go\nfunc Open(root, sessionID string) (*Writer, error)\n```\nOpen creates (or reopens) the on-disk log for a session and returns a Writer. A nil Writer is safe to Append/Close on, so callers can ignore the error and degrade gracefully if the directory can't be created.\n\n```go\nfunc (w *Writer) Append(r Record)\n```\nAppend writes one record to the append-only log and mirrors a human line into the transcript. Safe on a nil Writer and safe under concurrent calls.\n\n```go\nfunc (w *Writer) Close() error\n```\nClose flushes and closes the underlying files. Safe on a nil Writer.\n\n","path":"github.com/memcode-ai/memcode/internal/sessionlog","name":"sessionlog","synopsis":"Package sessionlog is memcode's episodic memory: a local, append-only record of the high-level causal trail of a session — user messages, assistant messages, meaningful actions (commands, edits, commits), and approvals — written to disk as it happens, independent of the LLM context window.","isRedistributable":true}
