Documentation
¶
Overview ¶
Package sync hosts the git-backed sync engine. The bulk of the engine (engine.go, import.go, export.go, etc.) lands across phases per docs/git-sync-implementation.md.
Index ¶
- Constants
- Variables
- func AppendRedirect(target, prefix string, r Redirect) error
- func CommentFile(issueFolder string, createdAt time.Time, uuid string) (yamlPath, mdPath string)
- func ConfigPath(projectRoot string) string
- func ContentHash(b []byte) string
- func DetectCaseInsensitiveCollisions(folders []string) map[string][]string
- func DocumentContentFile(docFolder string) string
- func DocumentFolder(prefix, filename string) string
- func DocumentYAMLFile(docFolder string) string
- func Emit(root Node) ([]byte, error)
- func FeatureDescriptionFile(featureFolder string) string
- func FeatureFolder(prefix, slug string) string
- func FeatureYAMLFile(featureFolder string) string
- func IsSyncRepo(workingTreeRoot string) bool
- func IssueDescriptionFile(issueFolder string) string
- func IssueFolder(prefix string, number int64) string
- func IssueYAMLFile(issueFolder string) string
- func New() string
- func NormalizeBody(b []byte) []byte
- func NormalizeNFC(s string) string
- func RedirectsFile(prefix string) string
- func RepoFolder(prefix string) string
- func RepoYAMLFile(prefix string) string
- func ResolveLabel(rs []Redirect, kind, label string) (string, bool)
- func WriteProjectConfig(projectRoot string, c ProjectConfig) error
- func WriteSentinel(repoRoot string, s Sentinel) error
- type CloneOptions
- type CloneResult
- type CollisionPreview
- type DanglingRef
- type DeletionEntry
- type Engine
- func (e *Engine) CloneSyncRepo(ctx context.Context, projectRoot string, opts CloneOptions) (*CloneResult, error)
- func (e *Engine) Export(ctx context.Context, target string) (*ExportResult, error)
- func (e *Engine) ExportStaged(ctx context.Context, gitRepo *git.Repo) (*StagedExportResult, error)
- func (e *Engine) Import(ctx context.Context, source string) (*ImportResult, error)
- func (e *Engine) InitSyncRepo(ctx context.Context, projectRoot string, opts InitOptions) (*InitResult, error)
- func (e *Engine) Inspect(ctx context.Context, syncRepoRoot string, opts InspectOptions) (*InspectResult, error)
- func (e *Engine) Run(ctx context.Context, projectRoot string, syncRepo *git.Repo, opts RunOptions) (*RunResult, error)
- func (e *Engine) Verify(ctx context.Context, syncRepoRoot string) (*VerifyResult, error)
- type ExportResult
- type ImportResult
- type InitOptions
- type InitResult
- type InspectComment
- type InspectDocument
- type InspectFeature
- type InspectIssue
- type InspectOptions
- type InspectRepoSummary
- type InspectResult
- type Node
- type Pair
- type ParsedComment
- type ParsedDocLink
- type ParsedDocument
- type ParsedFeature
- type ParsedIssue
- type ParsedRedirect
- type ParsedRef
- type ParsedRelations
- type ParsedRepo
- type ProjectConfig
- type ProjectSync
- type Redirect
- type ReleaseFunc
- type RenameEntry
- type RenumberEntry
- type RunOptions
- type RunResult
- type Sentinel
- type StagedExportResult
- type VerifyIssue
- type VerifyResult
Constants ¶
const ( ReasonLabelCollision = "label_collision" ReasonManualRename = "manual_rename" ReasonLabelChangedRemotely = "label_changed_remotely" )
Allowed reason values, mirroring the design doc.
const ( VerifyKindParseError = "parse_error" VerifyKindUUIDCollision = "uuid_collision" VerifyKindDanglingRef = "dangling_reference" VerifyKindCaseCollision = "case_collision" VerifyKindRedirectCycle = "redirect_cycle" VerifyKindRedirectChainCap = "redirect_chain_too_long" VerifyKindOrphanComment = "orphan_comment" VerifyKindHashMismatch = "hash_mismatch" VerifyKindRepoInconsistent = "repo_inconsistent" )
Verify-issue Kind values. Each value reads as the failing check's short name; the renderer groups by Kind for the human-friendly summary so users can spot e.g. "all hash mismatches" at once.
const LockTimeoutSeconds = 30
LockTimeoutSeconds bounds the time AcquireSyncLock will wait before giving up. 30 s matches the design doc; a `bacio sync` invocation should complete well within that window, so anything longer means either a stuck sync from a crashed process or a developer-side debugging stall.
const MaxPushRetries = 1
MaxPushRetries hardcodes the design doc's "retry once on non-fast-forward" policy. If observed in the wild we'll revisit.
const SchemaVersion = 1
SchemaVersion is the current sentinel schema version. Bumped when the layout under repos/ changes in a non-backward-compatible way.
const SentinelFilename = "bacio-sync.yaml"
SentinelFilename is the file at the root of a sync repo whose presence flips bacio into sync-repo mode (no auto-register, no `bacio issue create` etc.). Spelled out in the design doc — the file is canonical YAML so it round-trips through the existing emitter.
Variables ¶
var ErrLockTimeout = errors.New("sync: timed out waiting for sync lock; another bacio sync may be running")
ErrLockTimeout is returned when AcquireSyncLock can't get the lock within LockTimeoutSeconds.
var ErrNoConfig = errors.New("no .bacio/config.yaml in project repo")
ErrNoConfig is the sentinel error returned by ReadProjectConfig when .bacio/config.yaml is missing. Callers use this to distinguish "no sync configured here" (a setup-hint case) from "the config exists but is broken" (a real error).
Functions ¶
func AppendRedirect ¶
AppendRedirect adds a new entry to repos/<prefix>/redirects.yaml in `target`, preserving sort order by ChangedAt. The file is rewritten via the canonical emitter so it stays hash-stable and human-reviewable. If the file doesn't exist yet, it's created.
Duplicates (same uuid + old + new) are deliberately allowed — the caller decides whether to dedupe; for instance, two import passes resolving the same collision should each record an entry.
func CommentFile ¶
CommentFile returns the (yaml, md) sibling paths for one comment under an issue folder. The filename format is "<RFC3339-with-colons-as-dashes>--<full-uuid>.{yaml,md}". The colons in the timestamp become dashes so the file is creatable on Windows and case-insensitive filesystems; the dashes-as-separator looks odd at first glance but it's what the design doc specifies and matches what humans see in `ls`.
The full uuid is included (not a short prefix) so concurrent comment adds across machines never collide on filename, even in the astronomically unlikely event of two timestamp-identical UUIDv7 generations.
func ConfigPath ¶
ConfigPath returns the absolute path to a project's .bacio/config.yaml given the project's working-tree root.
func ContentHash ¶
ContentHash returns the canonical "sha256:<hex>" identity of a byte blob. The emitter is what makes the input canonical (sorted keys, LF-only, single trailing newline, always-quoted user strings); this function is the thin wrapper that turns those bytes into the value stored in `sync_state.last_synced_hash` and embedded as `description_hash` / `body_hash` / `content_hash` in the YAML.
We prefix with the algorithm name so a future rotation to (say) blake3 stays observable on disk without a schema change.
func DetectCaseInsensitiveCollisions ¶
DetectCaseInsensitiveCollisions groups folder names that case-fold (NFC-normalised + lower-cased) to the same value. The map's key is the case-folded form; the value is the list of original names that collide. Singleton groups are omitted — only true collisions appear in the result.
Phase 2 doesn't use this directly (it's an import-side check), but the helper sits naturally with the rest of the path utilities and has its own tests, so we land it here. Phase 3's import pipeline is what wires it into the validation step.
func DocumentContentFile ¶
DocumentContentFile is the markdown sibling of doc.yaml.
func DocumentFolder ¶
DocumentFolder returns the slash-separated relative path of a document's folder, e.g. "repos/MINI/docs/auth-overview.md". The filename is used verbatim (with NFC normalisation) — bacio's ValidateDocFilenameStrict already rejects `/`, `\`, NUL, and control chars, so the result is always safe as a single path segment.
func DocumentYAMLFile ¶
DocumentYAMLFile is the doc.yaml inside a doc folder.
func Emit ¶
Emit serialises a top-level Map (or Seq) to canonical YAML bytes: sorted keys, double-quoted user strings, LF line endings, single trailing newline. The hash function downstream relies on this being byte-stable across runs.
Emit only accepts top-level Map or Seq nodes; other top-level shapes don't match anything the sync layer needs to write today.
func FeatureDescriptionFile ¶
FeatureDescriptionFile is the markdown sibling of feature.yaml.
func FeatureFolder ¶
FeatureFolder returns the slash-separated relative path of a feature's folder, e.g. "repos/MINI/features/auth-rewrite". Slugs are NFC-normalised; bacio's slug validator already constrains them to lowercase kebab-case so this is a no-op in practice but cheap.
func FeatureYAMLFile ¶
FeatureYAMLFile is the feature.yaml inside a feature folder.
func IsSyncRepo ¶
IsSyncRepo reports whether the directory at workingTreeRoot contains an bacio-sync.yaml at its root. Tolerant of read errors (e.g. a permission-denied stat returns false rather than an error) because the caller uses this to decide whether to take the sync-mode branch — the sync-mode branch is the safe default if the file is plausibly present.
func IssueDescriptionFile ¶
IssueDescriptionFile is the markdown sibling of issue.yaml.
func IssueFolder ¶
IssueFolder returns the slash-separated relative path of an issue's folder under the sync repo root, e.g. "repos/MINI/issues/MINI-7". The number isn't NFC-normalised (it's a non-negative integer) and the prefix is already constrained by the validator to ASCII alnum.
func IssueYAMLFile ¶
IssueYAMLFile is the issue.yaml inside an issue folder.
func New ¶
func New() string
New is a thin re-export of identity.New so callers inside the sync package don't have to import a second package just for uuid generation. The canonical home for the helper is internal/identity — it lives there so the store layer can consume it without importing internal/sync (which would create a cycle: store → sync → store).
func NormalizeBody ¶
NormalizeBody coerces CRLF and bare-CR line endings to LF so that hash computation is invariant under git's autocrlf checkout behaviour. Bodies (description.md, comment .md, doc content.md) are the user-supplied free-form fields where this can bite: a sync repo cloned on Windows with default core.autocrlf=true comes back as CRLF, and re-hashing that on import would not match the LF bytes we originally wrote.
Apply this to body bytes before both writing them to disk and hashing them, so the hash stored in YAML matches the on-disk bytes regardless of how git delivered the working tree.
func NormalizeNFC ¶
NormalizeNFC returns the NFC-normalised form of s. NFC is the standard "precomposed" Unicode form (é as one code point rather than e + combining acute). We normalise on the way out so the on-disk YAML is canonical regardless of how the user typed it; the DB itself isn't touched in Phase 2.
func RedirectsFile ¶
RedirectsFile is the relative slash-separated path of the redirects file inside a per-repo folder. Used by both load and append so the "where does this live" answer has a single source of truth.
func RepoFolder ¶
RepoFolder is the per-repo folder under the sync repo root.
func RepoYAMLFile ¶
RepoYAMLFile is the per-repo metadata file.
func ResolveLabel ¶
ResolveLabel walks the redirect list to find the current label for (kind, label). Returns (currentLabel, true) when at least one move matched, and ("", false) when the input label has no entries.
A redirect chain can be multi-hop: A → B → C (same uuid). The resolver follows by uuid, not by label, so it terminates correctly even if a user reuses old labels for new records (which the collision rule already forbids in steady state, but defensive code is cheap).
Cycles (rare and only possible from manual file editing) are detected via a seen-uuids set; if we'd revisit a uuid the chain is truncated at the last good label and (label, true) is returned. We don't error out — bad input shouldn't break `bacio issue show OLD-7`.
func WriteProjectConfig ¶
func WriteProjectConfig(projectRoot string, c ProjectConfig) error
WriteProjectConfig writes .bacio/config.yaml at projectRoot with the given config. Creates the .bacio directory if it doesn't yet exist. The output goes through the canonical emitter so it's byte-stable across runs.
func WriteSentinel ¶
WriteSentinel emits a canonical bacio-sync.yaml at the root of repoRoot. Uses the standard emitter so the file is byte-stable across re-init; we keep the create-time of an existing sentinel intact if the file is already there (some unrelated CI step might have re-init'd the repo with a fresh `git init` and we don't want to pretend the sync data is new).
Types ¶
type CloneOptions ¶
CloneOptions controls `bacio sync clone`. LocalPath defaults to `~/.bacio/sync/<basename>` if empty. AllowRenumber gates the "local DB has data for this prefix" preflight; DryRun runs the preview without touching DB or disk.
type CloneResult ¶
type CloneResult struct {
LocalPath string `json:"local_path"`
Remote string `json:"remote"`
DryRun bool `json:"dry_run,omitempty"`
// Import counts (from the underlying ImportResult). When DryRun
// is true, this carries the preview.
Import *ImportResult `json:"import,omitempty"`
// PreviewCollisions captures the projected renumbers/renames a
// full clone would produce. Populated when local DB has data
// for the prefix and AllowRenumber is false (or DryRun is true);
// the caller can render this for user confirmation.
PreviewCollisions *CollisionPreview `json:"preview_collisions,omitempty"`
}
CloneResult is the structured outcome of `bacio sync clone`.
type CollisionPreview ¶
type CollisionPreview struct {
Renumbered []RenumberEntry `json:"renumbered,omitempty"`
Renamed []RenameEntry `json:"renamed,omitempty"`
}
CollisionPreview is the dry-run report produced when `bacio sync clone` detects that the local DB has data that would be renumbered/renamed by the import. Empty fields are emitted but with `omitempty` so a JSON consumer doesn't have to special-case "no churn".
type DanglingRef ¶
type DanglingRef struct {
From string `json:"from"` // e.g. "MINI-7"
FromUUID string `json:"from_uuid"`
Kind string `json:"kind"` // "blocks", "feature", "doc_link"...
TargetLabel string `json:"target_label"`
TargetUUID string `json:"target_uuid"`
}
DanglingRef describes a cross-reference whose target uuid wasn't resolvable on import. The reference is left in place on disk; we just don't write a DB-side edge.
type DeletionEntry ¶
type DeletionEntry struct {
Kind string `json:"kind"`
UUID string `json:"uuid"`
Label string `json:"label,omitempty"`
}
DeletionEntry records one record dropped because its uuid was previously synced but didn't appear in the latest scan.
type Engine ¶
type Engine struct {
// Store is the live SQLite-backed *store.Store. Phase 2 used a
// narrow read-only interface (StoreReader) to avoid an import
// cycle that no longer exists — once Phase 1's identity helper
// moved into internal/identity, sync was free to depend on store
// directly. Tests use store.Open(":memory:") for the real schema.
Store *store.Store
Actor string
DryRun bool
}
Engine is the top-level coordinator for the sync layer. Phase 2 shipped Export; Phase 3 adds Import; Phase 4 will add the pull/commit/push shell as Run().
Actor is recorded against any audit op the sync engine writes (none directly; the cli layer wraps each phase with its own recordOp call, but the field is here so a future internal audit path doesn't have to thread it in twice).
DryRun is honoured (where it makes sense) by every method on Engine. Export honours it by short-circuiting before any filesystem write; Import honours it by rolling back the outer transaction before commit.
func (*Engine) CloneSyncRepo ¶
func (e *Engine) CloneSyncRepo(ctx context.Context, projectRoot string, opts CloneOptions) (*CloneResult, error)
CloneSyncRepo joins an existing sync remote: clones (or validates) the repo at opts.LocalPath, runs the import-only flow, and records the local-path mapping in DB. Refuses without `--allow-renumber` when local DB already has rows that would collide with imported labels.
func (*Engine) Export ¶
Export walks every repo in the DB and writes the canonical YAML + markdown layout under `target`. Phase 2 uses full overwrite — atomic staging, delta computation, and `git mv`-aware rename detection are Phase 4 work. We do, however, only write each file once (the emitter is deterministic, so re-running on an unchanged DB produces byte-identical output).
The ctx parameter is honoured by checking ctx.Err() between repos — per-record cancellation isn't worth the bookkeeping for Phase 2's scale.
func (*Engine) ExportStaged ¶
ExportStaged runs the export pipeline into the working tree at gitRepo.Root, atomically. The scratch dir is a sibling of the target (so os.Rename stays cheap — same filesystem). When DryRun is set we still build the staging dir, compute the ops, but don't apply them.
On error (any stage), the scratch dir is cleaned up; the target is left untouched if the diff hadn't begun applying yet, or in an in-progress state we document on the panic-recovery branch (we don't try to be clever about rollback once mvs have started — the caller's response is "re-run bacio sync").
func (*Engine) Import ¶
Import reads `source` (a sync-repo working tree) and applies it to the local DB. The four phases of the design doc run in one outer SQLite transaction so a partial failure rolls back cleanly:
- Scan: walk repos/<prefix>/ trees and parse every record into memory. Build seenUUIDs[kind] and incoming-labels maps.
- Resolve label collisions: for each kind, find DB rows whose label matches an incoming label but whose uuid differs. Those rows are local-only (otherwise git would have produced a folder conflict). Renumber/rename them, append to redirects.yaml, log audit ops.
- Apply: walk every scanned record and dispatch on the "DB row × sync_state row × seen-on-disk" case table.
- Detect deletions: every uuid in sync_state that wasn't seen on disk → propagate the delete and drop the sync_state row.
After phase 4, RecomputeNextIssueNumber runs once per repo so a remotely-imported MINI-50 doesn't get re-used locally.
DryRun rolls back the outer transaction before commit so the user sees what would happen without permanent effect; the result is still populated.
func (*Engine) InitSyncRepo ¶
func (e *Engine) InitSyncRepo(ctx context.Context, projectRoot string, opts InitOptions) (*InitResult, error)
InitSyncRepo creates a sync repo at opts.LocalPath, exports the project's data into it, and (if opts.Remote is set) wires up origin + .bacio/config.yaml so collaborators can clone. Refuses to run if the remote already has commits.
func (*Engine) Inspect ¶
func (e *Engine) Inspect(ctx context.Context, syncRepoRoot string, opts InspectOptions) (*InspectResult, error)
Inspect walks the sync repo for `opts.Prefix` and returns the requested view. Returns a Go error on missing prefix, missing record, or unreadable filesystem; per-record parse problems propagate as errors here (unlike Verify, where they're findings) because Inspect is "show me one specific thing" — if the parse fails, there's nothing to show.
func (*Engine) Run ¶
func (e *Engine) Run(ctx context.Context, projectRoot string, syncRepo *git.Repo, opts RunOptions) (*RunResult, error)
Run executes the full sync pipeline against an already-cloned sync repo. The caller resolves the project root and the sync repo working tree before calling; this function just orchestrates the pull → import → export → commit → push sequence.
projectRoot is the path of the project repo this user is currently working from. It's only used today as audit context (the actor name already lives on the engine); future expansions might use it for per-project-only sync.
The lock is the caller's responsibility — see AcquireSyncLock. Run does not acquire it itself because the CLI layer has more information (the actual DB path, including the --db override).
func (*Engine) Verify ¶
Verify walks `syncRepoRoot` (the working tree of an bacio-sync-yaml sync repo) and returns the structured result. Returns a Go error only for "couldn't even start" — sync repo missing, filesystem unreadable. Per-record problems land in VerifyResult.Errors / Warnings and are normal output.
Verify never opens a DB. It operates purely on the YAML + description files under repos/, and the redirects.yaml / repo.yaml metadata. The DB is the moving target — sync repo content is the frozen artifact this command audits.
type ExportResult ¶
type ExportResult struct {
Repos int `json:"repos"`
Features int `json:"features"`
Issues int `json:"issues"`
Comments int `json:"comments"`
Documents int `json:"documents"`
Files int `json:"files"`
BytesWritten int64 `json:"bytes_written"`
Target string `json:"target"`
DryRun bool `json:"dry_run,omitempty"`
}
ExportResult is the structured summary of one Export pass — what was (or would have been) written. Phase 2 reports only counts; later phases will likely add per-record diffs and op-level details.
type ImportResult ¶
type ImportResult struct {
Source string `json:"source"`
DryRun bool `json:"dry_run,omitempty"`
Repos int `json:"repos"`
Features int `json:"features"`
Issues int `json:"issues"`
Comments int `json:"comments"`
Documents int `json:"documents"`
Inserted int `json:"inserted"`
Updated int `json:"updated"`
NoOp int `json:"noop"`
Renumbered []RenumberEntry `json:"renumbered,omitempty"`
Renamed []RenameEntry `json:"renamed,omitempty"`
Deleted []DeletionEntry `json:"deleted,omitempty"`
Dangling []DanglingRef `json:"dangling_refs,omitempty"`
Warnings []string `json:"warnings,omitempty"`
}
ImportResult is the structured summary of one Import pass. The counts and lists are populated as the four-phase pipeline runs; `--output json` serialises the whole struct so an agent can react to renumbers / dangling refs / deletions without re-parsing human text.
"Touched" counts cover any record the importer either inserted, updated, or no-op'd. "Renumbered" / "renamed" / "deleted" are the observable side-effects worth surfacing.
type InitOptions ¶
InitOptions controls `bacio sync init`. LocalPath is where the sync repo will be created on disk; Remote is the optional canonical remote URL to register as `origin` and write into the project's .bacio/config.yaml.
type InitResult ¶
type InitResult struct {
LocalPath string `json:"local_path"`
Remote string `json:"remote,omitempty"`
CommitSHA string `json:"commit_sha,omitempty"`
Pushed bool `json:"pushed"`
// First-export counts (from the underlying ExportResult). One
// pointer is enough; we don't need a separate StagedExportResult
// because init is always a full export into an empty tree.
Export *ExportResult `json:"export,omitempty"`
}
InitResult is the structured outcome of `bacio sync init`. Fields match the JSON shape `bacio sync init --output json` emits.
type InspectComment ¶
type InspectComment struct {
Comment *ParsedComment `json:"comment"`
Body string `json:"body"`
}
InspectComment is one comment with its body.
type InspectDocument ¶
type InspectDocument struct {
Document *ParsedDocument `json:"document"`
Content string `json:"content"`
}
InspectDocument is the parsed doc.yaml plus its content.
type InspectFeature ¶
type InspectFeature struct {
Feature *ParsedFeature `json:"feature"`
Description string `json:"description"`
}
InspectFeature is the parsed feature.yaml plus its description body.
type InspectIssue ¶
type InspectIssue struct {
Issue *ParsedIssue `json:"issue"`
Description string `json:"description"`
Comments []*InspectComment `json:"comments,omitempty"`
}
InspectIssue carries the parsed YAML and the loaded body so the human-text renderer can produce a clean read-out without re-parsing markdown. Comments are surfaced too — they're cheap and a common thing to want when debugging.
type InspectOptions ¶
type InspectOptions struct {
Prefix string
Issue string // issue label, e.g. "MINI-7" — exact match against folder name
Feature string // feature slug
Document string // document filename
}
InspectOptions selects what Inspect returns. Exactly one of Issue / Feature / Document is non-empty when picking a single record; leaving all three empty produces a per-prefix summary.
type InspectRepoSummary ¶
type InspectRepoSummary struct {
Repo *ParsedRepo `json:"repo"`
Issues int `json:"issues"`
Features int `json:"features"`
Documents int `json:"documents"`
Comments int `json:"comments"`
RecentRedirects []Redirect `json:"recent_redirects,omitempty"`
}
InspectRepoSummary is what `bacio sync inspect <prefix>` (no flags) returns: a parsed repo.yaml plus per-kind counts and a list of recent renumbers/renames driven from the redirects.yaml file. We cap the recent-redirects list so a long history doesn't drown the summary.
type InspectResult ¶
type InspectResult struct {
SyncRepo string `json:"sync_repo"`
Prefix string `json:"prefix"`
RepoSummary *InspectRepoSummary `json:"repo_summary,omitempty"`
Issue *InspectIssue `json:"issue,omitempty"`
Feature *InspectFeature `json:"feature,omitempty"`
Document *InspectDocument `json:"document,omitempty"`
}
InspectResult is the structured outcome of one Inspect call. Exactly one of the four pointer fields is populated.
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node is the union of value shapes the emitter understands. Production callers build these via the Map / Seq / Str / Int / Bool / Time helpers rather than constructing Node values directly, which keeps the wire types invisible to the rest of the package.
func BuildRedirectYAML ¶
BuildRedirectYAML produces the canonical Node tree for a sorted redirect list. Exposed so the import pipeline can compute the final YAML bytes at the same moment as it persists the DB-side changes (writing to disk happens later, when staging is real).
func Int ¶
Int wraps an integer. Emitted unquoted; safe because integers can't be misread as YAML 1.1 booleans or other ambiguous scalars.
func Map ¶
Map wraps a sequence of (key, value) pairs. The emitter sorts keys alphabetically before writing for hash stability — pair order at construction time is irrelevant.
func Null ¶
func Null() Node
Null emits a YAML null. Used sparingly — most "absent" fields are omitted from the map entirely.
type Pair ¶
Pair is a (key, value) tuple used to build maps. We export this rather than letting callers stuff a Go map[string]Node directly so callers pick the order they like in the source code (the emitter sorts at emit time anyway, but readability wins).
type ParsedComment ¶
type ParsedComment struct {
UUID string `yaml:"uuid" json:"uuid"`
Author string `yaml:"author" json:"author"`
BodyHash string `yaml:"body_hash" json:"body_hash"`
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
}
ParsedComment is the on-disk shape of a comment .yaml file.
func ParseCommentYAML ¶
func ParseCommentYAML(b []byte) (*ParsedComment, error)
ParseCommentYAML decodes a comment .yaml file's bytes.
type ParsedDocLink ¶
type ParsedDocLink struct {
Kind string `yaml:"kind" json:"kind"` // "issue" | "feature"
TargetLabel string `yaml:"target_label" json:"target_label"`
TargetUUID string `yaml:"target_uuid" json:"target_uuid"`
}
ParsedDocLink is one entry in doc.yaml's `links:` sequence.
type ParsedDocument ¶
type ParsedDocument struct {
UUID string `yaml:"uuid" json:"uuid"`
Filename string `yaml:"filename" json:"filename"`
Type string `yaml:"type" json:"type"`
SourcePath string `yaml:"source_path" json:"source_path"`
Links []ParsedDocLink `yaml:"links" json:"links"`
ContentHash string `yaml:"content_hash" json:"content_hash"`
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
}
ParsedDocument is the on-disk shape of doc.yaml.
func ParseDocumentYAML ¶
func ParseDocumentYAML(b []byte) (*ParsedDocument, error)
ParseDocumentYAML decodes doc.yaml bytes.
type ParsedFeature ¶
type ParsedFeature struct {
UUID string `yaml:"uuid" json:"uuid"`
Slug string `yaml:"slug" json:"slug"`
Title string `yaml:"title" json:"title"`
DescriptionHash string `yaml:"description_hash" json:"description_hash"`
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
}
ParsedFeature is the on-disk shape of feature.yaml.
func ParseFeatureYAML ¶
func ParseFeatureYAML(b []byte) (*ParsedFeature, error)
ParseFeatureYAML decodes feature.yaml bytes.
type ParsedIssue ¶
type ParsedIssue struct {
UUID string `yaml:"uuid" json:"uuid"`
Number int64 `yaml:"number" json:"number"`
Title string `yaml:"title" json:"title"`
State string `yaml:"state" json:"state"`
Assignee string `yaml:"assignee" json:"assignee"`
Tags []string `yaml:"tags" json:"tags"`
PRs []string `yaml:"prs" json:"prs"`
Feature *ParsedRef `yaml:"feature,omitempty" json:"feature,omitempty"`
Relations ParsedRelations `yaml:"relations" json:"relations"`
DescriptionHash string `yaml:"description_hash" json:"description_hash"`
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
}
ParsedIssue is the on-disk shape of issue.yaml.
func ParseIssueYAML ¶
func ParseIssueYAML(b []byte) (*ParsedIssue, error)
ParseIssueYAML decodes issue.yaml bytes. Slugs/labels in cross-references are NFC-normalised; uuids are passed through unchanged (they're already 8-4-4-4-12 hex).
type ParsedRedirect ¶
type ParsedRedirect struct {
Kind string `yaml:"kind" json:"kind"` // "issue" | "feature" | "document"
Old string `yaml:"old" json:"old"`
New string `yaml:"new" json:"new"`
UUID string `yaml:"uuid" json:"uuid"`
ChangedAt time.Time `yaml:"changed_at" json:"changed_at"`
Reason string `yaml:"reason" json:"reason"`
}
ParsedRedirect is one entry in redirects.yaml. The file is a top-level YAML sequence of these.
func ParseRedirectsYAML ¶
func ParseRedirectsYAML(b []byte) ([]ParsedRedirect, error)
ParseRedirectsYAML decodes redirects.yaml bytes. The file is a top-level YAML sequence; an empty/missing file is the caller's responsibility to skip — this function expects valid bytes.
type ParsedRef ¶
type ParsedRef struct {
Label string `yaml:"label" json:"label"`
UUID string `yaml:"uuid" json:"uuid"`
}
ParsedRef is a {label, uuid} cross-reference. Both fields are always present in emitted YAML; the importer treats uuid as canonical and label as a stale-tolerant hint.
type ParsedRelations ¶
type ParsedRelations struct {
Blocks []ParsedRef `yaml:"blocks" json:"blocks"`
RelatesTo []ParsedRef `yaml:"relates_to" json:"relates_to"`
DuplicateOf []ParsedRef `yaml:"duplicate_of" json:"duplicate_of"`
}
ParsedRelations is the `relations: {blocks, relates_to, duplicate_of}` map inside issue.yaml. Each bucket is always emitted (with `[]` when empty), so missing keys here means hand-editing or schema drift.
type ParsedRepo ¶
type ParsedRepo struct {
UUID string `yaml:"uuid" json:"uuid"`
Prefix string `yaml:"prefix" json:"prefix"`
Name string `yaml:"name" json:"name"`
RemoteURL string `yaml:"remote_url" json:"remote_url"`
NextIssueNumber int64 `yaml:"next_issue_number" json:"next_issue_number"`
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
}
ParsedRepo is the on-disk shape of repos/<prefix>/repo.yaml.
JSON tags mirror the YAML field names so `bacio sync inspect`'s `-o json` output matches the canonical on-disk schema rather than the Go field names. The yaml/JSON contract is that both speak the same vocabulary — we just use Go's idiomatic PascalCase internally.
func ParseRepoYAML ¶
func ParseRepoYAML(b []byte) (*ParsedRepo, error)
ParseRepoYAML decodes repo.yaml bytes into a ParsedRepo with strict typing. Returns an error on unknown fields, type mismatches, or invalid YAML. NFC-normalises string fields used as labels.
type ProjectConfig ¶
type ProjectConfig struct {
Sync ProjectSync `yaml:"sync"`
}
ProjectConfig is the parsed shape of .bacio/config.yaml — the reverse pointer that lets a project repo find its sync remote. Checked into the project repo so every collaborator agrees on where the data lives.
func ReadProjectConfig ¶
func ReadProjectConfig(projectRoot string) (*ProjectConfig, error)
ReadProjectConfig parses .bacio/config.yaml at projectRoot. Returns ErrNoConfig if the file is missing.
type ProjectSync ¶
type ProjectSync struct {
Remote string `yaml:"remote"`
}
ProjectSync holds the sync-specific configuration. v1 only carries the canonical remote URL; later we may add a `mode` field to flip in-repo vs external sync. Forward-compatible: an older bacio reading a future config with extra keys errors loudly thanks to KnownFields(true), so we'll bump SchemaVersion when the time comes.
type Redirect ¶
type Redirect struct {
Kind string `json:"kind"`
Old string `json:"old"`
New string `json:"new"`
UUID string `json:"uuid"`
ChangedAt time.Time `json:"changed_at"`
Reason string `json:"reason"`
}
Redirect describes a single label move recorded in repos/<prefix>/redirects.yaml. The on-disk file is a chronologically-sorted top-level YAML sequence of these. Every renumber (issue) and every rename (feature/document) appends a new entry; nothing is ever pruned in v1.
`Reason` is one of the small set the design doc spelled out: "label_collision" (the import side gives up the label to a just-imported uuid that's already in git), "manual_rename" (the user explicitly renamed in DB, propagated on next export), or "label_changed_remotely" (an incoming file uses a different label for a uuid bacio already knows about).
UUID is the canonical identity — chains of (old → new) for the same uuid resolve forward to the current label.
func LoadRedirects ¶
LoadRedirects reads repos/<prefix>/redirects.yaml from `target` (the sync repo root) and returns the parsed entries. A missing file is fine — returns an empty slice and no error. The strict parser handles unknown fields and type mismatches.
Entries are returned in the order they appear in the file. The emit side keeps them sorted by ChangedAt; importers rely on this during forward-chase resolution but tolerate any order (the chain follows uuid references, not file order).
type ReleaseFunc ¶
type ReleaseFunc func() error
ReleaseFunc releases an acquired sync lock. Idempotent — safe to call more than once; subsequent calls are no-ops.
func AcquireSyncLock ¶
func AcquireSyncLock(dbPath string) (ReleaseFunc, error)
AcquireSyncLock takes an exclusive flock-style lock on <dbPath>.sync.lock. Returns a release function the caller must invoke (typically via defer) to drop the lock. On Windows the implementation is a best-effort no-op with a warning to stderr — per the implementation doc's "v1 might accept no lock on Windows" note. Switching to LockFileEx is a follow-up.
The lock file is created on first acquire and left in place afterwards (lifetime tied to the DB, not the sync run). Removing it would require a release-time race with anyone waiting for the lock; the cost of one stale empty file is minimal.
type RenameEntry ¶
type RenameEntry struct {
Kind string `json:"kind"` // "feature" | "document"
Prefix string `json:"prefix"`
UUID string `json:"uuid"`
Old string `json:"old"`
New string `json:"new"`
}
RenameEntry records one feature/document rename driven by the collision-resolution phase.
type RenumberEntry ¶
type RenumberEntry struct {
Prefix string `json:"prefix"`
UUID string `json:"uuid"`
OldNumber int64 `json:"old_number"`
NewNumber int64 `json:"new_number"`
}
RenumberEntry records one issue renumber driven by the collision-resolution phase.
type RunOptions ¶
RunOptions controls a single steady-state `bacio sync` invocation. Each "skip" flag short-circuits one phase of the pipeline. DryRun is a hard skip on writes (DB rolls back, no commit, no push) but still produces a result the user can inspect.
type RunResult ¶
type RunResult struct {
Import *ImportResult `json:"import,omitempty"`
Export *StagedExportResult `json:"export,omitempty"`
Commit string `json:"commit,omitempty"`
Pushed bool `json:"pushed"`
DryRun bool `json:"dry_run,omitempty"`
// Warnings buffer non-fatal hiccups encountered during the run
// (e.g. last_sync_at update failure). The user-visible command
// still succeeds; the warnings just bubble up via stderr.
Warnings []string `json:"warnings,omitempty"`
}
RunResult is the structured outcome of one `bacio sync` invocation. All sub-results are pointers so absence (skipped phase, no changes) is unambiguous in JSON.
type Sentinel ¶
type Sentinel struct {
SchemaVersion int `yaml:"schema_version"`
CreatedAt time.Time `yaml:"created_at"`
}
Sentinel is the parsed shape of bacio-sync.yaml.
func ReadSentinel ¶
ReadSentinel parses the bacio-sync.yaml at the given path. Returns the parsed Sentinel or an error wrapping the underlying parse failure.
type StagedExportResult ¶
type StagedExportResult struct {
*ExportResult
// Op counts after diff application. Renames are applied with git mv
// so git history follows the rename; writes are os.WriteFile and
// deletes are os.RemoveAll on the affected folder.
Renames int `json:"renames"`
Writes int `json:"writes"`
Deletes int `json:"deletes"`
}
StagedExportResult mirrors ExportResult but adds the per-op counts the steady-state path needs to surface for the commit message.
type VerifyIssue ¶
type VerifyIssue struct {
Kind string `json:"kind"`
Path string `json:"path,omitempty"`
Detail string `json:"detail"`
Related []string `json:"related,omitempty"`
}
VerifyIssue is one finding. Path is sync-repo-relative (slash separated, matching the layout doc). Related is optional — used by uuid-collision findings to point at the second offending file, by dangling-reference findings to identify the missing target uuid, and so on.
type VerifyResult ¶
type VerifyResult struct {
SyncRepo string `json:"sync_repo"`
Repos int `json:"repos"`
Features int `json:"features"`
Issues int `json:"issues"`
Documents int `json:"documents"`
Comments int `json:"comments"`
// Errors are structural problems that should fail verify (parse
// errors, uuid collisions, orphan comment files, repo-uuid
// inconsistencies, redirect cycles). Non-empty Errors → exit
// non-zero from the CLI wrapper.
Errors []VerifyIssue `json:"errors,omitempty"`
// Warnings are soft problems that don't necessarily indicate a
// broken sync repo (dangling cross-references, body-hash drift).
// They surface to the user but don't change exit status.
Warnings []VerifyIssue `json:"warnings,omitempty"`
}
VerifyResult is the structured summary of one Verify pass. The kind-counts at the top let users sanity-check that Verify saw what they expected ("did it pick up my new repo?"), while Errors / Warnings carry the actionable findings.