{"modulePath":"github.com/chainloop-dev/chainloop","version":"v1.138.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package trace\n\n## Constants\n\n```go\nconst (\n\t// AttributionAI marks file changes produced by an AI agent.\n\tAttributionAI = \"ai\"\n\t// AttributionHuman marks file changes produced by a human.\n\tAttributionHuman = \"human\"\n\n\tRoleUser      = \"user\"\n\tRoleAssistant = \"assistant\"\n)\n```\nAttribution constants for file-level code attribution.\n\n```go\nconst DefaultProviderName = \"claude-code\"\n```\nDefaultProviderName is the provider used when a SessionRecord predates the Provider field or when no explicit provider is selected. Kept here so both the providers registry and the action package can reference it without a package import.\n\n## Variables\n\n```go\nvar ErrAnnounceUnsupported = errors.New(\"agent cannot show messages to the user\")\n```\nErrAnnounceUnsupported is returned by AnnounceToUser when the agent has no channel for showing the user a message. It means nothing was displayed, as opposed to a delivery that was attempted and failed, so a caller holding single-use content can keep it rather than throw it away unseen.\n\n## Functions\n\n```go\nfunc GuardHookCommand(command string) string\n```\nGuardHookCommand wraps an agent hook command so that a repository with the hooks installed keeps working when the chainloop CLI is not on PATH: the hook exits 0 instead of failing with \"command not found\" (127). When the CLI is present, exec hands it stdin, stdout and the exit status unchanged.\n\n```go\nfunc GuardHookCommandWithOutput(command, output string) string\n```\nGuardHookCommandWithOutput is GuardHookCommand for a hook whose agent needs a response even when the CLI is missing: the guard prints output before it exits 0. output must not contain a single quote.\n\n```go\nfunc MustRawSessionEntry(e RawSessionEntry) json.RawMessage\n```\nMustRawSessionEntry marshals a RawSessionEntry to json.RawMessage. Panics only on impossible encoding failures (struct field bugs).\n\n## Types\n\n```go\ntype HookEdit struct {\n\t// OldString is the text that was replaced.\n\tOldString string\n\t// NewString is the text that replaced OldString.\n\tNewString string\n}\n```\nHookEdit represents a single old\\_string → new\\_string replacement applied to a file.\n\n```go\ntype HookInput struct {\n\t// SessionID is the agent-assigned identifier for the session.\n\tSessionID string `json:\"session_id\"`\n\t// HookEventName is the agent-specific event name (e.g., \"PreToolUse\", \"afterFileEdit\").\n\tHookEventName string `json:\"hook_event_name,omitempty\"`\n\t// ToolName is the name of the tool being invoked, if applicable.\n\tToolName string `json:\"tool_name,omitempty\"`\n\t// FilePath is the absolute path of the file being edited, set by provider's ReadHookInput.\n\tFilePath string `json:\"-\"`\n\t// FilePaths holds all paths of a file tool that edits several files.\n\t// Handlers process each path with its own snapshot and checkout.\n\tFilePaths []string `json:\"-\"`\n\t// Command is the command line of a shell command tool, set by provider's\n\t// ReadHookInput. Empty when the provider does not report it.\n\tCommand string `json:\"-\"`\n\t// RawToolInput is the provider's full tool input. A provider that rewrites\n\t// shell input preserves every field and changes only Command.\n\tRawToolInput json.RawMessage `json:\"-\"`\n\t// Cwd is the directory the agent session runs in, which is where the\n\t// agent files its transcripts. It can differ from the checkout that owns\n\t// FilePath, e.g. for an edit in a linked git worktree. Empty when the\n\t// agent does not report it.\n\tCwd string `json:\"cwd,omitempty\"`\n\t// TranscriptPath is the path of the session transcript as the agent\n\t// reports it. Unlike Cwd, it does not move when the agent works in\n\t// another directory (e.g. a subagent in its own git worktree). Empty\n\t// when the agent does not report it.\n\tTranscriptPath string `json:\"transcript_path,omitempty\"`\n\t// AgentID identifies the subagent the hook fires in. Subagents share\n\t// their parent's SessionID, so this is what tells concurrent agents of\n\t// one session apart. Empty for the main agent.\n\tAgentID string `json:\"agent_id,omitempty\"`\n\t// ToolUseID is the agent's identifier for one tool call. Its pre and post\n\t// hooks carry the same value, so it tells overlapping calls of one agent\n\t// apart. Empty when the agent does not report it.\n\tToolUseID string `json:\"tool_use_id,omitempty\"`\n\t// AgentVersion is the agent runtime version reported in the hook payload\n\t// (e.g., Cursor's cursor_version). Captured at session-start so parsing\n\t// can set Agent.Version even when the transcript itself doesn't carry it.\n\tAgentVersion string `json:\"-\"`\n\t// Model is the model identifier reported in the hook payload (e.g.,\n\t// Cursor's \"model\" field). Captured at session-start so parsing can\n\t// set Model.Primary even when the transcript itself doesn't carry it.\n\tModel string `json:\"-\"`\n\t// Edits carries per-file string replacements reported by the agent.\n\t// Providers that snapshot files pre-edit leave this empty; providers that\n\t// only emit post-edit events (e.g., Cursor's afterFileEdit) populate it so\n\t// consumers can reconstruct the \"before\" content via reverse application.\n\tEdits []HookEdit `json:\"-\"`\n\t// SkillDir is the folder of the skill that the tool call loaded, when the\n\t// hook payload gives it. Empty otherwise.\n\tSkillDir string `json:\"-\"`\n\t// ToolFailed reports that the hook fires after a tool call that failed\n\t// (Claude's PostToolUseFailure). The tool can still have changed files,\n\t// so its changes are recorded. But the agent expects a different hook\n\t// response for a failure, so nothing is written back to it.\n\tToolFailed bool `json:\"-\"`\n}\n```\nHookInput represents parsed hook invocation data from an AI agent.\n\n```go\ntype ParseOpts struct {\n\t// SessionDir is the directory holding the copied session transcript.\n\tSessionDir string\n\t// SessionID identifies the session to parse.\n\tSessionID string\n\t// AgentVersion is the runtime version captured at session-start (when\n\t// the agent reports it via hook payload). Providers whose transcripts\n\t// don't embed a version can use this to populate Agent.Version.\n\tAgentVersion string\n\t// Model is the model identifier captured at session-start. Providers\n\t// whose transcripts don't embed model info can use this to populate\n\t// Model.Primary.\n\tModel string\n}\n```\nParseOpts configures session parsing.\n\n```go\ntype PastedImage struct {\n\t// Data is the decoded image, as the model got it.\n\tData []byte\n\t// Digest is the digest of Data, in the form of pointer.Digest.\n\tDigest string\n\t// MediaType is the media type of the image, as the agent recorded it.\n\tMediaType string\n\t// Number is the number of the paste as the agent showed it to the user,\n\t// or the position of the image in the session, from 1, when the agent\n\t// showed no number.\n\tNumber int\n\t// Timestamp is the time of the transcript entry that holds the image,\n\t// RFC3339 in UTC, or empty when the agent recorded none that can be read.\n\tTimestamp string\n}\n```\nPastedImage is one image that the user pasted into a session.\n\n```go\ntype PastedImageFinder interface {\n\t// PastedImages returns each distinct image that the user pasted, in each\n\t// stream of the raw session: the main stream first, then the subagent\n\t// streams by name. An image pasted many times is returned one time, from\n\t// its first paste. An image whose data cannot be decoded is left out.\n\tPastedImages(raw map[string][]json.RawMessage) []PastedImage\n}\n```\nPastedImageFinder is implemented by a provider that can find the images that the user pasted into its transcript (spec issue-3569). The push stores each one as a spec source, and ReplaceSpecCopies of the same provider then replaces it with a pointer. For the sessions of a provider without it, the pasted images stay inline.\n\n```go\ntype Provider interface {\n\t// Name returns the agent identifier (e.g., \"claude-code\", \"cursor\").\n\tName() string\n\n\t// ParseSession parses a session and returns structured evidence.\n\tParseSession(ctx context.Context, opts *ParseOpts) (*aicodingsession.Evidence, error)\n\n\t// CopySessionData copies the agent's on-disk session artifacts into\n\t// the store's raw/ directory so pre-push can parse them independently of\n\t// the agent's own storage (which may be rotated/cleaned later).\n\t// loc says where the agent keeps the session's transcripts; it need not\n\t// be in the checkout that owns store.\n\tCopySessionData(store *state.Store, loc SessionLocation) error\n\n\t// CaptureFileSnapshot is invoked from the pre-edit hook to record any\n\t// state the provider needs to later reconstruct the file's pre-edit\n\t// content. Providers whose post-edit hook delivers the edit payload\n\t// directly (e.g. Cursor's afterFileEdit with old/new strings)\n\t// implement this as a no-op.\n\tCaptureFileSnapshot(store *state.Store, input *HookInput) error\n\n\t// ResolveBeforeContent reconstructs the file's content as it was\n\t// before the edit, given its current (\"after\") content. Returns nil\n\t// when no reconstruction is possible (no snapshot, no edits, or the\n\t// file was newly created); callers treat nil as \"all lines are AI\".\n\tResolveBeforeContent(store *state.Store, input *HookInput, after []byte) []byte\n\n\t// CleanupAfterEdit releases any per-edit state captured in\n\t// CaptureFileSnapshot. Called once the post-edit handler is done with\n\t// the file, regardless of whether ranges were recorded.\n\tCleanupAfterEdit(store *state.Store, input *HookInput)\n\n\t// InstallHooks installs the agent's hooks in the repo (e.g., .claude/settings.json).\n\tInstallHooks(repoRoot string) error\n\n\t// InstallHooksForTraceRun installs the data-gathering subset of hooks\n\t// used by `chainloop trace run`. End-of-session hooks are omitted —\n\t// trace run drives attestation itself.\n\tInstallHooksForTraceRun(repoRoot string) error\n\n\t// SettingsFile returns the absolute path to the agent's on-disk\n\t// hooks/settings file (e.g. .claude/settings.json). Callers use it to\n\t// back up the file before install and restore it afterwards.\n\tSettingsFile(repoRoot string) string\n\n\t// UninstallHooks removes the agent's hooks from the repo.\n\tUninstallHooks(repoRoot string) error\n\n\t// HooksInstalled reports whether the repo already carries the agent's\n\t// Chainloop hooks, so `trace init` can offer the harnesses a repository\n\t// is set up for when it runs again. Hooks the user wrote do not count.\n\tHooksInstalled(repoRoot string) (bool, error)\n\n\t// ReadHookInput reads hook invocation input from the given reader.\n\tReadHookInput(r io.Reader) (*HookInput, error)\n\n\t// IsFileWritingTool returns true if the named tool modifies files on disk.\n\tIsFileWritingTool(toolName string) bool\n\n\t// IsCommandTool returns true if the named tool runs a shell command (e.g.\n\t// Claude's \"Bash\"). Such tools can create or modify arbitrary files without\n\t// firing the file-writing hooks, so they are captured via a before/after\n\t// working-tree snapshot instead of a per-file snapshot.\n\tIsCommandTool(toolName string) bool\n\n\t// AnnounceSessionStart writes the session-start hook response to stdout,\n\t// as the one document the agent will read. A message with nothing on\n\t// either channel emits nothing, so the hook stays a no-op rather than\n\t// handing the agent an empty envelope to parse.\n\tAnnounceSessionStart(msg SessionStartMessage) error\n\n\t// SupportsSessionStartBanner reports whether the Banner of a message\n\t// handed to AnnounceSessionStart reaches the user rather than being\n\t// discarded. Callers check it before composing the banner, which costs a\n\t// control-plane round trip.\n\tSupportsSessionStartBanner() bool\n\n\t// SupportsSessionStartInstruction reports whether the Instruction of a\n\t// message handed to AnnounceSessionStart reaches the model rather than\n\t// being discarded.\n\tSupportsSessionStartInstruction() bool\n\n\t// AnnouncePromptSubmit writes the prompt-submit hook response to stdout,\n\t// so that reminder reaches the model's context for this turn. An empty\n\t// reminder emits nothing.\n\tAnnouncePromptSubmit(reminder string) error\n\n\t// SupportsPromptReminder reports whether a reminder handed to\n\t// AnnouncePromptSubmit reaches the model at each user prompt. An agent\n\t// without it gets the session-start instruction only.\n\tSupportsPromptReminder() bool\n\n\t// AnnounceToUser writes a hook response to stdout so the agent puts msg\n\t// in front of the user, after a shell command the agent ran. Which\n\t// channel that uses is the provider's business: agents differ in whether\n\t// they render text directly, relay it through the model, or both.\n\t//\n\t// Providers with no way to reach the user return ErrAnnounceUnsupported,\n\t// so callers can tell \"shown\" apart from \"nothing happened\" and avoid\n\t// discarding a message nobody saw.\n\tAnnounceToUser(msg string) error\n}\n```\nProvider captures and parses AI coding sessions for a specific agent.\n\nProviders are stateless singletons from a registry, so the state-touching methods below take a \\*state.Store per call rather than holding one. The store already knows where trace state lives — the .git directory inside a repository, or the out-of-tree directory \\`chainloop trace run\\` picks outside one — so implementations never reason about that distinction.\n\n```go\ntype RawSessionEntry struct {\n\tType        string            `json:\"type,omitempty\"`\n\tRole        string            `json:\"role,omitempty\"`\n\tUUID        string            `json:\"uuid,omitempty\"`\n\tTimestamp   string            `json:\"timestamp,omitempty\"`\n\tIsMeta      bool              `json:\"isMeta,omitempty\"`\n\tMessage     RawSessionMessage `json:\"message\"`\n\tSourceEvent json.RawMessage   `json:\"source_event,omitempty\"`\n}\n```\nRawSessionEntry is the normalized wire format most providers use for a single message in raw\\_session\\[\"main\"]. A provider whose persisted format carries a native timeline may retain those objects instead, so valid unknown entries are not discarded. Consumers can select a renderer by Agent.Name. This shape mirrors Claude's JSONL transcript format, which the frontend was originally built against.\n\n```go\ntype RawSessionMessage struct {\n\tRole    string          `json:\"role,omitempty\"`\n\tContent json.RawMessage `json:\"content,omitempty\"`\n\tModel   string          `json:\"model,omitempty\"`\n}\n```\nRawSessionMessage is the message body inside a RawSessionEntry.\n\n```go\ntype RawSessionTextBlock struct {\n\tType string `json:\"type\"`\n\tText string `json:\"text\"`\n}\n```\nRawSessionTextBlock is a content block carrying plain text.\n\n```go\ntype RawSessionToolResultBlock struct {\n\tType      string          `json:\"type\"`\n\tToolUseID string          `json:\"tool_use_id\"`\n\tContent   json.RawMessage `json:\"content\"`\n}\n```\nRawSessionToolResultBlock carries the result of a tool\\_use with the same ID. It belongs to a user-shaped entry, not to a new user prompt.\n\n```go\ntype RawSessionToolUseBlock struct {\n\tType  string          `json:\"type\"`\n\tID    string          `json:\"id,omitempty\"`\n\tName  string          `json:\"name,omitempty\"`\n\tInput json.RawMessage `json:\"input,omitempty\"`\n}\n```\nRawSessionToolUseBlock is a content block representing a tool call.\n\n```go\ntype SessionLocation struct {\n\t// SessionID identifies the session.\n\tSessionID string\n\t// Cwd is the directory the session runs in. Providers that key their\n\t// storage by directory use it when TranscriptPath is empty.\n\tCwd string\n\t// TranscriptPath is the transcript path the agent reported, if any.\n\t// Providers that get one prefer it over Cwd.\n\tTranscriptPath string\n}\n```\nSessionLocation tells a provider where to find a session's transcripts.\n\n```go\ntype SessionStartMessage struct {\n\t// Banner is shown to the user verbatim by the agent client, without\n\t// costing a model turn. Empty means nothing is shown.\n\tBanner string\n\n\t// Instruction is addressed to the model rather than the user: it reaches\n\t// the session's context so the agent can act on it. Empty means the model\n\t// is told nothing.\n\tInstruction string\n}\n```\nSessionStartMessage is everything the session-start hook has to say, on the two channels an agent offers: one the user reads, one the model reads.\n\nIt is one value rather than two calls because an agent parses a hook's stdout as a single JSON document. A second write would be discarded, silently, together with whatever it carried — so the two channels are made inseparable here rather than left to each caller to remember.\n\n```go\nfunc (m SessionStartMessage) Empty() bool\n```\nEmpty reports that there is nothing to deliver on either channel.\n\n```go\ntype ShellCommandTagger interface {\n\tTagShellCommand(input *HookInput, token string) error\n}\n```\nShellCommandTagger is implemented by a provider whose pre-tool hook can replace shell input before execution. The opaque token reaches git hooks through the command environment, tying a commit to one exact tool call.\n\n```go\ntype SkillTracker interface {\n\t// NewSkillLoads returns the folders of the skills that the session loaded\n\t// since the last call for the session, as far as the hook can tell. The\n\t// caller copies each folder. It never fails: a hook that cannot tell\n\t// returns nothing, and the push copies the folder later.\n\tNewSkillLoads(store *state.Store, input *HookInput) []string\n\n\t// SessionSkills returns the skills that the session used, from the\n\t// session data under opts.SessionDir, in the order of their first use.\n\t// The warnings are for uses that could not be read.\n\tSessionSkills(opts *ParseOpts) ([]SkillUse, []string, error)\n\n\t// SkillRoots returns the folders that tell where a skill came from, for a\n\t// session in repoRoot.\n\tSkillRoots(repoRoot string) skill.Roots\n}\n```\nSkillTracker is implemented by a provider that records the skills that a session used. A provider without it records no skills, and for its sessions no skill entry means \"not recorded\", not \"no skill used\".\n\n```go\ntype SkillUse struct {\n\t// Name is the name that the agent used for the skill.\n\tName string\n\t// Dir is the folder that the agent loaded the skill from, or \"\" when the\n\t// skill has no folder (a skill built into the agent) or the session data\n\t// does not tell. A use with no folder is not recorded.\n\tDir string\n\t// FirstUsedAt is the time of the first use, RFC3339 in UTC with whole\n\t// seconds, or \"\" when no use has a time that can be read.\n\tFirstUsedAt string\n\t// ByModel counts the uses that the model started with a tool call.\n\tByModel int\n\t// ByUser counts the uses that the user started with a slash command.\n\tByUser int\n\t// InSubagents counts the uses, of either start, that came from subagents.\n\tInSubagents int\n}\n```\nSkillUse is one skill that a session used, with the counts of its uses.\n\n```go\nfunc SortedSkillUses(uses map[string]*SkillUse) []SkillUse\n```\nSortedSkillUses returns the uses in the order of their first use. The uses with no time come last, so that the limit on skill entries, which keeps the first ones, does not drop a skill with a known time for one with no time. The name breaks ties, so that the same session data always gives the same order.\n\n```go\nfunc (u *SkillUse) Merge(other SkillUse)\n```\nMerge adds the uses of other, of the same skill, to u.\n\n```go\nfunc (u *SkillUse) Record(at string, byModel, subagent bool)\n```\nRecord adds one use at time at, RFC3339, to the counts. The first use is the earliest time recorded, whatever the order of the calls. A use whose time cannot be read is counted, but its time is ignored.\n\n```go\ntype SpecCopyReplacer interface {\n\t// ReplaceSpecCopies replaces, in each stream of the raw session, each\n\t// exact copy of a source with a pointer to its material, and reports the\n\t// result per finder. It updates the lines in place and never fails: a\n\t// copy that does not match stays inline.\n\tReplaceSpecCopies(raw map[string][]json.RawMessage, sources pointer.Sources) pointer.Report\n}\n```\nSpecCopyReplacer is implemented by a provider that can find the copies of spec sources in its transcript (spec issue-3556). For the sessions of a provider without it, the transcript keeps its copies.\n\n","path":"github.com/chainloop-dev/chainloop/app/cli/internal/trace","name":"trace","synopsis":"","isRedistributable":true}
