claude

package
v0.0.0-...-53bd38a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package claude owns the Claude Code session-metadata contract: the shape agentop's harvester writes to ~/.cortex/session-metadata.json, the path it lives at, and the harvest that produces it.

It exists because that file is a contract between two things that cannot import each other: the harvester, reached from agentop's package main, and the viewer in cmd/agentop/tui. Before this, both the shape and the harvest lived in package main, so nothing else could reach them and `agentop observe` could not name a session without shelling out to another subcommand.

Anything that changes the file's name or shape belongs here, so that a change breaks compilation in every reader rather than only the behaviour in one. Same reasoning as core/clientstate, which owns ~/.cortex/claude-code-state.json.

Under core/observe because it serves OBSERVATION rather than authorization: nothing here makes an access decision, and no part of the auth path reads it. A session title only ever answers "which session is this?" for someone reading a pane. That is the dividing line for this subtree — core's other packages exist to decide whether a request proceeds; these exist to describe traffic that already happened.

One package per agent is the intended shape. SessionMetadata carries AgentType and AgentConfigDir precisely so a second harvester can merge into the same file, and that one would sit beside this as core/observe/<agent>. When it lands, the shape and the path are the parts worth hoisting; the transcript layout is not.

Index

Constants

View Source
const ConfigDirEnv = "CLAUDE_CONFIG_DIR"

ConfigDirEnv is the variable Claude Code itself honours for relocating its config tree. Read here so a user who has moved it is not told there are no sessions.

View Source
const MaxCwdLen = 1024

MaxCwdLen caps the cwd fallback, in RUNES.

Deliberately much larger than MaxTitleLen: this tier exists to show a directory, whose leaf is the identifying part, so clipping it to a title's budget would defeat it. It is not a display budget — the renderer truncates to the column anyway — it is a BOUND, so that one field in a transcript cannot hand the renderer an arbitrarily long string. Linux caps a path at 4096 bytes; this is comfortably above any real one and still finite.

View Source
const MaxTitleLen = 80

MaxTitleLen caps a harvested title, in RUNES.

EXPORTED so the renderer's tests can hold the cross-module contract: the cap is only safe because every renderer re-truncates by display width, and while it was package-private neither side could name the other's half. cmd/agentop/tui asserts the relationship against this constant.

A prompt is unbounded — the longest on the measured tree ran to several KB — and a title is a table cell. Clipping at the source keeps the metadata file small and stops every consumer having to defend itself; the viewer truncates again to whatever the column allows, which is narrower still. Runes, not bytes, so a multi-byte prompt is not cut mid-character.

NOT A DISPLAY-COLUMN BUDGET. 80 runes of CJK occupy 160 columns, so nothing may treat this as a width. It is safe only because every renderer re-truncates by display width — the sessions pane measures with lipgloss.Width.

THAT IS NOT THE ONLY RULER THE CELL MEETS, and saying only "the pane measures with lipgloss.Width" was incomplete: bubbles v1.0.0 applies runewidth.Truncate to every cell before styling it, and runewidth is NOT ANSI-aware. Today that is harmless, because a title cell carries no escape bytes — this package guarantees it, and the pane asserts it. But the two facts are load-bearing together: if a title were ever styled, the escape bytes would be charged against the column budget and an 11-column cell would collapse to a lone ellipsis. Anyone adding colour to a title needs to know that before they do it, which is why it is recorded here rather than left to be rediscovered.

THAT RELATIONSHIP IS GUARDED, from the renderer's side: TestTitleCap_IsSafeOnlyBecauseTheRendererRemeasures in cmd/agentop/tui takes a title at exactly this cap in the worst case for the mismatch — MaxTitleLen runes of CJK, twice that in columns — and requires the rendered cell to fit anyway. Removing the renderer's truncation fails it, along with ten other tests in that package.

An earlier version of this comment said the opposite: that no single test held the relationship and that "nothing fails if someone removes the renderer's truncation". That was true when written and false once the guard landed, which is the worse direction for a comment to be wrong in — it invites a maintainer to delete guarded code. This package still cannot assert the width half itself (it has no width library, and the exported constant is what lets the other side name it), so the guard lives there and this comment points at it by name.

View Source
const SessionMetadataRel = ".cortex/session-metadata.json"

SessionMetadataRel is the harvested metadata file, relative to the user's home.

One constant so the harvester that writes the file and the viewer that reads it name the same path. Two constants for one path is the kind of drift that only shows up as an empty column nobody can explain.

Follows yankDirRel and cmd_claudecode.go's cortexCfgRel / stateRel, so there is one ~/.cortex tree rather than a new dotfile per feature.

Variables

View Source
var ErrCorruptMetadata = errors.New("corrupt session metadata")

ErrCorruptMetadata reports that an existing metadata file was there and could not be read, so a merge refused rather than replacing a file whose contents are unknown.

NARROWER THAN THE NAME SUGGESTS: a file that reads fine but does not parse no longer comes back here, because Harvest rebuilds it instead. What is left is every file Harvest refuses because a rebuild might replace good entries — one that could not be read (a permission or I/O failure) and one too large to read whole (ErrMetadataTooLarge). The two need different advice, so a caller printing a remedy must check the narrower sentinel first rather than assuming this one means permissions.

Exported because the repair is a CLI affordance: `agentop experimental read-claude-sessions` names --merge=false as the way past, and only the command layer knows its own flags. Callers discriminate with errors.Is.

View Source
var ErrLockTimeout = errors.New("timed out waiting for the session metadata lock")

ErrLockTimeout reports that the metadata lock could not be acquired before its deadline, so the harvest proceeded UNLOCKED rather than not at all.

Its own error so a caller can tell "this filesystem cannot flock" from "another process is holding it": both proceed unlocked, but only the second means a concurrent harvest is real and a lost update is possible.

Declared here rather than in lock_unix.go so it is part of the package API on every platform — an errors.Is against it must compile where the lock is a no-op too, which is the Windows cross-check lock_other.go exists to keep working.

View Source
var ErrMetadataTooLarge = errors.New("session metadata file is too large to read")

ErrMetadataTooLarge reports that the metadata file is larger than ReadMetadata's cap, so it could not be read whole and was refused rather than rebuilt over.

Exported, unlike errMetadataNotJSON, because the remedy differs and callers must not give the wrong one: this file is intact and its permissions are fine, so "fix the permissions" is wrong advice. It is also permanent — every launch refuses again — which a caller may want to say before a full-screen viewer hides it.

Functions

func DefaultConfigDir

func DefaultConfigDir() (string, error)

DefaultConfigDir resolves Claude Code's config directory: CLAUDE_CONFIG_DIR when set, else ~/.claude.

func OpenMetadata deprecated

func OpenMetadata(path string) (*os.File, error)

OpenMetadata opens a session metadata file for reading: os.Open, retried on Windows while a save is replacing the file. It shipped in v0.10.3, before the retry moved to core/fsutil, and is kept so callers of this package still build.

Deprecated: use fsutil.Open.

func ReadMetadata

func ReadMetadata(path string) (map[string]SessionMetadata, error)

ReadMetadata reads the existing file, distinguishing absent from unreadable.

An empty map with a nil error means genuinely no file yet — the first run, which is not a problem. A non-nil error means a file was there and could not be trusted; what the caller should DO about it depends on which error, and this function's job is only to keep them apart. Same distinction, for the same reason, as readState in cmd_claudecode.go.

Three outcomes a caller can discriminate, because Harvest treats them differently: errMetadataNotJSON for a file whose bytes are not JSON, which Harvest rebuilds over; ErrMetadataTooLarge for a valid file past the read cap, which it refuses because rebuilding would destroy intact entries; and a bare os/io error — permission, EIO — which it also refuses, since nothing there says the contents are bad.

A file holding JSON `null` decodes to a nil map, which is indistinguishable from an empty object for merging purposes, so it is normalised rather than refused.

func ReadSessions

func ReadSessions(configDir string, since map[string]SessionMetadata) (map[string]SessionMetadata, []string, int, error)

ReadSessions harvests every session transcript under configDir/projects.

One level down only — projects/<project>/<id>.jsonl. Deliberately not filepath.WalkDir, which the rest of this module uses: deeper files are subagent transcripts (<id>/subagents/agent-*.jsonl) whose basenames are agent ids, not session ids, so walking would key 92 non-sessions into the map on the machine this was written against.

A missing projects directory is not an error: a machine that has never run Claude Code has none, and an empty result already says so.

A non-nil since makes the read INCREMENTAL: a transcript no newer than the entry since already holds for it is skipped, on the reasoning that a file that has not changed cannot have grown a new title. Skipped sessions are absent from the returned map rather than copied into it, so an incremental caller MUST merge the result over since — see Harvest, which refuses to do otherwise. Pass nil to parse everything.

The second return names transcripts whose title may be incomplete — a read that stopped early. Not an error: those sessions are still in the map with the best title found. The caller reports them, because a truncated read is otherwise indistinguishable from a session that has no title. The third counts what since skipped.

func RedactStoredTitles

func RedactStoredTitles(m map[string]SessionMetadata)

RedactStoredTitles runs the secret rules over the titles in m, which may have been harvested before they applied. Both readers of the metadata file call it, so an old title is shown redacted at once and the next harvest saves it so. A stored title of MaxTitleLen runes was cut there by the old clip, so a key prefix at its end ("… ghp_Gx7Gx7") is a key cut short: the harvest skips unchanged transcripts, so it would never be rebuilt.

func SaveMetadata

func SaveMetadata(path string, meta map[string]SessionMetadata) error

SaveMetadata writes the map atomically, creating ~/.cortex if needed.

Same mechanics as saveUserConfig, for the same reasons: CreateTemp rather than a fixed path+".tmp" (crash debris at a predictable name wedges every later write, and CreateTemp's unpredictable name passes O_EXCL itself), Rename rather than truncate (a half-written file would be read back as malformed), dir 0700 and file 0600. Plus an fsync between write and rename, so a crash leaves either the old file or the new one. File-level guarantee only: a crash between rename and the directory entry hitting disk still loses the update. #1554 tracks the directory-fsync upgrade across the tree.

SECURITY: the residual symlink risk is closed the way saveUserConfig closes it, not with tui's checkYankDir Lstat sweep. An earlier version of this comment argued the sweep was unnecessary because these paths name the reader's own ~/.claude tree — but saveUserConfig's own tripwire names "a filesystem path" as the trigger for the sweep's posture, and reading that clause as "unless the path looks harmless" is how a tripwire stops working. What the two cases actually share is the mechanism: os.CreateTemp picks a name an attacker cannot predict and passes O_EXCL itself, and os.Rename REPLACES a symlink at the destination rather than following it, so a planted ~/.cortex/session-metadata.json symlink is overwritten, not written through.

What the sweep would add here is a check on the DIRECTORY chain, and it is declined for the reason saveUserConfig declines it: its other half chmods 0700 in place, so merely running this would retighten a ~/.cortex an installer deliberately set. The narrower half of that tradeoff — refusing to write through a symlinked ~/.cortex — is the part worth having, and is a follow-up noted in the PR rather than a silent omission.

What would change this calculus outright: harvesting an agent whose config lives somewhere the user cannot already read, or adding any field carrying transcript CONTENT rather than a path. Either makes this file carry something its reader could not otherwise obtain.

func SessionMetadataPath

func SessionMetadataPath() (string, error)

SessionMetadataPath returns ~/.cortex/session-metadata.json.

func SetNickname

func SetNickname(path, id, name string) error

SetNickname sets the nickname of session id in the metadata file at path, or clears it when name is blank, under the harvest's lock. An entry with nothing else in it is removed when its nickname is cleared. The nickname is trimmed and capped at MaxTitleLen runes.

Types

type Options

type Options struct {
	// ConfigDir is the agent config directory to read. Empty resolves via
	// DefaultConfigDir.
	ConfigDir string
	// Merge upserts into the existing file rather than replacing it.
	//
	// A harvest only ever sees the sessions its config dir holds, so replacing would
	// silently drop entries the file already had — another config directory, or a
	// session whose transcript Claude Code has since pruned.
	//
	// THE TWO SIDES OF THAT, both deliberate and neither free:
	//
	//   - Merge KEEPS an entry forever once written. A session whose transcript Claude Code has
	//     pruned keeps its title in the file indefinitely, since no harvest ever sees it again to
	//     notice it is gone. The file therefore grows monotonically with sessions-ever-seen rather
	//     than sessions-that-exist. Cheap — one small JSON object per session — but it means the
	//     file is a cache with no eviction, and `--merge=false` is the only thing that prunes it.
	//   - Merge:false DROPS every entry this harvest did not see, which includes entries from any
	//     OTHER config dir and any session pruned since. That is what makes it the way to rebuild a
	//     file whose entries are WRONG — a file that parses but says the wrong thing, which nothing
	//     else can fix — and also why it is not the default: run it with a --dir narrower than the
	//     one that produced the file and it discards the difference without asking. It is no longer
	//     needed for a file that does not parse; Harvest rebuilds that one itself, and reports it
	//     on Result.Rebuilt.
	Merge bool
	// Incremental skips transcripts no newer than the entry already recorded for
	// them, so only recently-touched sessions are parsed.
	//
	// Requires Merge, and Harvest refuses the combination rather than trusting the
	// caller: skipped transcripts contribute nothing to this harvest's map, so
	// rebuilding the file from an incremental run would drop every session it
	// skipped. This is the mode `agentop observe` uses, where the harvest is a side
	// effect of opening the viewer and a full scan of every transcript (measured:
	// 0.73-1.18s over 207MB) is too much to pay before the first frame.
	Incremental bool
}

Options selects how much work one harvest does.

type Result

type Result struct {
	// ConfigDir is the directory actually read, after DefaultConfigDir resolution.
	ConfigDir string
	// Path is the metadata file written.
	Path string
	// Harvested counts the entries this run read from transcripts.
	Harvested int
	// Skipped counts transcripts left unparsed because they had not changed. Always
	// zero unless Options.Incremental.
	Skipped int
	// Kept counts entries retained from the existing file that this harvest did not see.
	// Always zero unless Options.Merge, and excludes Recovered — an entry another run wrote
	// concurrently was not in the file this run read, so it is not "kept" from it.
	//
	// Total = Harvested + Kept + Recovered. Replaced is NOT a term: it counts keys overwritten in
	// place, which do not change Total, so including it would drive this negative.
	Kept int
	// Total counts the entries written.
	Total int
	// Partial names transcripts whose read ended early, so their titles may be stale.
	// Not an error: those sessions are still in the map with the best title found.
	Partial []string
	// Recovered counts entries another run wrote concurrently that this one ADDED back — ids it
	// did not have. Counts only the shape that grows the map, so it can be subtracted from Total;
	// see Replaced for the other one.
	Recovered int
	// Replaced counts shared ids where another run's copy was fresher and this one adopted it.
	//
	// Its own field rather than folded into Recovered because it REPLACES a key: the map does not
	// grow, so counting it as recovered drove Kept negative and the subcommand printed
	// "-1 kept from the existing file". Not part of the Total identity below for the same reason.
	Replaced int
	// Rebuilt reports that the existing file did not parse, so this harvest replaced it from
	// the transcripts instead of merging into it.
	//
	// Worth a field because the counts alone cannot show it: a rebuild looks exactly like an
	// ordinary first run — everything Harvested, nothing Kept — and the entries it dropped
	// (sessions whose transcripts are gone) leave no trace anywhere for a caller to notice.
	Rebuilt bool
	// LockTimedOut reports that the metadata lock could not be taken before its deadline, so
	// this harvest ran unlocked and a concurrent run's rename may erase its entries.
	//
	// A field because the alternative is silence: without it, the one failure mode this lock
	// exists to prevent is invisible from outside, and "some titles vanished" has no diagnosis.
	LockTimedOut bool
	// LockFailed carries a lock failure that was NOT a timeout — flock refused for some other
	// reason, e.g. the lock file could not be created or the filesystem rejected the call.
	//
	// Separate from LockTimedOut because the two need different words: a timeout means someone
	// else holds it, while this means locking did not work at all, and reporting "timed out" for
	// an EIO would send the reader looking for a process that does not exist. Empty when locking
	// succeeded, was not attempted (no Merge), or is a no-op on this platform.
	//
	// Same consequence as a timeout, which is why it is reported at all: the harvest proceeds
	// UNLOCKED, so a concurrent run's rename can erase everything it wrote. Before this, that
	// state was the only one where wholesale loss was possible and nothing recorded it.
	LockFailed string
	// Meta is what the run wrote: the merged whole under Merge, or just this harvest
	// otherwise. Keyed by session id.
	//
	// Returned because the caller usually wants it and Harvest already holds it. Without
	// this a caller had to re-read the file it just wrote — a third read of the same file
	// in one launch, and subtly not the same thing either: a re-read returns whatever is
	// on disk when it lands, so a concurrent run's union can arrive instead of this run's
	// result. Harmless under merge semantics, but it made the function say less than it knew.
	//
	// The map is the one that was saved, not a copy, so a caller must not mutate it.
	Meta map[string]SessionMetadata
}

Result is what one harvest did, for a caller that wants to report it.

func Harvest

func Harvest(opts Options) (Result, error)

Harvest reads configDir's transcripts and writes ~/.cortex/session-metadata.json.

The whole of the work, with none of the reporting: every count and warning comes back on Result for the caller to print however suits it. That split is what lets one implementation serve both `agentop experimental read-claude-sessions`, where the harvest is the subject and reports in full, and `agentop observe`, where it is a side effect that must stay quiet.

type SessionMetadata

type SessionMetadata struct {
	// Title is a human-readable name for the session. From Claude Code this is the
	// model-generated title when the transcript carries one, and otherwise the
	// working directory it ran in — so it may well be a path rather than a phrase,
	// and a consumer that assumes prose will be wrong most of the time (measured: 2
	// of 109 local sessions had a real title).
	Title string `json:"title,omitempty"`
	// AgentType names the agent that produced the session, e.g. "Claude Code". A
	// plain display string, not an enum: the set of agents Cortex fronts is open,
	// and a consumer showing this has no decision to make on it.
	AgentType string `json:"agentType,omitempty"`
	// AgentConfigDir is the directory the metadata was harvested from — the parent
	// of the agent's own per-session layout. Recorded per entry rather than once per
	// file so a future harvester can merge two agents, or two config dirs of one
	// agent, into the same map without the entries becoming ambiguous.
	AgentConfigDir string `json:"agentConfigDir,omitempty"`
	// LogFile is the transcript this entry was read from, as a path. The one field
	// that lets a reader go and check: a title that looks wrong is answerable by
	// opening the file it came from.
	//
	LogFile string `json:"logFile,omitempty"`
	// LogModTime is the transcript's modification time as of the harvest that wrote
	// this entry, and it is what makes an incremental harvest possible: a transcript
	// whose mtime has not moved past this cannot have grown a new title, so it does
	// not need re-reading. See ReadSessions.
	//
	// Recorded rather than derived. The obvious cheaper design — re-Stat LogFile and
	// compare — cannot work: it compares the transcript's mtime against ITSELF, which
	// is never "after", so every transcript would be skipped forever and a renamed
	// session would keep its old title permanently. A test caught exactly that.
	//
	// Optional, like every other field, and its zero value is the safe answer: an
	// entry written before this field existed has no timestamp, cannot vouch for its
	// transcript, and is therefore re-parsed rather than trusted.
	//
	// NOT omitempty, unlike every field above, because it could not work: encoding/json
	// treats only empty scalars, maps and slices as empty, so a zero time.Time is a struct
	// and gets written out as "0001-01-01T00:00:00Z" regardless. Tagging it omitempty would
	// have read as a promise this file does not keep — every entry carries a timestamp,
	// which is why the rule that matters is stated on the READING side: harvestedAt treats
	// the zero value as "cannot tell" and re-parses.
	LogModTime time.Time `json:"logModTime"`
	// Subagents are the subagents Claude Code spawned in this session, keyed by the
	// id it uses everywhere (the X-Claude-Code-Agent-Id a request carries, and the
	// <id> in subagents/agent-<id>.meta.json). Read from those meta.json files, not
	// the subagent transcripts beside them: a label is what the pane wants, and the
	// transcript holds none that the meta file lacks.
	//
	// Like every field but LogModTime, optional — a session with no subagents, or
	// harvested before this field existed, has none, and a consumer falls back to
	// the raw id (which is what a non-Claude-Code agent or an agent-team teammate
	// renders anyway, having no meta.json to join to).
	Subagents map[string]SubagentInfo `json:"subagents,omitempty"`
	// Nickname is the name the person gave the session in agentop (`r` on the sessions pane):
	// shown instead of Title, and never sent anywhere. NOT HARVESTED: a harvest that rewrites an
	// entry carries it over (mergeHarvest), and SetNickname is its only writer.
	Nickname string `json:"nickname,omitempty"`
}

SessionMetadata is what a coding agent knows about one of its own sessions that Cortex does not.

Cortex buckets traffic by session id and nothing more: `/v1/sessions` returns a UUID, and a UUID does not tell an operator which session it is. The agent that produced the traffic already knows — Claude Code writes a per-session transcript carrying an AI-generated title and the directory it ran in — so this is the shape that carries those facts back, keyed by the same id Cortex uses.

Every field is optional. A harvester that cannot determine one must leave it empty rather than invent a value, and a consumer must render an entry that has only some of them: the fields come from an agent's own on-disk layout, which is not a contract anyone here controls.

This is written as JSON to ~/.cortex/session-metadata.json. Key names stay camelCase to match the sortColumn / sortDesc keys in agentop's own settings file rather than introducing a second convention.

type SubagentInfo

type SubagentInfo struct {
	AgentType   string `json:"agentType,omitempty"`
	Description string `json:"description,omitempty"`
}

SubagentInfo is one harvested subagent: what Claude Code's own record of it says that the wire does not carry. Every field optional, for the same reason as SessionMetadata's — this is another agent's on-disk layout, not a contract.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL