config

package
v0.0.44 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: Apache-2.0, MIT Imports: 14 Imported by: 1 module, 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.

README

draft/config

Resolves runtime configuration from command-line flags, environment variables and defaults, in that order of precedence.

Go reference Website

Contents

Install

go get github.com/sebastienrousseau/draft@latest
import "github.com/sebastienrousseau/draft/config"

Quick start

package main

import (
	"fmt"
	"os"

	"github.com/sebastienrousseau/draft/config"
)

func main() {
	// Environment sits between defaults and flags.
	os.Setenv("DRAFT_NUM_CTX", "2048")

	// Flags are the already-parsed command-line values. A zero value means
	// "not set", so the environment or the default wins for that field.
	cfg := config.Load(config.Flags{Engine: config.EngineOllama})

	fmt.Println(cfg.Engine)        // ollama   — from the flag
	fmt.Println(cfg.ContextLength) // 2048     — from the environment
	fmt.Println(cfg.OllamaModel)   // gemma3:4b — from the default

	// Constructing a Config directly is fine for tests and embedding: nothing
	// in the library requires Load to have run.
	test := config.Config{HomeDir: os.TempDir(), DraftsDir: os.TempDir(), MaxContinue: 3}
	fmt.Println(test.MaxContinue)
}

API

Symbol Signature Purpose
Config struct The fully-resolved run configuration shared across packages
Flags struct Raw command-line values before merging
Load func(flags Flags) Config Defaults → environment → flags
TrustProjectConfig func() (string, error) Trust ./draft.toml as it now stands; returns its path
EngineAuto / EngineOllama const Engine-selection sentinels; any other value names a session provider
Default* const Every default in one place: models, context length, retries, concurrency, call timeout
OllamaHost const http://127.0.0.1:11434
FocusBlock const 25 * time.Minute, the dashboard's focus timer
Config.Warnings []string Problems recovered from during resolution; print them

Precedence

Flags beat environment variables. Environment variables beat defaults.

Load treats a zero-valued Flags field as absent, so partially-populated Flags is the normal case — cmd/draft passes whatever the user typed and lets everything else fall through.

Nothing fails silently

Every numeric variable is clamped at both ends — DRAFT_NUM_CTX to [512, 1048576], DRAFT_EXTRACT_CONCURRENCY to [1, 32], and so on. A floor alone leaves a fat-fingered or hostile value free to exhaust memory; a ceiling alone leaves it free to starve a generation.

When a value is rejected, the default is used and the reason is appended to Config.Warnings, which cmd/draft prints to stderr. A tunable you believe took effect but did not is worse than one that was refused outright.

Three resolutions can warn:

Situation Behaviour
os.UserHomeDir fails (no HOME — routine under systemd, cron, containers) Falls back to the working directory, then to os.TempDir. SourcesDir and DraftsDir are always absolute, so drafts can never land in whatever directory the process started in
OLLAMA_HOST is not a valid http/https URL Refused in favour of the default rather than concatenated into a request URL. A bare host:port is normalised, not rejected
OLLAMA_HOST is not loopback Accepted, but reported — draft is documented as working offline, so a remote host means prompts and verbatim source text leave the machine

Load never returns an error: a run should not be blocked by a bad tunable it can recover from. Warnings is how it stays honest about having recovered.

Environment variables

Variable Default Purpose
DRAFT_ENGINE auto Backend selection
DRAFT_MODEL_SESSION — Session-provider model override
DRAFT_MODEL — Sets all three Ollama models at once
DRAFT_WRITE_MODEL gemma3:4b Ollama writing model
DRAFT_EXTRACT_MODEL gemma3:4b Ollama claim-extraction model
DRAFT_EDIT_MODEL gemma3:4b Ollama surgical-review model
DRAFT_NUM_CTX 8192 Ollama context window (floor 512)
DRAFT_NUM_PREDICT 6000 Ollama output-token ceiling (floor 1024)
DRAFT_WRITE_RETRIES 2 Rewrite attempts on rule violations
DRAFT_MAX_CONTINUE 3 Continuations on a length-limited stop
DRAFT_EXTRACT_CONCURRENCY 4 Parallel extraction workers (max 32)
DRAFT_CALL_TIMEOUT 1800 Seconds bounding one generation call; 0 disables
DRAFT_EXPERIMENTAL — 1 to let auto use experimental providers
OLLAMA_HOST http://127.0.0.1:11434 Ollama server address

DRAFT_CLAUDE_MODEL is a deprecated alias for DRAFT_MODEL_SESSION, read only when the latter is unset. Config.Site is the publisher identity: the [site] section of a config file, overridden by DRAFT_SITE_*. The key names and the variables are defined once, in frontmatter.

A draft.toml in the working directory is read only once it is trusted: TrustProjectConfig records its SHA-256 and path beside the user config, and an edit lapses the trust. Until then Load ignores it and says so in Config.Warnings. The user config and a DRAFT_CONFIG file need no trust.

License

Licensed under either of Apache License 2.0 or MIT License, at your option. © Sebastien Rousseau.

Back to top ↑

Documentation

Overview

Package config resolves runtime configuration from command-line flags, environment variables, an optional draft.toml config file, and sensible defaults, in that order of precedence.

Index

Examples

Constants

View Source
const (
	// EngineAuto picks the first installed session provider and falls back to
	// Ollama if a call fails (offline). This is the default.
	EngineAuto = "auto"
	// EngineOllama forces the local Ollama backend and never touches a session
	// CLI or the network.
	EngineOllama = "ollama"
)

Engine selection sentinels. Any other value names a specific session provider (claude, codex, agy, copilot, cursor-agent, amp, crush, goose, grok, ...).

View Source
const (
	// DefaultReader is the fast plain-text reader; see internal/pdf.Readers.
	DefaultReader = "pdftotext"

	DefaultOllamaModel        = "gemma3:4b"
	DefaultExtractModel       = "gemma3:4b"
	DefaultEditModel          = "gemma3:4b"
	DefaultContextLen         = 8192
	DefaultPredictLen         = 6000
	DefaultWriteRetries       = 2
	DefaultMaxContinue        = 3
	DefaultExtractConcurrency = 4
	OllamaHost                = "http://127.0.0.1:11434"
	FocusBlock                = 25 * time.Minute
	// DefaultCallTimeout bounds a single generation call. Generation is slow —
	// a full article on a small local model can run for many minutes — so the
	// ceiling is generous; its job is only to stop a wedged provider CLI or a
	// black-holed HTTP connection from hanging the run forever. Set
	// DRAFT_CALL_TIMEOUT=0 to disable it.
	DefaultCallTimeout = 30 * time.Minute
)

Defaults captured as constants so they are documented in one place.

All three Ollama stages default to gemma3:4b. On a memory-constrained machine a single shared model means the server never swaps a second 4B model in and out between extraction and writing. gemma also follows the writing brief far more closely than qwen3:4b, which tended to overshoot the word budget and leak its own planning text into the article.

Variables

This section is empty.

Functions

func TrustProjectConfig added in v0.0.44

func TrustProjectConfig() (string, error)

TrustProjectConfig records the draft.toml in the working directory as trusted in its current form, and returns its path. Any later edit lapses the trust. It replaces an earlier record for the same path rather than adding a second one.

Types

type Config

type Config struct {
	Engine string // "auto", "ollama", or a session provider name
	// Per-stage engine overrides. Empty means "use Engine". Extraction is a
	// dozen cheap, mechanical calls per paper while writing is one
	// quality-critical call, so routing them separately lets a local model do
	// the bulk without spending session quota on it.
	ExtractEngine string // DRAFT_EXTRACT_ENGINE
	WriteEngine   string // DRAFT_WRITE_ENGINE
	EditEngine    string // DRAFT_EDIT_ENGINE

	// Reader names the document reader: "pdftotext" (default) or "docling".
	// See internal/pdf for what each trades.
	Reader string // DRAFT_READER

	// Style is the editorial policy the writer follows and the validator
	// enforces: word band, banned vocabulary, language variant. It defaults
	// to draft's house style and is replaced by a --style / DRAFT_STYLE file.
	Style rules.Style
	// StylePath is the file the style was loaded from, for display and doctor.
	StylePath string

	Model        string // session-provider model override ("" = provider default)
	OllamaModel  string // writing model for the Ollama backend
	ExtractModel string // claim-extraction model for the Ollama backend
	EditModel    string // surgical-review model for the Ollama backend

	ContextLength      int
	PredictLength      int
	WriteRetries       int
	MaxContinue        int // max length-driven continuations for a single generation
	ExtractConcurrency int // parallel claim-extraction workers (session engines only)
	ForceNew           bool
	Merge              bool // combine every input into one draft instead of queueing
	Resume             bool // reuse a verified claim ledger from an earlier attempt
	KeepArtifacts      bool // keep prompt/ledger files beside a successful draft
	Experimental       bool // let auto-selection consider experimental providers
	// StrictNumbers blocks a save when the article carries a number that
	// appears in no verified claim, instead of only warning.
	StrictNumbers bool
	// SecondGate runs an opt-in semantic second pass over the verified claims:
	// a local model judges whether each claim's quote actually supports it, and
	// unsupported claims are dropped before writing. Off by default; the
	// verbatim gate is always the primary check.
	SecondGate bool

	// SignCert and SignKey are PEM paths for a C2PA signing certificate chain
	// (leaf first) and its private key. When both are set and c2patool is
	// installed, draft signs each article's manifest into a detached .c2pa
	// credential beside the set. Empty (the default) leaves the manifest an
	// unsigned definition, exactly as before. SignAlg overrides the default
	// signature algorithm (es256).
	SignCert   string
	SignKey    string
	SignAlg    string
	OllamaHost string

	// CallTimeout bounds a single generation call (0 = no timeout).
	CallTimeout time.Duration

	HomeDir    string
	SourcesDir string
	DraftsDir  string
	// CacheDir holds cached claim extractions, addressed by content. Empty
	// disables caching entirely.
	CacheDir string

	// Site is the publisher identity stamped into generated frontmatter:
	// the [site] section of a config file, overridden by DRAFT_SITE_*. It is
	// empty unless one of them sets it.
	Site frontmatter.Site

	// Version is the release of draft that is running, set by the binary
	// rather than read from the environment. It is written into every
	// article's provenance, so a reader can tell which draft made it.
	Version string

	// Warnings records configuration problems that were recovered from rather
	// than fatal: an unreadable home directory, an out-of-range tunable, a
	// non-loopback Ollama host. The CLI prints them to stderr so a silent
	// fallback is never mistaken for the configuration the user asked for.
	Warnings []string
}

Config is the fully-resolved run configuration shared across packages.

func Load

func Load(flags Flags) Config

Load builds a Config from defaults, overlays environment variables, then overlays the already-parsed flag values passed in from the caller.

Example

Flags win over environment variables, which win over defaults.

package main

import (
	"fmt"

	"github.com/sebastienrousseau/draft/config"
)

func main() {
	cfg := config.Load(config.Flags{Engine: "ollama", ContextLength: 2048})
	fmt.Println(cfg.Engine, cfg.ContextLength)
}
Output:
ollama 2048

type Flags

type Flags struct {
	Engine        string
	ExtractEngine string
	WriteEngine   string
	Reader        string
	Style         string
	Model         string
	ContextLength int
	PredictLength int
	// DraftsDir and SourcesDir override where finished drafts are written and
	// where bare filenames are resolved from. Empty means the default.
	DraftsDir     string
	SourcesDir    string
	ForceNew      bool
	Merge         bool
	Resume        bool
	KeepArtifacts bool
	Experimental  bool
	StrictNumbers bool
	NoCache       bool
	SecondGate    bool
}

Flags holds the raw command-line values before they are merged into a Config.

Jump to

Keyboard shortcuts

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