Documentation
¶
Overview ¶
Package journal reads and writes .mtqg/journal.jsonl and the files around it.
It is the lowest layer of the core (.claude/rules/directory-structure.md). It does not know what an event means: to it a line is an event, and a todo being done is just another line. Everything that writes to .mtqg/ lives here: the rules for how a line is written, the lock, and the rewriting used by undo and archive. The layers above never repeat them.
Index ¶
- Constants
- Variables
- func ArchivePath(name string) string
- func GitBranch(root string) (string, error)
- func GitHead(root string) (string, error)
- func GitStatusDigest(root string) (string, error)
- func GitUserName(root string) (string, error)
- func Scan(r io.Reader) ([]Line, []Warning, error)
- func SchemaMarker(text string) (version string, ok bool)
- type AlreadyInitializedError
- type Author
- type Event
- type FormatTooNewError
- type GitUnavailableError
- type InvalidEventError
- type Journal
- func (j *Journal) Append(ev Event) (Event, error)
- func (j *Journal) Archive(name string, fn func(lines []Line) (move, keep []Line, err error)) error
- func (j *Journal) Location() Location
- func (j *Journal) PruneSessions(now time.Time)
- func (j *Journal) Read() (Result, error)
- func (j *Journal) ReadSession(id string) (Session, bool)
- func (j *Journal) Rewrite(fn func(lines []Line) ([]Line, error)) error
- func (j *Journal) UncommittedEvents() ([]Event, error)
- func (j *Journal) Upgrade(schema string, dryRun bool) (from, to int, schemaUpdated bool, err error)
- func (j *Journal) Version() int
- func (j *Journal) WriteSession(id string, s Session) error
- type Line
- type Location
- type LockTimeoutError
- type NotInitializedError
- type Options
- type Result
- type Session
- type VersionFileError
- type Warning
- type WarningKind
Constants ¶
const ( OpCreate = "create" OpStatus = "status" OpEdit = "edit" OpDelete = "delete" )
The operations of the format (docs/reference/schema.md). A new operation is a change of the format, so the set is closed.
const ( TypeMemo = "memo" TypeTodo = "todo" TypeQA = "qa" TypeBug = "bug" TypeGlossary = "glossary" TypeRule = "rule" StatusOpen = "open" StatusDone = "done" )
The kinds of record and the states of the format (docs/reference/schema.md). The journal layer only checks that a written value is one of them; what they mean is the business of the layers above.
const ( AuthorHuman = "human" AuthorAI = "ai" )
The kinds of author (docs/reference/schema.md).
const DefaultLockTimeout = 5 * time.Second
DefaultLockTimeout is how long a write waits for the lock before it gives up. The lock is held for one append or one rewrite, so a longer wait means that some process is stuck while holding it.
const SchemaVersion = "1.1.0"
SchemaVersion is the mtqg release docs/reference/schema.md's content matches, as a marker comment near the end of that file also says (<!-- schema as of mtqg X.Y.Z -->). It is independent of SupportedVersion: schema.md's wording can change without the format itself changing. Raise this whenever schema.md's content changes, and update the marker to match in the same change; a test checks the two agree.
const SessionMaxAge = 7 * 24 * time.Hour
SessionMaxAge bounds how long a session file is kept. SessionStart prunes files older than this every time it runs, so .local/sessions/ does not grow forever across many sessions.
const SupportedVersion = 1
SupportedVersion is the newest format version this build reads and writes. Before mtqg v1 the version was 0, meaning "not yet stable"; mtqg upgrade raises a repository to this version without touching any line (docs/reference/schema.md "Versioning").
Variables ¶
var ( // ErrNotInRepository means the search reached the top of the file system // without meeting a .mtqg/ directory or a .git entry. ErrNotInRepository = errors.New("journal: not inside a git repository") // ErrConflictMarkers means journal.jsonl still holds unresolved merge // conflict markers. Reading warns; writing refuses. ErrConflictMarkers = errors.New("journal: journal.jsonl has unresolved conflict markers") // ErrLockTimeout means the write lock could not be taken in time. ErrLockTimeout = errors.New("journal: timed out waiting for the write lock") // ErrInvalidEvent means an event cannot be written as a valid line. ErrInvalidEvent = errors.New("journal: invalid event") // ErrInvalidVersionFile means .mtqg/version is missing or unreadable. ErrInvalidVersionFile = errors.New("journal: invalid .mtqg/version") )
The journal layer returns error kinds, not sentences. Callers test them with errors.Is and errors.As; the wording shown to people belongs to the CLI layer (.claude/rules/cli-output.md). The Error methods are for logs and tests.
var ErrAlreadyInitialized = errors.New("journal: .mtqg/ already exists")
ErrAlreadyInitialized means Init found a .mtqg/ where it was to make one.
ErrGitUnavailable means the git command could not be run (it is not installed, or it did not answer in time).
var ErrNoUserName = errors.New("journal: git has no user.name")
ErrNoUserName means git has no user.name for the repository.
Functions ¶
func ArchivePath ¶
ArchivePath names an archive file the way a person is told where it is: relative to the repository, with slashes.
func GitBranch ¶
GitBranch returns the name of the branch that is checked out in the repository at root, or "" when there is none (a detached HEAD). A branch that has no commit yet has a name. If git cannot be run, the error is ErrGitUnavailable.
func GitHead ¶
GitHead returns the commit HEAD points to in the repository at root, or "" when there is no commit yet (a fresh repository, or a detached HEAD that somehow fails). It is used to notice that a commit was made while an agent session was open (§11.3). If git cannot be run, the error is ErrGitUnavailable.
func GitStatusDigest ¶
GitStatusDigest is a hash of what "git status --porcelain -z" reports for the repository at root, leaving out .mtqg/ itself. It says only whether the working tree looks different from one call to the next, not what changed: it is used to notice that a session did some work (§11.3), not to read the status. If git cannot be run, the error is ErrGitUnavailable.
func GitUserName ¶
GitUserName returns user.name as git sees it in the repository at root, so a setting of that repository applies. It returns ErrNoUserName when there is none, and an error that is ErrGitUnavailable when git cannot be run.
func Scan ¶
Scan reads lines of the format from r. It is used for journal.jsonl and for any other text that holds event lines.
Blank lines are skipped without a warning. Every other line is returned, so that a rewrite can keep it; a line that cannot be read as an event has a nil Event and a warning. A line ending of CRLF is read as LF. Lines can be of any length. The error is only for a failure of r.
func SchemaMarker ¶ added in v1.1.0
SchemaMarker extracts the "schema as of mtqg X.Y.Z" marker from text (the embedded schema.md, or an existing .mtqg/SCHEMA.md). ok is false if no marker is present or it is not in the X.Y.Z form.
Types ¶
type AlreadyInitializedError ¶
type AlreadyInitializedError struct {
Path string
}
AlreadyInitializedError names the .mtqg/ that Init found.
func (*AlreadyInitializedError) Error ¶
func (e *AlreadyInitializedError) Error() string
func (*AlreadyInitializedError) Is ¶
func (e *AlreadyInitializedError) Is(target error) bool
Is makes errors.Is(err, ErrAlreadyInitialized) true.
type Event ¶
type Event struct {
ID string `json:"id"`
Op string `json:"op"`
Type string `json:"type,omitempty"`
Re string `json:"re,omitempty"`
From string `json:"from,omitempty"`
Status string `json:"status,omitempty"`
Basis int `json:"basis,omitzero"`
Word string `json:"word,omitempty"`
Text string `json:"text,omitempty"`
V int `json:"v"`
TS string `json:"ts"`
Author Author `json:"author"`
TTY string `json:"tty,omitempty"`
}
Event is one line of journal.jsonl. The journal layer does not know what an event means; it only reads and writes the format.
The fields are declared in the key order of the format, which is the order they are written in: id, op, type, re, from, status, basis, word, text, at, v, ts, author, tty. Fields without a value are left out, except v, which is written even when it is 0.
type FormatTooNewError ¶
FormatTooNewError means .mtqg/version declares a format newer than this build understands. Reading and writing are both refused.
func (*FormatTooNewError) Error ¶
func (e *FormatTooNewError) Error() string
type GitUnavailableError ¶
type GitUnavailableError struct {
}
GitUnavailableError says why git could not be run.
func (*GitUnavailableError) Error ¶
func (e *GitUnavailableError) Error() string
func (*GitUnavailableError) Is ¶
func (e *GitUnavailableError) Is(target error) bool
Is makes errors.Is(err, ErrGitUnavailable) true.
func (*GitUnavailableError) Unwrap ¶
func (e *GitUnavailableError) Unwrap() error
type InvalidEventError ¶
InvalidEventError names the field that made an event unwritable.
func (*InvalidEventError) Error ¶
func (e *InvalidEventError) Error() string
func (*InvalidEventError) Is ¶
func (e *InvalidEventError) Is(target error) bool
Is makes errors.Is(err, ErrInvalidEvent) true.
type Journal ¶
type Journal struct {
// contains filtered or unexported fields
}
Journal is an open .mtqg/ directory. It keeps no file open: every operation opens what it needs and closes it again, because a short-lived command is the normal user and Windows cannot replace a file that is open.
func Open ¶
Open finds .mtqg/ from start (see Find) and checks its format version. A version newer than SupportedVersion is refused with a *FormatTooNewError, for reading as well as for writing.
func (*Journal) Append ¶
Append writes one event to the end of journal.jsonl and returns it as written.
The caller gives only the meaning of the event: op, type, re, from, status, word, text, at, and the id of the record for every op except create. The journal layer fills in the rest and overwrites anything the caller put there: the id of a new record, v, ts, author and tty.
The steps, all under the write lock:
- Refuse if journal.jsonl still holds conflict markers.
- If the file does not end with a line feed (a line was cut off by a crash, or the file was edited by hand), start with one, so that the new line does not get glued to the broken one.
- Write the line with a single write. There is no fsync: the speed of writing a note down comes first.
Nothing is written when an error is returned, except that a failed write may leave a cut-off line, which step 2 then keeps apart from the next one.
func (*Journal) Archive ¶
Archive moves lines of journal.jsonl to the archive file .mtqg/archive/<name>. Together with undo (Rewrite) it is the only operation that removes or moves lines.
Under the write lock, fn is given every non-blank line of journal.jsonl and says which of them to move and which to keep. The lines are written as they are, byte for byte, so unknown fields, lines that could not be read and hand-made formatting survive on either side.
The lines to move are first appended to the archive file and synced, and only then is journal.jsonl replaced by the lines to keep. A crash in between leaves the moved lines in both files, which reads as they were before (a line that is in a file twice is one event) and is put right by archiving again. The other order would lose them. The archive file is made when it is needed; one that is there already is appended to, and a line ending is added first if its last line has none (as Append does).
Nothing is written if fn returns an error, if it moves nothing (the archive directory is not made either), or if the lines it moves and keeps are not together the lines it was given: moving is the one way a line can be lost, so a miscount is refused here and not left to the caller. Archiving is refused while journal.jsonl holds conflict markers. fn must not call Append or Rewrite: the lock is not re-entrant.
func (*Journal) PruneSessions ¶
PruneSessions removes session files whose last write is older than SessionMaxAge. It is best effort: a session file it cannot read or remove is left alone, and there is nothing to report (the same as everything else in .local/ - journal-format.md "いつ消えても困らないものだけを置く").
func (*Journal) Read ¶
Read returns the events of journal.jsonl. It does not take the lock: an append is one write, and a rewrite replaces the file in one step, so a reader sees the file either before or after. A line that is still being written shows up as a warning.
A missing journal.jsonl reads as an empty journal. Lines that cannot be read are skipped with a warning; conflict markers are among them. Reading never fails because of them.
func (*Journal) ReadSession ¶
ReadSession returns what is remembered of a session, and whether there was anything. A missing file, one that cannot be read, or one that does not parse is "nothing" (false), never an error: a hook must not fail because its own bookkeeping went missing (.local/ may be deleted at any time).
func (*Journal) Rewrite ¶
Rewrite replaces journal.jsonl with the lines fn returns. It is what undo is made of; undo and archive (Archive) are the only operations that remove or move lines.
Under the write lock, fn is given every non-blank line of journal.jsonl, and returns the lines to keep, in the order to write them. A line fn gives back as it got it is written byte for byte, so unknown fields, lines that could not be read and hand-made formatting all survive; only what fn leaves out is gone. A line with a nil Raw is written from its Event by the writing rules. Lines with the same content are not merged, as they are when reading. Blank lines are dropped and CRLF becomes LF.
The new file is written to .mtqg/.local/tmp/, synced, and then put in place of journal.jsonl, so an append that comes in the meantime waits for the lock instead of being lost, and a crash leaves either the old file or the new one.
If fn returns an error, nothing is written. Rewriting is refused while journal.jsonl holds conflict markers. fn must not call Append or Rewrite: the lock is not re-entrant, so it would wait for itself until the timeout.
func (*Journal) UncommittedEvents ¶
UncommittedEvents returns the events of journal.jsonl that are not in the last commit (HEAD): the lines that were added since, whether they are staged or not. Lines that only the last commit has (removed since, by undo or archive) are not events of the present journal and are not returned. Lines whose content is exactly the same are one event.
When there is no commit yet, or the last commit has no journal.jsonl, every event is uncommitted. If git cannot be run, the error is ErrGitUnavailable.
func (*Journal) Upgrade ¶ added in v1.0.0
Upgrade raises the format version declared by .mtqg/version to SupportedVersion, and rewrites SCHEMA.md (schema is the text of the new .mtqg/SCHEMA.md, as passed to Init) whenever the format is raised or the existing SCHEMA.md's marker is missing or older than SchemaVersion (docs/reference/schema.md "Versioning"). journal.jsonl is never touched: existing lines keep the meaning their own v had when they were written. schemaUpdated reports whether SCHEMA.md was (or, with dryRun, would be) rewritten; it can be true even when from == to.
dryRun reports what would happen without writing anything. Writing is refused while journal.jsonl holds conflict markers, the same as Append and Rewrite: a repository in that state should be resolved first. The check only runs when something would actually be written.
func (*Journal) WriteSession ¶
WriteSession saves what is remembered of a session, replacing what was there. The write goes to a temporary file first and is put in place with the same replace that Rewrite uses, so a reader never sees a half-written file; a session file lost to a crash just means the session is treated as new.
type Line ¶
type Line struct {
// Raw is the line as it was read, without its line ending. Rewriting keeps
// these bytes as they are, so unknown fields, lines that could not be read
// and hand-made formatting survive. It is nil for a line that is to be
// written from Event.
Raw []byte
// Event is the line read as an event. It is nil when the line could not be
// read as one; Scan has then reported a warning for it.
Event *Event
// Number is the 1-based number of the line in the input, counting blank
// lines. It is 0 for a line that was not read from a file.
Number int
}
Line is one non-blank line of a journal file.
type Location ¶
type Location struct {
// Root is the directory that holds .mtqg/ (the root of the repository).
Root string
// Dir is the .mtqg/ directory.
Dir string
}
Location says where the .mtqg/ directory of a repository is.
func Find ¶
Find looks for .mtqg/ the way git looks for .git: from start up to the parents, one directory at a time. In each directory it checks, in this order:
- .mtqg/ exists: use it.
- .git exists (a directory, or a file in a worktree or a submodule): this is the root of the repository and it has no .mtqg/ yet. Find returns a *NotInitializedError.
It never looks above the root of the repository, so an unrelated .mtqg/ outside it is not picked up. Outside a repository it returns ErrNotInRepository.
start is made physical first (symbolic links are resolved), like git does, so that the same .mtqg/ is found whichever path leads to it.
func Init ¶
Init makes .mtqg/ in the repository that start is in: at the root of the repository, next to .git, whichever directory it was called from. schema is the text of .mtqg/SCHEMA.md.
It walks up like Find. A .mtqg/ on the way is an *AlreadyInitializedError, and outside a repository the error is ErrNotInRepository. Nothing is overwritten, and nothing else is touched: Init does not change git's configuration and does not commit (.claude/rules/git-integration.md).
The files are journal.jsonl (empty), .gitattributes (union merge, so that two branches that both append keep the lines of both), .gitignore (for .local/), version and SCHEMA.md. If one of them cannot be made, the .mtqg/ that was made is removed again.
type LockTimeoutError ¶
LockTimeoutError carries how long the lock was awaited.
func (*LockTimeoutError) Error ¶
func (e *LockTimeoutError) Error() string
func (*LockTimeoutError) Is ¶
func (e *LockTimeoutError) Is(target error) bool
Is makes errors.Is(err, ErrLockTimeout) true.
type NotInitializedError ¶
type NotInitializedError struct {
Root string
}
NotInitializedError means the search met the repository root (.git) before it met a .mtqg/ directory. Root is where mtqg init would create .mtqg/.
func (*NotInitializedError) Error ¶
func (e *NotInitializedError) Error() string
type Options ¶
type Options struct {
// Author is written as the author of every event this Journal appends.
Author Author
// TTY identifies the terminal the events are written from. Empty when there
// is none (a server, CI): the field is then left out.
TTY string
// LockTimeout is how long to wait for the write lock. Zero means
// DefaultLockTimeout.
LockTimeout time.Duration
}
Options are what the journal layer fills into the events it writes and how it behaves. The caller of Append gives only the meaning of an event.
type Result ¶
type Result struct {
// Events are the events in the order of the file, with lines whose content
// is exactly the same counted once. Their order carries no meaning: the
// order of events is decided by ts and id (docs/reference/schema.md).
Events []Event
Warnings []Warning
}
Result is the events of a journal, ready to be turned into a state.
type Session ¶
type Session struct {
StartedAt time.Time `json:"started_at"`
Head string `json:"head,omitzero"`
StatusDigest string `json:"status_digest,omitzero"`
Prompted bool `json:"prompted,omitzero"`
}
Session is what a hook remembers about one agent session between its SessionStart and its Stop: what the repository looked like when the session began, and whether the agent has already been prompted once (docs/design/07-integrations.md §11.3).
type VersionFileError ¶
VersionFileError says why .mtqg/version could not be used.
func (*VersionFileError) Error ¶
func (e *VersionFileError) Error() string
func (*VersionFileError) Is ¶
func (e *VersionFileError) Is(target error) bool
Is makes errors.Is(err, ErrInvalidVersionFile) true.
type Warning ¶
type Warning struct {
Kind WarningKind
Line int
}
Warning reports a line that was skipped, or that may not be complete. The wording is left to the CLI layer.
type WarningKind ¶
type WarningKind int
WarningKind says why a line was skipped or is suspect.
const ( // WarnInvalidJSON: the line is not a valid JSON object, or a field has the // wrong type. WarnInvalidJSON WarningKind = iota + 1 // WarnInvalidUTF8: the line contains bytes that are not valid UTF-8. WarnInvalidUTF8 // WarnMissingField: the line has no id or no op. WarnMissingField // WarnConflictMarker: the line is a merge conflict marker. WarnConflictMarker // WarnNoTrailingNewline: the last line does not end with a line feed. It // may be a line that is still being written. WarnNoTrailingNewline )