refs

package
v0.2026327.605 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 22 Imported by: 7 modules, 8 packages

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

Documentation

Overview

Package refs is the spec fabric slice for the remote-repo GIT primitives — pure git-exec + string parsing + cache-path computation, host primitives a plugin composes but the kernel itself needs (reconcile's --remote tag query, the collection walk). RELOCATED from sdk/kit (#55 fabric-primitive extraction), so charly core reaches them via spec/refs directly and the remaining sdk/candy callers keep a thin kit re-export. The FETCH ORCHESTRATION (override → cache → clone → migrate) still lives in the refs plugin (candy/plugin-refs); these are the reusable mechanisms it composes. The only non-stdlib dependency is the advisory file lock (spec/lock) DownloadRepo serializes concurrent cache refresh with.

Index

Constants

View Source
const (
	DefaultRefsCacheTTL = time.Hour
	LatestTagTTL        = DefaultRefsCacheTTL
	DefaultBranchTTL    = DefaultRefsCacheTTL
)

Cache TTLs. ONE default — the eval-batch reality: a 16-lane, multi-phase check run re-resolves the same refs hundreds of times, so a shorter window re-probes mid-batch (spec CHANGELOG 0.2026247.2350: the former 5-minute window re-probed GitHub mid-batch — measured 152 concurrent `git ls-remote` -> throttling -> the deploy-add phase stalled at 493s+ with zero CPU/RAM pressure).

It bounds ONLY the two questions whose answer is a NAME (a tag list; a default branch name) and, for latest_tags, only the IN-PROCESS half: the persisted latest_tags entries are the OFFLINE FALLBACK (served on fetch failure only), never TTL-fresh data.

The question whose answer is CONTENT that can move upstream — which commit does this ref name NOW — is not bounded by a clock at all: see the struct's `downloads` field.

Variables

This section is empty.

Functions

func CompareSemver

func CompareSemver(a, b string) int

CompareSemver compares two semver-like version strings (e.g. "v1.2.3"). Returns -1 if a < b, 0 if equal, 1 if a > b. It delegates to spec/calver.CompareCalVer — the single dotted-version comparator (which strips the "v" prefix and falls back to lexical comparison for non-numeric parts) — so semver and CalVer strings share ONE implementation.

func DownloadRepo

func DownloadRepo(repoPath string, version string) (string, error)

DownloadRepo downloads a remote repo to the cache, as a WHOLE PROJECT: every submodule it declares is populated (see populateSubmodules), because a `--repo` cache is driven by the charly binary and any submodule may be load-bearing. Returns the cache path where the repo was stored.

Freshness contract: the cache is reused ONLY when its recorded provenance (the commit the export was cloned from) equals the ref's CURRENTLY resolved commit — so a branch that advanced upstream (main) is re-downloaded instead of silently serving stale content. The check costs the one ls-remote GitResolveRef already performs; for immutable tags the provenance always matches, so their cache-hit behavior is unchanged. A cache written before this contract has no provenance and is re-downloaded once, then self-heals.

A caller that reads only the repo's OWN TREE uses DownloadRepoFiles instead.

func DownloadRepoFiles added in v0.2026296.2332

func DownloadRepoFiles(repoPath string, version string) (string, error)

DownloadRepoFiles downloads a remote repo to the cache FILES-ONLY: the repo's own tree (its charly.yml, its .agents/ trees, its candy/ dirs) and nothing else. Declared submodules are NEITHER fetched NOR required, so an unreachable one can never fail this fetch.

It exists for the corpus/docs SOURCE readers — `charly marketplace generate` (via candywalk.CollectEntitiesRemote) is the caller that forced it: it reads a manifest and a skills tree and never a submodule, yet had to inherit a whole-project fetch that initialised all 412 gitlinks of opencharly/opencharly and failed outright when one could not be reached (spec#279). Fetching content the reader cannot use is a cost defect (spec#267); failing on it is a correctness defect.

The returned export is a DIFFERENT CACHE ENTRY from DownloadRepo's (<cache>/.files/<repo>@<version> vs <cache>/<repo>@<version>): content decides the key, so a corpus run and a `--repo` run never re-download each other's entry, and the submodule-completeness predicate the `--repo` cache needs is never applied to a tree export (see repoCacheFreshMode).

The signature is exactly candywalk.RemoteResolver's, so a generator passes it as the seam with no SDK change:

candywalk.CollectEntitiesRemote(roots, refs.DownloadRepoFiles)

func GitClone

func GitClone(repoURL string, ref string, commit string, targetDir string) error

GitClone clones a git repository at a specific ref into the target directory. Uses shallow clone for efficiency. It is the WHOLE-PROJECT clone (fetchProject), so it populates submodules.

func GitDefaultBranch

func GitDefaultBranch(repoURL string) (string, error)

GitDefaultBranch detects the default branch of a remote repository. Uses git ls-remote --symref to find what HEAD points to. Returns the branch name (e.g., "main", "master").

This is the RAW primitive — it always hits the network. Caching is the GitClient's job (refs/git_client.go): every consumer that needs a cached answer goes through GitClient.DefaultBranch: one cache, one layer (R3/R5).

func GitLatestTag

func GitLatestTag(repoURL string) (string, error)

GitLatestTag queries a remote repo for tags and returns the highest semver tag. Looks for tags matching v* pattern, sorts by semver, returns the highest. Returns an error if no version tags are found.

This is the RAW primitive — it always hits the network. Caching is the GitClient's job (refs/git_client.go): every consumer that needs a cached answer goes through GitClient.LatestTag, which wraps this primitive with the persistent `cache:` section of the per-host charly.yml: one cache, one layer (R3/R5).

func GitResolveRef

func GitResolveRef(repoURL string, ref string) (string, error)

GitResolveRef resolves a git reference (tag, branch, or commit) to a full commit hash. Uses git ls-remote for tags/branches; for commit hashes, validates length and returns as-is.

NOTE: deliberately NOT cached. DownloadRepo's freshness contract resolves the ref to its CURRENT commit on every call, so a mutable branch (main) that moved upstream is re-downloaded instead of serving stale content (refs/git_test.go TestDownloadRepoFrom_RefreshesMovedBranch). A TTL cache here would break that contract — the freshness check must see the live commit.

func IsCertifiedExport added in v0.2026305.2148

func IsCertifiedExport(cachePath string) bool

IsCertifiedExport reports whether cachePath holds a repo export that can CERTIFY its own content — the ONE content-validity predicate for a resolved ref's materialization, shared by EVERY path that decides whether a cached export may be served (R3).

An export is certified iff it is a directory AND carries v2 provenance (RepoCacheProvenance — the commit it was cloned from: its CONTENT identity, not its path) AND every submodule it declares has content on disk. Path existence alone is NOT validity: a wiped, half-populated or provenance-less export has a directory too, and serving it silently breaks the "content validity, never marker presence" invariant the resolved-ref identity rests on.

Two paths previously answered this question with two DIFFERENT predicates on the SAME object: the immutable-ref fast path (IsRepoCached) asked for content, while the ref-resolution cache (GitClient.Download) asked only `os.Stat().IsDir()` — strictly weaker. A persisted resolution whose export had lost its provenance sidecar was therefore served for the whole TTL with ZERO upstream contact (measured live 2026-10-07: 0 `git ls-remote` calls, the `.ref` sidecar never restored, the content-invalid export served). One object, one predicate.

func IsMutableRef

func IsMutableRef(version string) bool

IsMutableRef reports whether a repo ref version can ADVANCE upstream (a branch name such as main, or an empty version that resolves to the default branch). Immutable coordinates — CalVer/semver tags (v…) and full commit SHAs — never change what they point at; the project's tags are add-only. Mutable refs must re-resolve on every access: a cache hit on a branch otherwise freezes it at first-download content forever (the pre-#146 @main protocol skew — a stale main export served protocol-v1 plugin sources indefinitely).

func IsRepoCached

func IsRepoCached(repoPath, version string) (bool, error)

IsRepoCached reports whether a repo version is already in the cache AS A USABLE EXPORT — the directory exists, carries V2 provenance, AND every submodule it declares has content.

It answers the WHOLE-PROJECT question only (fetchProject): the entry it judges is RepoCachePath's, the one a `--repo` drive reads. A files-only export is a different entry with a different, smaller contract (repoFilesCachePath), and its freshness is decided by its own fetch (repoCacheFreshMode) — never by this predicate, whose submodule requirement such an export could not satisfy by design.

The completeness half is load-bearing for IMMUTABLE refs. EnsureRepoDownloaded short-circuits on `cached && !IsMutableRef(version)`, returning RepoCachePath directly and never entering DownloadRepo — so the repoCacheFreshMode completeness check cannot see a tag's cache at all. Directory-exists alone therefore pinned every incomplete TAG export permanently: a tag never moves, so nothing would ever re-fetch it. On the machine this was found, `charly@v2026.183.1359` held 0 of its 9 declared submodules and `charly@v2026.201.0706` held 1 of 10, both unrepairable for the life of the cache. Checking content here routes an incomplete export down the download branch instead, so tag and branch caches self-heal by the SAME predicate rather than one growing its own copy.

The provenance half is what heals a POLLUTED cache. A v1 (legacy bare-commit) sidecar cannot certify its tree — the pre-cutover loader could rewrite the export in place (auto-migrating charly.yml to the consumer's schema CalVer) — so a legacy export is treated as not-cached and re-fetched once, restoring pristine content. This is network-free (a sidecar read), so the immutable-ref short-circuit still avoids a fetch on every healthy tag access.

func RefProvenancePath added in v0.2026266.1044

func RefProvenancePath(cachePath string) string

RefProvenancePath is the sidecar recording how a cache export was produced.

func RepoCacheDir

func RepoCacheDir() (string, error)

RepoCacheDir returns the remote-repo cache directory. When the operator sets `CHARLY_REPO_CACHE`, its value is used VERBATIM as the repos directory — the variable's long-standing meaning. Kept by operator direction (2026-11-20): no CHARLY_ environment variable is dropped. When unset, the `repos` entry under the ONE cache root is used (D-STORE-1: `$XDG_CACHE_HOME/charly`, or its charly-only override `CHARLY_CACHE_HOME`, or the compatibility override `CHARLY_CACHE_DIR`, in that order).

The override names the REPOS DIRECTORY, not the cache root: `CHARLY_REPO_CACHE` and the cache root's `repos` entry are alternatives, and the latter is used only when the former is unset. A relative value is used verbatim, exactly as before.

func RepoCachePath

func RepoCachePath(repoPath, version string) (string, error)

RepoCachePath returns the cache path for a specific repo version. e.g. $XDG_CACHE_HOME/charly/repos/github.com/org/repo@v1.0.0/

This is the WHOLE-PROJECT entry (fetchProject): the export carries every submodule the repo declares. A files-only export is a DIFFERENT entry — see repoFilesCachePath — because the two exports hold different content, and a cache key has to name what it holds.

func RepoGitURL

func RepoGitURL(repoPath string) string

RepoGitURL converts a repo path to a git clone URL. e.g. "github.com/opencharly/ml-layers" -> "https://github.com/opencharly/ml-layers.git"

func WriteRepoCacheProvenance added in v0.2026266.1044

func WriteRepoCacheProvenance(cachePath, commit string) error

WriteRepoCacheProvenance records the clone's resolved commit next to the export.

Types

type GitClient added in v0.2026241.711

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

GitClient is the centralized git layer. Construct once per process (or per project) and share it — the cache is the point.

func NewGitClient added in v0.2026241.711

func NewGitClient(cacheFile string) *GitClient

NewGitClient returns a GitClient whose cache lives in the `cache:` section of the per-host charly.yml at cacheFile. When cacheFile is empty, the default deploy config path ($XDG_CONFIG_HOME/charly/charly.yml, honoring the CHARLY_DEPLOY_CONFIG override) is used.

func (*GitClient) BypassCache added in v0.2026247.2350

func (g *GitClient) BypassCache()

save persists the `cache:` section into the per-host charly.yml under the advisory lock (best-effort). It reads the CURRENT file, updates only the `cache:` key (preserving every other key — deploy:, provides:, ledger:, system:, …), and writes back atomically (tempfile + rename). BypassCache disables every cached lookup — the next resolutions are fresh (an operator on-demand truth: a new tag just released, a moved branch). Runtime-only: the flag does not survive the process (see SetBypass for the persisted form).

func (*GitClient) CacheStatus added in v0.2026247.2350

func (g *GitClient) CacheStatus() (string, int)

CacheStatus reports the cache file path and the number of cached git answers (the operator-facing `charly cache status` surface).

func (*GitClient) ClearCache added in v0.2026247.2350

func (g *GitClient) ClearCache() error

ClearCache drops every cached git answer (the in-memory entries and the persisted file), so the next resolutions are fresh — the `charly cache clear/refresh` surface.

func (*GitClient) DefaultBranch added in v0.2026241.711

func (g *GitClient) DefaultBranch(repoURL string) (string, error)

func (*GitClient) Download added in v0.2026241.711

func (g *GitClient) Download(repoPath, version string, download func(repoPath, version string) (string, error)) (string, error)

Download fetches repoPath@version into the repo cache and returns the cache path, deduped only by the IN-PROCESS memo below. There is no freshness WINDOW and no persisted entry: the mutable-ref question ("has this branch moved upstream?") is inherently a NETWORK question, and the only honest answers are "ask upstream" or "guess" — so this asks, once per process, rather than trading a measured staleness window for a saved round trip.

A mutable ref (a branch or the default branch) can move, so the freshness contract requires re-resolving it: the miss path below IS `downloadRepoFrom`, which resolves the ref's CURRENT commit (`GitResolveRef`), refuses a stale export (`repoCacheFresh(cachePath, commit)`), re-clones it and re-stamps the provenance. Within one process the memo means a command run twice in quick succession (e.g. the status fan-out resolving the envelope multiple times) pays that resolution once — the batch dedupe this layer exists for, which needs no time validity because a process is one moment in time. Across processes there is NO memo: a durable entry could only ever answer "has this ref moved upstream?" by not asking, which is the defect this cutover removes (opencharly/charly#715, #530).

The memoised path is further validated against its CONTENT (IsCertifiedExport): an export that can no longer certify what it holds — a wiped, evicted, half-populated or provenance-less repo-cache dir — is never served (the content-validity principle — the same class the materialized-tree cache fixed with component drift detection, and the same predicate the immutable-ref fast path uses).

func (*GitClient) LatestTag added in v0.2026241.711

func (g *GitClient) LatestTag(repoURL string) (string, error)

LatestTag returns the highest semver tag of repoURL.

Freshness contract (the offline-fallback cutover): the IN-PROCESS cache is the only fresh-data cache (batch dedupe within one process — the 152-concurrent- ls-remote throttling storm was a within-one-process fanout, solved by this layer). The PERSISTED latest_tags entries are an OFFLINE FALLBACK, never fresh data: a fresh process with a reachable network re-probes, so a tag pushed minutes ago is always seen. (The former model — serving persisted entries as fresh for the 1h TTL — was the stale-latest-tag bug: a fresh run resolved plugin refs to a tag list up to an hour old.) The persisted entry is served ONLY when the network fetch fails, with a loud stderr line — resilience, not freshness.

func (*GitClient) SetBypass added in v0.2026248.719

func (g *GitClient) SetBypass(on bool) error

SetBypass persists the bypass flag in the cache: git: section of the per-host charly.yml — the `charly cache bypass` operator surface. When on, every cached lookup is disabled (fresh resolutions) until turned off, and a NEW process (a fresh GitClient) honors it at construction (load reads the flag). When off, the flag is cleared and the cache resumes.

func (*GitClient) WarmUp added in v0.2026241.711

func (g *GitClient) WarmUp(repoURLs []string, stderr *os.File)

WarmUp prefetches the git metadata (latest tag + default branch) for a batch of repos so the first project load does not pay every `git ls-remote` on its critical path.

FOUR BOUNDS, because "bounded per fetch" is not "bounded".

  • PER FETCH: `git ls-remote` carries its own deadline (gitOpMetadataTimeout in git.go), so one stalled repo cannot hang forever.
  • TOTAL: this phase carries its OWN ceiling (warmUpTotalTimeout). Without it the phase can run for (len(repos)/workers) x per-fetch-bound, which is unbounded in the corpus size — and the process was observed parked at "fetching git metadata for 194 repo(s)" with no way for a reader to tell progress from a hang.
  • PROGRESS: the phase reports how many repos it warmed and says how many it did not reach, so "still working" and "gave up" are distinguishable in the log.
  • WRITES: ONE cache write for the whole batch. Each LatestTag/DefaultBranch would otherwise pay a full per-host YAML read-modify-write under an advisory file lock — ~388 whole-file rewrites for a 194-repo corpus, to record 388 small answers. The pool defers them.

A repo the TOTAL bound cuts off is NOT silently dropped: the on-demand path re-probes it (that is the offline-fallback contract — a fresh process always re-probes a tag list), so the only cost is that the first load pays it, which is exactly what is reported.

type RepoCacheProvenance added in v0.2026266.1044

type RepoCacheProvenance struct {
	Version int    `json:"version"`
	Commit  string `json:"commit"`
}

RepoCacheProvenance is the parsed provenance sidecar.

func ReadRepoCacheProvenance added in v0.2026266.1044

func ReadRepoCacheProvenance(cachePath string) (RepoCacheProvenance, bool)

ReadRepoCacheProvenance parses the sidecar. The legacy bare-commit format (and any unknown version) is NOT a provenance: it returns ok=false so the caller re-fetches, which is how a polluted legacy cache self-heals.

Jump to

Keyboard shortcuts

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