session

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 27 Imported by: 0

Documentation

Overview

Package session adds coding-application identity and single-writer ownership to the durable Harness session repository.

Index

Constants

View Source
const (
	ArchiveMaxTranscriptBytes = 128 << 20
	ArchiveMaxRecordBytes     = 16 << 20
	ArchiveMaxRecords         = 100_000
	ArchiveMaxRenderedBytes   = 128 << 20
	ArchiveMaxSegments        = 1024
	ArchiveMaxReferences      = 1024
	ArchiveMaxOutputBytes     = 64 << 10
)

Archive limits are independent of model request and tool output budgets.

Variables

View Source
var (
	// ErrArchiveInvalid identifies invalid input or unsafe file ownership/modes.
	ErrArchiveInvalid = errors.New("session archive: invalid input")
	// ErrArchiveLimit identifies an encoded, rendered or operation bound violation.
	ErrArchiveLimit = errors.New("session archive: limit exceeded")
	// ErrArchiveCorrupt identifies failed integrity or format validation.
	ErrArchiveCorrupt = errors.New("session archive: corrupt object")
	// ErrArchiveDenied identifies a reference absent from the bound allowlist.
	ErrArchiveDenied = errors.New("session archive: reference not authorized")
	// ErrArchiveNotFound identifies an absent object in the owning session.
	ErrArchiveNotFound = errors.New("session archive: object not found")
	// ErrArchiveIO identifies a storage operation failure; its cause is preserved.
	ErrArchiveIO = errors.New("session archive: storage failure")
	// ErrArchivePublicationUncertain means the final name exists but its directory
	// sync failed. Never remove that object or append a checkpoint on this error.
	ErrArchivePublicationUncertain = errors.New("session archive: publication durability uncertain")
)
View Source
var (
	// ErrInvalid means repository, session, or metadata input is invalid.
	ErrInvalid = errors.New("coding session: invalid input")
	// ErrLocked means another writer currently owns the requested session.
	ErrLocked = errors.New("coding session: session is locked")
	// ErrWorkspaceMismatch means a stored session belongs to another workspace
	// identity.
	ErrWorkspaceMismatch = errors.New("coding session: workspace mismatch")
	// ErrLineageMismatch means a Team Worker session is not owned by the exact
	// Team resource lineage supplied by its caller.
	ErrLineageMismatch = errors.New("coding session: Team Worker lineage mismatch")
	// ErrUnsupportedPlatform means this platform cannot enforce the P0
	// single-writer lock contract.
	ErrUnsupportedPlatform = errors.New("coding session: unsupported platform")
)

Functions

func ValidateArchiveID added in v0.1.5

func ValidateArchiveID(id string) error

ValidateArchiveID accepts only a lowercase SHA-256 content identity.

func ValidateID

func ValidateID(id string) error

ValidateID verifies that id is safe to use as a durable session name.

Types

type ArchiveInfo added in v0.1.5

type ArchiveInfo struct {
	ID              string        `json:"id"`
	Source          ArchiveSource `json:"source"`
	Records         int           `json:"records"`
	TranscriptBytes int64         `json:"transcript_bytes"`
	RenderedBytes   int64         `json:"rendered_bytes"`
	Segments        int           `json:"segments"`
}

ArchiveInfo contains bounded discovery metadata, not archived content.

type ArchiveLine added in v0.1.5

type ArchiveLine struct {
	Number int    `json:"number"`
	Text   string `json:"text"`
}

ArchiveLine numbers are one-based within the selected text segment.

type ArchiveListPage added in v0.1.5

type ArchiveListPage struct {
	Archives   []ArchiveInfo        `json:"archives,omitempty"`
	Segments   []ArchiveSegmentInfo `json:"segments,omitempty"`
	NextOffset int                  `json:"next_offset"`
	More       bool                 `json:"more"`
}

ArchiveListPage has deterministic ordering and bounded pagination.

type ArchiveListRequest added in v0.1.5

type ArchiveListRequest struct {
	ArchiveID string
	Offset    int
	Limit     int
}

ArchiveListRequest lists archives, or segments within one authorized archive. Offset is zero-based; Limit defaults to 10 and cannot exceed 20.

type ArchiveMatch added in v0.1.5

type ArchiveMatch struct {
	SegmentID string `json:"segment_id"`
	Line      int    `json:"line"`
	Text      string `json:"text"`
}

ArchiveMatch carries historical text and its exact retrieval cursor.

type ArchiveReadPage added in v0.1.5

type ArchiveReadPage struct {
	Lines      []ArchiveLine `json:"lines"`
	NextOffset int           `json:"next_offset"`
	More       bool          `json:"more"`
}

ArchiveReadPage contains at most 64 KiB of JSON, with an explicit continuation.

type ArchiveReadRequest added in v0.1.5

type ArchiveReadRequest struct {
	ArchiveID string
	SegmentID string
	Offset    int
	Limit     int
}

ArchiveReadRequest selects a text segment and a zero-based line offset. Limit defaults to 200 and cannot exceed 1000. Pages are also byte-bounded.

type ArchiveReader added in v0.1.5

type ArchiveReader struct {
	// contains filtered or unexported fields
}

ArchiveReader is a read-only snapshot of application-supplied active-path checkpoint references. It never enumerates storage to discover permission. Discard/rebind after navigation or checkpoint changes. Historical content is evidence only; callers must not promote it to system instructions.

func (*ArchiveReader) List added in v0.1.5

List exposes only the supplied references; there is no caller-supplied session.

func (*ArchiveReader) Read added in v0.1.5

Read returns checked text, never an arbitrary file or raw path.

func (*ArchiveReader) Search added in v0.1.5

Search supports bounded literal/RE2 retrieval without filesystem globs.

type ArchiveSearchCursor added in v0.1.5

type ArchiveSearchCursor struct {
	SegmentID string `json:"segment_id"`
	Line      int    `json:"line"`
}

ArchiveSearchCursor resumes a search at a one-based line within a segment.

type ArchiveSearchPage added in v0.1.5

type ArchiveSearchPage struct {
	Matches []ArchiveMatch       `json:"matches"`
	Next    *ArchiveSearchCursor `json:"next,omitempty"`
}

ArchiveSearchPage can have a cursor even when no matches were found: the scan budget may have ended. A nil Next means the archive was completely searched.

type ArchiveSearchRequest added in v0.1.5

type ArchiveSearchRequest struct {
	ArchiveID string
	Query     string
	Regexp    bool
	Cursor    *ArchiveSearchCursor
	Limit     int
}

ArchiveSearchRequest searches one authorized archive. Patterns are literal unless Regexp is true (Go RE2 syntax). Matching is case-sensitive, per line. Limit defaults to 50 and cannot exceed 100. Each page scans at most 8 MiB of rendered text, in addition to the bounded whole-object integrity verification.

type ArchiveSegmentInfo added in v0.1.5

type ArchiveSegmentInfo struct {
	ID          string `json:"id"`
	Bytes       int64  `json:"bytes"`
	Lines       int    `json:"lines"`
	FirstRecord int    `json:"first_record"`
	LastRecord  int    `json:"last_record"`
}

ArchiveSegmentInfo identifies text and its canonical record range. A record may span segments. Lines are wrapped at UTF-8 boundaries, at most 4096 bytes.

type ArchiveSource added in v0.1.5

type ArchiveSource struct {
	SessionID string `json:"session_id"`
	TipID     string `json:"tip_id"`
}

ArchiveSource identifies the captured path. IDs are provenance, not graph edges to resolve, filesystem paths, or authority to access another session.

type ArchiveStore added in v0.1.5

type ArchiveStore struct {
	// contains filtered or unexported fields
}

ArchiveStore is an application-owned storage boundary, not a model-facing service. Construct a separately allowlisted ArchiveReader using Bind. Its lifetime must remain within the owning repository/Handle lifetime.

func (*ArchiveStore) Bind added in v0.1.5

func (s *ArchiveStore) Bind(ids []string) (*ArchiveReader, error)

Bind copies an allowlist derived by the caller from its active checkpoint path. Empty references authorize nothing, including already published orphans. This is an application binding operation, not a model operation.

func (*ArchiveStore) Stage added in v0.1.5

func (s *ArchiveStore) Stage(ctx context.Context, source ArchiveSource, entries []harness.Entry) (*StagedArchive, error)

Stage captures canonical entries and searchable text without changing the Session. The caller supplies an immutable, raw selected path through TipID. External label/branch/checkpoint references remain inert provenance; no Harness graph reconstruction or transitive archive resolution is performed.

func (*ArchiveStore) Verify added in v0.1.5

func (s *ArchiveStore) Verify(ctx context.Context, id string) (ArchiveInfo, error)

Verify checks the entire object digest, manifest, canonical records and text segments. This privileged storage operation does not authorize model access.

type CreateOptions

type CreateOptions struct {
	WorkspaceID     string
	WorkspacePath   string
	RetainEmpty     bool
	Kind            Kind
	ParentSessionID string
	ParentRunID     string
	Agent           string
	// SubagentIdentity is an optional versioned, non-secret identity snapshot
	// for a child. Legacy callers may omit it; new child executions supply it.
	SubagentIdentity *SubagentIdentity
	TeamWorker       *TeamWorkerLineage
}

CreateOptions are the non-secret attributes persisted in a session header.

type ForkOptions

type ForkOptions struct {
	AtEntryID string
}

ForkOptions select the source node copied into a new Session. An empty node selects the source's current leaf.

type Handle

type Handle struct {
	// contains filtered or unexported fields
}

Handle owns a locked, writable Harness session.

func (*Handle) Close

func (h *Handle) Close() error

Close closes the writable store before releasing its writer lock. It is safe to call more than once and returns the first close result each time.

func (*Handle) Metadata

func (h *Handle) Metadata() Metadata

Metadata returns the session's typed, non-secret metadata.

func (*Handle) Session

func (h *Handle) Session() *harness.Session

Session returns the durable conversation tree owned by the handle.

type Kind

type Kind string

Kind identifies the product role of a durable Session.

const (
	// KindConversation is a resumable user conversation. It is also the
	// interpretation of legacy headers that do not contain a kind.
	KindConversation Kind = "conversation"
	// KindSubagent is an internal child transcript owned by one conversation.
	KindSubagent Kind = "subagent"
	// KindTeamWorker is one attempt-scoped Team Worker transcript. It belongs to
	// its real Worktree Workspace and carries separate parent Team lineage.
	KindTeamWorker Kind = "team_worker"
)

type LockedError

type LockedError struct {
	Path       string
	OwnerPID   int
	AcquiredAt time.Time
}

LockedError reports the best-effort owner of a contended kernel lock. Owner metadata is diagnostic only; ErrLocked remains the authority.

func (*LockedError) Error

func (e *LockedError) Error() string

func (*LockedError) Unwrap

func (*LockedError) Unwrap() error

Unwrap preserves errors.Is compatibility with ErrLocked.

type Metadata

type Metadata struct {
	ID               string
	CreatedAt        time.Time
	Path             string
	WorkspaceID      string
	WorkspacePath    string
	RetainEmpty      bool
	Kind             Kind
	ParentSessionID  string
	ParentEntryID    string
	ParentRunID      string
	Agent            string
	SubagentIdentity SubagentIdentity
	TeamWorker       TeamWorkerLineage
	Name             string
	Preview          string
	CurrentLeafID    string
	NodeCount        int
	BranchCount      int
	Truncated        bool
}

Metadata is the typed coding projection of Harness session metadata.

type MetadataListing added in v0.1.7

type MetadataListing struct {
	Sessions   []Metadata
	Unreadable int
	// Truncated reports that the pass stopped early because its context was
	// cancelled. The listing still carries every Session it read, so a cancelled
	// read is partial data rather than a failure. Unreadable counts Sessions that
	// could not be read at all and keeps that meaning separate.
	Truncated bool
}

List returns typed session metadata in newest-first order without taking writer locks. MetadataListing is a header-level view of the store: every durable conversation with the metadata a statistics surface reads, plus how many Sessions could not be read at all and whether the pass stopped before reading the rest.

type OpenOptions

type OpenOptions struct {
	ID          string
	WorkspaceID string
}

OpenOptions identify a stored session and the workspace allowed to own it.

type OpenTeamWorkerOptions

type OpenTeamWorkerOptions struct {
	ID          string
	WorkspaceID string
	Lineage     TeamWorkerLineage
}

OpenTeamWorkerOptions identifies a Team Worker and the exact resource lineage allowed to own it.

type Repository

type Repository struct {
	// contains filtered or unexported fields
}

Repository owns one directory of coding session files and their lock files.

func NewRepository

func NewRepository(dir string) (*Repository, error)

NewRepository returns a session repository rooted at dir.

func (*Repository) Archives added in v0.1.5

func (r *Repository) Archives(handle *Handle) (*ArchiveStore, error)

Archives binds storage ownership without enumerating or creating any objects.

func (*Repository) CopyArchives added in v0.1.5

func (r *Repository) CopyArchives(ctx context.Context, source *Handle, destinationID string, ids []string) error

CopyArchives publishes independent, verified copies in a reserved destination session before its transcript is published. The caller must hold its writer lock and derive ids from the selected fork path. No destination Handle is required because the fork transcript does not exist yet. Provenance and IDs remain unchanged; neither source deletion nor old checkpoint references create transitive dependencies. Failure may leave inaccessible orphan objects.

func (*Repository) Create

func (r *Repository) Create(ctx context.Context, options CreateOptions) (*Handle, error)

Create reserves and locks a new session. By default its JSONL file is created when the owning Harness Session persists its first entry. Callers that publish the ID before the first entry can retain an empty durable file.

func (*Repository) Delete

func (r *Repository) Delete(ctx context.Context, id string) (resultErr error)

Delete permanently removes one durable conversation and only its own history directory. The transcript deletion is synced before removing archives. Missing conversations succeed without cleaning archives that might be referenced by an uncertain write. Child and Team Worker transcripts are never deleted here.

func (*Repository) Dir

func (r *Repository) Dir() string

Dir returns the absolute session repository directory.

func (*Repository) Fork

func (r *Repository) Fork(
	ctx context.Context,
	source *Handle,
	options ForkOptions,
) (*Handle, error)

Fork creates and locks a failure-atomic copy of source's selected path. The source remains open and unchanged; callers own the returned Handle. Referenced archives are independently published for the destination before its transcript. Errors may leave unpublished-to-the-model archive objects; never remove them based only on a failed or durability-uncertain transcript publication.

func (*Repository) List

func (r *Repository) List(ctx context.Context) ([]Metadata, error)

func (*Repository) ListMetadata added in v0.1.7

func (r *Repository) ListMetadata(ctx context.Context) (MetadataListing, error)

ListMetadata returns header-level metadata for every durable conversation without reading session bodies. It reads one bounded entry per Session instead of the picker's full prefix, which is what makes a statistics surface cheap; the returned Sessions therefore carry header fields (id, kind, creation time) and no name, preview, or transcript counts.

A Session whose file fails the security check is skipped and counted rather than failing the whole listing, because one bad file must not blank a page that only reduces history. A cancelled context stops the pass and marks the listing truncated; the Sessions read so far are still returned and sorted.

func (*Repository) ListSubagents

func (r *Repository) ListSubagents(
	ctx context.Context,
	workspaceID string,
	parentSessionID string,
) ([]Metadata, error)

ListSubagents returns newest-first child metadata for exactly one Workspace and parent conversation without taking writer locks.

func (*Repository) ListTeamWorkers

func (r *Repository) ListTeamWorkers(
	ctx context.Context,
	parentSessionID string,
	teamID team.ID,
	limit int,
) ([]Metadata, error)

ListTeamWorkers returns a bounded newest-first projection for exactly one Lead Session and Team. Worker Workspace identities remain their real values.

func (*Repository) Open

func (r *Repository) Open(ctx context.Context, options OpenOptions) (*Handle, error)

Open locks and opens a stored session after verifying its workspace owner.

func (*Repository) OpenTeamWorker

func (r *Repository) OpenTeamWorker(
	ctx context.Context,
	options OpenTeamWorkerOptions,
) (*Handle, error)

OpenTeamWorker locks and opens one Team Worker only after verifying its real Workspace and every durable lineage component.

type StagedArchive added in v0.1.5

type StagedArchive struct {
	// contains filtered or unexported fields
}

StagedArchive owns one unpublished private temporary file. Close always removes only that temporary name, never a published content-addressed object. Publish and Close are serialized; publish is idempotent until Close.

func (*StagedArchive) Close added in v0.1.5

func (s *StagedArchive) Close() error

Close releases staging resources. It is safe after failed/uncertain Publish.

func (*StagedArchive) ID added in v0.1.5

func (s *StagedArchive) ID() string

ID is known before publication so a candidate checkpoint can be validated.

func (*StagedArchive) Info added in v0.1.5

func (s *StagedArchive) Info() ArchiveInfo

Info returns detached archive metadata.

func (*StagedArchive) Publish added in v0.1.5

func (s *StagedArchive) Publish(ctx context.Context) error

Publish verifies the complete staged object, exclusively publishes its final name and syncs the owning directory. Existing identical objects are reused; different/corrupt objects are never overwritten. It does not commit a Session checkpoint and does not grant retrieval permission.

type SubagentIdentity

type SubagentIdentity struct {
	Schema           string
	AgentID          string
	Kind             string
	Name             string
	DefinitionSchema string
	DefinitionDigest string
	DefinitionSource string
	GenerationID     uint64
	PlanDigest       string
}

SubagentIdentity is the non-secret session-header subset of a compiled child execution plan. The full plan remains in the child journal; this header lets session listing and lineage validation retain stable identity even after the definition file changes or disappears.

func (SubagentIdentity) IsZero

func (i SubagentIdentity) IsZero() bool

IsZero reports whether the legacy session header carries no identity snapshot. It is valid only for historical child sessions.

type TeamWorkerLineage

type TeamWorkerLineage struct {
	ParentSessionID string
	TeamID          team.ID
	MemberID        team.MemberID
	TaskID          team.TaskID
	AttemptID       team.AttemptID
	ContinuationID  continuation.ID
}

TeamWorkerLineage binds an attempt-scoped Worker Session to its Lead and exact durable Team resources.

Jump to

Keyboard shortcuts

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