Documentation
¶
Overview ¶
Package magus is the high-level library for the magus build orchestrator.
Entry points: Open returns a Magus for build/test cycles, Inspect for read-only commands. A Magus runs work via Magus.Run (one target), Magus.RunCI (the configured CI pipeline), and Magus.RunAffected (only projects touched since a baseline). Behavior is tuned with Option values passed to Open/Inspect (e.g. WithLimiter). Limiter caps concurrent spell executions and can be shared across daemon workspaces.
Boundary: the library links the engine-agnostic interp surface and the Buzz VM, but deliberately not the host bindings (interp/bindings) or the Buzz engine backend — cmd/magus blank-imports those. So a script-driven backend (e.g. the spell-backed remote backend) reaches the library only through registered hooks such as cache.RegisterRemoteBackendOpener, never a direct import.
Index ¶
- Constants
- func ApplyUnionSandbox(ctx context.Context, roots []string) error
- func BuildGlobalKnowledgeGraph(ctx context.Context, ws types.WorkspaceRepository, cfg config.Config, ...) (*knowledge.Graph, error)
- func BuildKnowledgeGraph(ctx context.Context, ws types.Inspector, root string, cfg config.Config, ...) (*knowledge.Graph, error)
- func CatalogFingerprint() string
- func CharmsForCI(charms []string) []string
- func ComposeGraph(ws types.WorkspaceRepository, opts ...ComposeOption) types.GraphOutput
- func DefaultConcurrency() int
- func FindRoot(dir string) (string, error)
- func IgnoreGlob(pattern string) types.IgnorePattern
- func IgnoreLiteral(pattern string) types.IgnorePattern
- func IgnoreRegex(pattern string) types.IgnorePattern
- func Inspect(ctx context.Context, root string, opts ...Option) (types.WorkspaceRepository, error)
- func ListSpells(ctx context.Context) ([]types.Spell, error)
- func MergeWorkspaceSymbols(ctx context.Context, ws types.Inspector, root string, cfg config.Config, ...) error
- func MergeWorkspaceSymbolsForRef(ctx context.Context, ws types.Inspector, root string, cfg config.Config, ...) error
- func ResolveCacheDir(root string, opts ...Option) (string, error)
- func ShortRevision(id string) string
- func SymbolGaps(ctx context.Context, ws types.Inspector, root string, cfg config.Config, ...) (gaps []types.KnowledgeSymbolGap, ok bool)
- func TargetLabel(targets []types.Target, source string) string
- func WithWorkspaceRegistryContext(ctx context.Context, reg *WorkspaceRegistry) context.Context
- type BindingOption
- type CacheStats
- type Command
- type ComposeOption
- type Daemon
- type Event
- type Invocation
- type Limiter
- type Magus
- func (m *Magus) Affected(ctx context.Context, base string) (*types.AffectedResult, error)
- func (m *Magus) AffectedFromPaths(ctx context.Context, paths []string) (*types.AffectedResult, error)
- func (m *Magus) Affinity(ctx context.Context, opts types.InsightOptions) (types.AffinityOutput, error)
- func (m *Magus) All() []*types.Project
- func (m *Magus) BeginInvocation(ctx context.Context, cmd journal.Command, magusVersion string, ...) (context.Context, func(error))
- func (m *Magus) BranchChanges(ctx context.Context, limit int) ([]types.BranchChange, error)
- func (m *Magus) CacheDir() string
- func (m *Magus) CacheDiskBytes() int64
- func (m *Magus) CacheStats() CacheStats
- func (m *Magus) ClassifyFiles(ctx context.Context, paths []string) ([]types.FileEntry, error)
- func (m *Magus) CleanCache(ctx context.Context, projects ...*types.Project) error
- func (m *Magus) CleanOutputs(ctx context.Context, projects []*types.Project, dryRun bool) ([]string, error)
- func (m *Magus) Close() error
- func (m *Magus) ComputeTargetKey(ctx context.Context, projectPath, target string, charms []string) (key string, lines []string, err error)
- func (m *Magus) ContextWithSecrets(ctx context.Context) context.Context
- func (m *Magus) CurrentRevision(ctx context.Context) (name, revision string, dirty bool)
- func (m *Magus) Diff(ctx context.Context, paths []string) (types.Diff, error)
- func (m *Magus) DiffTUIEnabled() bool
- func (m *Magus) EvaluateProjects(ctx context.Context) (types.EvaluatedProjectsOutput, error)
- func (m *Magus) EvaluateTarget(ctx context.Context, t types.Target) ([]types.EvaluatedTarget, error)
- func (m *Magus) ExpandAffected(ctx context.Context, target string, baseRef string) (targets []types.Target, source string, fellBack bool, err error)
- func (m *Magus) ExpandCwd(t types.Target) (targets []types.Target, found bool, err error)
- func (m *Magus) ExpandPath(t types.Target) ([]types.Target, error)
- func (m *Magus) ExportCache(ctx context.Context, w io.Writer) error
- func (m *Magus) FileAt(ctx context.Context, rev, path string) (string, error)
- func (m *Magus) FindOutputProducer(absPath string) *types.Project
- func (m *Magus) Get(path string) *types.Project
- func (m *Magus) GetArtifact(ctx context.Context, v cache.ArtifactVersion, dst string) error
- func (m *Magus) Graph() (*types.Graph, error)
- func (m *Magus) HeldLocks() []types.StatusLock
- func (m *Magus) Hotspots(ctx context.Context, opts types.InsightOptions) (types.HotspotOutput, error)
- func (m *Magus) IdentifyRef(ctx context.Context, ref string) ([]types.RefMatch, error)
- func (m *Magus) ImportCache(ctx context.Context, r io.Reader) error
- func (m *Magus) InvocationByID(inv string) (Invocation, error)
- func (m *Magus) InvocationEventsByID(inv string) (Invocation, []Event, error)
- func (m *Magus) KnowledgeGraph(ctx context.Context, refresh bool) (*knowledge.Graph, error)
- func (m *Magus) KnowledgeGraphHealthy() (watching, valid bool)
- func (m *Magus) KnowledgeGraphWithSymbols(ctx context.Context) (*knowledge.Graph, error)
- func (m *Magus) KnowledgeGraphWithSymbolsForRef(ctx context.Context, ref string) (*knowledge.Graph, error)
- func (m *Magus) LastRecordedRun(projectPath, target string) (cache.RecordedRun, error)
- func (m *Magus) ListArtifacts(ctx context.Context, projectPath, wsPath string) ([]cache.ArtifactVersion, error)
- func (m *Magus) ListCharms(ctx context.Context) ([]types.Charm, error)
- func (m *Magus) ListProjects(ctx context.Context) (types.ProjectsOutput, error)
- func (m *Magus) ListTargets(ctx context.Context) ([]types.TargetEntry, error)
- func (m *Magus) LogBase(ctx context.Context, base, vcs string)
- func (m *Magus) LogCache(ctx context.Context)
- func (m *Magus) LogCharms(ctx context.Context, charms string)
- func (m *Magus) LogScope(ctx context.Context, label, source string)
- func (m *Magus) MetricsCollector() (*MetricsCollector, bool)
- func (m *Magus) MetricsSnapshot(ctx context.Context) ([]byte, error)
- func (m *Magus) OutputAttempts(ref string) ([]OutputDescriptor, error)
- func (m *Magus) OutputByRef(ref string) ([]byte, OutputDescriptor, error)
- func (m *Magus) OutputByRefRemote(ctx context.Context, ref string) ([]byte, OutputDescriptor, error)
- func (m *Magus) OutputDescriptorByRef(ref string) (OutputDescriptor, error)
- func (m *Magus) OutputKeyInputs(ref string) ([]string, error)
- func (m *Magus) Ownership(ctx context.Context, opts types.InsightOptions) (types.OwnershipOutput, error)
- func (m *Magus) Plan(ctx context.Context, target string, opts PlanOptions) (types.ShardPlan, error)
- func (m *Magus) ProjectTargets(ctx context.Context, project string) []string
- func (m *Magus) PruneCache(ctx context.Context, cutoff time.Time, dryRun bool) (removed int, freed int64, err error)
- func (m *Magus) PruneRemoteCache(ctx context.Context, olderThan time.Duration, keepLast int, dryRun bool) error
- func (m *Magus) PublishOutput(ctx context.Context, ref string) (string, error)
- func (m *Magus) RangeDiff(ctx context.Context, base, head string, paths []string) (string, error)
- func (m *Magus) RefMatchCommand(mt types.RefMatch) string
- func (m *Magus) ReindexSymbols(ctx context.Context) (int, error)
- func (m *Magus) ResolveProjects(targets []types.Target) []*types.Project
- func (m *Magus) ResolveTargetOutputs(ctx context.Context, projects []*types.Project, target string) ([]TargetArtifact, error)
- func (m *Magus) ReviewOrigin(ctx context.Context) types.ReviewOrigin
- func (m *Magus) RevisionCheckpoint(ctx context.Context, rev string) (types.VCSCheckpoint, error)
- func (m *Magus) Root() string
- func (m *Magus) Run(ctx context.Context, targets []types.Target, opts ...RunOption) error
- func (m *Magus) RunAffected(ctx context.Context, target string, opts ...RunOption) error
- func (m *Magus) RunCI(ctx context.Context, targets []types.Target, opts ...RunOption) error
- func (m *Magus) SecretProvider() string
- func (m *Magus) ServeDaemon(ctx context.Context) error
- func (m *Magus) SetDaemon(d Daemon)
- func (m *Magus) SetGraphObserver(o types.Observer)
- func (m *Magus) Stream(ctx context.Context, r io.Reader, target string, errFn func(error), ...) error
- func (m *Magus) SymbolGaps(ctx context.Context) ([]types.KnowledgeSymbolGap, bool)
- func (m *Magus) SymbolIndexStatus(ctx context.Context) []types.SymbolIndexStatus
- func (m *Magus) SymbolOccurrences(ctx context.Context, key string) (SymbolOccurrenceRead, bool)
- func (m *Magus) TailLog(projectPath, target string) (logPath string, err error)
- func (m *Magus) TargetGraph(ctx context.Context) (types.TargetGraphOutput, error)
- func (m *Magus) Telemetry() observability.Provider
- func (m *Magus) Trend(ctx context.Context, opts types.InsightOptions) (types.TrendOutput, error)
- func (m *Magus) Unreferenced(ctx context.Context) (types.UnreferencedOutput, error)
- func (m *Magus) VCSOptions() types.VCSOptions
- func (m *Magus) Volatility(ctx context.Context) (types.VolatilityReport, error)
- func (m *Magus) WatchKnowledgeGraph(ctx context.Context) (func(), error)
- func (m *Magus) WatchSymbolIndexing(ctx context.Context) (func(), error)
- func (m *Magus) Where(dir string) (*types.Project, bool)
- func (m *Magus) WorkingDiff(ctx context.Context, paths []string) (string, error)
- func (m *Magus) Workspace(ctx context.Context, cfg types.WorkspaceConfig) (types.WorkspaceEntry, error)
- type MetricsCollector
- type Option
- func WithConfigFile(path string) Option
- func WithLimiter(l *Limiter) Option
- func WithLoadedConfig(cfg config.Config) Option
- func WithMetricsCollection() Option
- func WithProvider(p observability.Provider) Option
- func WithVersion(v string) Option
- func WithWorkspaceRegistry(reg *WorkspaceRegistry) Option
- func WithoutWorkspaceProviders() Option
- type OutputDescriptor
- type PlanOptions
- type ProjectOption
- func WithDependsOn(paths ...string) ProjectOption
- func WithExclusive() ProjectOption
- func WithOutputs(paths ...string) ProjectOption
- func WithSpell(name string, opts ...BindingOption) ProjectOption
- func WithTarget(name string, opts ...TargetOption) ProjectOption
- func WithWatchIgnore(patterns ...types.IgnorePattern) ProjectOption
- type ReportWriter
- type RunOption
- func WithBaseRef(ref string) RunOption
- func WithCharms(charms ...string) RunOption
- func WithDryRun() RunOption
- func WithExtraArgs(args []string) RunOption
- func WithNoCache() RunOption
- func WithNoVolatilityRetry() RunOption
- func WithRace() RunOption
- func WithRaceReplay() RunOption
- func WithReport(rw *ReportWriter) RunOption
- func WithReportWriter(w io.Writer) RunOption
- func WithSpellFilter(name string) RunOption
- func WithStep() RunOption
- func WithWrite() RunOption
- type StreamOption
- type SymbolOccurrenceRead
- type TargetArtifact
- type TargetHandler
- type TargetOption
- type WorkspaceRegistry
Examples ¶
Constants ¶
const BaseLastPassed = "last-passed"
BaseLastPassed is the base ref that means "the commit this branch last completed a fully passing run at", read from the run history rather than from the VCS. Every entry point that takes a base ref accepts it, so `--base last-passed`, MAGUS_VCS_BASE_REF, and magus\affected() all reach the same resolution.
const CacheKeyVersion = cache.KeyVersion
CacheKeyVersion is the hashing-recipe version this binary computes cache keys with. Two keys from different recipes are not comparable, which is what makes a mismatch worth reporting rather than treating as changed inputs.
const LockStaleAfter = 10 * time.Minute
LockStaleAfter is how long a lock is held, or a wait runs, before "busy" stops being the likely explanation and "abandoned" starts.
Exported because it is a JUDGMENT the whole product has to agree on. It was previously decided twice - two minutes here and ten in the console tile - which put a CLI warning that a holder "may be abandoned" beside a dashboard row still styled as perfectly healthy. One threshold, one place; the console reads it off the wire.
const StreamAllSentinel = "\x00ALL"
StreamAllSentinel is a stream-batch marker that triggers a full-workspace selection. The NUL prefix ensures it cannot collide with a real file path.
Variables ¶
This section is empty.
Functions ¶
func ApplyUnionSandbox ¶
ApplyUnionSandbox unions the landlock policies of every workspace root and applies the combined ruleset to the current process exactly once. Roots whose config disables the sandbox still contribute filesystem rules but no binding-layer policy (MGS2011). It is a no-op (returns nil) when no root requests kernel sandboxing.
This is the multi-workspace (daemon) counterpart to the per-workspace sandbox that Run applies. It lives in the library so callers — the CLI daemon in particular — never import internal/sandbox directly: policy assembly and application stay behind one seam, so the two paths cannot drift.
func BuildGlobalKnowledgeGraph ¶ added in v0.2.0
func BuildGlobalKnowledgeGraph(ctx context.Context, ws types.WorkspaceRepository, cfg config.Config, refresh bool, log *slog.Logger) (*knowledge.Graph, error)
BuildGlobalKnowledgeGraph unions the current workspace with each registered one (cfg.Knowledge.Workspaces), namespacing node IDs by workspace so repos can't collide. A workspace that fails to open is skipped with a warning, not fatal: the query degrades to what it can reach.
func BuildKnowledgeGraph ¶ added in v0.2.0
func BuildKnowledgeGraph(ctx context.Context, ws types.Inspector, root string, cfg config.Config, refresh bool, log *slog.Logger) (*knowledge.Graph, error)
BuildKnowledgeGraph assembles, persists, and returns the workspace knowledge graph. It is the single graph-loading path shared by the `magus graph` subcommands, the query/explain/path verbs, and the MCP tools: it gathers the describe outputs the graph is composed from, resolves the cache dir, and runs the cache-first build. ws is any workspace view that can describe itself (the read-only Inspect result or a full *Magus).
func CatalogFingerprint ¶ added in v0.4.0
func CatalogFingerprint() string
CatalogFingerprint identifies the compiled-in catalogs a binary contributes to generated output: diagnostic codes, built-in spells, module surface. Stamped into the exported graph so drift can be attributed to the build that produced it (MGS4005).
Hashes the catalogs, not the version: `git describe` moves every commit and would churn the artifact, while these change only when the output would change anyway.
func CharmsForCI ¶ added in v0.4.0
CharmsForCI returns charms with the write-granting ones removed, which is what a ci run actually executes under. Exported because the CLI has to print the same set it runs: a header reporting the RESOLVED charms would announce "charms: rw" for `magus run ci` and then run read-only, since RunCI strips them afterwards. Whoever reads that header is checking exactly this, so both sides read it from here.
func ComposeGraph ¶
func ComposeGraph(ws types.WorkspaceRepository, opts ...ComposeOption) types.GraphOutput
ComposeGraph assembles the structured graph view. Edges to unknown projects are dropped.
func DefaultConcurrency ¶
func DefaultConcurrency() int
DefaultConcurrency returns the concurrency cap used when no explicit cap is set, resolved by precedence: the MAGUS_CONCURRENCY env var if set to a positive int, then 4 on GitHub-hosted runners (GITHUB_ACTIONS=true and RUNNER_ENVIRONMENT is not self-hosted), then min(NumCPU, 8).
func FindRoot ¶
FindRoot walks up from dir (or cwd when empty) to find the workspace root.
The NEAREST magus.yaml wins, because it is the only file that declares "the workspace starts here" and the closest declaration is the governing one - the same rule .git follows, and the reason a git worktree nested inside its parent repo resolves to itself rather than being swallowed by the parent.
Absent any magus.yaml, the root is the outermost CONTIGUOUS project marker. Contiguous so a stray magusfile in an unrelated ancestor (a home directory, /tmp) cannot silently adopt everything beneath it, which an unbounded walk would allow.
func IgnoreGlob ¶
func IgnoreGlob(pattern string) types.IgnorePattern
IgnoreGlob constructs a doublestar-glob ignore pattern.
func IgnoreLiteral ¶
func IgnoreLiteral(pattern string) types.IgnorePattern
IgnoreLiteral constructs a literal ignore pattern matching any path segment at any depth.
func IgnoreRegex ¶
func IgnoreRegex(pattern string) types.IgnorePattern
IgnoreRegex constructs a Go-regexp ignore pattern.
func Inspect ¶
Inspect discovers the workspace without opening the cache (for introspection commands).
Example ¶
ExampleInspect shows how to discover projects in a workspace without opening the cache. Inspect is the right entry point for read-only commands (list, graph, describe) where cache overhead is unnecessary.
// Create a minimal workspace with one project for illustration.
root, err := os.MkdirTemp("", "magus-example-*")
if err != nil {
fmt.Println("setup error:", err)
return
}
defer os.RemoveAll(root)
// A directory is a project if it contains a magusfile.buzz.
projDir := filepath.Join(root, "myapp")
if err := os.MkdirAll(projDir, 0o755); err != nil {
fmt.Println("setup error:", err)
return
}
if err := os.WriteFile(filepath.Join(projDir, "magusfile.buzz"), []byte(""), 0o644); err != nil {
fmt.Println("setup error:", err)
return
}
ws, err := Inspect(context.Background(), root)
if err != nil {
fmt.Println("inspect error:", err)
return
}
for _, p := range ws.All() {
fmt.Println(p.Path)
}
Output: myapp
func ListSpells ¶ added in v0.4.0
ListSpells returns the catalog of registered spells, sorted by name. A package-level function, not a *Magus method: it reads only the global spell registry (project.DefaultSpellRegistry), never the receiver, so it is not on the Inspector interface - a workspace method that ignores its workspace is a global query wearing a domain method's clothes.
func MergeWorkspaceSymbols ¶ added in v0.2.0
func MergeWorkspaceSymbols(ctx context.Context, ws types.Inspector, root string, cfg config.Config, g *knowledge.Graph, log *slog.Logger) error
MergeWorkspaceSymbols pulls every persisted per-project @symbols shard into g, for a symbol-seeded query (the default graph excludes them for scale). Best-effort: no store or no symbol shards is a no-op.
func MergeWorkspaceSymbolsForRef ¶ added in v0.2.0
func MergeWorkspaceSymbolsForRef(ctx context.Context, ws types.Inspector, root string, cfg config.Config, g *knowledge.Graph, ref string, log *slog.Logger) error
MergeWorkspaceSymbolsForRef merges symbols into g for `magus refs`, targeting only the shards that mention ref (via the xref routing index) when ref is an exact symbol ID - the scale-safe reverse lookup - or all symbol shards when ref is a fuzzy name whose exact ID is not yet known.
func ResolveCacheDir ¶ added in v0.4.0
ResolveCacheDir returns the cache directory that an Open or Inspect workspace rooted at root would use without discovering projects or evaluating magusfiles. Sidecar writers that need the shared cache location before a command runs use this narrow path so instrumentation does not pay workspace-load cost merely to append an event.
func ShortRevision ¶ added in v0.4.0
ShortRevision abbreviates a full VCS revision id for display, leaving a short id untouched. Matches this codebase's convention of a 12-hex-digit truncation elsewhere (PortableRef); the stored/compared value is always the full revision, this is presentation only.
func SymbolGaps ¶ added in v0.4.0
func SymbolGaps(ctx context.Context, ws types.Inspector, root string, cfg config.Config, log *slog.Logger) (gaps []types.KnowledgeSymbolGap, ok bool)
SymbolGaps reports every project that declares a SCIP index magus could not read, so a lookup can say whether it searched everywhere it should have. ok is false when the probe itself could not run: a nil slice would otherwise be indistinguishable from "no gaps" and would turn an internal failure into a confident claim of absence, which is the one outcome the verdict exists to prevent.
It keys off the same declarations loadKnowledgeSymbols ingests, which is deliberately NOT the set magus status reports: declarations include knowledge.symbols overrides, and a project indexed only through one of those is invisible to the status lens.
The probe is one Stat per declared index and nothing more. It deliberately does not decode the index to check it parses: that is a full protobuf unmarshal plus symbol accumulation per lookup, and a never-built index is the case that actually occurs. A present-but-corrupt index therefore reads as covered here; the graph build logs it.
Freshness is out of scope for the same reason: deciding whether an index is merely STALE needs a cache handle, and the read verbs that call this inspect the workspace rather than opening it (opening writes).
func TargetLabel ¶
TargetLabel returns a one-line summary of a target slice suitable for log headers.
func WithWorkspaceRegistryContext ¶
func WithWorkspaceRegistryContext(ctx context.Context, reg *WorkspaceRegistry) context.Context
WithWorkspaceRegistryContext installs reg in ctx so interpreters can retrieve it.
Types ¶
type BindingOption ¶
type BindingOption = workspace.BindingOption
BindingOption mutates a spell Binding at registration time.
type CacheStats ¶ added in v0.4.0
type CacheStats struct {
Hit int
Miss int
Error int
// SavedMs is the summed recorded duration of the runs those hits replayed - work the cache
// avoided, measured per entry rather than averaged. Understates when an entry predates the
// recorded duration; never overstates.
SavedMs int64
}
CacheStats is this workspace's live cache counters (hits/misses/errors), a caller-facing projection of cache.Stats that carries no type from an internal/ package.
type Command ¶ added in v0.4.0
type Command struct {
Arguments []string `json:"arguments,omitempty"` // the full argument vector, subcommand included (e.g. ["run", "build", "api"])
Cwd string `json:"cwd,omitempty"` // directory the command was invoked in
Trigger string `json:"trigger,omitempty"` // one of the journal.Trigger* constants
}
Command is a magus invocation's lineage - the caller-facing projection of journal.Command. Field tags match it exactly for JSON wire compat.
type ComposeOption ¶
type ComposeOption func(*compose)
ComposeOption configures a ComposeGraph call.
func WithComposeRoots ¶
func WithComposeRoots(paths ...string) ComposeOption
WithComposeRoots restricts the graph to the listed project paths.
func WithComposeSpell ¶
func WithComposeSpell(name string) ComposeOption
WithComposeSpell limits the graph to projects that use the named spell.
func WithGraphHistory ¶
func WithGraphHistory(h *forecast.History, target string) ComposeOption
WithGraphHistory enables per-node DurationMs prediction in ComposeGraph using adaptive CI history for the given target (typically "ci" or "test").
func WithGraphInput ¶
func WithGraphInput(g *types.Graph) ComposeOption
WithGraphInput enables blast-radius enrichment.
func WithUpstream ¶
func WithUpstream() ComposeOption
WithUpstream switches graph direction to upstream (dependents instead of dependencies).
type Daemon ¶ added in v0.2.0
Daemon is the long-running server this workspace hosts (the MCP HTTP endpoint plus the console API routes, and whatever else the daemon grows to serve). It is injected by the CLI in daemon mode ONLY - so ordinary command paths never construct one - and held as an interface so the root magus package need not import the daemon/handler packages (which depend on magus), breaking that cycle. The concrete *daemon.Daemon satisfies it.
type Event ¶ added in v0.4.0
type Event struct {
Ts int64 `json:"ts"` // unix milliseconds
Inv string `json:"inv,omitempty"` // invocation id (one per run command)
Project string `json:"project,omitempty"` // repo-relative project path
Target string `json:"target,omitempty"` // target name (with charms, as the CLI spells it)
Kind string `json:"kind"` // one of the journal.Kind* constants
Stream string `json:"stream,omitempty"` // stdout|stderr, for output events
Level string `json:"level,omitempty"` // info|warn|error, for magus events
Status string `json:"status,omitempty"` // pass|fail|cached, for result events
Ref string `json:"ref,omitempty"` // target-output ref, for result events
DurMs int64 `json:"dur_ms,omitempty"` // duration in ms, for result events
Text string `json:"text,omitempty"` // output line or message
// Set only on the started event (Kind==journal.KindStarted): the run's identity.
Command *Command `json:"command,omitempty"`
MagusVersion string `json:"magus_version,omitempty"`
}
Event is one journal entry (output line, magus log line, or a run's result) - the caller-facing projection of journal.Event. See Magus.InvocationEventsByID. Field tags match journal.Event's exactly for JSON wire compat.
type Invocation ¶ added in v0.4.0
type Invocation struct {
ID string `json:"id"`
Command Command `json:"command"`
StartedMs int64 `json:"started_ms"` // unix milliseconds
FinishedMs int64 `json:"finished_ms,omitempty"` // unix milliseconds; 0 while running
Status string `json:"status,omitempty"` // overall outcome (pass|fail), from the finished event
MagusVersion string `json:"magus_version,omitempty"`
}
Invocation is one magus command, launch to exit, read back from the journal - the caller-facing projection of journal.Invocation. See Magus.InvocationByID. Field tags match journal.Invocation's exactly for JSON wire compat.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter is a weighted semaphore that caps concurrent spell executions. Obtain one with NewLimiter and share it across daemon workspaces via WithLimiter.
func NewLimiter ¶
NewLimiter creates a Limiter with capacity n. n ≤ 0 defaults to DefaultConcurrency.
type Magus ¶
type Magus struct {
// contains filtered or unexported fields
}
Magus is the high-level orchestrator. Read paths and the daemon's warm caches (warmGraph, symbolStatus) are safe for concurrent use - that is what backs daemon mode, where one Magus is shared across goroutines; concurrent callers should use types.ContextWithGraphObserver rather than a shared default observer. SetGraphObserver and SetDaemon are NOT concurrency-safe - each mutates shared state with no lock and is meant to be called once, before the workspace is shared (SetGraphObserver mutates the underlying *types.Workspace, which documents itself as safe only for a sole owner). Inspect-constructed workspaces have no cache.
func Open ¶
Open opens a Magus orchestrator rooted at root with cache and telemetry. It evaluates magusfiles first, so project registration and any remote-cache wiring are set up before the cache is built. Use Inspect for read-only callers that need no cache.
Example ¶
ExampleOpen shows the canonical entry point: open a Magus orchestrator rooted at "." and run a target across every project.
m, err := Open(context.Background(), ".")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
targets, err := m.ExpandPath(types.Target{Name: "build"})
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
if err := m.Run(context.Background(), targets); err != nil {
fmt.Fprintln(os.Stderr, err)
}
func (*Magus) Affected ¶
Affected computes projects touched by VCS changes since base.
Files that seeded a project by directory containment while it declares none of them come back on types.AffectedResult.UndeclaredBySeed; reporting them (MGS1028) is the caller's, because this is a library call and its caller owns whatever stream a person is reading. The CLI reports it in cmd/magus/affected.go.
func (*Magus) AffectedFromPaths ¶
func (m *Magus) AffectedFromPaths(ctx context.Context, paths []string) (*types.AffectedResult, error)
AffectedFromPaths computes the affected set from an explicit file list. Undeclared seeding files ride types.AffectedResult.UndeclaredBySeed, the same as Magus.Affected; see it for who reports them.
func (*Magus) Affinity ¶
func (m *Magus) Affinity(ctx context.Context, opts types.InsightOptions) (types.AffinityOutput, error)
Affinity is the temporal-coupling lens: projects that change together, with the pairs that lack any declared dependency between them flagged as hidden affinity.
func (*Magus) BeginInvocation ¶ added in v0.2.0
func (m *Magus) BeginInvocation(ctx context.Context, cmd journal.Command, magusVersion string, extra ...slog.Handler) (context.Context, func(error))
BeginInvocation opens the structured journal for one `magus` command (launch to exit). It mints an invocation id, opens the union event log (<cacheDir>/runs/<inv>.jsonl) behind a capture *slog.Logger, threads that logger + the id onto ctx so every captured event (subprocess output + target results) streams into it, and emits the invocation's opening lifecycle event: a started event carrying the command lineage (subcommand/args/cwd/trigger) and magus version. Folding the identity into the stream this way means both the durable file and any live watcher learn which command produced the run from frame one - there is no separate metadata file. Extra handlers (e.g. a live SSE broadcaster) fan out from the same logger.
The returned cleanup takes the run's error: it emits the closing finished event (overall pass/fail outcome, final timing), then flushes and closes the log. Call it as `defer func() { end(runErr) }()` so the outcome reflects the final result.
It is best-effort: if the log cannot be opened, the id is still stamped on ctx and the lifecycle events still reach any extra handlers, so a run never fails on capture. The command/lineage is what the viewer surfaces; see magus.viewer.v1.Invocation.
func (*Magus) BranchChanges ¶ added in v0.4.0
BranchChanges reports what other remote-tracking branches are changing, so a reader can be told that a file in front of them is also being edited elsewhere.
Empty rather than an error whenever the answer cannot be had - no VCS, a backend without the capability, a repository with no other branches. The three are the same to the reader, and a surface that has nothing to say about competition should say nothing. That is also why a backend lacking BranchChangeReporter must not be reported as "nothing competes": those are different facts, and the caller can only tell them apart by getting nothing at all here.
Read through the optional capability rather than by shelling a git command, for the reason ReviewOrigin reads the remote that way: the backend is asked, never its name.
func (*Magus) CacheDir ¶ added in v0.2.0
CacheDir returns the resolved workspace cache directory - the same location the journal run logs and per-ref output store live under. Callers that persist their own sidecar stores (e.g. the MCP audit log) hang them off this so everything shares one cache root and one retention regime.
func (*Magus) CacheDiskBytes ¶ added in v0.2.0
CacheDiskBytes returns the approximate on-disk size of this workspace's cache in bytes (memoized; cheap to poll). Zero when no cache is attached.
func (*Magus) CacheStats ¶ added in v0.2.0
func (m *Magus) CacheStats() CacheStats
CacheStats returns this workspace's live cache counters (hits/misses/errors) accumulated since the cache was opened. In daemon mode the cache is long-lived, so these grow across adopted runs - the source for the /dashboard cache-activity panel. Zero value when no cache is attached (an Inspect workspace).
func (*Magus) ClassifyFiles ¶ added in v0.4.0
ClassifyFiles classifies workspace-relative paths against every project's declared source and output globs (the same workspace-rooted globs baseStep feeds the cache), plus directory containment for ownership, and reports each matching declaration individually (FileEntry.Claims) with the target that made it. The classification is pure declaration lookup - no target evaluation, no VCS - so it is cheap enough to run over a whole dirty tree; the one filesystem call per path is the Lstat behind FileEntry.Exists, which is what separates a declared-but-absent path from a declared-and-present one. An absolute path is re-rooted onto the workspace; a path that resolves outside it is classified against nothing, because every glob here is rooted at this workspace. ctx bounds the walk so classifying a large path list stays cancellable.
func (*Magus) CleanCache ¶
CleanCache removes all cached build entries for the given projects. Pass no projects to clear the entire cache.
func (*Magus) CleanOutputs ¶
func (m *Magus) CleanOutputs(ctx context.Context, projects []*types.Project, dryRun bool) ([]string, error)
CleanOutputs removes files matched by each project's declared Outputs globs. It returns the list of removed absolute file paths. When dryRun is true, no files are deleted — only the matched paths are collected and returned.
func (*Magus) Close ¶
Close releases workspace resources (VM pools, telemetry); cache and limiter are caller-owned. A provider built by Open is shut down here so its spans/metrics flush rather than being lost on exit. An injected provider (WithProvider) is left running - it is shared across every workspace the daemon holds (and the bridge Magus), so one workspace's eviction must not stop telemetry for the rest; the daemon itself owns and shuts down that provider.
func (*Magus) ComputeTargetKey ¶ added in v0.4.0
func (m *Magus) ComputeTargetKey(ctx context.Context, projectPath, target string, charms []string) (key string, lines []string, err error)
ComputeTargetKey computes target's live cache key and the pre-hash key inputs behind it for the project at projectPath, without executing anything. The step is keyed exactly as a run with these charms would key it - spell claims, tool versions and the env allowlist all included - so the returned key equals the one a real run mints, and PortableRef of it equals the ref that run would print. Only args after `--` are absent (this is not a run, so there are none). It is the live half of the works-on-my-machine diff: `describe target --cache` compares these lines against the set stored behind a ref. Returns types.ErrNoCache on an Inspect workspace.
func (*Magus) ContextWithSecrets ¶ added in v0.4.0
ContextWithSecrets installs this workspace's secret resolver on ctx, so a caller outside the run path can redact against the credentials this workspace has resolved.
It hands out a CONTEXT, not the resolver. The daemon needs redaction on its serving paths - internal/trail writes MCP request and response payloads verbatim, and those are the largest credential-shaped thing magus persists - but nothing outside this package needs to read or mutate the resolver to get it.
The resolver is per workspace Open, so this is only meaningful for a caller already bound to one workspace. A daemon-wide action has no workspace and therefore nothing to redact against, which is the honest answer rather than a gap.
func (*Magus) CurrentRevision ¶ added in v0.4.0
CurrentRevision resolves the workspace's active VCS revision (full hash) and dirty state, collapsing BOTH a resolution error and no VCS into ("", false).
That differs from gateDrift, which treats a vcs.Resolve error as a hard failure, and it is correct here because this is provenance metadata rather than a drift gate: a target with nothing to gate never asked to have its VCS state checked, so a missing revision is "unknown", never a reason to fail the caller.
executeStages resolves it ONCE per invocation and copies it onto every step, as toolVersionsByProject does - probing per target would spawn a VCS subprocess per step. The revision and dirty returns are types.VCSMeta's ID and IsDirty. ("Hash" is git's word alone - hg reports a node, jj a commit id - which is why the field is named ID.)
func (*Magus) Diff ¶ added in v0.4.0
Diff annotates a changed-path set with what the workspace already knows about each file: whether it is generated, which project owns it, how widely its changed symbols are referenced, and what coverage was observed on it.
It is a JOIN, not a computation. Every input already exists - ClassifyFiles reads the same declared globs `magus describe file` reads, and impact.Compute/Enrich are what `magus affected --impact` prints. Assembling them here rather than in the console keeps one definition of review order (types.Diff.SortForReading), so a Buzz advisor writing a pull-request comment ranks files the same way the console scrolls them.
EVERY overlay is best-effort and degrades to a Note rather than an error. A workspace with no symbol index still gets roles and ownership, which is most of the value; failing the whole review because coverage was never run would make the useful part unreachable. A reader must be able to tell "nothing depends on this" from "nothing was measured", which is what Notes is for.
func (*Magus) DiffTUIEnabled ¶ added in v0.4.0
DiffTUIEnabled reports whether `magus diff` may open its viewer, per workspace config.
One question rather than an exported Config accessor: the caller needs this answer, not the whole configuration, and a broad getter is how a command ends up branching on settings that were never meant to reach it.
func (*Magus) EvaluateProjects ¶ added in v0.4.0
EvaluateProjects returns the fully-evaluated project inventory. ctx bounds the walk so a large workspace's introspection stays cancellable.
func (*Magus) EvaluateTarget ¶ added in v0.4.0
func (m *Magus) EvaluateTarget(ctx context.Context, t types.Target) ([]types.EvaluatedTarget, error)
EvaluateTarget returns the fully-evaluated dispatch plan for t. Like every other Inspector method, a cancelled ctx is reported as an error rather than truncating the plan silently: a partial dispatch plan is exactly the misleading result describeCancelled exists to prevent.
func (*Magus) ExpandAffected ¶
func (m *Magus) ExpandAffected(ctx context.Context, target string, baseRef string) (targets []types.Target, source string, fellBack bool, err error)
ExpandAffected resolves targets for VCS-affected projects; falls back to all projects on VCS failure. fellBack is true precisely when the VCS couldn't compute a definitive set and every project was selected as a safety net — a typed signal callers can act on (e.g. annotate the plan) rather than parsing the free-text source string, which on the fallback path carries the underlying error message.
Example ¶
ExampleMagus_ExpandAffected shows how to compute the VCS-diff affected project set, with automatic fallback to all projects when the VCS command is unavailable (shallow clone, missing binary, etc.).
m, err := Open(context.Background(), ".")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
targets, source, _, err := m.ExpandAffected(context.Background(), "test", "")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
fmt.Printf("[%s]\n", source)
for _, t := range targets {
fmt.Println(" ", t.Path)
}
func (*Magus) ExpandCwd ¶
ExpandCwd resolves t for the project containing cwd; found=false when cwd is not inside any project.
func (*Magus) ExpandPath ¶
ExpandPath resolves the target pattern to concrete per-project targets; empty or "/" fans out to all.
func (*Magus) ExportCache ¶
ExportCache writes the entire cache to w as a gzip-compressed tar archive. Returns types.ErrNoCache on Inspect workspaces.
func (*Magus) FileAt ¶ added in v0.4.0
FileAt returns a repo-relative path's content at a revision.
A path absent at that revision is an error and not empty content, which is RevisionFileReader's own contract: the two are indistinguishable to a caller, and only one of them means the file was empty. Callers digesting for a receipt must treat the error as "nothing to attest to" rather than hashing "".
func (*Magus) FindOutputProducer ¶ added in v0.4.0
FindOutputProducer returns the project whose target REGENERATES absPath, or nil when no project declares the path as an output. absPath must be absolute.
The producer is not always the project the file sits in. For an output a project declares for itself the two coincide, but for one another project writes into its tree (InboundOutputs) only the WRITER can rebuild it - the owner has no target that produces those bytes. The merge driver is the consumer that makes this distinction load-bearing: handed the owner, it would run a target that touches nothing, then copy the unregenerated file over the conflict and report a clean merge.
func (*Magus) GetArtifact ¶ added in v0.4.0
GetArtifact writes a cached version to dst, cloning from the store when the filesystem supports reflink.
func (*Magus) HeldLocks ¶ added in v0.4.0
func (m *Magus) HeldLocks() []types.StatusLock
HeldLocks reports every per-project workspace lock currently held under cacheDir, read from the owner sidecars.
Reported as state, not as a fault: a held lock is what a normal mutating run looks like, but one held by a process nobody remembers starting is invisible while every other run waits. Naming the holder makes that a fact instead of a hang.
Best-effort throughout - an unreadable sidecar is skipped rather than failing the caller. A sidecar can outlive its flock if a holder was killed between unlocking and cleanup, so treat an entry as a strong hint, never proof.
func (*Magus) Hotspots ¶
func (m *Magus) Hotspots(ctx context.Context, opts types.InsightOptions) (types.HotspotOutput, error)
Hotspots is the churn Ă— complexity lens. The project view is the dependency graph heat-colored by churn (with authors, recency, blast radius, and CI duration on each node); --files ranks individual files by edit frequency weighted by complexity.
func (*Magus) IdentifyRef ¶ added in v0.4.0
IdentifyRef inverts a ref back to the workspace target(s) that could have minted it. A ref cannot be decoded - it is a truncated hash, not an encoding - so identification works by PREDICTION instead: key every candidate target exactly as a run would (via ComputeTargetKey) and compare its PortableRef against ref. This is the whole point of the method: it exists for the moment someone pastes a ref from a teammate's terminal or a CI log and asks "what is this", with no other metadata to go on.
Each target is tried under two charm sets - the workspace's configured default charms and the empty set, deduped - because CI runs `--no-default-charms` and CI is the peer whose refs most often get pasted into a local terminal: a ref minted by the bare CI variant must still resolve even though this workspace's local runs always carry the configured defaults. The defaults are read from m.cfg.DefaultCharms rather than taken as a parameter, exactly as ListCharms reads them (see its doc comment): a caller that forgets to pass defaults must not silently degrade to a bare-charm-only sweep.
ref may be a full portable ref or a unique prefix of one, mirroring the resolver in internal/cache/output.go: matches are ref-as-prefix-of-full-ref, not equality, so a shortened ref still finds its target. A ref that is not shaped like a ref, or that matches nothing, yields a nil slice and no error - "nothing matched" is a finding here, not a failure. A single target that fails to key (an unresolved project, a malformed step) is skipped rather than aborting the sweep, since this runs on a best-effort error path. The one exception is types.ErrNoCache, checked up front - mirroring computeTargetKey's own first line - rather than left to surface from deep in the sweep: a cache-free (Inspect) workspace can mint no keys at all, so the whole method is meaningless without a cache, and there is no point walking every project and probing every spell's tool version first only to discover that.
Both nil-slice cases - ref not shaped like a ref, and a well-formed ref matching nothing - render identically to a caller, which would be misleading for a garbage string. That is deliberate here rather than a gap: cmd/magus/query.go's queryCmd and internal/handler/mcp's outputTool.Invoke both reject a non-ref-shaped ref with cache.LooksLikeRef up front, before either reaches a code path that calls IdentifyRef, so every real caller already knows ref is ref-shaped by the time the nil slice would need distinguishing.
Matches are sorted by project, then target, then charms, so repeated calls and rendered output are stable.
func (*Magus) ImportCache ¶
ImportCache extracts a gzip-compressed tar archive produced by Magus.ExportCache. Returns types.ErrNoCache on Inspect workspaces.
func (*Magus) InvocationByID ¶ added in v0.2.0
func (m *Magus) InvocationByID(inv string) (Invocation, error)
InvocationByID resolves an invocation id (OutputDescriptor.Inv) to its run header - the command lineage (subcommand/args/trigger), timing, and outcome - read from the union run log. It is the lineage source for `magus query output <ref> --meta` and the viewer. Returns fs.ErrNotExist when the run log has aged out.
func (*Magus) InvocationEventsByID ¶ added in v0.4.0
func (m *Magus) InvocationEventsByID(inv string) (Invocation, []Event, error)
InvocationEventsByID resolves an invocation id to its run header AND the events behind it. Magus.InvocationByID answers "what was this run"; this answers "what happened during it", which is what an audit of a run's credential reads needs. Returns fs.ErrNotExist when the run log has aged out.
func (*Magus) KnowledgeGraph ¶ added in v0.2.0
KnowledgeGraph returns the workspace knowledge graph. In the daemon, once WatchKnowledgeGraph is running, this answers from a warm in-memory graph without re-parsing magusfiles; otherwise (and on refresh) it rebuilds cache-first. It is always fresh: the warm graph is served only while a watcher can invalidate it.
func (*Magus) KnowledgeGraphHealthy ¶ added in v0.2.0
KnowledgeGraphHealthy reports the daemon's warm-knowledge-graph watcher state, for the /readyz readiness surface's "knowledge_graph" component. It goes through warmKnowledgeGraph (the same lazily-created holder KnowledgeGraph reads), so calling it before WatchKnowledgeGraph has ever run reports watching=false rather than panicking on a nil holder, and calling it after does not create a second holder (sync.Once).
func (*Magus) KnowledgeGraphWithSymbols ¶ added in v0.2.0
KnowledgeGraphWithSymbols returns a graph that INCLUDES the lazily-loaded @symbols shards, for a symbol-seeded MCP query (magus_query on symbols, magus_refs). It builds cache-first into a FRESH graph - not the shared warm graph - and merges symbols into it, so the warm graph the other MCP tools answer from is never polluted with a workspace's (potentially huge) symbol set.
func (*Magus) KnowledgeGraphWithSymbolsForRef ¶ added in v0.2.0
func (m *Magus) KnowledgeGraphWithSymbolsForRef(ctx context.Context, ref string) (*knowledge.Graph, error)
KnowledgeGraphWithSymbolsForRef is KnowledgeGraphWithSymbols for magus_refs: it merges only the symbol shards that mention ref (targeted reverse lookup) when ref is an exact symbol ID, or all of them for a fuzzy name. Also fresh-not-warm, so the shared warm graph stays symbol-free.
func (*Magus) LastRecordedRun ¶ added in v0.4.0
func (m *Magus) LastRecordedRun(projectPath, target string) (cache.RecordedRun, error)
LastRecordedRun returns the most recent cache entry recorded for target in projectPath together with the key inputs behind it - the peer `describe target --cache` compares a live key against to explain why a run here would MISS. Wraps fs.ErrNotExist when nothing is recorded for that target; types.ErrNoCache on an Inspect workspace.
func (*Magus) ListArtifacts ¶ added in v0.4.0
func (m *Magus) ListArtifacts(ctx context.Context, projectPath, wsPath string) ([]cache.ArtifactVersion, error)
ListArtifacts returns every cached version of the workspace-relative wsPath, newest first, with identical consecutive content collapsed.
Returns types.ErrNoCache on an Inspect workspace: "no versions" and "no store to look in" are different answers.
func (*Magus) ListCharms ¶ added in v0.4.0
ListCharms builds the inverse charm index: every charm name a target declares, plus the reserved built-ins and the workspace's default_charms, and for each the project/target/spell declarations that give it a patch. The transpose of EvaluateTarget.
It reads m.cfg directly rather than taking a defaults parameter because a caller reaching this through the Inspector interface has no other way to see the workspace's config, and passing nil made every charm report Default: false over MCP.
ctx bounds the walk: this is the most expensive Inspector method (ExplainCommand per charm, per target, per spell, across every project).
func (*Magus) ListProjects ¶ added in v0.4.0
ListProjects returns the project inventory of the workspace.
func (*Magus) ListTargets ¶ added in v0.4.0
ListTargets enumerates targets known in the workspace. ctx bounds each of its three walks so a large workspace's introspection stays cancellable.
func (*Magus) LogBase ¶ added in v0.4.0
LogBase emits the affected-set base header through the cache logger. No-op on Inspect workspaces.
func (*Magus) LogCache ¶ added in v0.4.0
LogCache emits the cache-tier header through the cache logger. No-op on Inspect workspaces, which have no cache to describe.
func (*Magus) LogCharms ¶ added in v0.2.0
LogCharms emits the active-charm header through the cache logger. No-op on Inspect workspaces.
func (*Magus) LogScope ¶
LogScope emits a scope header through the cache logger. No-op on Inspect workspaces.
func (*Magus) MetricsCollector ¶ added in v0.2.0
func (m *Magus) MetricsCollector() (*MetricsCollector, bool)
MetricsCollector returns a narrow accessor over this workspace's in-process metrics ManualReader for the daemon's derived-dashboard aggregation, or (nil, false) when metrics collection was not enabled at Open (the CLI default). Unlike Magus.MetricsSnapshot (OTLP bytes for external export), this reads raw metricdata - histogram buckets and counters - with no exporter hop and without exposing the generated dashboard proto here.
func (*Magus) MetricsSnapshot ¶ added in v0.2.0
MetricsSnapshot returns this workspace's current metrics as standard OTLP protobuf (an ExportMetricsServiceRequest), or (nil, nil) when metrics collection was not enabled at Open (the CLI default). A workspace opened with WithMetricsCollection can export this to any OTLP-compatible collector. Reuses magus's existing OTel instruments; no bespoke metrics contract. Its only caller today is the test suite.
func (*Magus) OutputAttempts ¶ added in v0.4.0
func (m *Magus) OutputAttempts(ref string) ([]OutputDescriptor, error)
OutputAttempts lists every stored execution of the step ref names, newest first - the keep-last-K history behind one portable ref, for `magus query output <ref> --attempts`. Like OutputByRef it reads the store straight off the resolved cache dir, so Inspect workspaces work too. Returns fs.ErrNotExist when no ref matches, or *cache.AmbiguousRefError when a prefix matches several.
func (*Magus) OutputByRef ¶ added in v0.2.0
func (m *Magus) OutputByRef(ref string) ([]byte, OutputDescriptor, error)
OutputByRef resolves a target-output reference id (or a unique prefix, git-style) to its reconstructed raw text and metadata. It reads the output store directly from the resolved cache dir, so it works on Inspect workspaces too (no live cache needed) - the retrieval path for `magus query output <ref>` (print). Returns fs.ErrNotExist when no ref matches, or *cache.AmbiguousRefError when a prefix matches several.
func (*Magus) OutputByRefRemote ¶ added in v0.4.0
func (m *Magus) OutputByRefRemote(ctx context.Context, ref string) ([]byte, OutputDescriptor, error)
OutputByRefRemote resolves a ref to its captured bytes and descriptor, falling back to the remote published-output namespace when the ref is unknown locally - so an inspect line pasted from CI or a teammate resolves even on a machine that never ran the target. Requires a live cache (the remote backend and trust set live there); on an Inspect workspace it degrades to the local-only path.
func (*Magus) OutputDescriptorByRef ¶ added in v0.4.0
func (m *Magus) OutputDescriptorByRef(ref string) (OutputDescriptor, error)
OutputDescriptorByRef resolves a ref to just its stored descriptor, without reading the output blob. The metadata views (`query output <ref> --meta`, `describe target --cache --against <ref>`) want the identity, not the bytes, and a captured log can be large.
func (*Magus) OutputKeyInputs ¶ added in v0.4.0
OutputKeyInputs returns the pre-hash key inputs stored behind ref - the deterministic label:value lines hashStep consumed to mint the step's cache key, secret-redacted at write. They are the explanation surface for `magus query output <ref> --meta` (component-class digests) and `describe target --cache --against <ref>` (the exact disagreeing line). Returns fs.ErrNotExist when the ref resolves but the run predates key-input persistence.
func (*Magus) Ownership ¶
func (m *Magus) Ownership(ctx context.Context, opts types.InsightOptions) (types.OwnershipOutput, error)
Ownership is the knowledge-risk lens: author concentration, bus factor, and abandonment (projects gone quiet in the recent half of the window).
func (*Magus) Plan ¶
Plan computes a provider-neutral CI shard plan for the affected project set using target as the CI target (typically "ci"). Adaptive sharding is applied when runtime history is available at the resolved HistoryPath.
func (*Magus) ProjectTargets ¶ added in v0.4.0
ProjectTargets names the targets one project declares, in the order Magus.TargetGraph reports them. Empty for a project this workspace does not know.
It is a projection of that graph rather than a second source: the graph is already the answer to "what does this project declare", and a membership test computed any other way would be a second definition free to drift from the one MAGUS.md and `magus ls targets` are generated from.
It exists as its own method because it is the ALLOWLIST a run triggered from outside a terminal is checked against, and that check has two call sites - the console's run route and the daemon's job dispatch. The dispatch admits only argvs the jobs registry recognises, deliberately, "so the fire-and-forget job RPC can never be used to run an arbitrary command"; a console button able to name any command would hand a browser-reachable surface exactly that. Both sites asking THIS is what keeps the capability strictly smaller than a terminal's `magus run`.
func (*Magus) PruneCache ¶
func (m *Magus) PruneCache(ctx context.Context, cutoff time.Time, dryRun bool) (removed int, freed int64, err error)
PruneCache removes entries older than cutoff and GC-collects orphaned blobs.
func (*Magus) PruneRemoteCache ¶
func (m *Magus) PruneRemoteCache(ctx context.Context, olderThan time.Duration, keepLast int, dryRun bool) error
PruneRemoteCache evicts entries from the configured remote cache backend per a retention policy (age and/or newest-N). Errors when no remote backend is wired, the backend can't prune, or it's inactive here. Scalar args keep this public facade free of the internal cache.RetentionPolicy type.
func (*Magus) PublishOutput ¶ added in v0.4.0
PublishOutput uploads the run behind ref to the configured remote cache as a signed OUTPUT BUNDLE, and returns the ref a teammate can then resolve. A passing run's output already travels with its cache artifact; this is what makes a FAILING run - never cached, never pushed - shareable, and it is always an explicit act because captured output can contain anything the target printed. The bundle carries no manifest and no blobs, so it can never be replayed as a cache hit. Requires a remote backend and a signing key; types.ErrNoCache on an Inspect workspace.
func (*Magus) RangeDiff ¶ added in v0.4.0
RangeDiff returns the unified diff of what head added since it diverged from base: the COMMITTED half of review, which is a colleague's branch or your own agent's finished work.
The counterpart to WorkingDiff, and separate from it on purpose. A range names two revisions and the working tree names none, so folding them into one signature would make the common case carry arguments it never uses - the reason WorkingDiff's doc gives for not answering both.
A gap is REFUSED rather than answered empty, which is the opposite of BranchChanges. There, silence and "nothing competes" are both true-ish and the caller can tell them apart by getting nothing at all. Here an empty string reads as "this branch changed nothing", and reporting a colleague's work as untouched is the one wrong answer this surface must never give.
func (*Magus) RefMatchCommand ¶ added in v0.4.0
RefMatchCommand renders a types.RefMatch (as returned by IdentifyRef) as the "magus run" invocation that would key it: the target name (with a :charm1,charm2 suffix when the match required explicit charms), the project (omitted for the workspace root "."), and --no-default-charms when the match required the bare CI variant while m.cfg.DefaultCharms is non-empty, since the workspace's configured defaults would otherwise apply and mint a different key.
It is a method on *Magus, not a free function, so it reads m.cfg.DefaultCharms itself rather than taking it as a parameter a caller could pass stale or out of sync with the *Magus that produced the match in the first place.
Shared by cmd/magus/query.go's ref-lookup suggestion and internal/handler/mcp's magus_output not-found fallback, so the CLI and the MCP surface render the exact same reproduce command instead of two copies that can drift. It renders the "magus run" prefix via hint.Run so the command path itself stays single-sourced with every other canonical command reference.
func (*Magus) ReindexSymbols ¶ added in v0.2.0
ReindexSymbols runs the scip op for every symbol-capable project, refreshing each project's cached SCIP index. A project whose indexer is missing or fails is reported with an actionable install hint but does not stop the rest. It returns how many projects were reindexed and the joined errors. This is the manual counterpart to the daemon's background auto-indexer, invoked by `magus graph build`.
func (*Magus) ResolveProjects ¶
ResolveProjects resolves targets to project records; unmatched targets are silently dropped.
func (*Magus) ResolveTargetOutputs ¶ added in v0.4.0
func (m *Magus) ResolveTargetOutputs(ctx context.Context, projects []*types.Project, target string) ([]TargetArtifact, error)
ResolveTargetOutputs expands the output globs target declares for each project into the files that exist on disk right now.
It reads buildStep, not the project-wide union, so the answer is scoped to the ONE target asked about - the same fold the cache keys and snapshots, so what this reports and what the cache replays cannot disagree.
This is the question an agent otherwise has to guess at: a build says it passed, and where the artifact landed is left to be inferred from the target's name.
func (*Magus) ReviewOrigin ¶ added in v0.4.0
func (m *Magus) ReviewOrigin(ctx context.Context) types.ReviewOrigin
ReviewOrigin reports the branch this tree is on and the remote it would be pushed to, for a caller asking a provider which review is open.
Never an error. A workspace with no VCS, a backend that cannot name a remote, a detached HEAD: all of them yield an empty field, and every one is an ordinary state of a tree rather than a failure. The caller's next question - "is a review open?" - has the same answer for all of them, so making this fail would only move a branch nobody needs up a layer.
The remote is read through the optional RemoteReporter capability rather than by shelling a git command, so it works on every backend that implements one and degrades to empty on the ones that do not.
func (*Magus) RevisionCheckpoint ¶ added in v0.4.0
RevisionCheckpoint resolves a revision expression to the checkpoint that names it.
The point is Revision: a movable name resolves to the full id it currently points at, so a caller recording what it read records something that still means the same thing after somebody pushes to that branch. Dirty and PatchDigest stay zero, because a committed revision is not a working tree and reporting it as clean-or-dirty would be answering a question nobody asked.
func (*Magus) Run ¶
Run executes targets against their projects. Independent pairs run concurrently up to the limiter budget. "ci" is an ordinary magusfile target (compose its pipeline with magus.needs); magus no longer hardcodes a CI chain.
func (*Magus) RunAffected ¶
RunAffected computes the VCS-diff target set and runs target on it.
func (*Magus) RunCI ¶
RunCI runs the ci target(s) with write mode forced off. "ci" is an ordinary magusfile-defined target; magus keeps it only as the affected-set anchor, not a hardcoded preflight...test chain. The magusfile composes the pipeline order via magus.needs.
func (*Magus) SecretProvider ¶ added in v0.4.0
SecretProvider returns the NAME of the secret-provider spell this workspace's magusfile selected, or "" when none is declared and the built-in environment provider applies.
The name only. There is deliberately no accessor for the references a workspace can reach, let alone their values: a standing inventory of what a build can fetch is a map of what to go after, and magus does not store secrets in the first place - it reads them through a provider. Which provider is loaded is configuration a reader should be able to see; what it can reach is not magus's to publish.
func (*Magus) ServeDaemon ¶ added in v0.2.0
ServeDaemon runs the injected daemon, blocking until ctx is cancelled or the server fails. It errors if no daemon was installed via SetDaemon.
func (*Magus) SetDaemon ¶ added in v0.2.0
SetDaemon installs the daemon that ServeDaemon delegates to. Called once, in daemon mode; other command paths leave it nil so no server is ever constructed.
func (*Magus) SetGraphObserver ¶
SetGraphObserver installs an observer on the workspace; pass nil to clear.
func (*Magus) Stream ¶
func (m *Magus) Stream(ctx context.Context, r io.Reader, target string, errFn func(error), opts ...StreamOption) error
Stream reads file-path batches from r and runs target on the affected projects. Builds run synchronously; batches arriving during a build are merged and run after. StreamAllSentinel triggers a full-workspace build. Per-batch errors go to errFn.
func (*Magus) SymbolGaps ¶ added in v0.4.0
SymbolGaps reports the projects whose declared symbol index this workspace could not read, and whether the probe ran at all. Method form of the package-level SymbolGaps, for callers that already hold a Magus (the MCP handlers).
func (*Magus) SymbolIndexStatus ¶ added in v0.2.0
func (m *Magus) SymbolIndexStatus(ctx context.Context) []types.SymbolIndexStatus
SymbolIndexStatus reports, for each symbol-capable project, whether its cached SCIP index reflects current sources: fresh, out-of-date, or not-indexed. In the daemon it answers from a watcher-invalidated memo (a status push does not re-stat source trees); elsewhere it recomputes each call. Powers `magus status` and the dashboard.
func (*Magus) SymbolOccurrences ¶ added in v0.4.0
SymbolOccurrences returns every verified source range where the symbol keyed by key appears. Method form of the package-level SymbolOccurrences, for callers that already hold a Magus - the pairing SymbolGaps keeps, since the two answers are read together.
func (*Magus) TailLog ¶
TailLog returns the log-file path of the most recent cache entry for projectPath, optionally restricted to target. Wraps fs.ErrNotExist when not found; types.ErrNoCache on Inspect.
func (*Magus) TargetGraph ¶ added in v0.4.0
TargetGraph returns the target dependency graph of each project, read statically from the magusfile source (describe.Extract) - deterministic and side-effect free, so introspection never runs a target body. Buzz magusfiles are supported; a project on any other engine yields an engine-tagged entry with no nodes until that extractor lands. ctx bounds the walk so a large workspace's introspection stays cancellable.
func (*Magus) Telemetry ¶ added in v0.2.0
func (m *Magus) Telemetry() observability.Provider
Telemetry returns this workspace's observability provider (nil on an Inspect workspace, which builds no cache and no provider). When several Magus instances were opened with a shared provider via WithProvider this returns that same instance, so metrics recorded through one are visible through another's Magus.MetricsCollector.
func (*Magus) Trend ¶
func (m *Magus) Trend(ctx context.Context, opts types.InsightOptions) (types.TrendOutput, error)
Trend is// Trend is the rising/cooling lens: each project's churn in the recent vs earlier half of the window.
func (*Magus) Unreferenced ¶ added in v0.4.0
Unreferenced is the knowledge-graph lens: code symbols this workspace defines that nothing in it names. Like Volatility it takes no window - it reads the graph, not a commit scan - so it is workspace-wide.
The result carries a coverage verdict alongside the list, and that pairing is the whole design. A project whose symbol index was never built contributes no symbols, so its unreferenced code would render as a clean report; without the verdict, the lens would be most reassuring exactly where it knows least.
func (*Magus) VCSOptions ¶
func (m *Magus) VCSOptions() types.VCSOptions
func (*Magus) Volatility ¶ added in v0.2.0
Volatility is the run-outcome lens: each (project, target) pair's recent pass/fail record scored by its Wilson lower bound, flagged volatile at or above the configured threshold. Unlike the git-history lenses it reads the shared runtime-history file (config.HistoryPath), not a commit scan - so it is workspace-wide and takes no InsightOptions window.
func (*Magus) WatchKnowledgeGraph ¶ added in v0.2.0
WatchKnowledgeGraph starts a file watcher that keeps the warm knowledge graph fresh, so daemon MCP calls answer from memory. It returns a stop function; the long-lived daemon calls it once at startup. A one-shot CLI never calls it and pays the cache-first rebuild per command (equally fresh, just not warm).
func (*Magus) WatchSymbolIndexing ¶ added in v0.2.0
WatchSymbolIndexing starts the daemon's background symbol auto-indexer: a file watcher that re-runs each symbol-capable project's scip op when its sources change, throttled and idle-gated (see symbolIndexer). It returns a stop function; the long-lived daemon calls it once at startup, alongside WatchKnowledgeGraph. A no-op (never an error) when disabled by config or when no project is symbol-capable, so nothing is spun up need- lessly. A one-shot CLI never calls it and so never auto-indexes.
func (*Magus) WorkingDiff ¶ added in v0.4.0
WorkingDiff returns the working tree's uncommitted changes as the backend's own unified diff, scoped to paths when non-empty and repository-wide otherwise. Empty when the tree is clean.
It is the SELF-REVIEW half of the review surface: what you are about to commit, before any provider is involved. The committed-range half (base..head, a pull request) is a different question and deliberately not folded in here - a range diff has to name two revisions, and answering both through one signature would make the common case carry arguments it never uses.
Every backend already implements DirtyDiff, so this is VCS-agnostic without a per-backend branch. The bytes are NOT identical across backends and are not meant to be: git, hg, and jj each emit their native diff header, and a wrapper that reconciled them would be lying about what ran. A reader parses the unified body, which they do share.
A workspace with no VCS is not an error - it is a clean tree with nothing to review - so an unresolvable backend yields "" rather than failing the caller.
func (*Magus) Workspace ¶ added in v0.4.0
func (m *Magus) Workspace(ctx context.Context, cfg types.WorkspaceConfig) (types.WorkspaceEntry, error)
Workspace returns the single-entry view of m's workspace. A *Magus is always exactly one workspace; the CLI's `describe workspaces` merges these across the daemon's declared roots when daemon.workspaces is set.
type MetricsCollector ¶ added in v0.4.0
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector wraps otlp.Collector for the SDK boundary: the same one in-process metricdata read, exposed without naming an internal/ type.
func (*MetricsCollector) Collect ¶ added in v0.4.0
func (c *MetricsCollector) Collect(ctx context.Context) (metricdata.ResourceMetrics, error)
Collect gathers the current metricdata from the underlying reader. See otlp.Collector.Collect.
type Option ¶
Option configures Open or Inspect.
func WithConfigFile ¶
WithConfigFile causes the constructor to load magus.yaml from path instead of <root>/magus.yaml.
func WithLimiter ¶
WithLimiter injects a pre-built Limiter (e.g. shared across daemon workspaces). When omitted, Open constructs a private limiter from magus.yaml/Concurrency.
func WithLoadedConfig ¶
WithLoadedConfig injects an already-parsed configuration, bypassing the default magus.yaml discovery. Env-var and flag overrides should be applied before calling this.
func WithMetricsCollection ¶ added in v0.2.0
func WithMetricsCollection() Option
WithMetricsCollection builds an always-on in-process metrics collector for this workspace (OTel instruments record even with telemetry export off), so the daemon can derive the /dashboard's metrics via Magus.MetricsCollector. The CLI leaves it off.
func WithProvider ¶ added in v0.2.0
func WithProvider(p observability.Provider) Option
WithProvider injects an already-constructed observability provider so several Magus instances (a daemon's bridge Magus plus each per-workspace registry Magus) share ONE set of OTel instruments and one metrics collector. The provider is owned by the daemon process, not any single workspace, so workspace eviction never discards accumulated metrics. It supersedes WithMetricsCollection: Open adopts the injected provider instead of constructing its own.
Keeps the shorter public name even though the internal option it wraps was renamed to WithTelemetryProvider (disambiguating it from WithoutWorkspaceProviders and internal/workspace's workspace-provider family): cmd/magus/mcp.go also calls this exported symbol, so renaming it here is a separate, wider change than this package's own internal cleanup.
func WithVersion ¶ added in v0.4.0
WithVersion supplies the running build's version so Open and Inspect can check it against the workspace's magus.yaml required_version floor (MGS1021). cmd/magus passes its linker-stamped version; a library caller that omits it gets no floor check, since a caller with no version has no version to be too old.
func WithWorkspaceRegistry ¶
func WithWorkspaceRegistry(reg *WorkspaceRegistry) Option
WithWorkspaceRegistry injects a pre-built WorkspaceRegistry, replacing the default one.
func WithoutWorkspaceProviders ¶ added in v0.4.0
func WithoutWorkspaceProviders() Option
WithoutWorkspaceProviders opens the workspace without running its wired workspace providers (magus\workspace.provider), leaving only the magusfile-declared projects. For a caller inspecting a tree that is not a working checkout - an exported revision has no installed toolchain for a provider to shell out to. Unrelated to WithProvider, which injects an observability provider.
type OutputDescriptor ¶ added in v0.4.0
type OutputDescriptor struct {
Ref string `json:"ref"`
Project string `json:"project"`
Target string `json:"target,omitempty"`
Inv string `json:"inv,omitempty"` // invocation id of the run that produced this output
Failed bool `json:"failed"`
ErrMsg string `json:"error,omitempty"` // failure message; empty on success
TimestampMs int64 `json:"timestamp_ms"` // unix milliseconds, matching DurationMs' unit
DurationMs int64 `json:"duration_ms"`
Key string `json:"key,omitempty"` // full cache key hash (64 hex)
KeyVersion int `json:"key_version,omitempty"` // hashStep KeyVersion that produced Key
Attempt string `json:"attempt,omitempty"` // execution-unique id; the file stem
MagusVersion string `json:"magus_version,omitempty"`
Revision string `json:"revision,omitempty"` // full VCS revision hash inputs were read at; "" when unknown
Dirty bool `json:"dirty,omitempty"` // working tree had uncommitted changes at capture time
Spell string `json:"spell,omitempty"` // spell::op filter that selected the definition
ExtraArgs []string `json:"extra_args,omitempty"` // trailing args forwarded after --
VCSName string `json:"vcs,omitempty"` // provider Revision came from: git, hg, sl, jj
Platform string `json:"platform,omitempty"` // GOOS/GOARCH the run executed on
}
OutputDescriptor is a stored target execution's identity and outcome - the caller-facing projection of cache.OutputDescriptor, the metadata behind a target-output ref. Field tags match cache.OutputDescriptor's exactly, so embedding this in a CLI JSON record (`magus query output <ref> -o json`) reproduces the same wire shape.
type PlanOptions ¶
type PlanOptions struct {
// MaxShards caps the number of CI shards. -1 = unlimited; 0 uses the
// value from magus.yaml (CI.MaxShards).
MaxShards int
// RunnerPoolBudget limits cross-shard concurrency. 0 = unlimited.
RunnerPoolBudget int
// HistoryPath overrides the configured history_path when non-empty.
HistoryPath string
// BaseRef overrides the VCS base used to compute the affected set.
// It is mutually exclusive with ChangedPaths.
BaseRef string
// ChangedPaths computes the affected set from these repo-relative paths
// instead of a VCS diff. A non-nil empty slice deliberately means no paths.
ChangedPaths []string
}
PlanOptions configures a Magus.Plan call.
type ProjectOption ¶
type ProjectOption = workspace.ProjectOption
ProjectOption mutates a Project at registration time. A non-nil error aborts Open.
func WithDependsOn ¶
func WithDependsOn(paths ...string) ProjectOption
WithDependsOn adds upstream project paths as dependencies (repo-relative or project-relative).
func WithExclusive ¶
func WithExclusive() ProjectOption
WithExclusive marks a project as must-not-run-alongside-peers (also serializes multi-spell fan-out).
func WithOutputs ¶
func WithOutputs(paths ...string) ProjectOption
WithOutputs declares the project-relative file globs this project produces.
func WithSpell ¶
func WithSpell(name string, opts ...BindingOption) ProjectOption
WithSpell registers a built-in spell by name; multiple calls fan out in parallel (sequential with WithExclusive).
func WithTarget ¶
func WithTarget(name string, opts ...TargetOption) ProjectOption
WithTarget attaches a behavioral policy to the named target; multiple calls are merged.
func WithWatchIgnore ¶
func WithWatchIgnore(patterns ...types.IgnorePattern) ProjectOption
WithWatchIgnore appends patterns to the project's watch ignore list; malformed patterns error at Open.
type ReportWriter ¶
type ReportWriter struct {
// contains filtered or unexported fields
}
ReportWriter is an async JSONL event sink for run telemetry. Create one with NewReportWriter, pass it to Run via WithReport, and close it after the run completes.
func NewReportWriter ¶
func NewReportWriter(dst io.Writer, filter []string) (*ReportWriter, error)
NewReportWriter constructs a ReportWriter that writes JSONL events to dst. filter is an optional list of event-type terms; an empty or nil slice disables filtering (all events pass through).
func (*ReportWriter) Close ¶
func (rw *ReportWriter) Close() error
Close flushes and closes the writer. Must be called after the run finishes.
func (*ReportWriter) GraphObserver ¶
func (rw *ReportWriter) GraphObserver() types.Observer
GraphObserver returns an types.Observer that records graph-traversal events to this writer. Pass the result to Magus.SetGraphObserver.
func (*ReportWriter) RecordShardTotal ¶
RecordShardTotal appends a shard-level wall-clock observation (job start → last project end) for adaptive CI forecast. Call after the run completes when running in a CI matrix; shardID and nShards come from --shard / --n-shards.
Written, not yet read: nothing ingests the shard.total JSONL line back into a forecast.History, so it does not (yet) feed the SetupP50Ms/AlphaMs fit described at forecast.DefaultSetupMs.
type RunOption ¶
type RunOption func(*run)
RunOption configures a Magus.Run, Magus.RunCI, or Magus.RunAffected invocation.
func WithBaseRef ¶
WithBaseRef overrides MAGUS_VCS_BASE_REF for RunAffected invocations.
func WithCharms ¶
WithCharms sets execution charms propagated to spells via context.
func WithDryRun ¶
func WithDryRun() RunOption
WithDryRun prints what would run without invoking any handler.
func WithExtraArgs ¶
WithExtraArgs forwards args to spells via project.WithExtraArgs.
func WithNoCache ¶ added in v0.2.0
func WithNoCache() RunOption
WithNoCache forces every selected target to run fresh even on a cache hit. Unlike a skip_cache target policy (which never snapshots), a --no-cache run still refreshes the cache entry on success, so a subsequent ordinary run replays the rebuilt result instead of the stale one.
func WithNoVolatilityRetry ¶ added in v0.2.0
func WithNoVolatilityRetry() RunOption
WithNoVolatilityRetry disables the volatility auto-retry logic.
func WithRace ¶
func WithRace() RunOption
WithRace enables race-condition diagnostics (MGS4001/4002/4004). Diagnostic only.
func WithRaceReplay ¶
func WithRaceReplay() RunOption
WithRaceReplay enables determinism replay (MGS4003). Compose with WithRace for MGS4001/4002/4004.
func WithReport ¶
func WithReport(rw *ReportWriter) RunOption
WithReport attaches rw to receive one JSONL event per executed target. Mutually exclusive with WithReportWriter.
func WithReportWriter ¶
WithReportWriter streams one JSONL event per target to w; the run engine constructs and closes the report.Writer around it.
func WithSpellFilter ¶
WithSpellFilter restricts Run to projects that have the named spell.
type StreamOption ¶
type StreamOption func(*streamOpts)
StreamOption configures a [Stream] invocation.
func WithStreamDryRun ¶
func WithStreamDryRun() StreamOption
WithStreamDryRun prints what would run without invoking handlers.
func WithStreamExtraArgs ¶
func WithStreamExtraArgs(args []string) StreamOption
WithStreamExtraArgs forwards args to spells via project.WithExtraArgs.
func WithStreamNull ¶
func WithStreamNull() StreamOption
WithStreamNull expects NUL-separated paths and double-NUL batch boundaries.
type SymbolOccurrenceRead ¶ added in v0.4.0
type SymbolOccurrenceRead struct {
Files []types.SymbolOccurrenceFile
// Names are the spellings an occurrence may hold; Names[0] is the identifier a rename
// targets. See symbols.ParseOccurrences.
Names []string
Unreadable []types.KnowledgeSymbolGap
}
SymbolOccurrenceRead is what SymbolOccurrences could read: the verified sites, the spellings they were checked against, and every declared index that exists but yielded nothing usable.
Unreadable is the field that keeps the result honest. The occurrence list claims to be complete, so an index magus could not decode has to travel WITH the sites rather than be dropped on the way - a caller folds it into the coverage gaps, which turns the verdict from "searched everywhere" into "unknown, not absent" and names the project to rebuild. The sites that WERE read are still returned: a partial answer plus an accurate account of what is missing beats discarding both.
func SymbolOccurrences ¶ added in v0.4.0
func SymbolOccurrences(ctx context.Context, ws types.Inspector, root string, cfg config.Config, log *slog.Logger, key string) (read SymbolOccurrenceRead, ok bool)
SymbolOccurrences returns every exact source range where the symbol keyed by key appears, with each range verified against the file on disk. It reads the SAME declared indexes the graph is built from, so it can never disagree with `magus refs` about which projects were searched - but it goes back to the index rather than to the graph, because the graph edge stores a MaxRefLines-capped line list with no columns. Those are storage decisions that are right for a shard and unusable for an edit.
key is a symbol node's key (a node ID with the "symbol:" prefix removed). Resolving a user-supplied name to one is the caller's job; the graph already does it for refs.
Inspect-only, like SymbolGaps: it stats and reads index files and source files, and opens nothing. That is what lets a read verb call it.
The returned names are the spellings the ranges may hold, taken from the index itself; names[0] is the identifier a rename targets. An empty set verifies nothing - see symbols.Verify - which is the conservative outcome for an index that names the symbol nowhere.
type TargetArtifact ¶ added in v0.4.0
type TargetArtifact struct {
Path string // workspace-relative
Glob string // the declaration it matched
// ProjectPath is the project whose target DECLARED the glob - not necessarily the
// project the file sits in, since a target may declare an output into another
// project's tree. Recorded here because this is the only place that knows it: a
// consumer re-deriving attribution from Path has to guess, and the guess fails
// outright for a file no project's tree claims.
ProjectPath string
}
TargetArtifact is one file a target actually produced: a declared output glob expanded against the working tree. Glob is carried alongside Path because the declaration is what makes the file a build artifact rather than an incidental file, and a reader chasing an unexpected artifact needs to know which ctx.writesFiles(...) claimed it.
type TargetHandler ¶
TargetHandler runs one target on one resolved project. It is the single executor seam the run pipeline schedules: the same handler serves both a real run and a dry run - types.WithTrace(ctx) switches it, so under a tracing context the effect boundary (proc/run.Exec, fs, net) records each op's intent and skips it instead of executing. One path, two modes: no separate dry-run executor, just a tracing context over this one contract. (The in-browser evaluator in internal/dry is a different thing - it takes raw source, never a resolved *Project, so it sits before this seam and cannot implement it; see that package's doc.)
type TargetOption ¶
type TargetOption = workspace.TargetOption
TargetOption sets a per-target execution-policy field at registration time.
func Drift ¶ added in v0.4.0
func Drift(policy types.DriftPolicy, reason string) TargetOption
Drift sets what happens when this target's declared output moves under a read-only run. The zero policy already gates a target that declares output, so this is for stating that out loud, downgrading to a warning, or switching it off with a reason.
func Exclusive ¶
func Exclusive() TargetOption
Exclusive runs the target alone — no other target runs concurrently while it does.
func IncludeArch ¶ added in v0.4.0
func IncludeArch(v bool) TargetOption
func IncludeOS ¶ added in v0.4.0
func IncludeOS(v bool) TargetOption
IncludeOS and IncludeArch override cache.include.*.enabled for one target, for a target whose artifact varies along one axis but not the other.
func RetryOnVolatile ¶ added in v0.2.0
func RetryOnVolatile(reason string) TargetOption
RetryOnVolatile routes this target through volatility detection, so a failure magus predicts is volatile is rerun once. reason states why this target fails without the code being wrong. The opt-in binds to this target alone.
type WorkspaceRegistry ¶
type WorkspaceRegistry = workspace.WorkspaceRegistry
WorkspaceRegistry holds project-option overrides and target policies for a single Open.
Example (WithSpell) ¶
ExampleWorkspaceRegistry_withSpell shows the recommended way to attach a spell to a project using the string-name API. The registry is passed to Inspect or Open via WithWorkspaceRegistry.
reg := NewWorkspaceRegistry()
reg.RegisterProject(
"api",
WithSpell("go"),
)
// pass reg to Inspect or Open:
// Inspect(ctx, root, WithWorkspaceRegistry(reg))
func NewWorkspaceRegistry ¶
func NewWorkspaceRegistry() *WorkspaceRegistry
NewWorkspaceRegistry returns an empty WorkspaceRegistry.
func WorkspaceRegistryFromContext ¶
func WorkspaceRegistryFromContext(ctx context.Context) *WorkspaceRegistry
WorkspaceRegistryFromContext returns the WorkspaceRegistry from ctx, or nil.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
buzz-playground
command
Command buzz-playground is the browser entry point for the Buzz playground.
|
Command buzz-playground is the browser entry point for the Buzz playground. |
|
langservice-manifest
command
Command langservice-manifest regenerates internal/langservice/manifest_data.go: a build-time snapshot of the magus host module surface (every module, with its fields and methods and rendered Buzz signatures) that the browser playground's completion and hover read.
|
Command langservice-manifest regenerates internal/langservice/manifest_data.go: a build-time snapshot of the magus host module surface (every module, with its fields and methods and rendered Buzz signatures) that the browser playground's completion and hover read. |
|
magus
command
Command magus is the magus CLI: a standalone build orchestrator and content-addressed cache for multi-language monorepos, and an evolution of Mage.
|
Command magus is the magus CLI: a standalone build orchestrator and content-addressed cache for multi-language monorepos, and an evolution of Mage. |
|
magus-configdocs
command
Command magus-configdocs generates the magus.yaml configuration reference from the code-generated schema inventory.
|
Command magus-configdocs generates the magus.yaml configuration reference from the code-generated schema inventory. |
|
magus-docs
command
Command magus-docs generates Markdown documentation for every module registered in the host package.
|
Command magus-docs generates Markdown documentation for every module registered in the host package. |
|
magus-examples
command
Command magus-examples keeps the worked examples in the docs honest: it builds the current magus binary, runs curated retrieval-verb invocations against a small fixture workspace, captures their ACTUAL stdout, and injects each into docs/knowledge.md between HTML markers (<!-- example:<slug> --> ...
|
Command magus-examples keeps the worked examples in the docs honest: it builds the current magus binary, runs curated retrieval-verb invocations against a small fixture workspace, captures their ACTUAL stdout, and injects each into docs/knowledge.md between HTML markers (<!-- example:<slug> --> ... |
|
magus-manpage
command
Command magus-manpage generates magus man pages from the CLI registry.
|
Command magus-manpage generates magus man pages from the CLI registry. |
|
magus-protodocs
command
Command magus-protodocs generates the daemon API reference from the .proto contract, so a third party can build a client without reading the schema out of the repository.
|
Command magus-protodocs generates the daemon API reference from the .proto contract, so a third party can build a client without reading the schema out of the repository. |
|
magus-skilldocs
command
Command magus-skilldocs generates the agent-skill reference: one page per embedded skill showing both curated permutations, plus an index.
|
Command magus-skilldocs generates the agent-skill reference: one page per embedded skill showing both curated permutations, plus an index. |
|
magus-spelldocs
command
Command magus-spelldocs generates Markdown reference documentation for every built-in spell in the internal/spellruntime registry.
|
Command magus-spelldocs generates Markdown reference documentation for every built-in spell in the internal/spellruntime registry. |
|
magus-termcast
command
Command magus-termcast turns a recorded magus session into the animated SVG the README leads with.
|
Command magus-termcast turns a recorded magus session into the animated SVG the README leads with. |
|
magus-termshots
command
Command magus-termshots renders magus's interactive terminal surfaces to SVG for the documentation.
|
Command magus-termshots renders magus's interactive terminal surfaces to SVG for the documentation. |
|
magus-utils
command
Subcommand `moduleset` emits internal/interp/bindings/gen's module registry: the table mapping each host module's bind name to its generated Register trampoline.
|
Subcommand `moduleset` emits internal/interp/bindings/gen's module registry: the table mapping each host module's bind name to its generated Register trampoline. |
|
magus/gen
Code generated by magus-utils config; DO NOT EDIT.
|
Code generated by magus-utils config; DO NOT EDIT. |
|
gen
|
|
|
internal
|
|
|
agent
Package agent owns the two provider-neutral halves of Magus's agent surface: the agent-skill artifact (this file - command packages supply embedded source files, and this package renders, installs and verifies the generated surface without knowing about a particular CLI host), and the guard verdict wire contract (guard.go, which lives here because `package main` cannot be imported, so a parity check outside cmd/magus would otherwise have to restate it).
|
Package agent owns the two provider-neutral halves of Magus's agent surface: the agent-skill artifact (this file - command packages supply embedded source files, and this package renders, installs and verifies the generated surface without knowing about a particular CLI host), and the guard verdict wire contract (guard.go, which lives here because `package main` cannot be imported, so a parity check outside cmd/magus would otherwise have to restate it). |
|
audit
Package audit detects cross-project writes: when a spell's downward walk crosses into a descendant project.
|
Package audit detects cross-project writes: when a spell's downward walk crosses into a descendant project. |
|
auth
Package auth manages the shared-secret bearer token that guards the magus MCP HTTP endpoint and provides the HTTP middleware that enforces it.
|
Package auth manages the shared-secret bearer token that guards the magus MCP HTTP endpoint and provides the HTTP middleware that enforces it. |
|
cache
Package cache implements magus's content-addressed build cache.
|
Package cache implements magus's content-addressed build cache. |
|
cache/reflink
Package reflink copies regular files using the most efficient mechanism the host platform and filesystem provide, transparently falling back to a plain userspace copy where no acceleration is available.
|
Package reflink copies regular files using the most efficient mechanism the host platform and filesystem provide, transparently falling back to a plain userspace copy where no acceleration is available. |
|
changeset
Package changeset holds a change under review: the patch parsed into files, hunks and rows, and the shared session every surface reads while somebody works through it.
|
Package changeset holds a change under review: the patch parsed into files, hunks and rows, and the shared session every surface reads while somebody works through it. |
|
ci
Package ci computes provider-agnostic fan-out plans for CI systems from a magus workspace.
|
Package ci computes provider-agnostic fan-out plans for CI systems from a magus workspace. |
|
ci/annotate
Package annotate emits CI job-log structure: the fold markers and the warning/error notices a CI provider recognizes.
|
Package annotate emits CI job-log structure: the fold markers and the warning/error notices a CI provider recognizes. |
|
ci/forecast
Package forecast picks an adaptive CI shard count using a USL model (N* = sqrt(W/α)) and packs projects via LPT bin-packing.
|
Package forecast picks an adaptive CI shard count using a USL model (N* = sqrt(W/α)) and packs projects via LPT bin-packing. |
|
ci/volatility
Package volatility provides Wilson-score volatility prediction and auto-retry for magus test runs.
|
Package volatility provides Wilson-score volatility prediction and auto-retry for magus test runs. |
|
cli
Package cli is the declarative specification of the magus CLI: every subcommand, its flags, usage, examples and prose, as data.
|
Package cli is the declarative specification of the magus CLI: every subcommand, its flags, usage, examples and prose, as data. |
|
compress
Package compress provides the streaming compression primitives Magus uses for cache artifacts and archives.
|
Package compress provides the streaming compression primitives Magus uses for cache artifacts and archives. |
|
config
Package config holds the magus configuration schema and yaml-based loader.
|
Package config holds the magus configuration schema and yaml-based loader. |
|
config/gen
Code generated by magus-utils config; DO NOT EDIT.
|
Code generated by magus-utils config; DO NOT EDIT. |
|
config/generate
Package generate is the config generator: it reads the magus config struct and renders the flag-binding, schema-field, bind and env artifacts derived from it.
|
Package generate is the config generator: it reads the magus config struct and renders the flag-binding, schema-field, bind and env artifacts derived from it. |
|
daemon
Package daemon assembles the magus daemon HTTP server: it mounts the MCP Streamable-HTTP handler, the k8s health routes, and the browser Graph Explorer console onto one loopback listener, applying the shared bearer and DNS-rebind guards.
|
Package daemon assembles the magus daemon HTTP server: it mounts the MCP Streamable-HTTP handler, the k8s health routes, and the browser Graph Explorer console onto one loopback listener, applying the shared bearer and DNS-rebind guards. |
|
deps
Package deps reads a project's declared third-party dependencies out of its manifest, at the versions that manifest resolves to.
|
Package deps reads a project's declared third-party dependencies out of its manifest, at the versions that manifest resolves to. |
|
describe
Package describe extracts a magusfile's target dependency graph statically, without evaluating any target body.
|
Package describe extracts a magusfile's target dependency graph statically, without evaluating any target body. |
|
docs
Package docs holds the shared rendering helpers the docs generators (cmd/magus-docs, cmd/magus-spelldocs) use to emit the committed Markdown under docs/**.
|
Package docs holds the shared rendering helpers the docs generators (cmd/magus-docs, cmd/magus-spelldocs) use to emit the committed Markdown under docs/**. |
|
doctor
Package doctor validates a magus workspace and reports health checks.
|
Package doctor validates a magus workspace and reports health checks. |
|
dropin
Package dropin reads a configuration directory of one file per entry.
|
Package dropin reads a configuration directory of one file per entry. |
|
dry
Package dry is the in-process, non-executing magus evaluator: it runs Buzz source and magusfiles with every host effect (subprocess, filesystem, network) replaced by an in-memory tracer, then reports the project graph and the dry-run op trace instead of running anything.
|
Package dry is the in-process, non-executing magus evaluator: it runs Buzz source and magusfiles with every host effect (subprocess, filesystem, network) replaced by an in-memory tracer, then reports the project graph and the dry-run op trace instead of running anything. |
|
eventstream
Package eventstream maps magus's internal producers onto the single types.StreamEvent envelope external integrations subscribe to.
|
Package eventstream maps magus's internal producers onto the single types.StreamEvent envelope external integrations subscribe to. |
|
file
Package file provides filesystem primitives used across the magus module.
|
Package file provides filesystem primitives used across the magus module. |
|
file/diff
Package diff provides mtime+size snapshot diffing for attributing concurrent file writes.
|
Package diff provides mtime+size snapshot diffing for attributing concurrent file writes. |
|
file/record
Package record stores a small struct as ONE FILE of name-then-value lines, tab separated:
|
Package record stores a small struct as ONE FILE of name-then-value lines, tab separated: |
|
file/watch
Package watch provides a cross-platform filesystem watcher with recursive directory tracking, debouncing, and ignore filtering.
|
Package watch provides a cross-platform filesystem watcher with recursive directory tracking, debouncing, and ignore filtering. |
|
generate/emit
Package emit writes magus's generated artifacts: the last stage of every generator, after its source of truth has been read and its output rendered.
|
Package emit writes magus's generated artifacts: the last stage of every generator, after its source of truth has been read and its output rendered. |
|
generate/godecl
Package godecl reads declarations out of Go source, for the generators whose source of truth is a Go file.
|
Package godecl reads declarations out of Go source, for the generators whose source of truth is a Go file. |
|
graph/dependency
Package dependency constructs the project dependency DAG, translating path strings to node IDs.
|
Package dependency constructs the project dependency DAG, translating path strings to node IDs. |
|
graph/url
Package url builds daemon-origin Graph Explorer links with a pre-applied query or named view, so a magus CLI command can print a clickable "view this in the Graph Explorer" line as a COMPLEMENTARY aid alongside its normal output.
|
Package url builds daemon-origin Graph Explorer links with a pre-applied query or named view, so a magus CLI command can print a clickable "view this in the Graph Explorer" line as a COMPLEMENTARY aid alongside its normal output. |
|
handler/activity
Package activity is the console-facing ActivityService handler: it lists recent activity events (newest first, filtered) and serves a payload blob by ref for the /dashboard and log viewer.
|
Package activity is the console-facing ActivityService handler: it lists recent activity events (newest first, filtered) and serves a payload blob by ref for the /dashboard and log viewer. |
|
handler/diff
Package diff serves the review session's plain-JSON routes under /api/v1/diff.
|
Package diff serves the review session's plain-JSON routes under /api/v1/diff. |
|
handler/graph
Package graph holds the graph surfaces the daemon serves and the magus.graph.v1alpha1 wire mapping behind them: the GET /api/v1/graph route (a bulk subgraph document) and the GraphService RPCs (ranked retrieval - query, resolve, explain, path, stats).
|
Package graph holds the graph surfaces the daemon serves and the magus.graph.v1alpha1 wire mapping behind them: the GET /api/v1/graph route (a bulk subgraph document) and the GraphService RPCs (ranked retrieval - query, resolve, explain, path, stats). |
|
handler/insight
Package insight is the console-facing InsightService handler: it serves every insight lens (the four VCS-history lenses from one cached git-log scan, plus the run-outcome volatility lens folded in fresh) as the magus.insight.v1alpha1 wire type.
|
Package insight is the console-facing InsightService handler: it serves every insight lens (the four VCS-history lenses from one cached git-log scan, plus the run-outcome volatility lens folded in fresh) as the magus.insight.v1alpha1 wire type. |
|
handler/job
Package job is the console-facing JobService handler: the daemon's CONTROL surface, the mutating sibling of the read-only activity/status/viewer handlers.
|
Package job is the console-facing JobService handler: the daemon's CONTROL surface, the mutating sibling of the read-only activity/status/viewer handlers. |
|
handler/mcp
Package mcp implements the MCP (Model Context Protocol) server for magus.
|
Package mcp implements the MCP (Model Context Protocol) server for magus. |
|
handler/mcp/origin
Package origin carries agent origin metadata across goroutines via context.
|
Package origin carries agent origin metadata across goroutines via context. |
|
handler/memory
Package memory is the console-facing MemoryService handler: an observable, editable view over the durable handoff-journal entries the MCP magus_memory tool writes.
|
Package memory is the console-facing MemoryService handler: an observable, editable view over the durable handoff-journal entries the MCP magus_memory tool writes. |
|
handler/metrics
Package metrics is the daemon's derived-dashboard presentation layer for magus's OTel metrics.
|
Package metrics is the daemon's derived-dashboard presentation layer for magus's OTel metrics. |
|
handler/notes
Package notes is the console-facing NotesService handler: a READ-ONLY view over the workspace's human-authored notes, both the shared store in the checkout and the private one on this machine.
|
Package notes is the console-facing NotesService handler: a READ-ONLY view over the workspace's human-authored notes, both the shared store in the checkout and the private one on this machine. |
|
handler/status
Package status maps the live status report onto the magus.status.v1alpha1 wire message and base64-encodes it for the dashboard's SSE stream.
|
Package status maps the live status report onto the magus.status.v1alpha1 wire message and base64-encodes it for the dashboard's SSE stream. |
|
handler/token
Package token is the console-facing TokenService handler: the typed management surface for the daemon's auth tokens.
|
Package token is the console-facing TokenService handler: the typed management surface for the daemon's auth tokens. |
|
handler/tool
Package tool serves the toolchain view: every binary a workspace's spells drive, the version each one reported, and the window it is held to.
|
Package tool serves the toolchain view: every binary a workspace's spells drive, the version each one reported, and the window it is held to. |
|
handler/trailrpc
Package trailrpc is the audit interceptor for the daemon's Connect services: a connect.Interceptor that records MUTATING unary RPCs to the activity trail by construction, so auditing a state change is a structural default of the mount rather than a per-handler line a developer must remember to add.
|
Package trailrpc is the audit interceptor for the daemon's Connect services: a connect.Interceptor that records MUTATING unary RPCs to the activity trail by construction, so auditing a state change is a structural default of the mount rather than a per-handler line a developer must remember to add. |
|
handler/viewer
Package viewer holds the magus.viewer.v1alpha1 wire contract: the code that maps captured DOMAIN events onto the versioned protobuf tool-page contract and encodes them for a browser (a URL-fragment blob for a finished run, or a live SSE stream), plus the viewer's filter DSL.
|
Package viewer holds the magus.viewer.v1alpha1 wire contract: the code that maps captured DOMAIN events onto the versioned protobuf tool-page contract and encodes them for a browser (a URL-fragment blob for a finished run, or a live SSE stream), plus the viewer's filter DSL. |
|
hint
Package hint is the hints home: everything magus renders to point a reader at a better next command.
|
Package hint is the hints home: everything magus renders to point a reader at a better next command. |
|
hostmodules
Package hostmodules is the union of every host module magus exposes to Buzz: std's own self-registering set (the 24 modules still living flat in std/*.go) plus std/encoding's nine explicitly-aggregated leaf packages (base64, csv, hex, ini, json, toml, url, xml, yaml).
|
Package hostmodules is the union of every host module magus exposes to Buzz: std's own self-registering set (the 24 modules still living flat in std/*.go) plus std/encoding's nine explicitly-aggregated leaf packages (base64, csv, hex, ini, json, toml, url, xml, yaml). |
|
httpx
Package httpx owns the loopback-only HTTP server core and the DNS-rebind guard shared by magus's daemon-facing HTTP surfaces.
|
Package httpx owns the loopback-only HTTP server core and the DNS-rebind guard shared by magus's daemon-facing HTTP surfaces. |
|
interactive
Package interactive provides project scoring and session-state persistence for the magus x shorthand command.
|
Package interactive provides project scoring and session-state persistence for the magus x shorthand command. |
|
interactive/difftui
Package difftui is the terminal client of the shared diff session: the same changeset the console's Diff surface renders and an agent joins over MCP, read with a keyboard.
|
Package difftui is the terminal client of the shared diff session: the same changeset the console's Diff surface renders and an agent joins over MCP, read with a keyboard. |
|
interactive/screen
Package screen is a terminal emulator: it consumes an escape stream and reconstructs the grid a reader would be looking at.
|
Package screen is a terminal emulator: it consumes an escape stream and reconstructs the grid a reader would be looking at. |
|
interactive/tty
Package tty provides terminal-agnostic primitives: scroll regions, file-descriptor classification (TTY vs pipe vs regular file), and the picker.
|
Package tty provides terminal-agnostic primitives: scroll regions, file-descriptor classification (TTY vs pipe vs regular file), and the picker. |
|
interp
Package interp compiles and runs magusfile sources via the Buzz scripting backend.
|
Package interp compiles and runs magusfile sources via the Buzz scripting backend. |
|
interp/bindings
Package bindings registers the Go-backed modules (magus, std: os, platform, fs, vcs, env, crypto, json, log, http, archive) available to every magusfile script.
|
Package bindings registers the Go-backed modules (magus, std: os, platform, fs, vcs, env, crypto, json, log, http, archive) available to every magusfile script. |
|
interp/bindings/gen
Package gen is the generated native-to-Buzz adapter layer.
|
Package gen is the generated native-to-Buzz adapter layer. |
|
interp/engine
Package engine defines the Engine and Session interfaces that all scripting engine implementations must satisfy, along with the engine registry.
|
Package engine defines the Engine and Session interfaces that all scripting engine implementations must satisfy, along with the engine registry. |
|
interp/engine/buzz
Package buzz adapts the standalone Buzz interpreter (magus/gopherbuzz) to magus's engine.Engine/engine.Session interfaces and registers it under the "buzz" key.
|
Package buzz adapts the standalone Buzz interpreter (magus/gopherbuzz) to magus's engine.Engine/engine.Session interfaces and registers it under the "buzz" key. |
|
jobs
Package jobs is the registry of the daemon's background maintenance jobs: the single source of truth that maps a job's stable name to the worker argv the daemon runs for it.
|
Package jobs is the registry of the daemon's background maintenance jobs: the single source of truth that maps a job's stable name to the worker argv the daemon runs for it. |
|
journal
Package journal captures one magus invocation as a structured stream of events - the journal a run produces.
|
Package journal captures one magus invocation as a structured stream of events - the journal a run produces. |
|
langservice
Package langservice provides editor language features - completion and hover - for Buzz magusfiles, driven by a build-time snapshot of the magus host module surface (see cmd/langservice-manifest and manifest_data.go).
|
Package langservice provides editor language features - completion and hover - for Buzz magusfiles, driven by a build-time snapshot of the magus host module surface (see cmd/langservice-manifest and manifest_data.go). |
|
ledger
Package ledger persists the lease ledger: the rows an orchestrating agent declares about the plan it is running, kept where a human can read them.
|
Package ledger persists the lease ledger: the rows an orchestrating agent declares about the plan it is running, kept where a human can read them. |
|
maintenance
Package maintenance is the daemon's built-in background maintenance scheduler: a low-key, idle-gated loop that runs the rotation and sync JOBS on their configured intervals when the daemon is quiet.
|
Package maintenance is the daemon's built-in background maintenance scheduler: a low-key, idle-gated loop that runs the rotation and sync JOBS on their configured intervals when the daemon is quiet. |
|
memory
Package memory is the durable, per-repository handoff journal: discrete, categorized records (one markdown file per entry, YAML frontmatter carrying the structured fields) plus a legacy cursor snapshot.
|
Package memory is the durable, per-repository handoff journal: discrete, categorized records (one markdown file per entry, YAML frontmatter carrying the structured fields) plus a legacy cursor snapshot. |
|
notes
Package notes is the workspace's human-authored knowledge store: discrete entries (one markdown file per note, YAML frontmatter carrying the structured fields) that attach to graph entities without being derived from any of them.
|
Package notes is the workspace's human-authored knowledge store: discrete entries (one markdown file per note, YAML frontmatter carrying the structured fields) that attach to graph entities without being derived from any of them. |
|
observability
Package observability provides OpenTelemetry instrumentation for magus.
|
Package observability provides OpenTelemetry instrumentation for magus. |
|
observability/otlp
Package otlp holds the concrete OpenTelemetry/OTLP provider that backs the observability.Provider interface.
|
Package otlp holds the concrete OpenTelemetry/OTLP provider that backs the observability.Provider interface. |
|
playground
Package playground is the browser front end for the Buzz playground: the terminal Console (command dispatch, completion, history, rendering to HTML rows), editor syntax Highlight, and the Share deep-link json.
|
Package playground is the browser front end for the Buzz playground: the terminal Console (command dispatch, completion, history, rendering to HTML rows), editor syntax Highlight, and the Share deep-link json. |
|
proc
Package proc implements the magus "process adoption" mechanism: child magus processes detect MAGUS_DAEMON_SOCKET and forward work over a Unix-domain socket RPC, sharing the parent's cache, logger, and concurrency budget.
|
Package proc implements the magus "process adoption" mechanism: child magus processes detect MAGUS_DAEMON_SOCKET and forward work over a Unix-domain socket RPC, sharing the parent's cache, logger, and concurrency budget. |
|
proc/endpoint
Package endpoint is the parsed-transport-address value type, split out of internal/proc as a leaf with no OS or daemon dependencies (only context/fmt/net/strings).
|
Package endpoint is the parsed-transport-address value type, split out of internal/proc as a leaf with no OS or daemon dependencies (only context/fmt/net/strings). |
|
proc/run
Package run is the shared subprocess helper for magus spells.
|
Package run is the shared subprocess helper for magus spells. |
|
prompt
Package prompt assembles a prompt as a sequence of named sections.
|
Package prompt assembles a prompt as a sequence of named sections. |
|
race
Package race detects filesystem race conditions across concurrently executing projects.
|
Package race detects filesystem race conditions across concurrently executing projects. |
|
registry
Package registry reads the signed file of release and end-of-life facts that `magus self refresh` fetches and everything else only ever reads from disk.
|
Package registry reads the signed file of release and end-of-life facts that `magus self refresh` fetches and everything else only ever reads from disk. |
|
render
Package render contains graph presentation helpers: ASCII tree, DOT, and Mermaid formatters.
|
Package render contains graph presentation helpers: ASCII tree, DOT, and Mermaid formatters. |
|
render/md
Package md is a small typed Markdown builder for magus's generated docs (MAGUS.md, the insight report).
|
Package md is a small typed Markdown builder for magus's generated docs (MAGUS.md, the insight report). |
|
report
Package report writes per-task JSONL events for post-processing.
|
Package report writes per-task JSONL events for post-processing. |
|
retry
Package retry provides exponential-backoff retry helpers: Do runs an arbitrary operation with capped, context-aware backoff, and NewHTTPClient wraps an http.Client so idempotent requests retry on transport errors and 5xx responses (honoring Retry-After).
|
Package retry provides exponential-backoff retry helpers: Do runs an arbitrary operation with capped, context-aware backoff, and NewHTTPClient wraps an http.Client so idempotent requests retry on transport errors and 5xx responses (honoring Retry-After). |
|
review
Package review records which changed files have been marked as read.
|
Package review records which changed files have been marked as read. |
|
sandbox
Package sandbox confines spell code to a workspace-bounded filesystem and environment.
|
Package sandbox confines spell code to a workspace-bounded filesystem and environment. |
|
sandbox/apply
Package apply builds per-workspace sandbox policies from config and owns the process-wide landlock application state.
|
Package apply builds per-workspace sandbox policies from config and owns the process-wide landlock application state. |
|
sandbox/env
Package env holds the environment half of a sandbox policy: the allowlist of variable names a child process may inherit and the scrubbing logic.
|
Package env holds the environment half of a sandbox policy: the allowlist of variable names a child process may inherit and the scrubbing logic. |
|
sandbox/filesystem
Package filesystem holds the filesystem half of a sandbox policy: the path allowlist (Ruleset) and path-shape checks consulted before touching the filesystem.
|
Package filesystem holds the filesystem half of a sandbox policy: the path allowlist (Ruleset) and path-shape checks consulted before touching the filesystem. |
|
secret
Package secret resolves credential references through a workspace's selected secret provider, and remembers the values it handed out so magus can keep them out of everything it persists.
|
Package secret resolves credential references through a workspace's selected secret provider, and remembers the values it handed out so magus can keep them out of everything it persists. |
|
selfupdate
Package selfupdate downloads, verifies, and installs magus release binaries.
|
Package selfupdate downloads, verifies, and installs magus release binaries. |
|
service
Package service supervises long-running shared services and their lifecycle.
|
Package service supervises long-running shared services and their lifecycle. |
|
service/console
Package console is the pure application logic behind the browser Graph Explorer, dashboard, and log viewer.
|
Package console is the pure application logic behind the browser Graph Explorer, dashboard, and log viewer. |
|
service/identity
Package identity derives the identity of a long-running service from its resolved process command, for three purposes:
|
Package identity derives the identity of a long-running service from its resolved process command, for three purposes: |
|
serviceaudit
Package serviceaudit bridges magus's resolved projects to the pure near-duplicate detector in internal/identity.
|
Package serviceaudit bridges magus's resolved projects to the pure near-duplicate detector in internal/identity. |
|
sessions
Package sessions is the append-only record of what magus sessions did, kept where every worktree of a repository can read it.
|
Package sessions is the append-only record of what magus sessions did, kept where every worktree of a repository can read it. |
|
share
Package share implements the daemon side of "share to phone": an on-demand, time-boxed LAN listener that serves the console's READ surface to a phone on the same network, guarded by a single short-lived read-only token.
|
Package share implements the daemon side of "share to phone": an on-demand, time-boxed LAN listener that serves the console's READ surface to a phone on the same network, guarded by a single short-lived read-only token. |
|
symbols
Package symbols distills a SCIP index file into the language-agnostic types.KnowledgeSymbol shape the knowledge graph ingests.
|
Package symbols distills a SCIP index file into the language-agnostic types.KnowledgeSymbol shape the knowledge graph ingests. |
|
sys/mem
Package mem reads the memory of the machine magus is running on, and of the process trees it starts there.
|
Package mem reads the memory of the machine magus is running on, and of the process trees it starts there. |
|
sys/pid
Package pid answers whether a recorded process is still running.
|
Package pid answers whether a recorded process is still running. |
|
trail
Package trail is the magus activity trail: a durable, append-only record of consequential actions taken against the daemon - who did what, and did it succeed - kept next to the execution journal under a base directory.
|
Package trail is the magus activity trail: a durable, append-only record of consequential actions taken against the daemon - who did what, and did it succeed - kept next to the execution journal under a base directory. |
|
ward
Package ward runs "kind-coherence" checks on a resolved op: it verifies that the op's argv does not contradict the op's declared kind.
|
Package ward runs "kind-coherence" checks on a resolved op: it verifies that the op's argv does not contradict the op's declared kind. |
|
workspace
Package workspace holds the shared building blocks for opening a workspace: the WorkspaceRegistry and the project, spell, and target option constructors that a magusfile's register(...) calls produce, plus the Load accumulator for Open/Inspect.
|
Package workspace holds the shared building blocks for opening a workspace: the WorkspaceRegistry and the project, spell, and target option constructors that a magusfile's register(...) calls produce, plus the Load accumulator for Open/Inspect. |
|
libs
|
|
|
diagnostics
module
|
|
|
gopherbuzz
module
|
|
|
Package project discovers projects within a workspace via magusfile presence and exposes spell-based source/output/dep inference over the types in magus/types.
|
Package project discovers projects within a workspace via magusfile presence and exposes spell-based source/output/dep inference over the types in magus/types. |
|
impact
Package impact computes the forensic blast radius of a changeset: the changed files, the projects that directly contain them (seeds), and the transitive set of projects and targets a change ripples out to via the dependency-graph reverse closure.
|
Package impact computes the forensic blast radius of a changeset: the changed files, the projects that directly contain them (seeds), and the transitive set of projects and targets a change ripples out to via the dependency-graph reverse closure. |
|
proto
|
|
|
gen/go/magus/activity/v1alpha1/activityv1alpha1connect
Package magus.activity.v1alpha1 is the versioned wire contract for the magus activity trail: a time-ordered record of consequential actions taken against a workspace or its daemon, for accountability.
|
Package magus.activity.v1alpha1 is the versioned wire contract for the magus activity trail: a time-ordered record of consequential actions taken against a workspace or its daemon, for accountability. |
|
gen/go/magus/graph/v1alpha1/graphv1alpha1connect
Package magus.graph.v1alpha1 is the versioned wire contract for the knowledge graph the daemon serves to the browser Graph Explorer.
|
Package magus.graph.v1alpha1 is the versioned wire contract for the knowledge graph the daemon serves to the browser Graph Explorer. |
|
gen/go/magus/insight/v1alpha1/insightv1alpha1connect
Package magus.insight.v1alpha1 is the versioned wire contract for magus insight: where a codebase's attention and risk concentrate.
|
Package magus.insight.v1alpha1 is the versioned wire contract for magus insight: where a codebase's attention and risk concentrate. |
|
gen/go/magus/job/v1alpha1/jobv1alpha1connect
Package magus.job.v1alpha1 is the versioned wire contract for the daemon's CONTROL surface: the mutating sibling of the read-only console services (magus.activity.v1alpha1, magus.status.v1alpha1, magus.viewer.v1alpha1, magus.metrics.v1alpha1).
|
Package magus.job.v1alpha1 is the versioned wire contract for the daemon's CONTROL surface: the mutating sibling of the read-only console services (magus.activity.v1alpha1, magus.status.v1alpha1, magus.viewer.v1alpha1, magus.metrics.v1alpha1). |
|
gen/go/magus/memory/v1alpha1/memoryv1alpha1connect
Package magus.memory.v1alpha1 is the console-facing MemoryService: an observable, editable view over the durable agent-memory RECORDS the magus_memory MCP tool writes.
|
Package magus.memory.v1alpha1 is the console-facing MemoryService: an observable, editable view over the durable agent-memory RECORDS the magus_memory MCP tool writes. |
|
gen/go/magus/metrics/v1alpha1/metricsv1alpha1connect
Package magus.metrics.v1alpha1 is the versioned wire contract for the DERIVED dashboard metrics: magus's OTel instrument families rolled up into the numbers a developer reads to judge health - operation counts, cache hit-rates, and latency percentiles - plus a rolling time-series the daemon backfills so the utilization grid shows history from before the page opened.
|
Package magus.metrics.v1alpha1 is the versioned wire contract for the DERIVED dashboard metrics: magus's OTel instrument families rolled up into the numbers a developer reads to judge health - operation counts, cache hit-rates, and latency percentiles - plus a rolling time-series the daemon backfills so the utilization grid shows history from before the page opened. |
|
gen/go/magus/notes/v1alpha1/notesv1alpha1connect
Package magus.notes.v1alpha1 is the console-facing NotesService: a READ-ONLY view over the workspace's human-authored notes, both the shared store in the checkout and the private one on this machine.
|
Package magus.notes.v1alpha1 is the console-facing NotesService: a READ-ONLY view over the workspace's human-authored notes, both the shared store in the checkout and the private one on this machine. |
|
gen/go/magus/status/v1alpha1/statusv1alpha1connect
Package magus.status.v1alpha1 is the versioned wire contract for magus's status/dashboard view, scoped to LIVE state: overall health, the concurrency pool (capacity/running/ queued slots), what is running right now - the running targets, their workspace, and how long they have run - and live cache ACTIVITY (hit/miss/error tallies + real on-disk size).
|
Package magus.status.v1alpha1 is the versioned wire contract for magus's status/dashboard view, scoped to LIVE state: overall health, the concurrency pool (capacity/running/ queued slots), what is running right now - the running targets, their workspace, and how long they have run - and live cache ACTIVITY (hit/miss/error tallies + real on-disk size). |
|
gen/go/magus/token/v1alpha1/tokenv1alpha1connect
Package magus.token.v1alpha1 is the console-facing TokenService: the typed MANAGEMENT surface for the daemon's auth tokens.
|
Package magus.token.v1alpha1 is the console-facing TokenService: the typed MANAGEMENT surface for the daemon's auth tokens. |
|
gen/go/magus/tool/v1alpha1/toolv1alpha1connect
Package magus.tool.v1alpha1 is the versioned wire contract for the toolchain view: which binaries a workspace's spells drive, what version each one actually reported, and the version window it is held to.
|
Package magus.tool.v1alpha1 is the versioned wire contract for the toolchain view: which binaries a workspace's spells drive, what version each one actually reported, and the version window it is held to. |
|
gen/go/magus/viewer/v1alpha1/viewerv1alpha1connect
Package magus.viewer.v1alpha1 is the versioned wire contract for the magus log viewer (the /logs/ page, or any third-party frontend generated from this schema).
|
Package magus.viewer.v1alpha1 is the versioned wire contract for the magus log viewer (the /logs/ page, or any third-party frontend generated from this schema). |
|
Package schema provides a code-generated, zero-reflection schema for the magus Config struct.
|
Package schema provides a code-generated, zero-reflection schema for the magus Config struct. |
|
fieldtype
Package fieldtype holds the hand-written config-field types (Kind, Field, FlagNames) that the generated inventory in schema/gen populates.
|
Package fieldtype holds the hand-written config-field types (Kind, Field, FlagNames) that the generated inventory in schema/gen populates. |
|
gen
Code generated by magus-utils config; DO NOT EDIT.
|
Code generated by magus-utils config; DO NOT EDIT. |
|
Package spells is everything a spell is: the language/runtime adapters magus builds, tests, lints and formats projects with, and the types describing them.
|
Package spells is everything a spell is: the language/runtime adapters magus builds, tests, lints and formats projects with, and the types describing them. |
|
Package std is the single source of truth for host-binding APIs that magusfiles call into.
|
Package std is the single source of truth for host-binding APIs that magusfiles call into. |
|
encoding
Package encoding aggregates the nine text-codec host modules that live under std/encoding/*: base64, csv, hex, ini, json, toml, url, xml, yaml.
|
Package encoding aggregates the nine text-codec host modules that live under std/encoding/*: base64, csv, hex, ini, json, toml, url, xml, yaml. |
|
encoding/base64
Package base64 is the "encoding/base64" host module: base64 lives under std/encoding rather than in std's own flat root because it, like its eight siblings, uses none of std's shared sandbox/exec helpers (resolvePath, checkRead, checkWrite, optStringDefault, ...) - every helper a text codec needs is local to its own file, so splitting it into its own package hides nothing that std itself needs to reach back into.
|
Package base64 is the "encoding/base64" host module: base64 lives under std/encoding rather than in std's own flat root because it, like its eight siblings, uses none of std's shared sandbox/exec helpers (resolvePath, checkRead, checkWrite, optStringDefault, ...) - every helper a text codec needs is local to its own file, so splitting it into its own package hides nothing that std itself needs to reach back into. |
|
encoding/csv
Package csv is the "encoding/csv" host module.
|
Package csv is the "encoding/csv" host module. |
|
encoding/hex
Package hex is the "encoding/hex" host module.
|
Package hex is the "encoding/hex" host module. |
|
encoding/ini
Package ini is the "encoding/ini" host module.
|
Package ini is the "encoding/ini" host module. |
|
encoding/json
Package json is the "json" host module.
|
Package json is the "json" host module. |
|
encoding/toml
Package toml is the "toml" host module.
|
Package toml is the "toml" host module. |
|
encoding/url
Package url is the "encoding/url" host module.
|
Package url is the "encoding/url" host module. |
|
encoding/xml
Package xml is the "xml" host module.
|
Package xml is the "xml" host module. |
|
encoding/yaml
Package yaml is the "yaml" host module.
|
Package yaml is the "yaml" host module. |
|
Package types holds magus's pure domain types.
|
Package types holds magus's pure domain types. |
|
Package vcs provides a VCS interface and built-in implementations for git, hg (Mercurial), sl (Sapling), and jj (Jujutsu).
|
Package vcs provides a VCS interface and built-in implementations for git, hg (Mercurial), sl (Sapling), and jj (Jujutsu). |









