edify-agents-cli 0.2.0__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.
Files changed (102) hide show
  1. edify/__init__.py +19 -0
  2. edify/__main__.py +6 -0
  3. edify/_toml.py +286 -0
  4. edify/agents.py +261 -0
  5. edify/anim.py +499 -0
  6. edify/assets/commands/build.md +64 -0
  7. edify/assets/commands/plan.md +68 -0
  8. edify/assets/commands/spec.md +63 -0
  9. edify/assets/commands/tasks.md +65 -0
  10. edify/assets/commands/verify.md +67 -0
  11. edify/assets/formats/plan.example.md +455 -0
  12. edify/assets/formats/plan.format.md +128 -0
  13. edify/assets/formats/spec.example.md +483 -0
  14. edify/assets/formats/spec.format.md +116 -0
  15. edify/assets/formats/tasks.example.md +712 -0
  16. edify/assets/formats/tasks.format.md +199 -0
  17. edify/assets/harvest/harvest.md +91 -0
  18. edify/assets/harvest/sources.md +295 -0
  19. edify/assets/harvest/vocab.md +52 -0
  20. edify/assets/manifest.md +30 -0
  21. edify/assets/mcp/default-registry.md +66 -0
  22. edify/assets/skills/adversary.md +61 -0
  23. edify/assets/skills/debugger.md +64 -0
  24. edify/assets/skills/implementer-general.md +53 -0
  25. edify/assets/skills/implementer-go.md +63 -0
  26. edify/assets/skills/implementer-node.md +61 -0
  27. edify/assets/skills/implementer-postgres.md +63 -0
  28. edify/assets/skills/implementer-python.md +65 -0
  29. edify/assets/skills/implementer-react.md +65 -0
  30. edify/assets/skills/planner.md +58 -0
  31. edify/assets/skills/test-writer-node.md +64 -0
  32. edify/assets/skills/test-writer-python.md +60 -0
  33. edify/assets/skills/verifier.md +67 -0
  34. edify/assets/templates/CLAUDE.md +18 -0
  35. edify/assets.py +77 -0
  36. edify/cli.py +681 -0
  37. edify/commands/__init__.py +1 -0
  38. edify/commands/check_cmd.py +72 -0
  39. edify/commands/doctor_cmd.py +206 -0
  40. edify/commands/feedback_cmd.py +90 -0
  41. edify/commands/governance_cmd.py +65 -0
  42. edify/commands/graph_cmd.py +156 -0
  43. edify/commands/harvest_cmd.py +538 -0
  44. edify/commands/init_cmd.py +333 -0
  45. edify/commands/init_new_cmd.py +151 -0
  46. edify/commands/license_cmd.py +80 -0
  47. edify/commands/mcp_cmd.py +159 -0
  48. edify/commands/self_cmd.py +185 -0
  49. edify/commands/setup_cmd.py +79 -0
  50. edify/commands/skills_cmd.py +177 -0
  51. edify/commands/upgrade_cmd.py +178 -0
  52. edify/context.py +57 -0
  53. edify/conventions.py +275 -0
  54. edify/detect.py +313 -0
  55. edify/distribution.py +40 -0
  56. edify/errors.py +66 -0
  57. edify/feedback.py +207 -0
  58. edify/formats/__init__.py +11 -0
  59. edify/formats/check.py +573 -0
  60. edify/formats/document.py +238 -0
  61. edify/formats/finding.py +50 -0
  62. edify/formats/fix.py +114 -0
  63. edify/formats/mcp.py +126 -0
  64. edify/formats/plan.py +151 -0
  65. edify/formats/skill.py +139 -0
  66. edify/formats/spec.py +164 -0
  67. edify/formats/tasks.py +321 -0
  68. edify/governance.py +316 -0
  69. edify/graph/__init__.py +11 -0
  70. edify/graph/extract.py +351 -0
  71. edify/graph/ignore.py +107 -0
  72. edify/graph/langs/__init__.py +93 -0
  73. edify/graph/langs/ctags.py +145 -0
  74. edify/graph/langs/markdown.py +41 -0
  75. edify/graph/langs/patterns.py +361 -0
  76. edify/graph/langs/python_ast.py +154 -0
  77. edify/graph/langs/sqlish.py +86 -0
  78. edify/graph/model.py +102 -0
  79. edify/graph/queries.py +211 -0
  80. edify/graph/store.py +157 -0
  81. edify/harvest/__init__.py +28 -0
  82. edify/harvest/ledger.py +191 -0
  83. edify/harvest/screen.py +236 -0
  84. edify/harvest/sources.py +298 -0
  85. edify/host.py +345 -0
  86. edify/interview.py +354 -0
  87. edify/library.py +176 -0
  88. edify/licensing/__init__.py +30 -0
  89. edify/licensing/ed25519.py +154 -0
  90. edify/licensing/projects.py +223 -0
  91. edify/licensing/tier.py +172 -0
  92. edify/licensing/token.py +149 -0
  93. edify/paths.py +282 -0
  94. edify/selfinstall.py +244 -0
  95. edify/skills.py +108 -0
  96. edify/tsv.py +109 -0
  97. edify/ui.py +334 -0
  98. edify_agents_cli-0.2.0.dist-info/METADATA +408 -0
  99. edify_agents_cli-0.2.0.dist-info/RECORD +102 -0
  100. edify_agents_cli-0.2.0.dist-info/WHEEL +4 -0
  101. edify_agents_cli-0.2.0.dist-info/entry_points.txt +2 -0
  102. edify_agents_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,154 @@
1
+ """Ed25519, in pure Python over the standard library.
2
+
3
+ RFC 8032, the reference construction. It is here for one reason: a licence has to
4
+ verify with no network and no third-party package, on an air-gapped build server,
5
+ because everything else in this product works offline and a licence check that
6
+ phones home would be the one thing that does not.
7
+
8
+ Verification is what the CLI uses. Signing is included because the issuer, which
9
+ is not shipped, signs with it, and a signer nobody can run is a signer nobody can
10
+ test. Neither is fast, and neither needs to be: one signature
11
+ verification per command invocation is roughly a millisecond.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+
18
+ # Curve25519 in Edwards form, as specified.
19
+ _P = 2**255 - 19
20
+ _L = 2**252 + 27742317777372353535851937790883648493
21
+ _D = -121665 * pow(121666, _P - 2, _P) % _P
22
+ _I = pow(2, (_P - 1) // 4, _P)
23
+
24
+ _By = 4 * pow(5, _P - 2, _P) % _P
25
+ _Bx = 0 # filled in below
26
+
27
+
28
+ def _x_recover(y: int) -> int:
29
+ xx = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P)
30
+ x = pow(xx, (_P + 3) // 8, _P)
31
+ if (x * x - xx) % _P != 0:
32
+ x = (x * _I) % _P
33
+ if x % 2 != 0:
34
+ x = _P - x
35
+ return x
36
+
37
+
38
+ _Bx = _x_recover(_By)
39
+ _B = (_Bx % _P, _By % _P, 1, (_Bx * _By) % _P)
40
+
41
+
42
+ def _edwards_add(p: tuple[int, int, int, int], q: tuple[int, int, int, int]) -> tuple[int, int, int, int]:
43
+ x1, y1, z1, t1 = p
44
+ x2, y2, z2, t2 = q
45
+ a = (y1 - x1) * (y2 - x2) % _P
46
+ b = (y1 + x1) * (y2 + x2) % _P
47
+ c = t1 * 2 * _D * t2 % _P
48
+ dd = z1 * 2 * z2 % _P
49
+ e, f, g, h = b - a, dd - c, dd + c, b + a
50
+ return (e * f % _P, g * h % _P, f * g % _P, e * h % _P)
51
+
52
+
53
+ def _edwards_double(p: tuple[int, int, int, int]) -> tuple[int, int, int, int]:
54
+ return _edwards_add(p, p)
55
+
56
+
57
+ def _scalar_mult(p: tuple[int, int, int, int], e: int) -> tuple[int, int, int, int]:
58
+ q = (0, 1, 1, 0)
59
+ while e > 0:
60
+ if e & 1:
61
+ q = _edwards_add(q, p)
62
+ p = _edwards_double(p)
63
+ e >>= 1
64
+ return q
65
+
66
+
67
+ def _compress(p: tuple[int, int, int, int]) -> bytes:
68
+ x, y, z, _ = p
69
+ zinv = pow(z, _P - 2, _P)
70
+ x = x * zinv % _P
71
+ y = y * zinv % _P
72
+ return int.to_bytes(y | ((x & 1) << 255), 32, "little")
73
+
74
+
75
+ def _decompress(data: bytes) -> tuple[int, int, int, int] | None:
76
+ if len(data) != 32:
77
+ return None
78
+ value = int.from_bytes(data, "little")
79
+ sign = value >> 255
80
+ y = value & ((1 << 255) - 1)
81
+ if y >= _P:
82
+ return None
83
+ x = _x_recover(y)
84
+ if x & 1 != sign:
85
+ x = _P - x
86
+ point = (x, y, 1, x * y % _P)
87
+ if not _on_curve(point):
88
+ return None
89
+ return point
90
+
91
+
92
+ def _on_curve(p: tuple[int, int, int, int]) -> bool:
93
+ x, y, z, t = p
94
+ return (
95
+ (-x * x + y * y - z * z - _D * t * t) % _P == 0
96
+ and (x * y) % _P == (z * t) % _P
97
+ )
98
+
99
+
100
+ def _sha512_int(data: bytes) -> int:
101
+ return int.from_bytes(hashlib.sha512(data).digest(), "little")
102
+
103
+
104
+ def public_key(seed: bytes) -> bytes:
105
+ """The 32-byte public key for a 32-byte private seed."""
106
+ if len(seed) != 32:
107
+ raise ValueError("an ed25519 seed is 32 bytes")
108
+ h = hashlib.sha512(seed).digest()
109
+ a = _clamp(h[:32])
110
+ return _compress(_scalar_mult(_B, a))
111
+
112
+
113
+ def sign(message: bytes, seed: bytes) -> bytes:
114
+ if len(seed) != 32:
115
+ raise ValueError("an ed25519 seed is 32 bytes")
116
+ h = hashlib.sha512(seed).digest()
117
+ a = _clamp(h[:32])
118
+ prefix = h[32:]
119
+ pub = _compress(_scalar_mult(_B, a))
120
+ r = _sha512_int(prefix + message) % _L
121
+ big_r = _compress(_scalar_mult(_B, r))
122
+ k = _sha512_int(big_r + pub + message) % _L
123
+ s = (r + k * a) % _L
124
+ return big_r + int.to_bytes(s, 32, "little")
125
+
126
+
127
+ def verify(message: bytes, signature: bytes, pub: bytes) -> bool:
128
+ """True only for a signature this public key actually produced.
129
+
130
+ Every failure path returns False rather than raising, so a malformed licence
131
+ is treated exactly like an absent one: the free plan, stated plainly.
132
+ """
133
+ if len(signature) != 64 or len(pub) != 32:
134
+ return False
135
+ big_r_bytes, s_bytes = signature[:32], signature[32:]
136
+ s = int.from_bytes(s_bytes, "little")
137
+ if s >= _L:
138
+ return False
139
+ big_r = _decompress(big_r_bytes)
140
+ point_a = _decompress(pub)
141
+ if big_r is None or point_a is None:
142
+ return False
143
+ k = _sha512_int(big_r_bytes + pub + message) % _L
144
+ left = _scalar_mult(_B, s)
145
+ right = _edwards_add(big_r, _scalar_mult(point_a, k))
146
+ return _compress(left) == _compress(right)
147
+
148
+
149
+ def _clamp(data: bytes) -> int:
150
+ a = bytearray(data)
151
+ a[0] &= 248
152
+ a[31] &= 127
153
+ a[31] |= 64
154
+ return int.from_bytes(bytes(a), "little")
@@ -0,0 +1,223 @@
1
+ """The project ledger, retired in 0.2.0.
2
+
3
+ It counted how many repositories the free plan had installed into. The public
4
+ edition has no project cap any more, so nothing reads or writes `projects.tsv`. A
5
+ 0.1.x ledger file is left exactly where it is, in `user_config_dir()`, and never
6
+ deleted: it belongs to the person whose machine it is on.
7
+
8
+ What follows describes how the ledger worked while it was read.
9
+
10
+ **A project's identity is its `git remote origin`** (D-7). A re-clone, a second
11
+ worktree, and a fresh CI checkout are all the same project. Keying on the path
12
+ would burn a slot every CI run, which turns the free tier into a bug report; a
13
+ generated UUID inside `.edify/` would get committed and then shared between users.
14
+ The resolved path is the fallback for a folder with no remote, which is exactly
15
+ the case where the path *is* the identity.
16
+
17
+ **It never breaks work already done.** Only a *new* project is refused. A
18
+ repository already in the ledger keeps installing forever, `known()` prunes rows
19
+ whose path is gone so a deleted repository returns its slot without anyone asking,
20
+ and every non-install command ignores the ledger entirely.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import subprocess
26
+ import time
27
+ from dataclasses import dataclass
28
+ from pathlib import Path
29
+
30
+ from ..paths import user_config_dir
31
+ from ..tsv import read_rows, write_rows
32
+
33
+ HEADER = ("key", "path", "first_seen")
34
+
35
+ #: What `register` returns. Three outcomes, and the caller decides which of them
36
+ #: is a failure — this module never raises, because "over the cap" is a fact
37
+ #: about a licence and not an error inside a ledger.
38
+ ALREADY = "already"
39
+ REGISTERED = "registered"
40
+ OVER_CAP = "over_cap"
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Project:
45
+ key: str
46
+ path: str
47
+ first_seen: int = 0
48
+
49
+ @property
50
+ def exists(self) -> bool:
51
+ return Path(self.path).is_dir()
52
+
53
+ @property
54
+ def by_remote(self) -> bool:
55
+ """Keyed on a git remote rather than a path — so a re-clone is free."""
56
+ return not self.key.startswith("path:")
57
+
58
+ def as_dict(self) -> dict[str, object]:
59
+ return {
60
+ "key": self.key,
61
+ "path": self.path,
62
+ "first_seen": self.first_seen,
63
+ "exists": self.exists,
64
+ "keyed_on": "remote" if self.by_remote else "path",
65
+ }
66
+
67
+
68
+ def ledger_path() -> Path:
69
+ """`projects.tsv` beside the licence. `EDIFY_HOME` moves both together."""
70
+ return user_config_dir() / "projects.tsv"
71
+
72
+
73
+ def canonical(root: Path | str) -> str:
74
+ """One spelling of a path, for both the ledger and every comparison.
75
+
76
+ Forward slashes even on Windows. `tsv.escape` doubles a backslash, so a native
77
+ Windows path lands in the file with every separator doubled — reversible, and
78
+ unreadable, which costs exactly the property D-6 is for. `paths.rel` already
79
+ renders this way for the same reason.
80
+ """
81
+ try:
82
+ return Path(root).expanduser().resolve().as_posix()
83
+ except OSError:
84
+ return Path(root).as_posix()
85
+
86
+
87
+ def key_for(root: Path | str) -> str:
88
+ """This project's identity: its origin remote, else its resolved path.
89
+
90
+ Normalised so `git@github.com:me/x.git` and `https://github.com/me/x` are one
91
+ project — otherwise cloning over SSH after cloning over HTTPS costs a slot for
92
+ no reason a person could ever guess.
93
+ """
94
+ remote = _origin(root)
95
+ if remote:
96
+ return _normalise_remote(remote)
97
+ return "path:" + canonical(root)
98
+
99
+
100
+ def known() -> list[Project]:
101
+ """Every project in the ledger whose folder is still there.
102
+
103
+ Pruning on read rather than on a schedule: a deleted repository returns its
104
+ slot the next time anything looks, with no command to run and no support
105
+ ticket. The file is rewritten only when something actually went away.
106
+ """
107
+ rows = _read()
108
+ live = [p for p in rows if p.exists]
109
+ if len(live) != len(rows):
110
+ _write(live)
111
+ return live
112
+
113
+
114
+ def all_rows() -> list[Project]:
115
+ """Everything on disk, pruned or not. For `license projects`, which shows both."""
116
+ return _read()
117
+
118
+
119
+ def register(root: Path | str, cap: int | None) -> str:
120
+ """Record this project, or say it does not fit. Never raises.
121
+
122
+ `cap` is `None` on a paid plan, which means the ledger is still written — so
123
+ a licence that lapses does not suddenly find three arbitrary projects in it —
124
+ and never consulted.
125
+ """
126
+ key = key_for(root)
127
+ resolved = canonical(root)
128
+ rows = known()
129
+
130
+ for row in rows:
131
+ if row.key == key:
132
+ if row.path != resolved:
133
+ # The same project, moved or re-cloned somewhere else. Follow it
134
+ # rather than adding a second row, which is the whole point of D-7.
135
+ rows = [Project(key, resolved, row.first_seen) if r.key == key else r for r in rows]
136
+ _write(rows)
137
+ return ALREADY
138
+
139
+ if cap is not None and len(rows) >= cap:
140
+ return OVER_CAP
141
+
142
+ rows.append(Project(key, resolved, int(time.time())))
143
+ _write(rows)
144
+ return REGISTERED
145
+
146
+
147
+ def forget(key_or_path: str) -> Project | None:
148
+ """Release one slot, by key or by path. Returns what was removed, or None.
149
+
150
+ Releasing a slot must not require a support ticket, so this takes whichever
151
+ of the two things a person has in front of them.
152
+ """
153
+ wanted = str(key_or_path).strip()
154
+ resolved = canonical(wanted)
155
+ rows = _read()
156
+ for row in rows:
157
+ if row.key == wanted or row.path == wanted or (resolved and row.path == resolved):
158
+ _write([r for r in rows if r.key != row.key])
159
+ return row
160
+ return None
161
+
162
+
163
+ def slots(cap: int | None) -> tuple[int, int | None]:
164
+ """`(used, cap)` — what `license status` and the gate copy both print."""
165
+ return len(known()), cap
166
+
167
+
168
+ # ---------------------------------------------------------------------------
169
+
170
+
171
+ def _read() -> list[Project]:
172
+ out: list[Project] = []
173
+ for row in read_rows(ledger_path()):
174
+ if len(row) < 2:
175
+ continue
176
+ try:
177
+ first_seen = int(row[2]) if len(row) > 2 and row[2] else 0
178
+ except ValueError:
179
+ first_seen = 0
180
+ out.append(Project(row[0], row[1], first_seen))
181
+ return out
182
+
183
+
184
+ def _write(rows: list[Project]) -> None:
185
+ write_rows(ledger_path(), [[r.key, r.path, str(r.first_seen)] for r in rows], HEADER)
186
+
187
+
188
+ def _origin(root: Path | str) -> str:
189
+ """`git remote get-url origin`, or nothing.
190
+
191
+ `check=False` with a timeout, the pattern `doctor_cmd` already uses: a machine
192
+ without git, or a folder that is not a checkout, is an ordinary case here and
193
+ not a failure.
194
+ """
195
+ try:
196
+ proc = subprocess.run(
197
+ ["git", "remote", "get-url", "origin"],
198
+ cwd=str(root),
199
+ capture_output=True,
200
+ text=True,
201
+ timeout=10,
202
+ check=False,
203
+ )
204
+ except (OSError, subprocess.SubprocessError):
205
+ return ""
206
+ return proc.stdout.strip() if proc.returncode == 0 else ""
207
+
208
+
209
+ def _normalise_remote(url: str) -> str:
210
+ """`git@host:owner/repo.git` and `https://host/owner/repo` to one string."""
211
+ value = url.strip().rstrip("/")
212
+ for prefix in ("https://", "http://", "ssh://", "git://"):
213
+ if value.startswith(prefix):
214
+ value = value[len(prefix) :]
215
+ break
216
+ else:
217
+ if value.startswith("git@"):
218
+ value = value[4:].replace(":", "/", 1)
219
+ if "@" in value.split("/", 1)[0]: # https://user@host/…
220
+ value = value.split("@", 1)[1]
221
+ if value.endswith(".git"):
222
+ value = value[:-4]
223
+ return value.lower()
@@ -0,0 +1,172 @@
1
+ """Plans, entitlements, and the one limit the public edition keeps.
2
+
3
+ The public edition is the whole working system, on a repository of any size, in as
4
+ many repositories as a person likes, with no account. It has no caps except one:
5
+ the MCP registry scopes a single server into spawns. Every query, every check,
6
+ every command, `--json`, `--exit-code`, `edify upgrade` and the whole methodology
7
+ tree are free, forever.
8
+
9
+ Two licensed plans exist, and both add the same two things:
10
+
11
+ mcp.multi more than one server in the registry
12
+ team the team edition
13
+
14
+ `team` licences are issued on request; `partner` licences are issued free and
15
+ custom per client. Nothing is sold and no price is written anywhere in this
16
+ package.
17
+
18
+ `pro` and `enterprise` are retired. A token that still names one of them verifies,
19
+ and then resolves to the free plan with a stated reason, because a silent
20
+ downgrade is worse than a stated one.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ from dataclasses import dataclass, field
27
+ from pathlib import Path
28
+
29
+ from ..errors import TierRequired
30
+ from ..paths import user_config_dir
31
+ from .token import License, Verdict, parse
32
+
33
+ FREE_MCP_ENTRIES = 1
34
+
35
+ PLANS = ("free", "team", "partner")
36
+
37
+ #: Plans a token may still name but that no longer exist. They resolve to free,
38
+ #: and `current()` says why.
39
+ RETIRED_PLANS = ("pro", "enterprise")
40
+
41
+ # plan → the entitlements it carries.
42
+ _LICENSED = frozenset({"mcp.multi", "team"})
43
+
44
+ ENTITLEMENTS: dict[str, frozenset[str]] = {
45
+ "free": frozenset(),
46
+ "team": _LICENSED,
47
+ "partner": _LICENSED,
48
+ }
49
+
50
+ FEATURE_NAMES = {
51
+ "mcp.multi": f"more than {FREE_MCP_ENTRIES} server in the registry",
52
+ "team": "the team edition",
53
+ }
54
+
55
+
56
+ @dataclass
57
+ class Entitlement:
58
+ """What this machine is allowed to do, and where that came from."""
59
+
60
+ plan: str = "free"
61
+ license: License | None = None
62
+ source: str = "none"
63
+ problem: str = ""
64
+ features: frozenset[str] = field(default_factory=frozenset)
65
+
66
+ @property
67
+ def paid(self) -> bool:
68
+ """Not the free plan.
69
+
70
+ Nothing is paid for; the name is kept for the team-edition plugin seam.
71
+ """
72
+ return self.plan != "free"
73
+
74
+ def allows(self, feature: str) -> bool:
75
+ return feature in self.features
76
+
77
+ def require(self, feature: str) -> None:
78
+ if not self.allows(feature):
79
+ raise TierRequired(FEATURE_NAMES.get(feature, feature))
80
+
81
+ @property
82
+ def node_cap(self) -> int | None:
83
+ """Always `None`. Kept so that `--json` readers get `null`, never a `KeyError`."""
84
+ return None
85
+
86
+ @property
87
+ def mcp_cap(self) -> int | None:
88
+ return None if self.allows("mcp.multi") else FREE_MCP_ENTRIES
89
+
90
+ @property
91
+ def project_cap(self) -> int | None:
92
+ """Always `None`. Kept so that `--json` readers get `null`, never a `KeyError`."""
93
+ return None
94
+
95
+ def as_dict(self) -> dict[str, object]:
96
+ return {
97
+ "plan": self.plan,
98
+ "source": self.source,
99
+ "problem": self.problem,
100
+ "features": sorted(self.features),
101
+ "node_cap": self.node_cap,
102
+ "mcp_cap": self.mcp_cap,
103
+ "project_cap": self.project_cap,
104
+ "license": self.license.as_dict() if self.license else None,
105
+ }
106
+
107
+
108
+ def license_path() -> Path:
109
+ override = os.environ.get("EDIFY_LICENSE_FILE")
110
+ if override:
111
+ return Path(override).expanduser()
112
+ return user_config_dir() / "license"
113
+
114
+
115
+ def current() -> Entitlement:
116
+ """Resolve the entitlement for this invocation.
117
+
118
+ Order: the `EDIFY_LICENSE` environment variable, so CI can carry a token
119
+ without writing a file; then the licence file. A token that fails to verify
120
+ falls back to free and says why, because a silent downgrade is worse than a
121
+ stated one.
122
+ """
123
+ token = os.environ.get("EDIFY_LICENSE", "").strip()
124
+ source = "EDIFY_LICENSE"
125
+ if not token:
126
+ path = license_path()
127
+ if path.is_file():
128
+ token = path.read_text(encoding="utf-8").strip()
129
+ source = str(path)
130
+ if not token:
131
+ return Entitlement(plan="free", source="none", features=ENTITLEMENTS["free"])
132
+
133
+ verdict: Verdict = parse(token)
134
+ if not verdict.valid or verdict.license is None:
135
+ return Entitlement(
136
+ plan="free", source=source, problem=verdict.reason, features=ENTITLEMENTS["free"]
137
+ )
138
+
139
+ lic = verdict.license
140
+ if lic.plan in RETIRED_PLANS:
141
+ return Entitlement(
142
+ plan="free",
143
+ license=lic,
144
+ source=source,
145
+ problem=f"the {lic.plan} plan is retired; team and partner replace it — ask for a new token",
146
+ features=ENTITLEMENTS["free"],
147
+ )
148
+ plan = lic.plan if lic.plan in PLANS else "free"
149
+ features = set(ENTITLEMENTS.get(plan, frozenset()))
150
+ # An explicit feature list on the token can only add, never remove — that is
151
+ # how a bespoke enterprise agreement is expressed without a new plan name.
152
+ features |= {f for f in lic.features if f in FEATURE_NAMES}
153
+ return Entitlement(plan=plan, license=lic, source=source, features=frozenset(features))
154
+
155
+
156
+ def save(token: str) -> Path:
157
+ path = license_path()
158
+ path.parent.mkdir(parents=True, exist_ok=True)
159
+ path.write_text(token.strip() + "\n", encoding="utf-8")
160
+ try:
161
+ path.chmod(0o600)
162
+ except OSError:
163
+ pass
164
+ return path
165
+
166
+
167
+ def clear() -> bool:
168
+ path = license_path()
169
+ if path.is_file():
170
+ path.unlink()
171
+ return True
172
+ return False
@@ -0,0 +1,149 @@
1
+ """The licence token: a signed claim, verified locally.
2
+
3
+ Shape: `edify1.<base64url(payload json)>.<base64url(signature)>`. The signature is
4
+ Ed25519 over the payload bytes. There is no network call, no activation server,
5
+ and no machine fingerprint — the token is a receipt, not a lock.
6
+
7
+ That is a deliberate position: the source is readable, the check is local, and
8
+ anyone determined can remove it. A licence is a contract, and pretending otherwise
9
+ would cost real users offline operation for no protection.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import binascii
16
+ import json
17
+ import os
18
+ import time
19
+ from dataclasses import dataclass, field
20
+
21
+ from .ed25519 import verify
22
+
23
+ PREFIX = "edify1"
24
+
25
+ # The production issuing key. The private half never leaves the issuer, which
26
+ # signs by hand and is not shipped. It is a random 32-byte seed held in a
27
+ # secrets store — *not* a derivable one. The public key of an all-zeros seed,
28
+ # `3b6a27bc…59da29`, shipped in 0.1.0 and let anyone mint a `pro` token; the
29
+ # regression test in `tests/test_licensing.py` makes its return impossible.
30
+ DEFAULT_PUBLIC_KEY_HEX = "ceada7ea65d2959574910cd0c0fb1f5fd862d1da504deb4b27562361c4133ef5"
31
+
32
+
33
+ @dataclass
34
+ class License:
35
+ subject: str = ""
36
+ email: str = ""
37
+ plan: str = "free"
38
+ seats: int = 1
39
+ issued_at: int = 0
40
+ expires_at: int = 0
41
+ features: list[str] = field(default_factory=list)
42
+ raw: str = ""
43
+
44
+ @property
45
+ def expired(self) -> bool:
46
+ return bool(self.expires_at) and time.time() > self.expires_at
47
+
48
+ @property
49
+ def days_left(self) -> int:
50
+ if not self.expires_at:
51
+ return -1
52
+ return max(0, int((self.expires_at - time.time()) // 86400))
53
+
54
+ def as_dict(self) -> dict[str, object]:
55
+ return {
56
+ "subject": self.subject,
57
+ "email": self.email,
58
+ "plan": self.plan,
59
+ "seats": self.seats,
60
+ "issued_at": self.issued_at,
61
+ "expires_at": self.expires_at,
62
+ "expired": self.expired,
63
+ "days_left": self.days_left,
64
+ "features": self.features,
65
+ }
66
+
67
+
68
+ @dataclass
69
+ class Verdict:
70
+ license: License | None
71
+ reason: str = ""
72
+
73
+ @property
74
+ def valid(self) -> bool:
75
+ return self.license is not None
76
+
77
+
78
+ def public_key() -> bytes:
79
+ """The verifying key.
80
+
81
+ `EDIFY_LICENSE_PUBKEY` overrides it so a self-hosted or enterprise issuer can
82
+ sign its own tokens. That is a supported deployment, documented, and it is the
83
+ same reason the gate is a contract rather than a protection measure.
84
+ """
85
+ raw = os.environ.get("EDIFY_LICENSE_PUBKEY", DEFAULT_PUBLIC_KEY_HEX).strip()
86
+ try:
87
+ key = binascii.unhexlify(raw)
88
+ except (binascii.Error, ValueError):
89
+ return b""
90
+ return key if len(key) == 32 else b""
91
+
92
+
93
+ def parse(token: str) -> Verdict:
94
+ """Verify a token and return the licence it carries, or why it does not."""
95
+ token = token.strip()
96
+ if not token:
97
+ return Verdict(None, "no token")
98
+ parts = token.split(".")
99
+ if len(parts) != 3 or parts[0] != PREFIX:
100
+ return Verdict(None, "not an edify licence token")
101
+
102
+ try:
103
+ payload_bytes = _b64decode(parts[1])
104
+ signature = _b64decode(parts[2])
105
+ except (binascii.Error, ValueError):
106
+ return Verdict(None, "the token is not valid base64url")
107
+
108
+ key = public_key()
109
+ if not key:
110
+ return Verdict(None, "no usable verifying key")
111
+ if not verify(payload_bytes, signature, key):
112
+ return Verdict(None, "the signature does not match the issuing key")
113
+
114
+ try:
115
+ payload = json.loads(payload_bytes.decode("utf-8"))
116
+ except (UnicodeDecodeError, json.JSONDecodeError):
117
+ return Verdict(None, "the payload is not JSON")
118
+
119
+ lic = License(
120
+ subject=str(payload.get("sub", "")),
121
+ email=str(payload.get("email", "")),
122
+ plan=str(payload.get("plan", "free")).lower(),
123
+ seats=int(payload.get("seats", 1) or 1),
124
+ issued_at=int(payload.get("iat", 0) or 0),
125
+ expires_at=int(payload.get("exp", 0) or 0),
126
+ features=[str(f) for f in (payload.get("features") or [])],
127
+ raw=token,
128
+ )
129
+ if lic.expired:
130
+ return Verdict(None, f"the licence expired on {time.strftime('%Y-%m-%d', time.gmtime(lic.expires_at))}")
131
+ return Verdict(lic)
132
+
133
+
134
+ def issue(payload: dict[str, object], seed: bytes) -> str:
135
+ """Sign a payload. Used by the issuer, and by the tests that prove this works."""
136
+ from .ed25519 import sign
137
+
138
+ body = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
139
+ signature = sign(body, seed)
140
+ return f"{PREFIX}.{_b64encode(body)}.{_b64encode(signature)}"
141
+
142
+
143
+ def _b64encode(data: bytes) -> str:
144
+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
145
+
146
+
147
+ def _b64decode(data: str) -> bytes:
148
+ padding = "=" * (-len(data) % 4)
149
+ return base64.urlsafe_b64decode(data + padding)