magus

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: GPL-3.0 Imports: 74 Imported by: 0

README ¶

magus

magus gopher mascot

CI Go coverage textsearch coverage Go Reference

A fast, cross-platform task orchestrator for polyglot monorepos. One binary, no second toolchain to install. Targets are programs, not YAML.

Change a file and magus works out which projects it reaches, rebuilds only those, and caches every result so the same work never runs twice.

magus informs; it never decides. It hands you everything it knows about your repository - what a change reaches, which files are generated, where a symbol is used - and the call stays yours. It was built for humans, not for agents: agents drive it well anyway, because an interface legible to a person is legible to anything, and that ordering is the design.

One command, three runs: cold, fully cached, then narrowed to what a change reached.

Why magus exists

magus is the tool you type all day: build, test, lint, and ask the repo a question. Two problems shape everything else on this page. The first is what those commands cost you in time. The second is what they need you to already know.

The tools you run in a monorepo, you run all day. Build, test, lint, switch branches, do it again. So friction compounds fast. A few wasted seconds a run, one flaky target, a teammate's botched merge that starts failing on your checkout, and now you are babysitting the build instead of shipping the feature. Tooling this central earns its place by getting out of the way. It should be fast, and genuinely good at the narrow thing it does.

The other half of the job is knowledge. Monorepos outgrow the people and tools reading them. Humans grep; AI agents grep faster and guess more confidently; both drown in generated files, unfamiliar patterns, and dependency chains nobody holds in their head. magus takes the opposite bet. The build tool already has to know the repo precisely, down to every project, every target's inputs and declared outputs, and what a diff reaches, so it hands that knowledge back as answers instead of leaving everyone to rediscover it.

That is the rule for the whole surface. Every verb answers a question, deterministically, from declared sources: which projects a change affects, whether a file is generated and by what, where a symbol is used, how two things relate. Nothing in magus decides for you, plans for you, or injects itself into your workflow. Answering is the tool's job; deciding is yours, or your agent's.

The same discipline serves both audiences. A teammate on day one and an AI agent in a fresh session have the same problem: a repo they cannot yet trust their guesses about. magus gives them the same fix. Query the knowledge graph instead of grepping, run targets instead of raw tools, and let magus affected ci prove what a change touched. For agents, see Agents.

The longer argument behind that position, and what it was a reaction to, is in I think our tools are the problem.

Who this is for

If any of these is your week, the rest of this page is worth your time:

  • You came back to your own project after three months and cannot remember which command is the real one.
  • Your CI runs everything on every commit, you know most of it was pointless, and you cannot prove which part.
  • You inherited the build. Whoever wrote it has gone, and you need to change one step without discovering what else it fed.
  • You run more than one language in one repo, and your task runner was built for one of them.
  • Your agent greps and guesses. It is fast, it is confident, and it is wrong in ways that take longer to catch than to fix.
  • You have a .env full of tokens you keep meaning to clean up, in a shell where everything you launch inherits them.
  • Someone asked why a target rebuilt and the honest answer was a shrug.
  • You stopped trusting the cache and turned it off, and now everything is slow and at least it is honest.
  • A merge changed the lockfile and nothing told you. Your next command ran against stale dependencies and failed somewhere unrelated, and the fix was a command nobody printed.
  • Your task runner installs through the package manager it is supposed to be running. When it breaks you fix it by upgrading the toolchain you were using it to pin.
  • Generated files keep landing in review and nobody agrees which are safe to edit by hand.
  • Getting the build working is its own project, and it was supposed to be the thing that let you work on the other one.

There is one shape under all of them: a question about your own repository that something already knows and nothing will tell you.

Two of those waste whole afternoons, so here is what magus does about them.

The stale install. magus runs your package manager's install as a step of the build, not as something you are expected to remember after a merge. It does not try to work out whether the install is needed, and that is deliberate: the obvious check - does node_modules exist - is wrong in the case that matters, because an interrupted install leaves a directory that exists and is incomplete. So the install runs every time and lets the package manager be the judge. That costs about a second on a warm tree and fails loudly when the lockfile and the manifest disagree.

The bootstrap loop. magus is one binary and installs through none of the toolchains it drives. A task orchestrator that arrives through the package manager it orchestrates has put itself downstream of the thing it is meant to control: the failures arrive oblique, there is rarely anywhere sensible to attach an error explaining them, and the repair is to upgrade the runtime you adopted the tool to pin. That boundary is stated as a rule in Scope, not as a preference.

If you only have one project

Most of what is above does not depend on having several. A target's cache key is built from that target's own declared inputs, so a warm re-run skips work in a one-project repo exactly as it does in this repository's ten. The knowledge graph indexes symbols, docs and generated files, not just the edges between projects. One vocabulary is worth more on your own, not less, because there is nobody else to ask what the build step was called.

What does thin out is the affected set. With one project, "what did this change reach" has only one answer, and the shard planning behind magus affected ci has nothing to plan. That is the part that starts paying when you split out a second project, which is also why magus init scaffolds exactly one and expects to be right for a while.

Who it is not for

Stated plainly, because a list of strengths on its own is advertising:

  • You need a build farm. There is no remote execution. magus caches results and shares them; it does not run your work on someone else's machine.
  • You want your toolchain versions installed for you. magus compares what ran against what you declared and stops there. It will not select, install, or switch a version - see Scope.
  • You need a sandbox that fails on undeclared reads. magus's sandbox is a supply-chain defense: off by default, with no kernel layer on macOS. If you want Bazel's hermeticity guarantee, magus does not offer it and should not be read as claiming it - see Sandbox.
  • You want your build steps to run in containers. magus will not require a container runtime, because a task orchestrator that needs one cannot be used to bootstrap the machine it runs on - and it offers no opt-in container isolation either. (The container charm changes what a target produces, an image instead of a binary; the build still runs on the host.) If a fixed execution environment is what you are buying, a container-native runner is the better tool - the reasoning is in Scope.

How it works

Five ideas carry most of the tool. Each has a deeper page; this is the short version.

Affected sets

magus keeps a dependency graph of your projects and knows which files each target reads. Change a file and magus affected <target> runs only the projects that change can reach, in dependency order. magus affected ci runs the full pipeline over that set, so CI does the least work a change requires and still catches breakage in a project you never opened. See CI.

Content-addressed caching

Every target declares its inputs and outputs. magus hashes the inputs, and if it has already seen that hash it replays the stored output instead of running the work again. The cache is a plain content-addressed store on disk (SHA-256): the input hash is the key, and the stored outputs are addressed by their own content hash, so a replay is a byte-for-byte reproduction of the recorded run.

The knowledge graph

Most tools that offer you a codebase graph are observers: a separate indexer scans the repo, infers the structure, and can be wrong in ways nothing warns you about. magus is not observing - it is the thing that builds the repo, so it already has to know every project, every target's declared inputs and outputs, and what a diff reaches, and getting any of that wrong breaks builds loudly. The graph is that same knowledge handed back: a byproduct of being the source of truth, never an inference about it. No LLM pass, no fuzzy linking; every edge traces to a declaration you can open.

magus query "kind=target lint" finds nodes, magus explain <node> shows a node's edges and what reaches it, and magus refs <symbol> lists where a symbol is defined and used from a SCIP index.[^scip] The same graph answers "is this file generated," "what does my diff touch," and "how do these two things relate" without grepping. See the knowledge graph, including what this graph deliberately is not.

One vocabulary

magus names a thing once and reuses the name everywhere, in the CLI, the config, and the graph. A target is a unit of work such as build, test, or lint. A spell is a language adapter that supplies a target's operations (the go spell provides go-test; the buf spell provides buf-lint). A charm is a modifier applied to a run, like rw for read-write or cd for continuous delivery. An op is a single tool invocation. Learn the four words and the rest of the surface reads the same way.

There is a terminal UI. It stays out of your way

A run pins its progress, failures group by project beside their output, and the picker searches the graph as you type.

The band at the bottom holds still while your output scrolls past it. Nothing is cleared, the alternate screen is never touched, and your scrollback survives - so selection, copy and paste keep working the way they always did. Every one of these surfaces degrades to plain text when there is no terminal to draw on.

Getting started

Install

magus ships as a single self-contained binary, so there is no second toolchain to install.

curl --proto '=https' --tlsv1.2 -sSf https://eli.gladman.cc/magus/install -o install.sh
less install.sh
sh install.sh

Reviewing the downloaded script before executing it lets you audit the URL, verification, and installation steps instead of piping an unreviewed network response directly to your shell. See the Install guide for platform details, verification, and updates.

A first look

magus targets are written in Buzz, a small typed scripting language it embeds. A magusfile.buzz at the repo root declares your targets as exported functions - each one composes operations from the spells you bind:[^playground]

import "magus";
import "magus/spell/go";

magus\project({ "spells": [go] });

// Every exported function is a runnable target. It receives a magus\Context,
// the handle it uses to declare what it needs and hands to every op it runs.
// magus caches each target's result and runs it only when a change reaches
// this project.
export fun build(ctx: magus\Context, args: [str]) > void { go["go-build"](ctx); }
export fun test(ctx: magus\Context, args: [str])  > void { go["go-test"](ctx); }
export fun lint(ctx: magus\Context, args: [str])  > void { go["golangci-lint"](ctx); }

// format is read-only by default: go-fmt reports files that need formatting, and
// go-mod-tidy runs with --diff so it fails if go.mod/go.sum have drifted. They take
// DIFFERENT write charms, because they are not the same risk. gofmt is offline, so
// the same tree always yields the same bytes - `magus run format:rw` rewrites the
// code. Tidy resolves against the module proxy, so what it writes depends on what
// upstream serves today; that is a second, deliberate ask:
//   magus run format:rw          formatting only; go mod tidy still just reports
//   magus run format:rw,relock   also let go mod tidy amend go.mod and go.sum
export fun format(ctx: magus\Context, args: [str]) > void {
    go["go-fmt"](ctx);
    go["go-mod-tidy"](ctx);
}

// 'ci' is the anchor `magus affected ci` keys off: it composes the pipeline
// by declaring the targets it needs.
export fun ci(ctx: magus\Context, args: [str]) > void {
    ctx.needs(build, test, lint, format);
}

Point magus at that repo and each command returns an answer and stops:

magus ls                                  # which projects exist
magus run test                            # run a target, cache the result
magus affected ci                         # the pipeline, over only what your diff reaches
magus query "kind=spell"                  # what the graph knows
magus describe file docs/gen/index.html   # is this file generated, and by what

Nothing here plans a workflow or decides for you. magus describe file tells you a path is a generated output so you skip its diff; magus affected ci tells you which projects a change reaches so you run no more than that.

Architecture

One process (magus server start) exposes the workspace through two standing listeners, one per audience, and every browser page is a separate static asset; the binary serves no HTML. A third listener is raised only on demand: "share to phone" opens a time-boxed LAN listener that serves the read-only console to a phone on the same network, then tears itself down.

Four figures, one subject each. They were one flowchart until it carried roughly thirty-five boxes, which is the point at which a diagram stops being read and starts being skipped.

The HTTP surface

Agents and the console share one guarded front door: a DNS-rebind check, a bearer token and a CORS policy sit in front of /mcp, /api/v1, the Connect services and the share endpoint. The health endpoints are the deliberate exception, so a probe never needs a credential.

The local path

A CLI invocation never goes over HTTP. It dispatches across a private unix domain socket into the concurrency pool and the three registries the daemon keeps warm. Sharing a graph is the one case that spawns a separate short-lived loopback server.

The magus CLI dispatching over a unix socket into the daemon's pool and registries
What keeps it warm

File watchers, the SCIP auto-indexer and a coalesced graph-build job all exist to keep one thing current: the workspace registry, which holds the daemon's only warm copy of the knowledge graph.

File watchers, the SCIP indexer and the graph-build job all writing into the workspace registry
Sharing to a phone

The LAN listener is the only part of magus a second machine can reach. It is minted by a loopback-only endpoint, time-boxed (fifteen minutes by default), carries a read-only token, and serves no MCP, share or mutating route at all.

A loopback endpoint minting a time-boxed read-only LAN listener for a phone
How to read the diagram

The colors group the system by role, and each region is tagged with the Go package or project that owns it, so the diagram doubles as a code map: the runtime is the root module (cmd/magus plus internal/*), the browser console is the docs/ project, and the wire contracts are the proto/magus protobufs.

Green is the Unix domain socket, the local control plane: it dispatches magus run/magus affected into one shared concurrency pool, answers magus status, and adopts nested magus calls. Fast and private (0700); the local CLI and the liveness/readiness probes use it.

Orange is the HTTP server on mcp.address, for clients that cannot reach a Unix socket. It carries MCP for agents at /mcp, the read-only /api/v1 console routes, Connect services for metrics and the activity trail, and one bearer-gated job-control service for maintenance jobs - the daemon's only mutating surface. Its request and response types are the proto/magus protobufs, generated by buf and served over Connect/JSON.

Red is the guard chain every HTTP route but health passes through: a DNS-rebind host check, a bearer token (the cli token plus named connector tokens), and CORS scoped to the site and loopback origins.

Yellow is the health routes, left unguarded so a kubelet can probe them; they answer by querying the same socket. See container probes.

Purple is shared, warm daemon state: the knowledge graph and SCIP index in the workspace registry, plus the runs, services, metrics, and trail registries, and the graph's own declared inputs and exports.

Indigo is the background jobs that keep that state fresh without a foreground command: file watchers invalidate the warm graph and push an SSE event to the console, a throttled SCIP indexer keeps symbols current, and a branch switch fires the git hook, which submits one coalesced graph-build job over the socket.

Teal is the browser console, five static apps on the daemon, covered in The browser console below.

The graph itself is assembled from declared sources as shards (the magusfile registry, docs, @symbols from SCIP, @vcs from git history, CODEOWNERS). magus graph export -o json writes the graph data copied into the console's offline demo, and magus describe graph -o markdown writes the MAGUS.md routing index; live, the daemon serves the same graph byte-identical at /api/v1/graph.

Because the two listeners are separate, they can diverge: the socket can be healthy while the HTTP/MCP endpoint failed to bind, which is why magus status reports each one on its own line.

The browser console

magus is fully featured from the terminal, so everything here is optional. Alongside the CLI, the daemon can drive a set of read-only browser apps.

Want to see it first? Open the live demo: no install, no daemon. It fills the dashboard with synthesized activity, streams a build into the log viewer, and lets you jump between every app in demo mode. Everything below runs against your own daemon instead.

The apps

The apps ship as one console; each link below opens it on the matching app.

Dashboard
Dashboard
Pool, cache and daemon health, liveGraph Explorer
Graph Explorer
Targets, spells and their dependenciesLog Viewer
Log Viewer
Any run's captured output, streamed or replayedActivity Trail
Activity Trail
What agents did, and whenDiff
Diff
Review the working tree, paired with an agentThe dashboard's work plan
Work plan
Who holds which lease, and where two of them overlap (press p)The dashboard in Big Picture
Big Picture
The same dashboard with the console's own chrome gone, for a wall display (press b)Diff on a phone
Diff, mobile
The file index folds to a rail; split view falls back to unifiedLog Viewer on a phone
Log Viewer, mobile
The waterfall keeps its drawn size and scrolls, rather than shrinking its labels awayDashboard on a phone
Dashboard, mobile
Tiles stack, the rail gives way to the launcher grid, and controls take a 44pt touch target
  • Dashboard shows live daemon health, the concurrency pool, running targets, cache activity, and the live lease plan.[^app-dashboard]
  • Graph Explorer navigates targets, spells, and their dependency graph (magus graph export --open).[^app-graph]
  • Log Viewer reads or streams any past run's captured output (magus query output <ref> --open).[^app-logs]
  • Activity Trail shows recent MCP calls, agent-command observations, background jobs, and config changes.[^app-activity]
  • Diff annotates the working tree's uncommitted changes - generated vs source, blast radius, coverage - and hosts the human half of a paired review.
How it stays on your machine

These are add-ons, not a runtime you depend on. Two decisions keep them that way.

The binary embeds no UI

magus never embeds a web server that ships a UI, and a released binary carries no pages: the console is a separate static site (rendered from docs/ at deploy time, hosted at eli.gladman.cc/magus, or self-hosted from any file server). What the daemon exposes over loopback is a small API - read-only views (/api/v1/...), one bearer-gated job-control service for maintenance jobs, and the MCP endpoint. It will also serve a console build you point it at on disk (console/gen, or MAGUS_CONSOLE_DIR) so you can host your own copy, but it ships none and 404s /console/ until one is built.

Your data never leaves the loopback

The hosted page talks only to 127.0.0.1/[::1], a loopback lock it enforces before any request, or it receives your graph inline through a URL fragment. Nothing is uploaded. You can drop the UI entirely: set console.enabled: false and the daemon runs fine without it, serving no browser API at all. See the Console reference.

Working with AI agents

A tighter feedback loop does more for an agent working in your code base than a larger model does, and most of that loop already exists: the build, test, lint, format, and cache scripts you wrote so developers could set up an environment. magus is the hookup. Those same scripts become what the agent runs, deterministic and fast.

magus treats an AI agent and a new teammate as the same kind of user: someone who cannot yet trust their guesses about the repo. It ships an agent surface built on the knowledge graph, so an agent asks magus instead of grepping and guessing.

  • Installable skills teach an agent to query the graph, run work through targets, and triage generated files. For Codex, run magus agent install .agents/skills and paste the always-on AGENTS.md block it prints. Claude Code uses .claude/skills; there is a setup page per host behind Agents.
  • The committed MAGUS.md is a routing index, regenerated from the graph, that points an agent at the exact query for a given question.
  • The MCP server the daemon exposes lets an agent call magus tools directly over the protocol rather than shelling out.[^mcp]
  • The guard hook judges a command or a write before an agent runs it, from rules that live in the binary rather than in per-host integration code. The host-shaped wiring is a template you copy and own, so a host magus has never heard of gets the same rules, and one that changes its hook surface next month is your few-line edit instead of a magus release. Doctrine records why it works that way.

Full detail, including which tools exist and how to connect, is on the Agents page.

Documentation

Full docs live at eli.gladman.cc/magus.[^docs-source] The major sections:

Inside a workspace, the entry point is the committed MAGUS.md: a generated routing index of the workspace's projects, targets, and the exact knowledge-graph queries that answer questions about them. Projects can carry their own (this repo commits one for docs/ and for each project under libs/), scoped to that project. They are generated by magus describe graph -o markdown via the generate target; regenerate them, never hand-edit.

Development

magus is built and tested by magus, so this repository is a magus workspace like any other. That means parts of the contributor reference are generated from the workspace's own graph rather than written, and can show things a hand-maintained page cannot:

  • Project catalogs - one page per project: every runnable target, what it depends on, which toolchains it drives, and a run-order diagram built from the real ctx.needs edges.
  • Workspace dependencies - the projects in dependency order, with each one's blast radius: how many projects a change there can reach. Read it before you touch libs/gopherbuzz.
  • Contributing guide - the conventions worth knowing before opening a pull request, including the benchmark-evidence rule for performance changes.
  • Configuration reference - the magus.yaml keys and the MAGUS_* environment inventory.

The architecture diagram above tags each runtime component with the package it lives in, which is the quickest map of where code goes.

Building from source

magus builds magus, so the binary comes out of a magus target like anything else in this workspace:

mise install              # the pinned Go, Node, and esbuild
magus run go-build .      # writes ./magus

go-build regenerates the compiled built-in spells before it links, so the binary never embeds stale bytecode. It is the target to use over build, which also runs the format and image stages.

Do not have a magus yet? Install a release and point it at your checkout - then every build after that is the command above.

Failing that, a clone with no magus and no release can bootstrap one with Go directly. This is the only place a raw go build belongs, and only to produce the binary that runs everything after it:

GOEXPERIMENT=jsonv2 go build -o magus ./cmd/magus   # bootstrap only
./magus run go-build .

GOEXPERIMENT=jsonv2 is not optional: mise.toml sets it for this repository, so a build without it differs from every other build here and shows up later as generated-file drift that is not yours.

Running the tests

Run the tests through magus itself, since the whole point is that magus builds and tests magus:

magus run ci

[^docs-source]: Source: docs/.

[^playground]: Magusfiles are written in Buzz. You can run it in your browser, no install, at the Playground; the standard library modules are the API reference.

[^scip]: SCIP is Sourcegraph's code-index format. magus indexes on its own once a project uses the scip op, stores the index in the cache, and refreshes it in the background; the knowledge graph page covers the symbol layer and the @symbols shard.

[^app-dashboard]: What the tiles mean, and the metrics behind them: Telemetry and the daemon page.

[^app-graph]: The same graph the CLI queries, drawn. See magus graph for the verbs and knowledge graph for the schema.

[^app-logs]: A run's output is addressed by a short reference ID, which is what <ref> is above. See output references.

[^mcp]: Tool list, transport, and how to connect an agent: MCP.

[^app-activity]: The trail is the daemon's own record, kept in memory per workspace. See the daemon page.

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 ¶

Examples ¶

Constants ¶

View Source
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.

View Source
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.

View Source
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.

View Source
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 ¶

func ApplyUnionSandbox(ctx context.Context, roots []string) error

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

func CharmsForCI(charms []string) []string

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 ¶

func FindRoot(dir string) (string, error)

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 ¶

func Inspect(ctx context.Context, root string, opts ...Option) (types.WorkspaceRepository, error)

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

func ListSpells(ctx context.Context) ([]types.Spell, error)

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

func ResolveCacheDir(root string, opts ...Option) (string, error)

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

func ShortRevision(id string) string

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 ¶

func TargetLabel(targets []types.Target, source string) string

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

type Daemon interface {
	Serve(ctx context.Context) error
}

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 ¶

func NewLimiter(n int) *Limiter

NewLimiter creates a Limiter with capacity n. n ≤ 0 defaults to DefaultConcurrency.

func (*Limiter) Capacity ¶

func (l *Limiter) Capacity() int

Capacity returns the configured concurrency cap.

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 ¶

func Open(ctx context.Context, root string, opts ...Option) (*Magus, error)

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 ¶

func (m *Magus) Affected(ctx context.Context, base string) (*types.AffectedResult, error)

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) All ¶

func (m *Magus) All() []*types.Project

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

func (m *Magus) BranchChanges(ctx context.Context, limit int) ([]types.BranchChange, error)

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

func (m *Magus) CacheDir() string

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

func (m *Magus) CacheDiskBytes() int64

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

func (m *Magus) ClassifyFiles(ctx context.Context, paths []string) ([]types.FileEntry, error)

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 ¶

func (m *Magus) CleanCache(ctx context.Context, projects ...*types.Project) error

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 ¶

func (m *Magus) Close() error

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

func (m *Magus) ContextWithSecrets(ctx context.Context) context.Context

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

func (m *Magus) CurrentRevision(ctx context.Context) (name, revision string, dirty bool)

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

func (m *Magus) Diff(ctx context.Context, paths []string) (types.Diff, error)

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

func (m *Magus) DiffTUIEnabled() bool

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

func (m *Magus) EvaluateProjects(ctx context.Context) (types.EvaluatedProjectsOutput, error)

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 ¶

func (m *Magus) ExpandCwd(t types.Target) (targets []types.Target, found bool, err error)

ExpandCwd resolves t for the project containing cwd; found=false when cwd is not inside any project.

func (*Magus) ExpandPath ¶

func (m *Magus) ExpandPath(t types.Target) ([]types.Target, error)

ExpandPath resolves the target pattern to concrete per-project targets; empty or "/" fans out to all.

func (*Magus) ExportCache ¶

func (m *Magus) ExportCache(ctx context.Context, w io.Writer) error

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

func (m *Magus) FileAt(ctx context.Context, rev, path string) (string, error)

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

func (m *Magus) FindOutputProducer(absPath string) *types.Project

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) Get ¶

func (m *Magus) Get(path string) *types.Project

func (*Magus) GetArtifact ¶ added in v0.4.0

func (m *Magus) GetArtifact(ctx context.Context, v cache.ArtifactVersion, dst string) error

GetArtifact writes a cached version to dst, cloning from the store when the filesystem supports reflink.

func (*Magus) Graph ¶

func (m *Magus) Graph() (*types.Graph, error)

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

func (m *Magus) IdentifyRef(ctx context.Context, ref string) ([]types.RefMatch, error)

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 ¶

func (m *Magus) ImportCache(ctx context.Context, r io.Reader) error

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

func (m *Magus) KnowledgeGraph(ctx context.Context, refresh bool) (*knowledge.Graph, error)

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

func (m *Magus) KnowledgeGraphHealthy() (watching, valid bool)

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

func (m *Magus) KnowledgeGraphWithSymbols(ctx context.Context) (*knowledge.Graph, error)

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

func (m *Magus) ListCharms(ctx context.Context) ([]types.Charm, error)

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

func (m *Magus) ListProjects(ctx context.Context) (types.ProjectsOutput, error)

ListProjects returns the project inventory of the workspace.

func (*Magus) ListTargets ¶ added in v0.4.0

func (m *Magus) ListTargets(ctx context.Context) ([]types.TargetEntry, error)

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

func (m *Magus) LogBase(ctx context.Context, base, vcs string)

LogBase emits the affected-set base header through the cache logger. No-op on Inspect workspaces.

func (*Magus) LogCache ¶ added in v0.4.0

func (m *Magus) LogCache(ctx context.Context)

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

func (m *Magus) LogCharms(ctx context.Context, charms string)

LogCharms emits the active-charm header through the cache logger. No-op on Inspect workspaces.

func (*Magus) LogScope ¶

func (m *Magus) LogScope(ctx context.Context, label, source string)

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

func (m *Magus) MetricsSnapshot(ctx context.Context) ([]byte, error)

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

func (m *Magus) OutputKeyInputs(ref string) ([]string, error)

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 ¶

func (m *Magus) Plan(ctx context.Context, target string, opts PlanOptions) (types.ShardPlan, error)

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

func (m *Magus) ProjectTargets(ctx context.Context, project string) []string

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

func (m *Magus) PublishOutput(ctx context.Context, ref string) (string, error)

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

func (m *Magus) RangeDiff(ctx context.Context, base, head string, paths []string) (string, error)

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

func (m *Magus) RefMatchCommand(mt types.RefMatch) string

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

func (m *Magus) ReindexSymbols(ctx context.Context) (int, error)

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 ¶

func (m *Magus) ResolveProjects(targets []types.Target) []*types.Project

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

func (m *Magus) RevisionCheckpoint(ctx context.Context, rev string) (types.VCSCheckpoint, error)

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) Root ¶

func (m *Magus) Root() string

func (*Magus) Run ¶

func (m *Magus) Run(ctx context.Context, targets []types.Target, opts ...RunOption) error

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 ¶

func (m *Magus) RunAffected(ctx context.Context, target string, opts ...RunOption) error

RunAffected computes the VCS-diff target set and runs target on it.

func (*Magus) RunCI ¶

func (m *Magus) RunCI(ctx context.Context, targets []types.Target, opts ...RunOption) error

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

func (m *Magus) SecretProvider() string

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

func (m *Magus) ServeDaemon(ctx context.Context) error

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

func (m *Magus) SetDaemon(d Daemon)

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 ¶

func (m *Magus) SetGraphObserver(o types.Observer)

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

func (m *Magus) SymbolGaps(ctx context.Context) ([]types.KnowledgeSymbolGap, bool)

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

func (m *Magus) SymbolOccurrences(ctx context.Context, key string) (SymbolOccurrenceRead, bool)

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 ¶

func (m *Magus) TailLog(projectPath, target string) (logPath string, err error)

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

func (m *Magus) TargetGraph(ctx context.Context) (types.TargetGraphOutput, error)

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 ¶

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

func (m *Magus) Unreferenced(ctx context.Context) (types.UnreferencedOutput, error)

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

func (m *Magus) Volatility(ctx context.Context) (types.VolatilityReport, error)

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

func (m *Magus) WatchKnowledgeGraph(ctx context.Context) (func(), error)

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

func (m *Magus) WatchSymbolIndexing(ctx context.Context) (func(), error)

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) Where ¶

func (m *Magus) Where(dir string) (*types.Project, bool)

func (*Magus) WorkingDiff ¶ added in v0.4.0

func (m *Magus) WorkingDiff(ctx context.Context, paths []string) (string, error)

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

Collect gathers the current metricdata from the underlying reader. See otlp.Collector.Collect.

type Option ¶

type Option = workspace.Option

Option configures Open or Inspect.

func WithConfigFile ¶

func WithConfigFile(path string) Option

WithConfigFile causes the constructor to load magus.yaml from path instead of <root>/magus.yaml.

func WithLimiter ¶

func WithLimiter(l *Limiter) Option

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 ¶

func WithLoadedConfig(cfg config.Config) Option

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

func WithVersion(v string) Option

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 ¶

func (rw *ReportWriter) RecordShardTotal(shardID string, nShards int, duration time.Duration) error

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 ¶

func WithBaseRef(ref string) RunOption

WithBaseRef overrides MAGUS_VCS_BASE_REF for RunAffected invocations.

func WithCharms ¶

func WithCharms(charms ...string) RunOption

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 ¶

func WithExtraArgs(args []string) RunOption

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 ¶

func WithReportWriter(w io.Writer) RunOption

WithReportWriter streams one JSONL event per target to w; the run engine constructs and closes the report.Writer around it.

func WithSpellFilter ¶

func WithSpellFilter(name string) RunOption

WithSpellFilter restricts Run to projects that have the named spell.

func WithStep ¶

func WithStep() RunOption

WithStep enables per-subprocess stepping mode; forces Concurrency=1.

func WithWrite ¶

func WithWrite() RunOption

WithWrite enables mutating mode for format/generate targets; sugar for the "rw" charm.

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 ¶

type TargetHandler func(context.Context, *types.Project) error

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() TargetOption

RetryOnVolatile enables volatility detection and auto-retry for this target.

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.

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.
std
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).

Jump to

Keyboard shortcuts

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