dreaming

package
v0.49.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 20 Imported by: ? 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

Index

Constants

View Source
const (
	ReasonSuperseded  = "superado"
	ReasonClosed      = "cerrado"
	ReasonRepeated    = "repetido"
	ReasonUnconfirmed = "por_confirmar"
)

Reasons an archived range may carry. ReasonUnconfirmed is the only one that needs no source, and it is paid for with a visible bullet in the state.

View Source
const (
	MaxSheetBytes   = 48 * 1024
	MaxArchiveBytes = 24 * 1024
)

Limits of what an assembled unit may produce.

View Source
const (
	VerdictKeep    = "conservar"
	VerdictArchive = "archivar"
	VerdictCorrect = "corregir"
)

Verdicts and limits of the memory pass.

View Source
const Ref = "refs/heads/main"

Ref is the branch the nightly history lives on.

View Source
const UndoToolName = "dreaming_undo"

UndoToolName is the owner's tool to undo a night.

Variables

View Source
var ErrBudget = errors.New("the night's budget would be exceeded")

ErrBudget reports that a call could exceed the night's cap.

View Source
var ErrBusy = errors.New("a dreaming is in progress; try again later")

ErrBusy reports that a night (or an undo) holds the run lock.

View Source
var ErrRefMoved = errors.New("dreaming: the history ref moved")

ErrRefMoved reports that the ref was not where the caller expected it.

Functions

func NewUndoTool

func NewUndoTool(codebaseDir string) core.Tool

NewUndoTool lets the owner undo one night of the book's dreaming, by the commit the morning news gave. It is registered only in the owner's own conversation, and only for an owner that has the dreaming configured.

func Protected

func Protected(rel string) bool

Protected reports whether a book path is never consolidated (I2): the user's file, the index, history kept by hand, and the archive itself. The archive only ever gains whole new files.

func Reservation

func Reservation(model core.Model, system, prompt string, requestedOut int) (float64, error)

Reservation is the most a request can cost.

func RoleFits

func RoleFits(role string, model core.Model, budget float64) bool

RoleFits reports whether one call of the role can be reserved inside the night's budget at all: even with an empty prompt, a model whose reservation at the role's output cap exceeds it would have every call refused and the night would defer everything.

func Verify

func Verify(u Unit, orig [][]byte, out Output, nonce string) error

Verify is the independent guard (I1): it rebuilds every original file of the unit from the bytes about to be written — the header the rule puts first, then each marked block, read as opaque payloads of their declared length — and requires the result to equal the original byte for byte. It shares no state with Assemble beyond the header rule and the marker format.

Types

type Archived

type Archived struct {
	File   int    `json:"f"`
	Lines  [2]int `json:"lineas"`
	Reason string `json:"motivo"`
	Source string `json:"fuente"`
}

Archived is one range the organizer retires, with why and on what evidence.

type AssembleInput

type AssembleInput struct {
	Unit  Unit
	Orig  [][]byte // one per Unit.Files
	Plan  Plan
	Date  string // YYYY-MM-DD, the night's civil date
	Nonce string // per night; must not occur in any original nor in the state
	S0    string // snapshot commit the sources are anchored to
	// SourceExists reports whether "path:line" names a real line of the
	// snapshot. It is how a reason other than por_confirmar proves it points at
	// something.
	SourceExists func(path string, line int) bool
}

AssembleInput is a unit, its original bytes and the context the guard needs.

type Budget

type Budget struct {
	Limit float64
	Spent float64
}

Budget is the night's hard cap (I10). Every call reserves its maximum cost before it is sent: the prompt counted as one token per byte (a token is at least one byte) at the dearest input rate the model has, plus the output cap at the dearest output rate. "Maximum" is what the provider can really be made to produce: the cap the call asks for where it is sent (Anthropic), the model's own maximum where it is not (OpenAI's plan login), and no fast-mode premium (the dreaming never asks for it); a pricing tier counts only when the prompt reaches it. What a call really cost replaces its reservation; a call that reports no usage keeps its whole reservation, except one that Stream refused outright, which was never billed.

type Change

type Change struct {
	Path string `json:"path"`
	Pre  string `json:"pre"`
	Post string `json:"post"`
}

Change is one path of a group: its expected content before and after, as blob ids ("" = the path does not exist). The bytes live in the object store, so a journal of ids is enough to finish or roll back.

type Finish

type Finish struct {
	Run   string            `json:"run"`
	Units map[string]string `json:"units,omitempty"` // state key → hash
	News  *News             `json:"news,omitempty"`
}

Finish is what has to happen once a commit is published: the state the run leaves behind and the news. It is in the journal so a crash after publishing still ends with both.

type Group

type Group struct {
	ID      string   `json:"id"`
	Kind    string   `json:"kind"` // "unit" or "fact"
	Changes []Change `json:"changes"`
	Sources []Change `json:"sources,omitempty"` // Pre only
	// Unit is every file of a unit as the models read it (path → blob). The
	// whole unit must still be exactly that, parts included and no new part,
	// even where only its first file is written; undo records it back.
	Unit map[string]string `json:"unit,omitempty"`
	// After is the state the group leaves its unit or fact in (see state.json).
	After string `json:"after,omitempty"`
}

Group is the smallest set of paths that is applied, undone or rolled back together: a unit with its new archive files, or a fact with its copy. Sources are other paths the plan relied on; they must still be what the models read.

type Mark

type Mark struct {
	Old      string `json:"vieja"`
	New      string `json:"nueva"`
	NewDate  string `json:"fecha_nueva"`
	Scope    string `json:"alcance"` // total | parcial
	Point    string `json:"punto"`
	Change   string `json:"que_cambia"`
	OldQuote Quote  `json:"cita_vieja"`
	NewQuote Quote  `json:"cita_nueva"`
}

Mark is one supersession the pairer proposes.

type News

type News struct {
	Key    string `json:"key"`
	Origin string `json:"origin"`
	Title  string `json:"title"`
	Body   string `json:"body"`
}

News is what the user reads in For you.

type Night

type Night struct {
	Started  string  `json:"started"`
	SpentUSD float64 `json:"spent_usd"`
}

Night is the persisted record of one civil date's run.

type NightConfig

type NightConfig struct {
	Date      string // the civil date in the owner's zone, YYYY-MM-DD
	BudgetUSD float64
	Factory   ProviderFactory
	Analyzer  core.Model // cheap reader (Luna)
	Organizer core.Model // writes the plans and the cross-sheet view (Sonnet)
	Publish   Publisher
	Now       func() time.Time
	// Notes are said in the morning news as they come: why the night did not
	// use the models its owner chose.
	Notes []string
}

NightConfig is one owner's night.

type NightResult

type NightResult struct {
	Ran       bool
	Commit    string
	Applied   []string
	Conflicts []string
	Rejected  map[string]string // unit → why its plan was refused
	Deferred  []string          // left for another night (budget)
	Marks     []Mark            // decisions marked as superseded
	Secrets   []string          // sheets and decisions left alone: they look like they hold a credential
	Questions []string          // for the user, from the decisions pass
	CostUSD   float64
}

NightResult is what a night did.

type Output

type Output struct {
	Files  map[string][]byte
	Remove []string
}

Output is everything one unit writes: whole files (the new sheet and the new archive files) and the paths it removes (the parts).

func Assemble

func Assemble(in AssembleInput) (Output, error)

Assemble builds a unit's output from its plan. It refuses anything the deterministic rules cannot prove (see Verify, which it runs on its own output before returning it).

type Plan

type Plan struct {
	NoChanges bool        `json:"sin_cambios"`
	State     string      `json:"estado"`
	Keep      [][3]int    `json:"conservar"` // [file, first, last], 1-based inclusive
	Archive   []Archived  `json:"archivar"`
	Promote   []Promotion `json:"nuevas_decisiones,omitempty"`
}

Plan is what the organizer model returns for a unit. It never carries text that ends up as a kept or archived line: only line numbers, plus the new state block, which is the single piece of new prose.

type Promotion

type Promotion struct {
	Path   string `json:"ruta"`   // decisions/<slug>.md, must not exist
	Title  string `json:"titulo"` // one line
	Source string `json:"fuente"` // <file of this unit>:<a>-<b>
}

Promotion asks for a new decision file for a decision of the user that only lives in a sheet (decisions/dreaming.md, 11/11). The model names the file, a title and the lines; the body is copied by code, byte for byte, from the snapshot, so the decision itself is never paraphrased.

type ProviderFactory

type ProviderFactory func(core.Model) (core.Provider, error)

ProviderFactory builds a provider for a model, with the user's auth.

type Publisher

type Publisher func(News) error

Publisher delivers the morning news. It must be idempotent on News.Origin: a recovery may deliver the same news again.

type Quote

type Quote struct {
	Path string `json:"ruta"`
	Line int    `json:"linea"`
	Text string `json:"texto"`
}

Quote is a literal line the mark rests on.

type Report

type Report struct {
	Commit    string
	Applied   []string
	Conflicts []string // group ids left alone because something else wrote them
	Recovered string   // "", "finished" or "rolled back"
}

Report is what an apply, undo or recovery did, for the news and the logs.

type Run

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

Run is one exclusive session over the store: a night, an undo or a recovery. It holds the run lock for its whole life; the book and memory locks are taken only around the short sections that read a snapshot or write.

func (*Run) Apply

func (r *Run) Apply(snap Snapshot, title string, groups []Group, content map[string][]byte, fin Finish, news func(Report) *News, pub Publisher) (Report, error)

Apply writes the accepted groups of a night (see commit) on top of the snapshot. content maps every post blob to its bytes.

news, when not nil, writes the morning news once the accepted groups and the commit are known; it goes into the journal with the rest of the ending.

func (*Run) Close

func (r *Run) Close() error

Close releases the run lock.

func (*Run) Snapshot

func (r *Run) Snapshot(title string) (Snapshot, error)

Snapshot reads both stores under their locks and commits them as S0, or reuses the current commit when nothing changed.

func (*Run) UnitGroup

func (r *Run) UnitGroup(snap Snapshot, u Unit, out Output, sources []string) (Group, map[string][]byte, error)

UnitGroup turns a verified output into the group that applies it.

type Snapshot

type Snapshot struct {
	Commit  string
	Files   map[string][]byte // repository path → bytes
	Blobs   map[string]string // repository path → blob id
	Skipped []string          // symlinks and other non-regular entries, never touched
}

Snapshot is S0: every regular file of the book and the memory as it was, committed with the exact bytes read.

func (Snapshot) HasSecret

func (snap Snapshot) HasSecret(u Unit) bool

HasSecret reports whether any file of a unit looks like it holds a credential.

func (Snapshot) Orig

func (snap Snapshot) Orig(u Unit) [][]byte

Orig returns a unit's original bytes, one slice per file.

func (Snapshot) SourceExists

func (snap Snapshot) SourceExists(path string, line int) bool

SourceExists reports whether path:line names a line of the snapshot's book.

func (Snapshot) UnitHash

func (snap Snapshot) UnitHash(u Unit) string

Hash identifies a unit's content in the snapshot: its paths and blobs.

func (Snapshot) Units

func (snap Snapshot) Units() []Unit

Units groups the snapshot's book files into units: a sheet x.md and the x/parte-NN.md files book-tidy split it into. Protected paths are not units.

type Store

type Store struct {
	Codebase string
	// Ctx, when set, makes every lock wait of a run cancellable (the night's
	// clock must be able to stop on shutdown). Nil waits like the tools do.
	Ctx context.Context
}

Store is one codebase directory (~/.config/moa/codebases/<key>): the owner's book and the project's memory, the history repository beside them, and the dreaming's own working files.

func (Store) Begin

func (s Store) Begin(wait bool, pub Publisher) (*Run, Report, error)

Begin takes the run lock (waiting when wait is true, otherwise failing with ErrBusy), opens or creates the history repository and recovers whatever a previous process left half done.

func (Store) Due

func (s Store) Due(snap Snapshot) ([]Unit, error)

Due returns the units whose content changed since the dreaming last processed (or undid) them; on the first night, all of them.

func (Store) DueDecisions

func (s Store) DueDecisions(snap Snapshot) (map[string]Unit, map[string]bool, error)

DueDecisions are the decisions that changed since they were last read.

func (Store) DueFacts

func (s Store) DueFacts(snap Snapshot) ([]string, error)

DueFacts returns the facts whose bytes changed since the dreaming last processed (or undid) them, most recently modified first.

func (Store) Night

func (s Store) Night(ctx context.Context, cfg NightConfig) (res NightResult, err error)

Night runs one night for the store if the date has not run yet: it never runs twice on a date, even after a failure.

It waits for another run (an undo) without blocking in the kernel, so a cancelled context always ends it: the server's shutdown must not hang on a lock.

func (Store) Undo

func (s Store) Undo(commit string, pub Publisher) (Report, error)

Undo reverts the night that produced commit: each of its groups whose paths still hold what that night wrote goes back to what it found; any other is left whole and reported. The undone units are recorded as processed, so the next night does not consolidate them again until someone changes them.

type Unit

type Unit struct {
	Sheet string   // book-relative path of x.md
	Files []string // Files[0] == Sheet, then the parts in order
}

A unit is one sheet of the book as the dreaming consolidates it: x.md plus the x/parte-NN.md files book-tidy split it into. File 0 is always the sheet itself; it is the only file that survives a consolidation.

Jump to

Keyboard shortcuts

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