lekton 0.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lekton/__init__.py +41 -0
- lekton/check.py +233 -0
- lekton/declare.py +234 -0
- lekton/kinds.py +34 -0
- lekton/promote.py +45 -0
- lekton/py.typed +0 -0
- lekton/registry.py +16 -0
- lekton/relations.py +76 -0
- lekton/thought.py +214 -0
- lekton-0.0.2.dist-info/METADATA +257 -0
- lekton-0.0.2.dist-info/RECORD +13 -0
- lekton-0.0.2.dist-info/WHEEL +4 -0
- lekton-0.0.2.dist-info/licenses/LICENSE +202 -0
lekton/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""lekton: claim kinds built from one primitive.
|
|
2
|
+
|
|
3
|
+
A thought is the primitive. Every other kind is a thought plus something:
|
|
4
|
+
fields it adds (is-a), claims it is made of (composition), or an edge it
|
|
5
|
+
owes (requires).
|
|
6
|
+
|
|
7
|
+
from lekton import Thought, Question, Decision
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .check import Report, check, qualifies, read, resolved_by, status
|
|
11
|
+
from .declare import declare, load_kind, load_kinds, to_yaml
|
|
12
|
+
from .kinds import Decision, Question
|
|
13
|
+
from .promote import promote
|
|
14
|
+
from .registry import kinds
|
|
15
|
+
from .relations import composed_of, requires
|
|
16
|
+
from .thought import About, Assertion, Link, Record, Ref, Thought
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"About",
|
|
20
|
+
"Assertion",
|
|
21
|
+
"Decision",
|
|
22
|
+
"Link",
|
|
23
|
+
"Question",
|
|
24
|
+
"Record",
|
|
25
|
+
"Ref",
|
|
26
|
+
"Report",
|
|
27
|
+
"Thought",
|
|
28
|
+
"check",
|
|
29
|
+
"composed_of",
|
|
30
|
+
"declare",
|
|
31
|
+
"kinds",
|
|
32
|
+
"load_kind",
|
|
33
|
+
"load_kinds",
|
|
34
|
+
"promote",
|
|
35
|
+
"qualifies",
|
|
36
|
+
"read",
|
|
37
|
+
"requires",
|
|
38
|
+
"resolved_by",
|
|
39
|
+
"status",
|
|
40
|
+
"to_yaml",
|
|
41
|
+
]
|
lekton/check.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""Deciding what a claim is by its structure, not its label.
|
|
2
|
+
|
|
3
|
+
`check` is the authority. A class name or a `kind` key is a label, and a
|
|
4
|
+
label can be wrong. `check` looks at what the claim actually carries.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Iterable, Mapping
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from pydantic import ValidationError
|
|
14
|
+
|
|
15
|
+
from .registry import kinds as all_kinds
|
|
16
|
+
from .thought import Link, Ref, Thought
|
|
17
|
+
|
|
18
|
+
Claim = Thought | Mapping[str, Any]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Report:
|
|
23
|
+
"""What `check` found.
|
|
24
|
+
|
|
25
|
+
missing fields or parts the claim lacks; without them it is not this kind
|
|
26
|
+
owed required edges not yet in place; it is this kind, but incomplete
|
|
27
|
+
unverified edges that exist but point at claims that could not be looked up
|
|
28
|
+
revised linked claims that have a newer version than the one pinned
|
|
29
|
+
detail the reason behind each `missing` entry
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
kind: str
|
|
33
|
+
missing: tuple[str, ...] = ()
|
|
34
|
+
owed: tuple[str, ...] = ()
|
|
35
|
+
unverified: tuple[str, ...] = ()
|
|
36
|
+
revised: tuple[str, ...] = ()
|
|
37
|
+
detail: Mapping[str, str] = field(default_factory=dict)
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def fits(self) -> bool:
|
|
41
|
+
"""Is the claim this kind?"""
|
|
42
|
+
return not self.missing
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def complete(self) -> bool:
|
|
46
|
+
"""Is it this kind with every required edge in place and looked up?"""
|
|
47
|
+
return self.fits and not self.owed and not self.unverified
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _data(claim: Claim) -> dict[str, Any]:
|
|
51
|
+
data = claim.model_dump() if isinstance(claim, Thought) else dict(claim)
|
|
52
|
+
data.pop("kind", None) # a label; structure decides
|
|
53
|
+
return data
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _index(known: Iterable[Thought] | Mapping[str, Thought]) -> dict[str, Thought]:
|
|
57
|
+
if isinstance(known, Mapping):
|
|
58
|
+
return dict(known)
|
|
59
|
+
return {claim.id: claim for claim in known}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _links(data: Mapping[str, Any]) -> list[Link]:
|
|
63
|
+
links = []
|
|
64
|
+
for raw in data.get("links") or []:
|
|
65
|
+
try:
|
|
66
|
+
links.append(raw if isinstance(raw, Link) else Link.model_validate(raw))
|
|
67
|
+
except ValidationError:
|
|
68
|
+
continue
|
|
69
|
+
return links
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _empty(value: Any) -> bool:
|
|
73
|
+
return value is None or value == "" or value == [] or value == {}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def check(
|
|
77
|
+
claim: Claim,
|
|
78
|
+
kind: type[Thought] | None = None,
|
|
79
|
+
*,
|
|
80
|
+
known: Iterable[Thought] | Mapping[str, Thought] = (),
|
|
81
|
+
) -> Report:
|
|
82
|
+
"""Check a claim against a kind. Never raises on a claim that falls short.
|
|
83
|
+
|
|
84
|
+
`kind` defaults to the claim's own class, or the thought for plain data.
|
|
85
|
+
`known` is the set of claims that edges can be looked up in.
|
|
86
|
+
"""
|
|
87
|
+
if kind is None:
|
|
88
|
+
kind = type(claim) if isinstance(claim, Thought) else Thought
|
|
89
|
+
data = _data(claim)
|
|
90
|
+
index = _index(known)
|
|
91
|
+
missing: list[str] = []
|
|
92
|
+
detail: dict[str, str] = {}
|
|
93
|
+
|
|
94
|
+
def lacks(name: str, why: str) -> None:
|
|
95
|
+
if name not in missing:
|
|
96
|
+
missing.append(name)
|
|
97
|
+
detail[name] = why
|
|
98
|
+
|
|
99
|
+
# Fields. Pydantic is the judge of shape.
|
|
100
|
+
try:
|
|
101
|
+
kind.model_validate(data)
|
|
102
|
+
except ValidationError as error:
|
|
103
|
+
for problem in error.errors():
|
|
104
|
+
name = str(problem["loc"][0]) if problem["loc"] else "claim"
|
|
105
|
+
lacks(name, problem["msg"])
|
|
106
|
+
# Required means present and not empty, whether or not the class says so.
|
|
107
|
+
for name, info in kind.model_fields.items():
|
|
108
|
+
if info.is_required() and _empty(data.get(name)):
|
|
109
|
+
lacks(name, "required and empty")
|
|
110
|
+
|
|
111
|
+
links = _links(data)
|
|
112
|
+
unverified: list[str] = []
|
|
113
|
+
revised: list[str] = []
|
|
114
|
+
|
|
115
|
+
def targets(verb: str) -> tuple[list[Thought], int]:
|
|
116
|
+
"""The claims a verb points at that could be looked up, and how many could not."""
|
|
117
|
+
found, lost = [], 0
|
|
118
|
+
for link in links:
|
|
119
|
+
if link.verb != verb:
|
|
120
|
+
continue
|
|
121
|
+
target = index.get(link.to.id)
|
|
122
|
+
if target is None:
|
|
123
|
+
lost += 1
|
|
124
|
+
continue
|
|
125
|
+
found.append(target)
|
|
126
|
+
if target.record.version > link.to.version:
|
|
127
|
+
revised.append(
|
|
128
|
+
f"{verb}: {target.id} pinned at v{link.to.version}, now v{target.record.version}"
|
|
129
|
+
)
|
|
130
|
+
return found, lost
|
|
131
|
+
|
|
132
|
+
# Parts. A composite without its parts is not that composite.
|
|
133
|
+
composition = kind.composition()
|
|
134
|
+
if composition is not None:
|
|
135
|
+
found, lost = targets("composed_of")
|
|
136
|
+
if len(found) + lost < composition.min:
|
|
137
|
+
lacks("composed_of", f"needs {composition.min} parts, has {len(found) + lost}")
|
|
138
|
+
for part in composition.parts:
|
|
139
|
+
if any(check(t, part, known=index).fits for t in found):
|
|
140
|
+
continue
|
|
141
|
+
if lost:
|
|
142
|
+
unverified.append(f"composed_of: {part.kind_name()}")
|
|
143
|
+
else:
|
|
144
|
+
lacks(f"composed_of: {part.kind_name()}", "no part of this kind")
|
|
145
|
+
if composition.allows is not None:
|
|
146
|
+
for target in found:
|
|
147
|
+
if not any(check(target, ok, known=index).fits for ok in composition.allows):
|
|
148
|
+
lacks(f"composed_of: {target.id}", f"a {target.kind} is not an allowed part")
|
|
149
|
+
|
|
150
|
+
# Required edges. Owed, not disqualifying.
|
|
151
|
+
owed: list[str] = []
|
|
152
|
+
for verb, wanted in kind.requirements().items():
|
|
153
|
+
label = f"{verb}: {wanted.kind_name()}"
|
|
154
|
+
found, lost = targets(verb)
|
|
155
|
+
if any(check(t, wanted, known=index).fits for t in found):
|
|
156
|
+
continue
|
|
157
|
+
if lost:
|
|
158
|
+
unverified.append(label)
|
|
159
|
+
else:
|
|
160
|
+
owed.append(label)
|
|
161
|
+
|
|
162
|
+
return Report(
|
|
163
|
+
kind=kind.kind_name(),
|
|
164
|
+
missing=tuple(missing),
|
|
165
|
+
owed=tuple(owed),
|
|
166
|
+
unverified=tuple(unverified),
|
|
167
|
+
revised=tuple(dict.fromkeys(revised)),
|
|
168
|
+
detail=detail,
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def qualifies(
|
|
173
|
+
claim: Claim,
|
|
174
|
+
*,
|
|
175
|
+
kinds: Iterable[type[Thought]] | None = None,
|
|
176
|
+
known: Iterable[Thought] | Mapping[str, Thought] = (),
|
|
177
|
+
) -> list[type[Thought]]:
|
|
178
|
+
"""The most specific kinds a claim's structure fits.
|
|
179
|
+
|
|
180
|
+
Empty if it is not even a thought. Kinds that cannot be told from
|
|
181
|
+
their parent by structure (see `Thought.is_distinct`) are skipped.
|
|
182
|
+
"""
|
|
183
|
+
pool = list(kinds) if kinds is not None else list(all_kinds().values())
|
|
184
|
+
index = _index(known)
|
|
185
|
+
fitting = [k for k in pool if k.is_distinct() and check(claim, k, known=index).fits]
|
|
186
|
+
return [k for k in fitting if not any(o is not k and issubclass(o, k) for o in fitting)]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def read(
|
|
190
|
+
data: Claim,
|
|
191
|
+
*,
|
|
192
|
+
kinds: Iterable[type[Thought]] | None = None,
|
|
193
|
+
known: Iterable[Thought] | Mapping[str, Thought] = (),
|
|
194
|
+
) -> Thought:
|
|
195
|
+
"""Build a claim as the most specific known kind its structure fits.
|
|
196
|
+
|
|
197
|
+
A kind this process has never seen comes back as its nearest known
|
|
198
|
+
ancestor with its extra fields intact. Raises if the data is not a thought.
|
|
199
|
+
"""
|
|
200
|
+
payload = _data(data)
|
|
201
|
+
best = qualifies(payload, kinds=kinds, known=known)
|
|
202
|
+
if not best:
|
|
203
|
+
return Thought.model_validate(payload) # raises, saying why
|
|
204
|
+
if len(best) == 1:
|
|
205
|
+
return best[0].model_validate(payload)
|
|
206
|
+
# It fits unrelated kinds at once. Fall back to what they share.
|
|
207
|
+
for shared in best[0].__mro__:
|
|
208
|
+
if issubclass(shared, Thought) and all(issubclass(k, shared) for k in best):
|
|
209
|
+
return shared.model_validate(payload)
|
|
210
|
+
return Thought.model_validate(payload)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def resolved_by(question: Thought, known: Iterable[Thought]) -> list[Thought]:
|
|
214
|
+
"""The claims that resolve a question and still stand.
|
|
215
|
+
|
|
216
|
+
A claim stands until another claim supersedes it.
|
|
217
|
+
"""
|
|
218
|
+
pool = list(known)
|
|
219
|
+
superseded = {ref.id for claim in pool for ref in claim.linked("supersedes")}
|
|
220
|
+
return [
|
|
221
|
+
claim
|
|
222
|
+
for claim in pool
|
|
223
|
+
if claim.id not in superseded
|
|
224
|
+
and any(ref.id == question.id for ref in claim.linked("resolves"))
|
|
225
|
+
]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def status(question: Thought, known: Iterable[Thought]) -> str:
|
|
229
|
+
"""`open` or `answered`. Worked out from edges every time; never stored."""
|
|
230
|
+
return "answered" if resolved_by(question, known) else "open"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
__all__ = ["Claim", "Ref", "Report", "check", "qualifies", "read", "resolved_by", "status"]
|
lekton/declare.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Kinds as data.
|
|
2
|
+
|
|
3
|
+
`declare` writes a kind out in the template format. `load_kind` reads the
|
|
4
|
+
format back and builds the kind at runtime, with no code written. This is
|
|
5
|
+
what lets a kind be shared between graphs.
|
|
6
|
+
|
|
7
|
+
The format, on a question and a decision:
|
|
8
|
+
|
|
9
|
+
question:
|
|
10
|
+
specializes: thought
|
|
11
|
+
adds:
|
|
12
|
+
settled_by: text
|
|
13
|
+
owner: text?
|
|
14
|
+
|
|
15
|
+
decision:
|
|
16
|
+
specializes: thought
|
|
17
|
+
adds:
|
|
18
|
+
chosen: text
|
|
19
|
+
alternatives: [text]
|
|
20
|
+
rationale: text
|
|
21
|
+
requires:
|
|
22
|
+
resolves: question
|
|
23
|
+
|
|
24
|
+
Types: text, integer, number, boolean, date, datetime, a list `[text]`,
|
|
25
|
+
or a choice `open|won|lost`. A trailing `?` marks a field optional, on
|
|
26
|
+
the type for plain values (`text?`) and on the name for lists (`tags?:`).
|
|
27
|
+
A required text or list field must not be empty.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import types
|
|
33
|
+
from collections.abc import Mapping
|
|
34
|
+
from datetime import date, datetime
|
|
35
|
+
from typing import Any, Literal, Union, get_args, get_origin
|
|
36
|
+
|
|
37
|
+
import yaml
|
|
38
|
+
from pydantic import BaseModel, Field, create_model
|
|
39
|
+
|
|
40
|
+
from .registry import kinds as all_kinds
|
|
41
|
+
from .relations import Composition, Requirement
|
|
42
|
+
from .thought import Thought
|
|
43
|
+
|
|
44
|
+
_NAMES: dict[type, str] = {
|
|
45
|
+
str: "text",
|
|
46
|
+
int: "integer",
|
|
47
|
+
float: "number",
|
|
48
|
+
bool: "boolean",
|
|
49
|
+
date: "date",
|
|
50
|
+
datetime: "datetime",
|
|
51
|
+
}
|
|
52
|
+
_TYPES: dict[str, type] = {name: py for py, name in _NAMES.items()}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# --- writing a kind out -----------------------------------------------------
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _spell(annotation: Any) -> tuple[Any, bool]:
|
|
59
|
+
"""An annotation in the template's words, and whether it allows None."""
|
|
60
|
+
origin = get_origin(annotation)
|
|
61
|
+
if origin in (Union, types.UnionType):
|
|
62
|
+
inner = [a for a in get_args(annotation) if a is not type(None)]
|
|
63
|
+
optional = len(inner) < len(get_args(annotation))
|
|
64
|
+
spelled = _spell(inner[0])[0] if len(inner) == 1 else "any"
|
|
65
|
+
return spelled, optional
|
|
66
|
+
if origin is Literal:
|
|
67
|
+
return "|".join(str(a) for a in get_args(annotation)), False
|
|
68
|
+
if origin in (list, tuple, set):
|
|
69
|
+
(inner,) = get_args(annotation) or (Any,)
|
|
70
|
+
return [_spell(inner)[0]], False
|
|
71
|
+
if isinstance(annotation, type) and issubclass(annotation, BaseModel):
|
|
72
|
+
return _fields(annotation.model_fields), False
|
|
73
|
+
return _NAMES.get(annotation, "any"), False
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _fields(model_fields: Mapping[str, Any]) -> dict[str, Any]:
|
|
77
|
+
out: dict[str, Any] = {}
|
|
78
|
+
for name, info in model_fields.items():
|
|
79
|
+
spelled, nullable = _spell(info.annotation)
|
|
80
|
+
# Optional means it may be absent: it allows None, or it is a list
|
|
81
|
+
# that may be empty. A plain value with a default is always present.
|
|
82
|
+
optional = nullable or (isinstance(spelled, list) and not info.is_required())
|
|
83
|
+
if not optional:
|
|
84
|
+
out[name] = spelled
|
|
85
|
+
elif isinstance(spelled, str):
|
|
86
|
+
out[name] = f"{spelled}?"
|
|
87
|
+
else:
|
|
88
|
+
out[f"{name}?"] = spelled
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def declare(kind: type[Thought]) -> dict[str, Any]:
|
|
93
|
+
"""A kind in the template format, as plain data."""
|
|
94
|
+
parent = kind.parent()
|
|
95
|
+
if parent is None:
|
|
96
|
+
return {kind.kind_name(): _fields(kind.model_fields)}
|
|
97
|
+
|
|
98
|
+
body: dict[str, Any] = {"specializes": parent.kind_name()}
|
|
99
|
+
own_composition = next(
|
|
100
|
+
(v for v in vars(kind).values() if isinstance(v, Composition)), None
|
|
101
|
+
)
|
|
102
|
+
if own_composition is not None:
|
|
103
|
+
made_of: dict[str, Any] = {"min": own_composition.min}
|
|
104
|
+
if own_composition.parts:
|
|
105
|
+
made_of["parts"] = [p.kind_name() for p in own_composition.parts]
|
|
106
|
+
if own_composition.allows is not None:
|
|
107
|
+
made_of["allows"] = [a.kind_name() for a in own_composition.allows]
|
|
108
|
+
body["composed_of"] = made_of
|
|
109
|
+
adds = _fields(kind.adds())
|
|
110
|
+
if adds:
|
|
111
|
+
body["adds"] = adds
|
|
112
|
+
own_requirements = {
|
|
113
|
+
verb: target.kind_name()
|
|
114
|
+
for value in vars(kind).values()
|
|
115
|
+
if isinstance(value, Requirement)
|
|
116
|
+
for verb, target in value.edges.items()
|
|
117
|
+
}
|
|
118
|
+
if own_requirements:
|
|
119
|
+
body["requires"] = own_requirements
|
|
120
|
+
return {kind.kind_name(): body}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class _TemplateDumper(yaml.SafeDumper):
|
|
124
|
+
"""Groups on their own lines, a list of plain types inline: `[text]`."""
|
|
125
|
+
|
|
126
|
+
def represent_list(self, data: Any) -> yaml.Node:
|
|
127
|
+
inline = all(isinstance(item, str) for item in data)
|
|
128
|
+
return self.represent_sequence("tag:yaml.org,2002:seq", data, flow_style=inline)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
_TemplateDumper.add_representer(list, _TemplateDumper.represent_list)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def to_yaml(*kinds: type[Thought]) -> str:
|
|
135
|
+
"""One or more kinds as a YAML template."""
|
|
136
|
+
merged: dict[str, Any] = {}
|
|
137
|
+
for kind in kinds:
|
|
138
|
+
merged.update(declare(kind))
|
|
139
|
+
return yaml.dump(merged, Dumper=_TemplateDumper, sort_keys=False, default_flow_style=False)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# --- reading a kind in ------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _class_name(kind_name: str) -> str:
|
|
146
|
+
return "".join(part.capitalize() for part in kind_name.split("_"))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _parse(name: str, spec: Any) -> tuple[str, Any]:
|
|
150
|
+
"""One `adds` entry as a field name and a pydantic field definition."""
|
|
151
|
+
optional = name.endswith("?")
|
|
152
|
+
name = name.rstrip("?")
|
|
153
|
+
if isinstance(spec, str) and spec.endswith("?"):
|
|
154
|
+
optional, spec = True, spec[:-1]
|
|
155
|
+
|
|
156
|
+
if isinstance(spec, list):
|
|
157
|
+
if len(spec) != 1 or spec[0] not in _TYPES:
|
|
158
|
+
raise ValueError(f"{name}: a list is written [type], such as [text]")
|
|
159
|
+
annotation: Any = list[_TYPES[spec[0]]]
|
|
160
|
+
non_empty = True
|
|
161
|
+
elif isinstance(spec, str) and "|" in spec:
|
|
162
|
+
annotation = Literal[tuple(choice.strip() for choice in spec.split("|"))]
|
|
163
|
+
non_empty = False
|
|
164
|
+
elif isinstance(spec, str) and spec in _TYPES:
|
|
165
|
+
annotation = _TYPES[spec]
|
|
166
|
+
non_empty = annotation is str
|
|
167
|
+
else:
|
|
168
|
+
raise ValueError(f"{name}: unknown type {spec!r}")
|
|
169
|
+
|
|
170
|
+
if optional:
|
|
171
|
+
return name, (annotation | None, None)
|
|
172
|
+
if non_empty:
|
|
173
|
+
return name, (annotation, Field(min_length=1))
|
|
174
|
+
return name, (annotation, ...)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _find(name: str, known: Mapping[str, type[Thought]], context: str) -> type[Thought]:
|
|
178
|
+
if name not in known:
|
|
179
|
+
raise ValueError(f"{context}: no kind named {name!r} is defined")
|
|
180
|
+
return known[name]
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def load_kinds(
|
|
184
|
+
source: str | Mapping[str, Any],
|
|
185
|
+
*,
|
|
186
|
+
kinds: Mapping[str, type[Thought]] | None = None,
|
|
187
|
+
) -> dict[str, type[Thought]]:
|
|
188
|
+
"""Build every kind in a template, in order. Later ones may use earlier ones."""
|
|
189
|
+
template = yaml.safe_load(source) if isinstance(source, str) else source
|
|
190
|
+
known = dict(kinds) if kinds is not None else all_kinds()
|
|
191
|
+
built: dict[str, type[Thought]] = {}
|
|
192
|
+
|
|
193
|
+
for name, body in template.items():
|
|
194
|
+
if "specializes" not in body:
|
|
195
|
+
raise ValueError(
|
|
196
|
+
f"{name}: a kind names the kind it specializes. "
|
|
197
|
+
"Only the thought has no parent, and it is not loaded from a template."
|
|
198
|
+
)
|
|
199
|
+
parent = _find(body["specializes"], known, name)
|
|
200
|
+
fields = dict(_parse(n, spec) for n, spec in (body.get("adds") or {}).items())
|
|
201
|
+
model = create_model(_class_name(name), __base__=parent, **fields)
|
|
202
|
+
model.__kind__ = name
|
|
203
|
+
|
|
204
|
+
made_of = body.get("composed_of")
|
|
205
|
+
if made_of:
|
|
206
|
+
model.parts = Composition(
|
|
207
|
+
*[_find(p, known, name) for p in made_of.get("parts", [])],
|
|
208
|
+
allows=(
|
|
209
|
+
[_find(a, known, name) for a in made_of["allows"]]
|
|
210
|
+
if "allows" in made_of
|
|
211
|
+
else None
|
|
212
|
+
),
|
|
213
|
+
min=made_of.get("min", 2),
|
|
214
|
+
)
|
|
215
|
+
owed = body.get("requires")
|
|
216
|
+
if owed:
|
|
217
|
+
model.needs = Requirement(
|
|
218
|
+
**{verb: _find(target, known, name) for verb, target in owed.items()}
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
known[name] = built[name] = model
|
|
222
|
+
return built
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def load_kind(
|
|
226
|
+
source: str | Mapping[str, Any],
|
|
227
|
+
*,
|
|
228
|
+
kinds: Mapping[str, type[Thought]] | None = None,
|
|
229
|
+
) -> type[Thought]:
|
|
230
|
+
"""Build the one kind a template declares."""
|
|
231
|
+
built = load_kinds(source, kinds=kinds)
|
|
232
|
+
if len(built) != 1:
|
|
233
|
+
raise ValueError(f"expected one kind, found {len(built)}; use load_kinds")
|
|
234
|
+
return next(iter(built.values()))
|
lekton/kinds.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""The kinds that ship with the library. These are opinions about what a
|
|
2
|
+
question and a decision are; everything else is yours to define.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from pydantic import Field
|
|
8
|
+
|
|
9
|
+
from .relations import requires
|
|
10
|
+
from .thought import Thought
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Question(Thought):
|
|
14
|
+
"""A thought that is waiting on an answer.
|
|
15
|
+
|
|
16
|
+
There is no status field. A question is open until a claim that still
|
|
17
|
+
stands resolves it (see `status`).
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
settled_by: str = Field(min_length=1) # what would count as an answer
|
|
21
|
+
owner: str | None = None # who is expected to bring it
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Decision(Thought):
|
|
25
|
+
"""A thought that commits to one option over at least one other.
|
|
26
|
+
|
|
27
|
+
The test: can you name what was chosen and one alternative passed over?
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
chosen: str = Field(min_length=1) # identity: a different choice is a different decision
|
|
31
|
+
alternatives: list[str] = Field(min_length=1)
|
|
32
|
+
rationale: str = Field(min_length=1)
|
|
33
|
+
|
|
34
|
+
needs = requires(resolves=Question)
|
lekton/promote.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Turning a thought into something more specific.
|
|
2
|
+
|
|
3
|
+
Promotion is not an edit. It makes a new claim with its own record that
|
|
4
|
+
points back at the thought it came from.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any, TypeVar
|
|
10
|
+
|
|
11
|
+
from .thought import Link, Record, Thought
|
|
12
|
+
|
|
13
|
+
K = TypeVar("K", bound=Thought)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def promote(
|
|
17
|
+
thought: Thought,
|
|
18
|
+
kind: type[K],
|
|
19
|
+
*,
|
|
20
|
+
author: str | None = None,
|
|
21
|
+
captured_from: str | None = None,
|
|
22
|
+
**adds: Any,
|
|
23
|
+
) -> K:
|
|
24
|
+
"""Make a new claim of a more specific kind from an existing one.
|
|
25
|
+
|
|
26
|
+
Pass the fields the kind adds as keyword arguments. Anything the
|
|
27
|
+
thought already carries comes along; pass it again to override (a new
|
|
28
|
+
`assertion`, for instance, when a hypothesis has become settled).
|
|
29
|
+
|
|
30
|
+
Raises if the added fields do not satisfy the kind. Required edges are
|
|
31
|
+
not checked here: run `check` on the result to see what it still owes.
|
|
32
|
+
"""
|
|
33
|
+
if not issubclass(kind, type(thought)) or kind is type(thought):
|
|
34
|
+
raise TypeError(
|
|
35
|
+
f"cannot promote a {thought.kind} to a {kind.kind_name()}: "
|
|
36
|
+
f"{kind.kind_name()} does not specialize {thought.kind}"
|
|
37
|
+
)
|
|
38
|
+
data = thought.model_dump(exclude={"id", "record", "links"})
|
|
39
|
+
data.update(adds)
|
|
40
|
+
data["record"] = Record(
|
|
41
|
+
author=author or thought.record.author,
|
|
42
|
+
captured_from=captured_from,
|
|
43
|
+
)
|
|
44
|
+
data["links"] = [Link(verb="evolved_from", to=thought.ref())]
|
|
45
|
+
return kind.model_validate(data)
|
lekton/py.typed
ADDED
|
File without changes
|
lekton/registry.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Every kind the process knows about, by name."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .thought import Thought
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def kinds() -> dict[str, type[Thought]]:
|
|
9
|
+
"""All defined kinds, the thought first. A later kind with the same name wins."""
|
|
10
|
+
found: dict[str, type[Thought]] = {Thought.kind_name(): Thought}
|
|
11
|
+
queue: list[type[Thought]] = [Thought]
|
|
12
|
+
while queue:
|
|
13
|
+
for sub in queue.pop(0).__subclasses__():
|
|
14
|
+
found[sub.kind_name()] = sub
|
|
15
|
+
queue.append(sub)
|
|
16
|
+
return found
|
lekton/relations.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""The two relations a kind can declare besides is-a.
|
|
2
|
+
|
|
3
|
+
Is-a is subclassing. These are the other two:
|
|
4
|
+
|
|
5
|
+
composed_of the kind is made of other claims
|
|
6
|
+
requires the kind owes an edge to another claim
|
|
7
|
+
|
|
8
|
+
Both are declared as class attributes:
|
|
9
|
+
|
|
10
|
+
class Bet(Thought):
|
|
11
|
+
parts = composed_of(Decision, Risk)
|
|
12
|
+
|
|
13
|
+
class Decision(Thought):
|
|
14
|
+
needs = requires(resolves=Question)
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import TYPE_CHECKING
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from .thought import Thought
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Composition:
|
|
26
|
+
"""What a composite kind is made of.
|
|
27
|
+
|
|
28
|
+
parts kinds it must contain, at least one claim of each
|
|
29
|
+
allows kinds a part may be; None means any claim
|
|
30
|
+
min fewest parts in total; a composite is two or more claims
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
*parts: type[Thought],
|
|
36
|
+
allows: list[type[Thought]] | None = None,
|
|
37
|
+
min: int = 2,
|
|
38
|
+
) -> None:
|
|
39
|
+
if min < 2:
|
|
40
|
+
raise ValueError("a composite is made of two or more claims")
|
|
41
|
+
self.parts = tuple(parts)
|
|
42
|
+
self.allows = tuple(allows) if allows is not None else None
|
|
43
|
+
self.min = max(min, len(self.parts))
|
|
44
|
+
|
|
45
|
+
def __repr__(self) -> str:
|
|
46
|
+
names = ", ".join(p.kind_name() for p in self.parts)
|
|
47
|
+
return f"composed_of({names}, min={self.min})"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Requirement:
|
|
51
|
+
"""Edges a kind owes, verb to target kind.
|
|
52
|
+
|
|
53
|
+
A required edge is a completeness check, not a gate. A decision with
|
|
54
|
+
no question is still a decision. It is an incomplete one.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def __init__(self, **edges: type[Thought]) -> None:
|
|
58
|
+
self.edges = dict(edges)
|
|
59
|
+
|
|
60
|
+
def __repr__(self) -> str:
|
|
61
|
+
pairs = ", ".join(f"{verb}={kind.kind_name()}" for verb, kind in self.edges.items())
|
|
62
|
+
return f"requires({pairs})"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def composed_of(
|
|
66
|
+
*parts: type[Thought],
|
|
67
|
+
allows: list[type[Thought]] | None = None,
|
|
68
|
+
min: int = 2,
|
|
69
|
+
) -> Composition:
|
|
70
|
+
"""Declare that a kind is made of other claims."""
|
|
71
|
+
return Composition(*parts, allows=allows, min=min)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def requires(**edges: type[Thought]) -> Requirement:
|
|
75
|
+
"""Declare an edge a kind owes. Keep these rare."""
|
|
76
|
+
return Requirement(**edges)
|