offline

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: CC0-1.0 Imports: 30 Imported by: 0 modules, 0 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 offline implements operations performed with the server stopped.

Index

Constants

View Source
const SetStatusContains = scrubContains

SetStatusContains is the SetResult.Status of a set that still holds purged content (only reported by --check; a real run rewrites such sets).

Variables

View Source
var ErrUsage = errors.New("invalid input")

ErrUsage marks a refusal caused by an invalid answer or argument the user can correct (an invalid `tkr init --mcp-token` expiry). It is wrapped in a domain validation error; the CLI reports it as a usage error (exit 2).

Functions

func Backup

func Backup(ctx context.Context, e *Env) (_ backup.SnapshotInfo, err error)

Backup replays purge intents, confirms WAL truncation and takes a manual backup.

func CleanRecoveryFiles

func CleanRecoveryFiles(ctx context.Context, paths config.Paths, keep, assumeYes bool,
	prompt func(q string, defaultYes bool) (bool, error)) (mode string, err error)

CleanRecoveryFiles handles this host's client recovery files, which may hold purged text: saved pending requests and editor drafts (A§12.6 step 8, R4-1). keep returns "kept" without touching anything; no files returns "none"; otherwise the user is asked (default yes, skipped with assumeYes) and the files are deleted ("deleted"). Answering no returns ("", nil): the caller must then leave the ledger records pending.

AIDEV-NOTE: SECURITY. Every non-directory entry counts, not only *.json/*.md: an interrupted atomic write leaves a temp file with the same body. Deletion removes the directory entry itself (never follows a symlink).

func ListBackups

func ListBackups(e *Env) ([]backup.SnapshotInfo, error)

ListBackups reads the configured snapshot inventory without taking the lock.

func Migrate

func Migrate(ctx context.Context, e *Env, statusOnly bool) (err error)

Migrate reports schema status or migrates and completes live purge recovery.

func PasswdReset

func PasswdReset(ctx context.Context, e *Env, passwordStdin bool) (err error)

PasswdReset resets the owner password with the server stopped (A§12.8): it replaces the password, revokes every token and web session, and writes a fresh owner token to the owner token file.

AIDEV-NOTE: SECURITY. The new password is read only from the terminal (twice) or one stdin line, never from argv or the environment, and is never logged or persisted: only its hash reaches the DB. The owner token secret exists only in memory until the owner.token file is written. A crash after the commit but before the file write leaves a file holding a revoked token; the reset is re-runnable (it needs no current password) and the CLI says so on a write failure (A§12.8, crash point "passwd:committed").

func RepairLedger

func RepairLedger(ctx context.Context, e *Env) (dropped []int, err error)

RepairLedger is `tkr purge --repair-ledger` (A§12.6): under the lock and the owner password, rewrite the ledger from its valid records, then replay it on the live database and checkpoint. It returns the dropped line numbers.

func RestoreResume

func RestoreResume(ctx context.Context, e *Env) error

RestoreResume finishes an interrupted restore or import swap. It cannot rerun the owner-token callback, so when a minted token was never saved it says so.

func RestoreRollback

func RestoreRollback(ctx context.Context, e *Env) error

RestoreRollback puts the old database back after an interrupted restore or import, before its old set was deleted.

func WithCrashHook

func WithCrashHook(ctx context.Context, h func(point string) error) context.Context

WithCrashHook installs a context-scoped test hook for offline crash points. A hook error stops the operation at that boundary for recovery testing.

Types

type Env

type Env struct {
	Paths        config.Paths
	Server       *config.Server
	Clock        clock.Clock
	In           io.Reader
	Out, Err     io.Writer
	TTY          bool
	ReadPassword func(prompt string) (string, error)
	Confirm      func(prompt string, defaultYes bool) (bool, error)
	Logger       *slog.Logger
}

Env supplies configuration, time and terminal interactions to offline commands. A nil Server is permitted only during init; a nil Clock uses real time.

type ImportResult

type ImportResult struct {
	Counts map[string]int
	Aside  string
}

ImportResult describes a published import.

func Import

func Import(ctx context.Context, e *Env, path string, yes bool) (_ ImportResult, err error)

Import replaces a freshly initialized database with the contents of an export file (A§12.5). The live database is only read until the swap.

AIDEV-NOTE: CRASH-SAFETY ORDER, mirrors Restore. Do not reorder:

  1. begin(refuseJournals): lock, no swap journal, CleanupTemps.
  2. read the live DB (must exist, be empty of user data); close it.
  3. decode the file with UseNumber, check header, re-validate titles/notes.
  4. confirm; stage a NEW database under StagingDir; ImportData in one tx; then (BF25, approved) RecordSystemOp in a second staged tx; replay the ledger, Reconcile, CheckAll, integrity/foreign-key/FTS checks; close.
  5. backup.Swap{Kind: import}. Only after this point is the live DB touched; an interrupted swap is finished or undone by `tkr restore --resume` or `--rollback`. Any failure before it removes the staging directory.

type InitOptions

type InitOptions struct {
	Timezone                                           string
	PasswordStdin, NoSystemd, Yes, MCPToken, UnitsOnly bool
	LocaltimePath, PasswdPath                          string
	Systemctl                                          func(ctx context.Context, args ...string) error
	Binary                                             string
	// Nix profile bin directories searched for a link to the binary; nil means the standard ones for this user.
	ProfileBins []string
}

InitOptions controls first-run initialization and unit regeneration.

type InitResult

type InitResult struct {
	DB, OwnerToken, MCPToken string
	AllowPlainLoopback       bool
}

InitResult contains file paths, never bearer secrets.

func Init

func Init(ctx context.Context, e *Env, o InitOptions) (result InitResult, err error)

Init bootstraps a private instance, publishing the DB only after its owner token is durable. UnitsOnly reads configuration and installs units exclusively.

type PurgeOptions

type PurgeOptions struct {
	Target                         string // "task" or "entry"
	ID                             int64
	WithEntries, KeepRecoveryFiles bool
	Yes                            bool
}

PurgeOptions are the arguments and flags of `tkr purge task|entry ID`.

type PurgeReport

type PurgeReport struct {
	TaskIDs, EntryIDs, LinkedNotIncluded []int64
	Changed                              bool
	Sets                                 []SetResult
	RecoveryFiles                        string // the mode on the complete lines; "" if not completed now
	Complete                             bool   // no pending ledger record remains
}

PurgeReport is the outcome of a purge run.

func Purge

func Purge(ctx context.Context, e *Env, o PurgeOptions) (rep PurgeReport, err error)

Purge is A§12.6 steps 1-10: scrub a tombstoned task or entry from the live database and every backup set, offline.

AIDEV-NOTE: SECURITY-CRITICAL ORDER (S4, R3-2, R4-1, BF26, BF27). Do not reorder:

  1. begin(refuseJournals): lock, refuse swap/scrub journals, CleanupTemps.
  2. Open the store, verify the password on a TTY (before ANY file other than the DB is read), then confirm the target from READ-ONLY queries: a declined or refused purge must not touch the ledger (OpenLedger itself truncates a torn tail) or write an ops row.
  3. OpenLedger ONCE (a damaged ledger refuses), replay it on the live DB and checkpoint, then service.PurgeLive. PurgeLive appends the pending record INSIDE its writer transaction, before ScrubEntities: the intent is durable before any scrub can commit, and a crash anywhere after is finished by the next replay.
  4. Confirmed wal_checkpoint(TRUNCATE), so no purged byte survives in the live -wal. Then a fresh (clean) prescrub snapshot, close the store, and scrubSets over every other backup set and pre-restore/pre-import set.
  5. CleanRecoveryFiles, and ONLY THEN complete lines for all pending records (completeScrub): any earlier failure leaves the records pending so a rerun or `tkr scrub-backups` finishes the job. Never append `complete` before every set is clean/rewritten.

type RestoreResult

type RestoreResult struct {
	Snapshot, Aside  string
	OwnerTokenMinted bool
}

RestoreResult describes a published restore.

func Restore

func Restore(ctx context.Context, e *Env, snapshot string, yes bool) (_ RestoreResult, err error)

Restore replaces the live database with a snapshot (A§12.2 steps 0-6).

AIDEV-NOTE: CRASH-SAFETY ORDER. Do not reorder these steps:

  1. begin(refuseJournals): lock, refuse an existing swap journal, CleanupTemps.
  2. confirm, BEFORE any copy; resolve/validate BEFORE the live DB is opened.
  3. Stage (the original is only read, R4-5) -> Verify the staged copy -> schema <= binary -> Migrate the staged copy.
  4. Only now open the live DB (read auth_state, tokens, sequences). Opening can checkpoint the live WAL, so it must follow every refusal above.
  5. stampRestore: one writer tx on the STAGED store only.
  6. system.restore op, ledger replay, reconcile, CheckAll, integrity+FTS checks, close, assert no sidecars, fsync. Nothing live is touched yet.
  7. backup.Swap with OwnerTokenPending set when a token was minted. The owner.token file is written ONLY by onInstalled: after the staged DB is installed and BEFORE the journal is removed (R4-10). A crash before that leaves the old DB + old token consistent (rollback); a crash after "installed" is finished by --resume, which cannot re-run onInstalled and therefore reports a lost token (OwnerTokenPending) so the user can run `tkr passwd --reset`. The secret is never journaled.

type ScrubOptions

type ScrubOptions struct{ Check, Resume, KeepRecoveryFiles, Yes bool }

ScrubOptions are the flags of `tkr scrub-backups`.

type SetResult

type SetResult struct{ Path, Status, Err string } // Status: clean | contains | rewritten | error

SetResult is the outcome for one backup file set.

func ScrubBackups

func ScrubBackups(ctx context.Context, e *Env, o ScrubOptions) (results []SetResult, err error)

ScrubBackups is A§12.7: apply the purge ledger to every backup set.

AIDEV-NOTE: SECURITY-CRITICAL ORDER (R4-8, R2-7). Do not reorder:

  1. begin(allowScrubJournal): lock, refuse swap.journal, and NO CleanupTemps yet (a scrub.journal's New/Aside must survive until it is resumed).
  2. password, before any file is touched; only then ResumeSwap of an existing scrub.journal, and only then CleanupTemps.
  3. OpenLedger once (BF26) -> replay live + confirmed checkpoint -> prescrub snapshot (taken AFTER the live scrub, so it is clean) -> scrubSets. A set judged clean by the logical replay but whose ORIGINAL -wal/-shm is non-empty is NOT clean (superseded WAL frames may hold purged text): it is reported "contains" under --check and rewritten through the swap otherwise, which removes the sidecars.
  4. Completion lines are appended LAST, only when every set is clean/rewritten, the ledger is healthy and CleanRecoveryFiles returned a mode. Any earlier exit leaves the records pending so the next run finishes the job.

Check mode (P9) never snapshots, never cleans recovery files and never writes the ledger.

Jump to

Keyboard shortcuts

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