model

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 7 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 model gives the events of the journal their meaning.

It builds the state of records from events, checks what may be done to a record (a memo cannot be done), resolves the IDs people type, and puts together the events that create a record or change its state. It never touches a file: it is given events, and hands events back to be written by the journal layer (.claude/rules/directory-structure.md). It also knows nothing about how anything is shown; the entry points do that.

Index

Constants

View Source
const (
	KindMemo     = "memo"
	KindTodo     = "todo"
	KindQuestion = "question"
	KindAnswer   = "answer"
	KindBug      = "bug"
	KindReply    = "reply"
	KindGlossary = "glossary entry"
	KindRule     = "rule"
)

The kinds of record as people speak of them. A qa record is a question or an answer, and a bug record is a bug or a reply; the journal tells them apart by re. The two have the same shape: a parent that can be replied to, and its replies.

View Source
const MinIDDigits = 4

MinIDDigits is how short a typed ID may be. Anything shorter is refused, so that a word such as add or bad is never taken for the ID of a record, and because a digit or two matches nearly everything.

Variables

View Source
var ErrAmbiguous = errors.New("model: the ID matches more than one record")

ErrAmbiguous means more than one record matches an ID that was typed.

View Source
var ErrEmptyText = errors.New("model: the text is empty")

ErrEmptyText means the text of a record is empty.

View Source
var ErrEmptyWord = errors.New("model: the word is empty")

ErrEmptyWord means the word of a glossary entry is empty.

View Source
var ErrHasLaterEvents = errors.New("model: the record has other events")

ErrHasLaterEvents means removing a line would leave events without their record.

View Source
var ErrNoChange = errors.New("model: the record is already in that state")

ErrNoChange means the record is already in the state that was asked for.

View Source
var ErrNoReplies = errors.New("model: the record has no replies")

ErrNoReplies means the record cannot be answered or replied to.

View Source
var ErrNoState = errors.New("model: the record has no state")

ErrNoState means the record has no state to change.

View Source
var ErrNotFound = errors.New("model: no record matches")

ErrNotFound means no record matches an ID that was typed.

View Source
var ErrNothingToUndo = errors.New("model: nothing to undo")

ErrNothingToUndo means no line was written by this author from this terminal.

View Source
var ErrTooShort = errors.New("model: the ID is too short")

ErrTooShort means an ID that was typed has fewer than MinIDDigits digits.

View Source
var ErrWrongKind = errors.New("model: the record is of another kind")

ErrWrongKind means the record is not of the kind the command is for.

Functions

func Delete

func Delete(rec *Record) (journal.Event, error)

Delete returns the event that hides a record. Its answers or replies are hidden with it: that is how the record is read (State.visible), not a second event.

func EditText

func EditText(rec *Record, text string) (journal.Event, error)

EditText returns the event that replaces the text of a record. Only the text: the word of a glossary entry and the state of a todo, a question or a bug are not touched. A text that is empty is ErrEmptyText. A text that is the same as the record has now is ErrNoChange, and nothing should be written for it.

It records how many events the record had (basis), the same way SetStatus records from: what shows an edit that was made without knowing of another change to the same record, whichever field that other change touched (review).

func EventOrder

func EventOrder(events []journal.Event) []int

EventOrder returns the indexes of events in the order they are applied in and shown in: by time, by ID for the same time, a create before the changes of a record and a delete after them, and for the rest in the order they were given. Anything that shows events from any source in time order (format) uses this, so that there is one order.

func EventTime

func EventTime(ev journal.Event) time.Time

EventTime is the time of an event, or the zero time if its ts cannot be read.

func GlossaryCreate

func GlossaryCreate(word, text string) (journal.Event, error)

GlossaryCreate returns the event that defines a word. The word is kept as it was given: two entries are of one word only if the words are the same character for character.

func IsIDLike

func IsIDLike(word string) bool

IsIDLike reports whether a word is made of hex digits only, and at least MinIDDigits of them: the shape of an ID that was typed (upper case counts as lower case). Whether such a word names a record is for Resolve to say.

func MemoCreate

func MemoCreate(text string) (journal.Event, error)

MemoCreate returns the event that creates a memo.

func ParentCreate

func ParentCreate(typ, text string) (journal.Event, error)

ParentCreate returns the event that creates a question (type qa) or a bug (type bug), which starts open. Any other type has nothing to be replied to.

func ParentKind

func ParentKind(typ string) string

ParentKind is the kind of a record of this type that is not a reply: what a create of the type starts (a question for qa, a bug for bug; for memo, todo and glossary, the kind itself).

func ReplyCreate

func ReplyCreate(parent *Record, text string) (journal.Event, error)

ReplyCreate returns the event that creates an answer to a question, or a reply to a bug. It has the type of its parent, and holds the full ID of the parent (re), whatever length of it was typed. Only a question or a bug can be replied to, and an answer or a reply has no state.

func ReplyKind

func ReplyKind(typ string) string

ReplyKind is the kind of a record of this type that has re: an answer for qa, a reply for bug. The other types have no replies, and it is their own kind.

func RuleCreate

func RuleCreate(text string) (journal.Event, error)

RuleCreate returns the event that creates a rule.

func SetStatus

func SetStatus(rec *Record, status string) (journal.Event, error)

SetStatus returns the event that puts a todo, a question or a bug into a state. It records the state the record was in, as the writer saw it (from), and how many events the record had (basis): together, that is what shows a change that was made without knowing of another one to the same record (review).

A record that has no state is a *NoStateError. A record that is in the state already is ErrNoChange, and nothing should be written for it.

func ShouldPrompt

func ShouldPrompt(prompted bool, startedAt time.Time, start, now RepoState, events []journal.Event) bool

ShouldPrompt says whether a Stop hook should ask the agent to record something with mtqg before ending its turn (docs/design/07-integrations.md §11.3 "セッションの記録と判定"). It knows nothing about any agent: the adapter (internal/cli/hook_claude.go) is the only place that does.

prompted is whether this session already asked once: it is never asked twice. start is what session-start saw, now is the same facts read again. events is every event of journal.jsonl (any author, any kind - create, status, edit and delete all count): if one of them happened at or after startedAt, something was already recorded and there is nothing to ask for.

Otherwise, the condition is that something changed in the repository since the session started: the commit HEAD points to, or anything in the working tree (GitStatusDigest already leaves .mtqg/ out). A session in which nothing happened is not asked to record anything.

startedAt is truncated to the second before it is compared with an event's ts: ts is written with second precision (journal-format.md "書き出し規則"), but startedAt comes from a hook's own clock and normally carries a fraction of a second. Without truncating, a record written in the same second the session started could read as "before" startedAt purely from that fraction, and be missed.

func TodoCreate

func TodoCreate(text string) (journal.Event, error)

TodoCreate returns the event that creates a todo, which starts open.

func UncommittedRecords

func UncommittedRecords(events []journal.Event) int

UncommittedRecords counts the records that the given events belong to. Give it the events that are not in the last commit: a record counts once, however many of its events there are.

func UndoTarget

func UndoTarget(lines []journal.Line, author journal.Author, tty string) (int, error)

UndoTarget returns the index of the line that undo removes: of the lines written by this author from this terminal (tty, which is empty for a line without one), the one with the latest time; of those with the same time, the one that comes last in the file.

The file order decides among lines of one second because their IDs are random and say nothing about which came first, while appends are made one after the other under the lock, so in one file the later line is the one that was written later. A merge can bring in lines of another machine, and if it wrote as the same author from the same tty it can be chosen: that is the case that MTQG_TTY is for.

A line that could not be read as an event is never the target.

Types

type AmbiguousError

type AmbiguousError struct {
	Prefix     string
	Candidates []*Record
}

AmbiguousError lists the records that an ID matched, oldest first.

func (*AmbiguousError) Error

func (e *AmbiguousError) Error() string

func (*AmbiguousError) Is

func (e *AmbiguousError) Is(target error) bool

Is makes errors.Is(err, ErrAmbiguous) true.

type ArchivePlan

type ArchivePlan struct {
	// Move is every record whose lines move, oldest first. An answer or a reply that follows its question or bug is here beside
	// it, and a deleted one is too.
	Move []*Record

	// Skipped are the records whose last event is in the range and that stay:
	// todos, questions and bugs that are open, glossary entries, and rules. Answers
	// and replies are not counted apart from their question or bug.
	Skipped []*Record
}

ArchivePlan is what archive does to the records of a journal for a range of time: what moves out of view and what has its last event in the range and stays.

type ContextData

type ContextData struct {
	// DuplicateWords are the words that have more than one definition.
	DuplicateWords []string
	// Conflicts are the records that have concurrent status changes (review).
	// Attention names them all, so they are never left out, like the words.
	Conflicts []*Record
	// Uncommitted is how many records are not committed: 0 when none, or when
	// that is not known.
	Uncommitted int

	// Rules are every rule, oldest first. They are never reduced: what is a
	// standing convention must stay in view, whatever the budget.
	Rules []*Record

	Todos      []*Record // open, oldest first
	TodosTotal int

	Questions      []Thread // open, oldest first
	QuestionsTotal int
	Bugs           []Thread
	BugsTotal      int
	// RepliesLeft says that the latest answers and replies were left out.
	RepliesLeft bool

	Recent      []*Record // newest first
	RecentTotal int

	Glossary      []GlossaryItem // the entries in the order they were written
	GlossaryTotal int            // the entries there are
	// DefinitionsLeft says that only the words are shown, each once.
	DefinitionsLeft bool
}

ContextData is what context shows. Everything in it is what is shown; the Total fields say how many there were, and so how many were left out.

func (*ContextData) Reduced

func (d *ContextData) Reduced(n int) *ContextData

Reduced returns d with its first n cuts made, in this order: the recent records to 5, the definitions of the glossary (each word stays), the latest answers and replies, the recent records to 3, then the oldest questions and bugs, one at a time (the two together, and never the newest few of each), the recent records to none, then the newest todos, one at a time. More cuts than Steps make no more difference. d itself is not changed, and the more cuts, the less there is.

The todos go newest first: they are mostly worked on in the order they were made, and the oldest is what comes next. The recent records go to none before the todos: the order is strict, so keeping the last 3 of them past the todos would leave out every todo to keep them.

func (*ContextData) Steps

func (d *ContextData) Steps() int

Steps is how many times Reduced can cut: the steps that are always there, and one for each todo and for each question and bug beyond the newest few that are kept. A step may cut nothing (when there are only 3 recent records, the step to 3 does nothing).

type Entry

type Entry struct {
	Event journal.Event
	At    time.Time // the time of the event, or the zero time if it could not be read

	// Answer is set on the create event of an answer or a reply, in the history of
	// its question or bug. It is nil for the events of the record itself.
	Answer *Record
}

Entry is one line of the history of a record.

type GlossaryItem

type GlossaryItem struct {
	Word        string
	Entry       *Record // nil when the definition is left out
	Definitions int     // how many entries the word has
}

GlossaryItem is a glossary entry, or when the definitions are left out, a word.

type HasLaterEventsError

type HasLaterEventsError struct {
	Record *Record
	Events []journal.Event
}

HasLaterEventsError says that a line cannot be undone: it creates a record that has other events, which would be left without a record. Events are those other events: the record's changes, edits and delete, and the creation of each answer or reply to it.

func (*HasLaterEventsError) Error

func (e *HasLaterEventsError) Error() string

func (*HasLaterEventsError) Is

func (e *HasLaterEventsError) Is(target error) bool

Is makes errors.Is(err, ErrHasLaterEvents) true.

type NoRepliesError

type NoRepliesError struct{ Record *Record }

NoRepliesError names the record that cannot be answered or replied to: only a question or a bug can be.

func (*NoRepliesError) Error

func (e *NoRepliesError) Error() string

func (*NoRepliesError) Is

func (e *NoRepliesError) Is(target error) bool

Is makes errors.Is(err, ErrNoReplies) true.

type NoStateError

type NoStateError struct{ Record *Record }

NoStateError names the record that has no state to change.

func (*NoStateError) Error

func (e *NoStateError) Error() string

func (*NoStateError) Is

func (e *NoStateError) Is(target error) bool

Is makes errors.Is(err, ErrNoState) true.

type NotFoundError

type NotFoundError struct{ Prefix string }

NotFoundError says which ID matched nothing.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

func (*NotFoundError) Is

func (e *NotFoundError) Is(target error) bool

Is makes errors.Is(err, ErrNotFound) true.

type Record

type Record struct {
	ID string

	// Type is the type field of the format: memo, todo, qa, bug or glossary.
	Type string

	// Text is the body. For a glossary entry it is the definition.
	Text string

	// Word is the term of a glossary entry.
	Word string

	// Re is the ID of the question or bug that an answer or a reply belongs to.
	Re string

	// Status is open or done for a todo, a question and a bug. It is empty for
	// records that have no state.
	Status string

	// Deleted records are hidden: no list shows them and no ID matches them. So is
	// an answer or a reply whose question or bug is deleted (State.visible).
	Deleted bool

	// Author wrote the create event.
	Author journal.Author

	// Created and Updated are the times of the first and of the last event. They
	// are the zero time if the ts of an event could not be read.
	Created time.Time
	Updated time.Time

	// Events are the events of the record in order.
	Events []journal.Event
}

Record is one memo, todo, question, answer, bug, reply or glossary entry, as its events leave it.

func (*Record) CanHaveReplies

func (r *Record) CanHaveReplies() bool

CanHaveReplies reports whether the record can be answered or replied to: a question or a bug. An answer or a reply cannot.

func (*Record) HasState

func (r *Record) HasState() bool

HasState reports whether the record has a state to change: todos, questions and bugs do; memos, answers, replies and glossary entries do not.

func (*Record) IsReply

func (r *Record) IsReply() bool

IsReply reports whether the record is an answer or a reply.

func (*Record) Kind

func (r *Record) Kind() string

Kind returns how to call the record: memo, todo, question, answer, bug, reply or glossary entry.

type RepoState

type RepoState struct {
	Head         string
	StatusDigest string
}

RepoState is the repository facts a Stop hook compares against what a SessionStart hook saw: the commit HEAD points to, and a digest of the working tree other than .mtqg/ itself (journal.GitHead, journal.GitStatusDigest). It knows nothing about any agent.

type State

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

State is the records that a journal's events amount to.

func Build

func Build(events []journal.Event) *State

Build puts events in order and applies them, record by record.

The order is by time (ts) and, for the same time, by ID: the order of lines in the file carries no meaning, because a merge does not keep it. Events that belong to one record and have the same time are told apart by what they do (an edit before a delete), and after that by the order they were given in, which is the one place where the order of lines counts.

A record starts with its create, whatever the times say. A change whose time is earlier than the create of its record still counts, applied after it, in order with the other changes: the clock of the machine that made the change may run behind the one that made the record, and dropping the change would lose what that person did.

An event for an ID that no create started is ignored (its record may have been archived). A second create of an ID is ignored. Events that are repeated change nothing the second time. None of these is an error: what the journal holds is shown as it is.

func (*State) All

func (s *State) All() []*Record

All returns every record that is in view, of every kind, oldest first.

func (*State) ArchiveTargets

func (s *State) ArchiveTargets(from, to time.Time) ArchivePlan

ArchiveTargets picks the items to archive for the times from up to, but not including, to (docs/reference/schema.md "Archive"). The caller decides what the dates of a range mean; this compares times.

An item is a record together with the answers or replies that follow it. Its last event is the latest of all of their events, deleted ones included, so that every line that moves is dated within the range. An item is archived when its last event is in the range and

  • it was deleted, whatever it is: it is out of view already; or
  • it is a memo, or an answer or a reply with no question or bug in the journal to follow; or
  • it is a todo, a question or a bug that is done.

A glossary entry or a rule that is not deleted is never archived. An item whose events have no time that can be read is not in any range, so it stays.

func (*State) Before added in v0.3.0

func (s *State) Before(rec *Record) []*Record

Before returns the records in view that were created earlier than rec, oldest first: a prefix of All(). rec itself is not included. A rec that came from a different State, or that is no longer in view, gives nil.

func (*State) CanUndo

func (s *State) CanUndo(ev journal.Event) error

CanUndo says whether the line of ev may be removed: a *HasLaterEventsError if it creates a record that has other events.

func (*State) ConcurrentStatusChanges

func (s *State) ConcurrentStatusChanges() []StatusConflict

ConcurrentStatusChanges returns the records in view that have changes made without knowing of one another, in the order they were created. Despite the name, an edit can be one of the changes listed (see below); it keeps the name (and the name of Summary's field, and of the --json field) it had before edits could be caught too, since that is a promise to whatever reads --json (only fields are added, cli-output.md).

Two independent signals catch this, so that a change written before basis existed is still caught.

  1. A status change whose from is not the state the record is in at that point, taken in the order the events are applied in and followed from the state the record was created in: it was written by someone who had not seen the change before it (two branches that each closed the todo, merged later). Counting changes with the same from would call a plain open, done, open, done a conflict, so the comparison is against the state at that point, not against other events' from. A change that has no from is not judged this way, and a state that is not open or done is not a change (the record ignores it too).
  2. A status change or an edit whose basis does not match how many events (including the create) the record actually had at that point: the writer had not seen something that came before it, whichever field that something touched. A change that has no basis is not judged this way (data written before the field existed, or by another tool).

Either signal, on any change, flags the whole record, which is then listed with all of its status changes and edits, oldest first.

func (*State) Context

func (s *State) Context(uncommitted int) *ContextData

Context gathers what context shows, all of it: Reduced cuts it. uncommitted is how many records are not committed (0 if none or not known).

func (*State) DuplicateWords

func (s *State) DuplicateWords() [][]*Record

DuplicateWords returns the words that are defined more than once, each with its entries in the order they were written, the words in the order of their first entry. Two words are the same only if they are the same character for character: mtqg does not decide that Token and token mean one thing. Nothing here says which definition is right.

func (*State) Every added in v0.4.0

func (s *State) Every() []*Record

Every returns every record, deleted or not, of every kind, oldest first (unlike All, it is not filtered by visible). log --json --events is the only caller: it is the one place a deleted record, or an answer or a reply hidden only because its question or bug was deleted, is shown again (journal-format.md says delete only hides; it does not say every reader must).

func (*State) EveryBefore added in v0.4.0

func (s *State) EveryBefore(rec *Record) []*Record

EveryBefore is Before over Every instead of All: it also accepts rec being a deleted record, or an answer or a reply hidden only because its parent was deleted (log --json --events pages through Every, so a page may end on one).

func (*State) Glossary

func (s *State) Glossary() []*Record

Glossary returns the glossary entries that are in view, oldest first.

func (*State) HasParent

func (s *State) HasParent(reply *Record) bool

HasParent reports whether the question or bug of an answer or a reply is in the journal. One without it (its parent may be in an archive) is left out of the lists of questions and bugs.

func (*State) Hidden added in v0.4.0

func (s *State) Hidden(r *Record) bool

Hidden reports whether a record is out of view for the usual reasons: it is deleted itself, or it is an answer or a reply whose question or bug is deleted. It is the negation of visible, exported for log --json --events to mark such a record deleted: true.

func (*State) History

func (s *State) History(rec *Record) []Entry

History returns what happened to a record, oldest first: its own events (the create, the changes of state, the edits, the delete) and, for a question or a bug, the creation of each of its answers or replies that is in view. Events with the same time keep the order the record has them in, and the record's own events come before the answers that arrived at the same moment.

func (*State) Memos

func (s *State) Memos() []*Record

Memos returns the memos that are in view, oldest first.

func (*State) Orphaned

func (s *State) Orphaned(ev journal.Event) []journal.Event

Orphaned returns the events that removing ev would leave without a record: if ev creates a record, the other events of that record and the creation of each answer or reply to it. Removing the line of any other event leaves nothing behind, and the state that is read is as if the change had not been made.

func (*State) Parent

func (s *State) Parent(reply *Record) *Record

Parent returns the question or bug that an answer or a reply belongs to, the same as HasParent decides it (nil for anything else, or if there is none).

func (*State) Parents

func (s *State) Parents(typ string, includeDone bool) []*Record

Parents returns the records of a type that can be replied to and are in view, oldest first: the questions of type qa, the bugs of type bug. Closed ones are included only when includeDone is set.

func (*State) Record

func (s *State) Record(id string) *Record

Record returns the record with this full ID, deleted or not, or nil.

func (*State) Replies

func (s *State) Replies(parentID string) []*Record

Replies returns the answers or replies in view to the question or bug with this full ID, oldest first. Only a question or a bug has them, and a reply has the type of its parent: a record whose re names a record of another type is not one.

func (*State) Resolve

func (s *State) Resolve(prefix string) (*Record, error)

Resolve finds the record that a typed ID stands for. The ID is a prefix of the full ID of at least MinIDDigits digits, as long as it is unique, the way git takes a prefix of a hash. Case does not matter. A record that is not in view (deleted, or an answer or a reply to a deleted question or bug) is never matched, so it can neither be found nor make another ID ambiguous.

It returns a *NotFoundError, a *TooShortError, or an *AmbiguousError that lists the candidates.

func (*State) ResolveAny added in v0.4.0

func (s *State) ResolveAny(prefix string) (*Record, error)

ResolveAny is Resolve without the visibility filter: a deleted record, or an answer or a reply hidden only because its question or bug was deleted, can be found too. log --json --events is the only caller (it pages through Every, so --before must be able to name one of those records).

func (*State) ResolveKind

func (s *State) ResolveKind(prefix, kind string) (*Record, error)

ResolveKind is Resolve for a command that works on one kind of record: a record of another kind is a *WrongKindError that says what it is.

func (*State) Rules

func (s *State) Rules() []*Record

Rules returns the rules that are in view, oldest first.

func (*State) Search

func (s *State) Search(query string) []*Record

Search returns the records in view whose text contains query, oldest first. A glossary entry is found by its word as well. Case is ignored and nothing else is: no patterns, no word boundaries. Only what is in view is searched, so a deleted record is never found.

func (*State) Summary

func (s *State) Summary() Summary

Summary counts the records that are in view.

func (*State) Todos

func (s *State) Todos(includeDone bool) []*Record

Todos returns the todos that are in view, oldest first. Done ones are included only when includeDone is set.

func (*State) UnattachedReplies

func (s *State) UnattachedReplies() []*Record

UnattachedReplies returns the answers and replies in view that belong to no question or bug: the record their re names is not in the journal, or is of another kind. Such a record is not shown under any question or bug, so this is where it is found. They are in the order they were created.

type StatusConflict

type StatusConflict struct {
	Record  *Record
	Changes []Entry
}

StatusConflict is a record whose status changes were made without knowing of each other: the record, and all of its status changes, oldest first.

type Summary

type Summary struct {
	OpenTodos int

	// OpenQuestions are the questions that are not closed. The ones awaiting
	// confirmation are those of them that have an answer. Likewise for the bugs and
	// their replies.
	OpenQuestions                 int
	QuestionsAwaitingConfirmation int
	OpenBugs                      int
	BugsAwaitingConfirmation      int

	// GlossaryEntries counts the entries, so that two definitions of one word are
	// two. DuplicateWords counts the words that have more than one.
	GlossaryEntries int
	DuplicateWords  int

	// ConcurrentStatusChanges counts the records that have them (ConcurrentStatusChanges).
	ConcurrentStatusChanges int
}

Summary counts what a person wants to know at a glance.

type Thread

type Thread struct {
	Parent     *Record
	ReplyCount int
	Latest     *Record // the latest answer or reply; nil if there is none, or it was left out
}

Thread is a question or a bug, with its latest answer or reply.

type TooShortError

type TooShortError struct{ Prefix string }

TooShortError says which ID had too few digits.

func (*TooShortError) Error

func (e *TooShortError) Error() string

func (*TooShortError) Is

func (e *TooShortError) Is(target error) bool

Is makes errors.Is(err, ErrTooShort) true.

type WrongKindError

type WrongKindError struct {
	Record *Record
	Want   string // a Kind constant
}

WrongKindError says what the record is and what the command wanted.

func (*WrongKindError) Error

func (e *WrongKindError) Error() string

func (*WrongKindError) Is

func (e *WrongKindError) Is(target error) bool

Is makes errors.Is(err, ErrWrongKind) true.

Jump to

Keyboard shortcuts

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