Source code for openloops.method

"""The organising method: the seam between the loop record and the system that organises it.

A loop (:class:`openloops.loops.Loop`) records one of the owner's commitments and stays
neutral about how commitments are organised: its ``list`` field is a *place* whose
vocabulary belongs to a method. A **method** supplies that vocabulary and the five
operations that personal organising methods share (Getting Things Done, Personal
Kanban, PARA, the Bullet Journal, the Eisenhower matrix and the apps that implement
them; the comparison is in ``docs/research/organising-methods-seam.md``):

- **capture**: where an unclarified item lands (``inbox``);
- **clarify**: which questions an item is asked, and where the answers send it
  (``questions``, ``clarify``);
- **organise**: the places, and the rules for moving a loop to one (``places``,
  ``default_place``, ``organise``);
- **review**: what is surfaced for a decision, as exceptions (``review``);
- **engage**: how the next thing to do is chosen (``criteria``, ``engage``).

The method only decides. The rules that hold whatever the method, and so live here
rather than in each method, are applied by :func:`organise`: a move is logged; only an
explicit acceptance turns an agent's proposal into a commitment; a loop the owner has
attended to, or given a new time, is scheduled again rather than left as fired.

Every function in openloops that needs a method takes it as one keyword argument,
``method=``, defaulting to :func:`default_method` (Getting Things Done,
:class:`openloops.gtd.GTD`), the only method implemented. A second one is a class with
the same attributes, passed in; nothing else changes.

>>> m = default_method()
>>> m.name, m.inbox, m.default_place
('gtd', 'in', 'next')
>>> isinstance(m, Method)
True
>>> sorted(describe(m))
['criteria', 'default_place', 'inbox', 'name', 'places', 'questions']
"""

from __future__ import annotations

from collections.abc import Iterable, Mapping
from dataclasses import dataclass, replace
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable

if (
    TYPE_CHECKING
):  # loops.py imports this module lazily; never the reverse at import time
    from openloops.loops import Loop

__all__ = [
    "Question",
    "Method",
    "default_method",
    "describe",
    "check_place",
    "organise",
    "capture",
]

#: Values a ``bool`` answer may arrive as from a form, a voice surface or JSON.
_TRUE = frozenset({"true", "yes", "y", "1", "on"})
_FALSE = frozenset({"false", "no", "n", "0", "off", ""})


[docs] @dataclass(frozen=True) class Question: """One question a method's clarify step asks of an item. ``key`` is the answer's name in the mapping given to ``clarify``; ``kind`` is one of ``bool``, ``choice`` (then ``choices`` lists them), ``text``, ``minutes``, ``time``, ``words`` (a list, or a comma/space separated string). ``when`` names the answer this question depends on (``"actionable=false"``), so an agent or a form can skip what does not apply. """ key: str ask: str kind: str = "bool" choices: tuple[str, ...] = () when: str | None = None def as_dict(self) -> dict[str, Any]: d = {"key": self.key, "ask": self.ask, "kind": self.kind} if self.choices: d["choices"] = list(self.choices) if self.when: d["when"] = self.when return d
[docs] def read(self, value: Any) -> Any: """``value`` as this question's kind, or ``ValueError`` saying what was expected. >>> Question("a", "?").read("No"), Question("m", "?", kind="minutes").read("15") (False, 15) """ if value is None: return None if self.kind == "bool": if isinstance(value, bool): return value if isinstance(value, str) and value.strip().lower() in _TRUE | _FALSE: return value.strip().lower() in _TRUE raise ValueError(f"{self.key} is yes or no, not {value!r}") if self.kind == "minutes": try: minutes = int(value) except (TypeError, ValueError): raise ValueError(f"{self.key} is a number of minutes, not {value!r}") if minutes < 0: raise ValueError(f"{self.key} cannot be negative") return minutes if self.kind == "choice": if value not in self.choices: raise ValueError(f"{self.key} is one of {', '.join(self.choices)}") return value if self.kind == "words": if isinstance(value, str): value = value.replace(",", " ").split() if not isinstance(value, (list, tuple)): raise ValueError(f"{self.key} is a list of words, not {value!r}") return tuple(str(v) for v in value if str(v).strip()) if not isinstance(value, (str, datetime)): raise ValueError(f"{self.key} is text, not {value!r}") return value
[docs] @runtime_checkable class Method(Protocol): """What an organising method supplies. Pure: no clock, file or network. - ``name``: a short id (``gtd``). - ``places``: the values a loop's ``list`` may take under this method. - ``inbox``: where an unclarified capture lands; ``default_place``: where an item the owner asked for directly lands (both among ``places``). - ``questions``: what ``clarify`` asks, in order. ``criteria``: the keyword filters ``engage`` understands. - ``clarify(answers)``: where the answers send the item, as data: ``{place, changes, do_now, close, why}``. ``place`` is ``None`` when the item leaves the system (``close`` then names the lifecycle state, e.g. ``canceled``). - ``organise(loop, place, now, *, others, **fields)``: the field changes a move to ``place`` makes, as a dict, after checking them; ``ValueError`` when the method refuses the move. ``others`` are the other loops, for a rule that counts (a work-in-progress limit). The move itself is applied by :func:`organise`. - ``review(loops, now)``: ``{method, at, sections: [{name, group, rows}], counts}``; only rows that need a decision, each ``{id, title, list, why}``. - ``engage(loops, now, *, limit, **criteria)``: the candidates to do now, best first, each a row with ``why``. """ name: str places: tuple[str, ...] inbox: str default_place: str questions: tuple[Question, ...] criteria: tuple[str, ...] def clarify(self, answers: Mapping[str, Any]) -> dict[str, Any]: ... def organise( self, loop: Loop, place: str, now: datetime, *, others: Iterable[Loop] = (), **fields: Any, ) -> dict[str, Any]: ... def review(self, loops: Iterable[Loop], now: datetime) -> dict[str, Any]: ... def engage( self, loops: Iterable[Loop], now: datetime, *, limit: int | None = None, **criteria: Any, ) -> list[dict[str, Any]]: ...
[docs] def default_method() -> Method: """The method used wherever ``method=`` is not given: Getting Things Done.""" from openloops.gtd import GTD return GTD()
[docs] def describe(method: Method | None = None) -> dict[str, Any]: """A method's vocabulary as flat JSON: what an agent reads before clarifying for it.""" method = method or default_method() return { "name": method.name, "places": list(method.places), "inbox": method.inbox, "default_place": method.default_place, "questions": [q.as_dict() for q in method.questions], "criteria": list(method.criteria), }
[docs] def check_place(method: Method, place: str) -> str: """``place`` if the method has it, else a ``ValueError`` naming its places. >>> check_place(default_method(), "later") Traceback (most recent call last): ... ValueError: gtd has no list 'later'; its lists are in, next, waiting, someday, reference """ if place not in method.places: raise ValueError( f"{method.name} has no list {place!r}; its lists are {', '.join(method.places)}" ) return place
[docs] def organise( loop: Loop, place: str, now: datetime, *, method: Method | None = None, by: str = "owner", accepted: bool = False, others: Iterable[Loop] = (), **fields: Any, ) -> Loop: """``loop`` moved to ``place``, with what the method's rules make of ``fields``. The rules that hold whatever the method: - the loop must be open, and the place one of the method's; - ``accepted=True`` means the owner said yes to this move, in their own words. It turns a proposal into a commitment, and settles a loop that came back (``input-required``): it is open again (``submitted``), with no second push for a time already past. Anyone's move otherwise leaves both as they were, so an agent never reschedules the owner's commitments; - a loop given a new time in the future is scheduled again, whoever moved it; - one ``organised`` entry is logged, by ``by``. >>> now = datetime(2026, 11, 28, 12, tzinfo=timezone.utc) >>> from openloops.loops import new_loop >>> loop = capture("Ask the bank", by="bosun", now=now, id="loop-b") >>> moved = organise(loop, "waiting", now, by="bosun", waiting={"on": "the bank"}) >>> moved.list, moved.proposed_by, moved.waiting["since"] ('waiting', 'bosun', '2026-11-28T12:00:00Z') >>> organise(moved, "waiting", now, accepted=True).proposed_by is None True """ from openloops import loops as _loops method = method or default_method() check_place(method, place) if not loop.open: raise ValueError(f"{loop.id} is already {loop.state}") changes = dict(method.organise(loop, place, now, others=others, **fields)) changes["list"] = place if accepted: changes["proposed_by"] = None if loop.state == "input-required": when = changes.get("remind_at", loop.remind_at) ahead = when is not None and _loops.to_utc(when) > _loops.to_utc(now) if ahead and changes.get("remind_at") not in (None, loop.remind_at): changes["state"] = "submitted" # a new time: it comes back then elif accepted: changes["state"] = "submitted" if not ahead: changes["remind_at"] = None # it already came back: no second push return _loops.mark( loop, now, "organised", by=by, note=f"{loop.list} -> {place}", **changes )
[docs] def capture( title: str, *, by: str, source: Mapping[str, Any] | None = None, method: Method | None = None, now: datetime | None = None, id: str | None = None, ) -> Loop: """A capture made by ``by``, on the method's inbox; an agent's is a proposal. It never pushes and never reaches ``engage`` until the owner accepts it. ``source`` (``{kind, ref, quote, said_by}``) is what makes it traceable; keep the owner's words. >>> loop = capture("Call the notary", by="bosun", source={"kind": "voice", "quote": "call the notary"}, ... now=datetime(2026, 11, 28, tzinfo=timezone.utc), id="loop-c") >>> loop.list, loop.proposed_by, loop.remind_at ('in', 'bosun', None) """ from openloops.loops import new_loop method = method or default_method() loop = new_loop( title, source=source, by=by, now=now, id=id, method=method, list=method.inbox, ) # The owner's own capture is unclarified, not a proposal: nobody else's yes is due. return loop if by == "owner" else replace(loop, proposed_by=by)