atlas-ade 1.0.0__tar.gz

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 (129) hide show
  1. atlas_ade-1.0.0/LICENSE +21 -0
  2. atlas_ade-1.0.0/PKG-INFO +48 -0
  3. atlas_ade-1.0.0/README.md +34 -0
  4. atlas_ade-1.0.0/ade/__init__.py +7 -0
  5. atlas_ade-1.0.0/ade/__main__.py +10 -0
  6. atlas_ade-1.0.0/ade/budget.py +125 -0
  7. atlas_ade-1.0.0/ade/burn.py +155 -0
  8. atlas_ade-1.0.0/ade/cli.py +79 -0
  9. atlas_ade-1.0.0/ade/config.py +119 -0
  10. atlas_ade-1.0.0/ade/firstrun.py +84 -0
  11. atlas_ade-1.0.0/ade/gitx.py +24 -0
  12. atlas_ade-1.0.0/ade/graph.py +320 -0
  13. atlas_ade-1.0.0/ade/guard.py +381 -0
  14. atlas_ade-1.0.0/ade/herdr.py +120 -0
  15. atlas_ade-1.0.0/ade/home.py +87 -0
  16. atlas_ade-1.0.0/ade/host.py +156 -0
  17. atlas_ade-1.0.0/ade/install.py +467 -0
  18. atlas_ade-1.0.0/ade/lang/__init__.py +12 -0
  19. atlas_ade-1.0.0/ade/lang/c.py +44 -0
  20. atlas_ade-1.0.0/ade/lang/cs.py +49 -0
  21. atlas_ade-1.0.0/ade/lang/go.py +56 -0
  22. atlas_ade-1.0.0/ade/lang/jvm.py +54 -0
  23. atlas_ade-1.0.0/ade/lang/py.py +62 -0
  24. atlas_ade-1.0.0/ade/lang/rs.py +107 -0
  25. atlas_ade-1.0.0/ade/lang/sh.py +43 -0
  26. atlas_ade-1.0.0/ade/lang/ts.py +121 -0
  27. atlas_ade-1.0.0/ade/lib/__init__.py +5 -0
  28. atlas_ade-1.0.0/ade/lib/agent.py +19 -0
  29. atlas_ade-1.0.0/ade/lib/askcard.py +14 -0
  30. atlas_ade-1.0.0/ade/lib/probe.py +72 -0
  31. atlas_ade-1.0.0/ade/meter.json +71 -0
  32. atlas_ade-1.0.0/ade/mods/flight-band/.claude-plugin/plugin.json +5 -0
  33. atlas_ade-1.0.0/ade/mods/flight-band/hooks/hooks.json +1 -0
  34. atlas_ade-1.0.0/ade/mods/flight-band/hooks/register.ts +129 -0
  35. atlas_ade-1.0.0/ade/orca.py +232 -0
  36. atlas_ade-1.0.0/ade/parts.py +85 -0
  37. atlas_ade-1.0.0/ade/parts.toml +67 -0
  38. atlas_ade-1.0.0/ade/providers.py +781 -0
  39. atlas_ade-1.0.0/ade/push.py +117 -0
  40. atlas_ade-1.0.0/ade/q.py +154 -0
  41. atlas_ade-1.0.0/ade/records.py +345 -0
  42. atlas_ade-1.0.0/ade/refuse.py +21 -0
  43. atlas_ade-1.0.0/ade/route.py +105 -0
  44. atlas_ade-1.0.0/ade/route.toml +61 -0
  45. atlas_ade-1.0.0/ade/setup.py +44 -0
  46. atlas_ade-1.0.0/ade/stages/__init__.py +117 -0
  47. atlas_ade-1.0.0/ade/stages/build.py +162 -0
  48. atlas_ade-1.0.0/ade/stages/land.py +826 -0
  49. atlas_ade-1.0.0/ade/stages/lane.py +118 -0
  50. atlas_ade-1.0.0/ade/stages/review.py +362 -0
  51. atlas_ade-1.0.0/ade/stages/test.py +286 -0
  52. atlas_ade-1.0.0/ade/starters/__init__.py +38 -0
  53. atlas_ade-1.0.0/ade/starters/harness/opencode-ade.ts +94 -0
  54. atlas_ade-1.0.0/ade/starters/harness/pi-ade.ts +83 -0
  55. atlas_ade-1.0.0/ade/starters/python.py +35 -0
  56. atlas_ade-1.0.0/ade/starters/typescript.py +41 -0
  57. atlas_ade-1.0.0/ade/survey.py +127 -0
  58. atlas_ade-1.0.0/ade/telemetry.py +481 -0
  59. atlas_ade-1.0.0/ade/template.toml +342 -0
  60. atlas_ade-1.0.0/ade/verbs/__init__.py +5 -0
  61. atlas_ade-1.0.0/ade/verbs/budget.py +64 -0
  62. atlas_ade-1.0.0/ade/verbs/card.py +241 -0
  63. atlas_ade-1.0.0/ade/verbs/cockpit.py +152 -0
  64. atlas_ade-1.0.0/ade/verbs/conduct.py +394 -0
  65. atlas_ade-1.0.0/ade/verbs/config.py +171 -0
  66. atlas_ade-1.0.0/ade/verbs/decide.py +447 -0
  67. atlas_ade-1.0.0/ade/verbs/digest.py +67 -0
  68. atlas_ade-1.0.0/ade/verbs/graph.py +75 -0
  69. atlas_ade-1.0.0/ade/verbs/handover.py +122 -0
  70. atlas_ade-1.0.0/ade/verbs/hook.py +458 -0
  71. atlas_ade-1.0.0/ade/verbs/init.py +259 -0
  72. atlas_ade-1.0.0/ade/verbs/land.py +20 -0
  73. atlas_ade-1.0.0/ade/verbs/link.py +121 -0
  74. atlas_ade-1.0.0/ade/verbs/loop.py +124 -0
  75. atlas_ade-1.0.0/ade/verbs/parts.py +49 -0
  76. atlas_ade-1.0.0/ade/verbs/push.py +20 -0
  77. atlas_ade-1.0.0/ade/verbs/q.py +52 -0
  78. atlas_ade-1.0.0/ade/verbs/rehearse.py +410 -0
  79. atlas_ade-1.0.0/ade/verbs/session.py +126 -0
  80. atlas_ade-1.0.0/ade/verbs/setup.py +115 -0
  81. atlas_ade-1.0.0/ade/verbs/status.py +131 -0
  82. atlas_ade-1.0.0/ade/verbs/telemetry.py +178 -0
  83. atlas_ade-1.0.0/ade/verbs/uninstall.py +39 -0
  84. atlas_ade-1.0.0/ade/verbs/wait.py +26 -0
  85. atlas_ade-1.0.0/ade/verbs/watch.py +113 -0
  86. atlas_ade-1.0.0/ade/wait.py +148 -0
  87. atlas_ade-1.0.0/atlas_ade.egg-info/PKG-INFO +48 -0
  88. atlas_ade-1.0.0/atlas_ade.egg-info/SOURCES.txt +127 -0
  89. atlas_ade-1.0.0/atlas_ade.egg-info/dependency_links.txt +1 -0
  90. atlas_ade-1.0.0/atlas_ade.egg-info/entry_points.txt +2 -0
  91. atlas_ade-1.0.0/atlas_ade.egg-info/top_level.txt +1 -0
  92. atlas_ade-1.0.0/pyproject.toml +29 -0
  93. atlas_ade-1.0.0/setup.cfg +4 -0
  94. atlas_ade-1.0.0/tests/test_budget.py +99 -0
  95. atlas_ade-1.0.0/tests/test_conduct.py +319 -0
  96. atlas_ade-1.0.0/tests/test_config.py +111 -0
  97. atlas_ade-1.0.0/tests/test_decide.py +231 -0
  98. atlas_ade-1.0.0/tests/test_digest.py +54 -0
  99. atlas_ade-1.0.0/tests/test_draft.py +56 -0
  100. atlas_ade-1.0.0/tests/test_firstrun.py +56 -0
  101. atlas_ade-1.0.0/tests/test_graph.py +209 -0
  102. atlas_ade-1.0.0/tests/test_guard.py +305 -0
  103. atlas_ade-1.0.0/tests/test_home.py +63 -0
  104. atlas_ade-1.0.0/tests/test_host.py +79 -0
  105. atlas_ade-1.0.0/tests/test_install.py +271 -0
  106. atlas_ade-1.0.0/tests/test_lang_c.py +35 -0
  107. atlas_ade-1.0.0/tests/test_lang_cs.py +36 -0
  108. atlas_ade-1.0.0/tests/test_lang_go.py +34 -0
  109. atlas_ade-1.0.0/tests/test_lang_jvm.py +37 -0
  110. atlas_ade-1.0.0/tests/test_lang_rs.py +36 -0
  111. atlas_ade-1.0.0/tests/test_link.py +38 -0
  112. atlas_ade-1.0.0/tests/test_loop.py +121 -0
  113. atlas_ade-1.0.0/tests/test_neighbours.py +50 -0
  114. atlas_ade-1.0.0/tests/test_orca.py +198 -0
  115. atlas_ade-1.0.0/tests/test_parts.py +28 -0
  116. atlas_ade-1.0.0/tests/test_port.py +132 -0
  117. atlas_ade-1.0.0/tests/test_providers.py +227 -0
  118. atlas_ade-1.0.0/tests/test_push.py +446 -0
  119. atlas_ade-1.0.0/tests/test_q.py +39 -0
  120. atlas_ade-1.0.0/tests/test_records.py +267 -0
  121. atlas_ade-1.0.0/tests/test_recurring.py +49 -0
  122. atlas_ade-1.0.0/tests/test_rehearse.py +26 -0
  123. atlas_ade-1.0.0/tests/test_session.py +75 -0
  124. atlas_ade-1.0.0/tests/test_setup.py +35 -0
  125. atlas_ade-1.0.0/tests/test_stages.py +406 -0
  126. atlas_ade-1.0.0/tests/test_start.py +33 -0
  127. atlas_ade-1.0.0/tests/test_status.py +78 -0
  128. atlas_ade-1.0.0/tests/test_telemetry.py +408 -0
  129. atlas_ade-1.0.0/tests/test_wait.py +44 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Practice Atlas Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,48 @@
1
+ Metadata-Version: 2.4
2
+ Name: atlas-ade
3
+ Version: 1.0.0
4
+ Summary: A small agentic development environment: one loop, a generated graph; works with Claude Code, Codex, OpenCode or Pi, alone or side by side.
5
+ Author: Practice Atlas Ltd
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://atlas-ade.dev/
8
+ Project-URL: Repository, https://github.com/The-Anthropocene/ade
9
+ Project-URL: Documentation, https://atlas-ade.dev/docs/
10
+ Requires-Python: >=3.11
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Dynamic: license-file
14
+
15
+ # ade
16
+
17
+ A small agentic meta-harness, so that your usage goes on building.
18
+
19
+ Atlas ADE drives Claude Code, Codex, OpenCode or Pi through one loop per card (lane, build, review, test, land), keeps a generated graph of your code, and records what every card cost.
20
+
21
+ <!-- GIF: 20 to 30 seconds, under 1 MB, recorded by the demo thread -->
22
+
23
+ ```sh
24
+ uv tool install git+https://github.com/The-Anthropocene/ade # or: pipx install git+https://github.com/The-Anthropocene/ade
25
+ ```
26
+
27
+ ```sh
28
+ ade init # in your repo: settings, hooks, a first graph
29
+ ade card add "say hello" --path hello.py --done "it prints hello"
30
+ ade loop c1 # lane, build, review, test, land
31
+ ```
32
+
33
+ You need git and one of Claude Code, Codex, OpenCode or Pi, installed and signed in. To try it without spending anything, run `ade rehearse`.
34
+
35
+ No account, no dependencies, nothing phones home. Python 3.11+ and the standard library.
36
+
37
+ ADE runs each vendor's own unmodified CLI under your login. It never reads or stores that login, and it can run on an API key instead.
38
+
39
+ ## Where this came from
40
+
41
+ ADE was built in private first, by Connor Roberts at Practice Atlas Ltd, using ADE itself. Public history starts here, and from now on every landed card is one public commit.
42
+
43
+ ## More
44
+
45
+ - Docs: https://atlas-ade.dev/docs/ (install, quickstart, the verbs)
46
+ - How the loop works: [ARCHITECTURE.md](ARCHITECTURE.md)
47
+ - Contributing: [CONTRIBUTING.md](CONTRIBUTING.md)
48
+ - Licence: MIT, see [LICENSE](LICENSE). The Atlas ADE name and logo are not part of the licence.
@@ -0,0 +1,34 @@
1
+ # ade
2
+
3
+ A small agentic meta-harness, so that your usage goes on building.
4
+
5
+ Atlas ADE drives Claude Code, Codex, OpenCode or Pi through one loop per card (lane, build, review, test, land), keeps a generated graph of your code, and records what every card cost.
6
+
7
+ <!-- GIF: 20 to 30 seconds, under 1 MB, recorded by the demo thread -->
8
+
9
+ ```sh
10
+ uv tool install git+https://github.com/The-Anthropocene/ade # or: pipx install git+https://github.com/The-Anthropocene/ade
11
+ ```
12
+
13
+ ```sh
14
+ ade init # in your repo: settings, hooks, a first graph
15
+ ade card add "say hello" --path hello.py --done "it prints hello"
16
+ ade loop c1 # lane, build, review, test, land
17
+ ```
18
+
19
+ You need git and one of Claude Code, Codex, OpenCode or Pi, installed and signed in. To try it without spending anything, run `ade rehearse`.
20
+
21
+ No account, no dependencies, nothing phones home. Python 3.11+ and the standard library.
22
+
23
+ ADE runs each vendor's own unmodified CLI under your login. It never reads or stores that login, and it can run on an API key instead.
24
+
25
+ ## Where this came from
26
+
27
+ ADE was built in private first, by Connor Roberts at Practice Atlas Ltd, using ADE itself. Public history starts here, and from now on every landed card is one public commit.
28
+
29
+ ## More
30
+
31
+ - Docs: https://atlas-ade.dev/docs/ (install, quickstart, the verbs)
32
+ - How the loop works: [ARCHITECTURE.md](ARCHITECTURE.md)
33
+ - Contributing: [CONTRIBUTING.md](CONTRIBUTING.md)
34
+ - Licence: MIT, see [LICENSE](LICENSE). The Atlas ADE name and logo are not part of the licence.
@@ -0,0 +1,7 @@
1
+ # id: ade
2
+ # what: Atlas ADE package; verbs live in ade/verbs and are discovered, never listed
3
+ # cmd: -
4
+ # reads: -
5
+ # writes: -
6
+
7
+ TAGLINE = "Atlas ADE, the meta-harness for your agentic workflows"
@@ -0,0 +1,10 @@
1
+ # id: ade.main
2
+ # what: `python -m ade` entry, same as bin/ade
3
+ # cmd: python -m ade <verb> [args]
4
+ # reads: -
5
+ # writes: -
6
+ import sys
7
+
8
+ from ade.cli import main
9
+
10
+ sys.exit(main())
@@ -0,0 +1,125 @@
1
+ # id: ade.budget
2
+ # what: measure core lines (total and per component), hooks, refusal codes and test functions against the budgets in ade.toml
3
+ # cmd: -
4
+ # reads: source files, ade/ package source
5
+ # writes: -
6
+ import ast
7
+ from collections import Counter
8
+
9
+ from ade import graph, host, install
10
+ from ade.config import KIT, matches
11
+ from ade.gitx import git
12
+
13
+
14
+ def text_of(node):
15
+ """A string literal as is, an f-string with each {expr} shown as <expr>, anything else as <set at run time>."""
16
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
17
+ return node.value
18
+ if isinstance(node, ast.JoinedStr):
19
+ return "".join(v.value if isinstance(v, ast.Constant) else f"<{ast.unparse(v.value)}>" for v in node.values)
20
+ return "<set at run time>"
21
+
22
+
23
+ def refusals():
24
+ """One entry per refuse() call whose code is a literal: code, cause, cure and file:line."""
25
+ out = []
26
+ for p in sorted((KIT / "ade").rglob("*.py")):
27
+ for node in ast.walk(ast.parse(host.read(p))):
28
+ if (isinstance(node, ast.Call) and getattr(node.func, "id", getattr(node.func, "attr", None)) == "refuse"
29
+ and node.args and isinstance(node.args[0], ast.Constant)):
30
+ rest = [text_of(a) for a in node.args[1:3]] + ["<set at run time>"] * 2
31
+ out.append({"code": node.args[0].value, "cause": rest[0], "cure": rest[1],
32
+ "at": f"{p.relative_to(KIT)}:{node.lineno}"})
33
+ return out
34
+
35
+
36
+ def refusal_codes():
37
+ return sorted({r["code"] for r in refusals()})
38
+
39
+
40
+ def test_count(root):
41
+ # Test functions under tests/, counted from the source so a skipped or renamed file still shows.
42
+ # Only files git tracks count, so a stray untracked .py cannot move the row; outside a git repo, every file does.
43
+ r = git(root, "ls-files", "--", "tests", check=False)
44
+ files = ([root / n for n in r.stdout.splitlines() if n.endswith(".py")] if r.returncode == 0
45
+ else (root / "tests").rglob("*.py"))
46
+ files = [p for p in files if not any(d.startswith("fixture_") for d in p.relative_to(root).parts[:-1])]
47
+ return sum(isinstance(n, ast.FunctionDef) and n.name.startswith("test")
48
+ for p in files for n in ast.walk(ast.parse(host.read(p))))
49
+
50
+
51
+ def is_core(ctx, name):
52
+ b = ctx.cfg["budgets"]
53
+ return matches(name, b["core"]) and not matches(name, b["core_exclude"]) and name != ctx.cfg["graph"]["out"]
54
+
55
+
56
+ def off(ctx):
57
+ return not ctx.cfg["budgets"]["core"]
58
+
59
+
60
+ def core_files(ctx):
61
+ names = git(ctx.root, "ls-files", "-co", "--exclude-standard").splitlines()
62
+ return [n for n in names if is_core(ctx, n) and (ctx.root / n).is_file()]
63
+
64
+
65
+ def component(ctx, name):
66
+ # Each core file belongs to exactly one component; none or several is a hole in the budget, reported as a row.
67
+ comps = ctx.cfg["budgets"]["components"]
68
+ if not comps:
69
+ return "core"
70
+ hits = [k for k, v in comps.items() if matches(name, v["globs"])]
71
+ return hits[0] if len(hits) == 1 else "overlapping" if hits else "unassigned"
72
+
73
+
74
+ class Rows(list):
75
+ """The budget rows, plus a note (core bytes) that render prints under them; never a row, never a cap."""
76
+ note = ""
77
+
78
+
79
+ def measure(ctx):
80
+ b = ctx.cfg["budgets"]
81
+ per = Counter()
82
+ size = 0
83
+ for n in core_files(ctx):
84
+ per[component(ctx, n)] += len(host.read(ctx.root / n, errors="replace").splitlines())
85
+ size += (ctx.root / n).stat().st_size
86
+ rows = Rows([("core lines", sum(per.values()), b["core_lines"])])
87
+ rows.note = f"core bytes {size / 1000:.0f} KB (note only, no cap)"
88
+ if b["components"]:
89
+ # The components' ceilings add up to the cap that really binds; printed beside the headline so it shows.
90
+ rows += [("component ceilings", sum(v["lines"] for v in b["components"].values()), b["core_lines"])]
91
+ rows += [(k, per[k], v["lines"]) for k, v in b["components"].items()]
92
+ rows += [(k, per[k], 0) for k in ("unassigned", "overlapping") if per[k]]
93
+ # Hooks and refusal codes are the kit's own budgets; a user's project shows only its lines.
94
+ if not ((ctx.root / "ade" / "cli.py").is_file() and (ctx.root / graph.ROUTE).is_file()):
95
+ return rows
96
+ # Counted from what init emits, not the file: settings.local.json is gitignored, so CI never has one.
97
+ s =install.local_settings({})
98
+ rows += [("hooks", install.hook_count(s), b["hooks"]),
99
+ ("refusal codes", len(refusal_codes()), b["refusal_codes"]),
100
+ ("test functions", test_count(ctx.root), b["tests"])]
101
+ return rows
102
+
103
+
104
+ def net_by_component(ctx, rev_range):
105
+ # Net core lines a change adds per component; files outside the core budget are summed as "not core".
106
+ net = Counter()
107
+ for line in git(ctx.root, "diff", "--numstat", "--no-renames", rev_range).splitlines():
108
+ add, rem, name = line.split("\t", 2)
109
+ if add != "-":
110
+ net[component(ctx, name) if is_core(ctx, name) else "not core"] += int(add) - int(rem)
111
+ return dict(sorted(net.items()))
112
+
113
+
114
+ HARD = ("core lines", "hooks", "refusal codes", "test functions") # the one rule: only these rows stop; the rest are notes
115
+
116
+
117
+ def over(rows):
118
+ # The rows over their limit, split into (hard, notes); the verb and land both read this, so they never disagree.
119
+ bad = [r for r in rows if r[1] > r[2]]
120
+ return [r for r in bad if r[0] in HARD], [r for r in bad if r[0] not in HARD]
121
+
122
+
123
+ def render(rows):
124
+ w = max(14, *(len(name) + 1 for name, _, _ in rows))
125
+ return "\n".join([f"{name:<{w}} {val:>6} / {lim:<6} {'ok' if val <= lim else 'OVER' if name in HARD else 'over (note)'}" for name, val, lim in rows] + ([rows.note] if getattr(rows, "note", "") else []))
@@ -0,0 +1,155 @@
1
+ # id: ade.burn
2
+ # what: the 7-day burn as one command: this machine's Claude Code and Codex token use, per day and by surface, thread, model and class, priced in meter points
3
+ # cmd: ade telemetry --week [--json] [--since ISO]
4
+ # reads: $CLAUDE_CONFIG_DIR or ~/.claude projects/**/*.jsonl (usage, model, timestamp, entrypoint, isSidechain only), $CODEX_HOME or ~/.codex sessions token counts, .ade/records.jsonl usage rows and the machine lanes.jsonl (lane labels), ade/meter.json
5
+ # writes: -
6
+ import json
7
+ import os
8
+ from collections import defaultdict
9
+ from datetime import datetime, timedelta, timezone
10
+ from pathlib import Path
11
+
12
+ from ade import records, telemetry
13
+ from ade.refuse import refuse
14
+
15
+ SURFACE = {"cli": "terminal", "claude-desktop": "desktop", "sdk-cli": "headless/SDK", "sdk-ts": "headless/SDK", "sdk-py": "headless/SDK"}
16
+ BLIND = "not visible here: cloud sessions, claude.ai, other machines"
17
+
18
+
19
+ def _lines(root, pattern, since=None):
20
+ # Every line of every matching file, unreadable files skipped (and, given `since`, files last written before it); the caller keeps only the fields it needs.
21
+ for p in sorted(root.glob(pattern)):
22
+ try:
23
+ if since and datetime.fromtimestamp(p.stat().st_mtime, timezone.utc) < since:
24
+ continue
25
+ yield from p.read_text(encoding="utf-8", errors="replace").splitlines()
26
+ except OSError:
27
+ continue
28
+
29
+
30
+ def _n(u, k):
31
+ # One count under whichever of the provider's names for it is present (Codex says cached_input_tokens).
32
+ return next((u[n] for n in telemetry.NAMES[k] if u.get(n)), 0)
33
+
34
+
35
+ def _json(line, *needles):
36
+ if all(n in line for n in needles):
37
+ try:
38
+ r = json.loads(line)
39
+ except ValueError:
40
+ return None
41
+ return r if isinstance(r, dict) else None
42
+
43
+
44
+ def rows(ctx, since, info=None):
45
+ """One dict per API message (Claude: once per message id and request id) or Codex token delta since `since`."""
46
+ cfg = Path(os.path.expanduser(os.environ.get("CLAUDE_CONFIG_DIR") or "~/.claude"))
47
+ lanes, nrepos = telemetry.lane_calls(ctx)
48
+ seen, out = set(), []
49
+ if info is not None:
50
+ info["lane_repos"] = nrepos
51
+ for line in _lines(cfg, "projects/**/*.jsonl", since):
52
+ r = _json(line, '"usage"')
53
+ m = (r or {}).get("message")
54
+ at = telemetry._when((r or {}).get("timestamp"))
55
+ if not (r and r.get("type") == "assistant" and isinstance(m, dict) and isinstance(m.get("usage"), dict) and at and at >= since):
56
+ continue
57
+ key = (m.get("id"), r.get("requestId"))
58
+ if key in seen: # an API message is written once per content block
59
+ continue
60
+ seen.add(key)
61
+ u = m["usage"]
62
+ lane = any(end - timedelta(seconds=w + 5) <= at <= end + timedelta(seconds=5) for end, w in lanes if end)
63
+ out.append({"day": at.astimezone(timezone.utc).date().isoformat(), "model": str(m.get("model", "?")),
64
+ "surface": "ADE lanes" if lane else SURFACE.get(r.get("entrypoint"), "other"),
65
+ "thread": "subagent" if r.get("isSidechain") else "main", "priced": True,
66
+ **{k: _n(u, k) for k in telemetry.KINDS}})
67
+ home = Path(os.path.expanduser(os.environ.get("CODEX_HOME") or "~/.codex"))
68
+ last = {}
69
+ for f in sorted((home / "sessions").glob("*/*/*/rollout-*.jsonl")):
70
+ prev = defaultdict(int)
71
+ for line in _lines(f.parent, f.name):
72
+ r = _json(line, '"token_count"')
73
+ p = (r or {}).get("payload") or {}
74
+ tot = (p.get("info") or {}).get("total_token_usage")
75
+ at = telemetry._when(r.get("timestamp")) if r else None
76
+ if not (isinstance(tot, dict) and p.get("type") == "token_count" and at):
77
+ continue
78
+ now = {k: _n(tot, k) for k in telemetry.KINDS}
79
+ d = {k: now[k] - prev[k] for k in now}
80
+ prev.update(now)
81
+ d["tokens_in"] -= d["cache_read"] # codex counts cached tokens inside input
82
+ if at >= since and min(d.values()) >= 0 and any(d.values()):
83
+ out.append({"day": at.astimezone(timezone.utc).date().isoformat(), "model": "codex", "surface": "codex",
84
+ "thread": "main", "priced": False, **d})
85
+ return out
86
+
87
+
88
+ def week(ctx, since=None):
89
+ """The burn as plain data: the same dict is printed and dumped as JSON."""
90
+ now = datetime.now(timezone.utc)
91
+ reset = telemetry._reading(ctx, "claude")[3]
92
+ start = since or (telemetry._when(reset) - timedelta(days=7) if reset and telemetry._when(reset) else None) or now - timedelta(days=7)
93
+ start = start if start.tzinfo else start.replace(tzinfo=timezone.utc)
94
+ info = {}
95
+ m, data = telemetry._model(ctx), rows(ctx, start, info)
96
+ days = max((now - start).total_seconds() / 86400, 1)
97
+ for r in data:
98
+ r["tokens"] = sum(r[k] for k in telemetry.KINDS)
99
+ r["points"] = round(telemetry.points(ctx, r, m) * 100, 3) if r["priced"] else 0.0
100
+ def by(key):
101
+ t = defaultdict(lambda: dict.fromkeys(("tokens", "points", *telemetry.KINDS), 0))
102
+ for r in data:
103
+ for k in ("tokens", "points", *telemetry.KINDS):
104
+ t[r[key]][k] += r[k]
105
+ return {n: {k: round(v, 3) for k, v in sorted(t[n].items())} for n in sorted(t)}
106
+ total = {k: round(sum(r[k] for r in data), 3) for k in ("tokens", "points", *telemetry.KINDS)}
107
+ meters = {n: {"state": s, "week": w} for n in ("claude", "codex") for s, w, *_ in [telemetry.reading(ctx, n)] if s != "none"}
108
+ cl = meters.get("claude", {})
109
+ gap = cl.get("week") if cl.get("state") == "ok" else None
110
+ rs = telemetry._when(reset) if reset else None
111
+ wk = rs - timedelta(days=7) if rs else None # the current meter week starts here; the gap never reaches before it
112
+ span = bool(since) and wk is None
113
+ if span:
114
+ gap = None
115
+ gap_rows = [r for r in data if wk is None or r["day"] >= wk.astimezone(timezone.utc).date().isoformat()]
116
+ from_week = wk.date().isoformat() if wk and wk > start else None
117
+ seen = max((r["seen"] for r in telemetry.readings(ctx) if r["provider"] == "claude" and "week" in r), default=None)
118
+ return {"since": start.isoformat(timespec="seconds"), "days": round(days, 2), "total": total,
119
+ "per_day_average": {k: round(v / days, 3) for k, v in total.items()},
120
+ "by_day": by("day"), "by_surface": by("surface"), "by_thread": by("thread"), "by_model": by("model"),
121
+ "by_class": {k: total[k] for k in telemetry.KINDS}, "meters": meters,
122
+ "meter_seen": seen if cl and cl["state"] != "ok" else None,
123
+ "priced_vs_meter_points": None if gap is None else round(gap * 100 - sum(r["points"] for r in gap_rows), 3),
124
+ "gap_since": from_week, "gap_may_span_reset": span,
125
+ "lane_repos": info["lane_repos"], "unit": "points are priced by ade/meter.json for Claude only; Codex shows tokens", "blind": BLIND}
126
+
127
+
128
+ def show(d):
129
+ t, a = d["total"], d["per_day_average"]
130
+ print(f"since {d['since'][:10]} ({d['days']} days): {t['tokens']} tokens, {t['points']:.1f} points; per day {a['tokens']:.0f} tokens, {a['points']:.1f} points")
131
+ for title, key in (("day", "by_day"), ("surface", "by_surface"), ("thread", "by_thread"), ("model", "by_model")):
132
+ print(f"by {title}:")
133
+ for n, v in d[key].items():
134
+ print(f" {n:<22} {v['tokens']:>12} tokens {v['points']:>8.1f} points")
135
+ print(f"lanes from {d['lane_repos']} repo{'s' * (d['lane_repos'] != 1)} on this machine")
136
+ print("by class: " + ", ".join(f"{k[7:] if k.startswith('tokens_') else k} {v}" for k, v in d["by_class"].items()))
137
+ for n, v in d["meters"].items():
138
+ print(f"{n} meter: {v['state']}, week {'?' if v['week'] is None else format(v['week'], '.0%')}")
139
+ if d["priced_vs_meter_points"] is not None:
140
+ print(f"meter minus priced burn: {d['priced_vs_meter_points']:.1f} points" + (f" (only the week since {d['gap_since']})" if d.get("gap_since") else ""))
141
+ elif d.get("gap_may_span_reset"):
142
+ print("no meter-minus-priced gap: the reset is unknown, so this window may span a reset")
143
+ elif "claude" in d["meters"]:
144
+ if d["meters"]["claude"]["state"] == "reset":
145
+ print("no fresh meter reading since the week reset")
146
+ else:
147
+ print(f"no fresh meter reading since {d['meter_seen']}")
148
+ print(d["blind"])
149
+
150
+
151
+ def run(ctx, args):
152
+ if args.since and not args.week or args.json and not args.week:
153
+ refuse("burn-args", "--json and --since go with --week", "run ade telemetry --week [--json] [--since ISO]")
154
+ d = week(ctx, args.since)
155
+ print(json.dumps(d, indent=1, sort_keys=True)) if args.json else show(d)
@@ -0,0 +1,79 @@
1
+ # id: ade.cli
2
+ # what: parse argv and dispatch to a verb discovered from ade/verbs (module name = verb, header `what` = help)
3
+ # cmd: ade <verb> [args]
4
+ # reads: ade/verbs/*.py
5
+ # writes: -
6
+ import argparse
7
+ import difflib
8
+ import importlib
9
+ import os
10
+ import pkgutil
11
+ import sys
12
+ from importlib import metadata
13
+
14
+ import ade.verbs
15
+ from ade import TAGLINE, config, host, records
16
+ from ade.graph import header
17
+ from ade.refuse import Refusal
18
+
19
+
20
+ def verbs():
21
+ return {m.name.replace("_", "-"): mod for m in pkgutil.iter_modules(ade.verbs.__path__)
22
+ if hasattr(mod := importlib.import_module(f"ade.verbs.{m.name}"), "run")}
23
+
24
+
25
+ def _version():
26
+ # install.kit(): the version plus the commit when the kit is a checkout; an installed release has no pyproject, so its metadata names it.
27
+ from ade import install
28
+ text = install.kit()
29
+ if text.startswith("unknown"):
30
+ try:
31
+ return metadata.version("atlas-ade") + text[len("unknown"):]
32
+ except metadata.PackageNotFoundError:
33
+ return "(from a clone, not installed)"
34
+ return text
35
+
36
+
37
+ def parser():
38
+ """The whole command line, built from each verb's own add(); the conductor's route is checked against it too."""
39
+ p = argparse.ArgumentParser(prog="ade", description=TAGLINE + ".",
40
+ epilog="Settings: ade.toml; find one with `ade config WORD`. ade.toml is protected: you may run `ade parts set` (and `ade setup`); name any other key to the person, who changes it and reruns `ade init`.")
41
+ p.add_argument("--version", action="version", version=f"ade {_version()}")
42
+ sub = p.add_subparsers(dest="verb", required=True, metavar="<verb>")
43
+ found = verbs()
44
+ for name, mod in sorted(found.items()):
45
+ what = (header(host.read(mod.__file__)) or {}).get("what", "")
46
+ sp = sub.add_parser(name, help=what, description=what)
47
+ if hasattr(mod, "add"):
48
+ mod.add(sp)
49
+ return p, found
50
+
51
+
52
+ def main(argv=None, cwd=None):
53
+ for stream in (sys.stdout, sys.stderr):
54
+ if hasattr(stream, "reconfigure"):
55
+ stream.reconfigure(errors="replace") # a console that cannot hold a character gets '?', not a traceback
56
+ cwd = cwd or os.getcwd()
57
+ argv = sys.argv[1:] if argv is None else argv
58
+ if not argv:
59
+ from ade import home
60
+ return home.show(cwd)
61
+ p, found = parser()
62
+ first = argv[0]
63
+ if not first.startswith("-") and first not in found:
64
+ hint = f"; did you mean {near[0]}?" if (near := difflib.get_close_matches(first, found, n=1)) else ""
65
+ print(f"ade: no verb {first}; run ade alone for the verb list{hint}", file=sys.stderr)
66
+ return 2
67
+ args = p.parse_args(argv)
68
+ try:
69
+ return found[args.verb].run(args, cwd) or 0
70
+ except BrokenPipeError:
71
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno()) # the exit flush must not raise again
72
+ return 141 # the shell's code for a closed pipe
73
+ except Refusal as r:
74
+ print(r.render(), file=sys.stderr)
75
+ try:
76
+ records.fired(config.load(cwd), r, getattr(args, "card", None))
77
+ except Refusal:
78
+ pass # not an ade repo, so there are no records to count it in
79
+ return 2
@@ -0,0 +1,119 @@
1
+ # id: ade.config
2
+ # what: find the repo root (the main worktree, even from a lane), load ade.toml over the bundled template, match globs
3
+ # cmd: -
4
+ # reads: ade.toml, ade/template.toml
5
+ # writes: -
6
+ import fnmatch
7
+ import json
8
+ import os
9
+ import subprocess
10
+ import tomllib
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ from ade import host
15
+ from ade.telemetry import PLANS
16
+ from ade.refuse import refuse
17
+
18
+ KIT = Path(__file__).resolve().parent.parent
19
+ TEMPLATE = Path(__file__).with_name("template.toml")
20
+
21
+
22
+ @dataclass
23
+ class Ctx:
24
+ root: Path
25
+ cfg: dict
26
+ renumbered: dict = field(default_factory=dict) # {old: new} card ids push.push moved when records met another machine's
27
+
28
+ @property
29
+ def state(self):
30
+ return self.root / ".ade"
31
+
32
+
33
+ def merge(base, over):
34
+ # Tables merge key by key; lists and scalars from ade.toml replace the template's.
35
+ out = dict(base)
36
+ for k, v in over.items():
37
+ out[k] = merge(out[k], v) if isinstance(v, dict) and isinstance(out.get(k), dict) else v
38
+ return out
39
+
40
+
41
+ def _git(cwd, *args):
42
+ try:
43
+ r = subprocess.run(["git", *args], cwd=cwd, capture_output=True)
44
+ except FileNotFoundError:
45
+ refuse("git.failed", "git is not on PATH", "install git or put it on PATH, then rerun the same ade command")
46
+ return r.stdout.decode("utf-8", "replace").strip() if r.returncode == 0 else None
47
+
48
+
49
+ def toplevel(cwd):
50
+ top = _git(cwd, "rev-parse", "--show-toplevel")
51
+ return Path(top).resolve() if top else None
52
+
53
+
54
+ def main_worktree(cwd):
55
+ # Lanes are worktrees elsewhere on disk; records and config belong to the main checkout.
56
+ out = _git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel")
57
+ if out is None:
58
+ return None
59
+ common, _, top = out.partition("\n")
60
+ common = Path(common).resolve()
61
+ return common.parent if common.name == ".git" else Path(top).resolve()
62
+
63
+
64
+ CHOICES = {("usage", "plan"): tuple(PLANS), ("usage", "unit"): ("dollars", "meter", "plan_dollars"),
65
+ ("land", "strays"): ("off", "warn")}
66
+
67
+
68
+ def load_at(root, own=True): # own=False: the template alone, for a broken ade.toml
69
+ cfg = tomllib.loads(host.read(TEMPLATE))
70
+ f = Path(root) / "ade.toml"
71
+ if own and f.is_file():
72
+ try:
73
+ cfg = merge(cfg, tomllib.loads(host.read(f)))
74
+ except tomllib.TOMLDecodeError as e:
75
+ refuse("config.value", f"ade.toml is not valid TOML: {e}", "fix that line in ade.toml, then rerun")
76
+ for kind in ("allow", "deny"): # a rule set to false in ade.toml drops the template's rule, for every reader
77
+ rules = cfg["permissions"][kind]
78
+ cfg["permissions"][kind] = {k: v for k, v in rules.items() if v is not False}
79
+ _flight(cfg, json.loads(os.environ.get("ADE_FLIGHT") or "{}"))
80
+ from ade.providers import check_pass_env # here, not at the top: providers imports install, which imports config
81
+ check_pass_env(cfg)
82
+ for (sec, key), ok in CHOICES.items(): # one table of the values a key takes; a typo refuses here, never guessed
83
+ if cfg.get(sec, {}).get(key, ok[0]) not in ok:
84
+ refuse("config.value", f"[{sec}] {key} = {cfg[sec][key]!r} is not a value", f"use one of: {', '.join(ok)}")
85
+ return Ctx(Path(root).resolve(), cfg)
86
+
87
+
88
+ def _flight(cfg, fl):
89
+ if fl.get("hold"): # --hold-land CARD: land stops for a person's 'land' on this card, this run only
90
+ cfg.setdefault("land", {})["hold"] = fl["hold"]
91
+ # This run's --model ROLE=ENGINE:MODEL and --effort ROLE=LEVEL, laid over the loaded config; never written back.
92
+ for kind in ("model", "effort"):
93
+ for spec in fl.get(kind, []):
94
+ role, _, rest = spec.partition("=")
95
+ eng, _, val = rest.partition(":") if kind == "model" else ("", "", rest)
96
+ if role not in cfg["roles"] or not val or (kind == "model" and not eng):
97
+ refuse("flight.spec", f"--{kind} {spec!r} is not ROLE=" + ("ENGINE:MODEL" if kind == "model" else "LEVEL") + " for a role in ade.toml",
98
+ "e.g. --model builder=claude:haiku --effort builder=max")
99
+ r = cfg["roles"][role]
100
+ if kind == "model":
101
+ r["provider"] = eng
102
+ r.setdefault("models" if kind == "model" else "effort", {})[r["provider"]] = val
103
+
104
+
105
+ def load(cwd):
106
+ root = main_worktree(cwd)
107
+ if root is None or not (root / "ade.toml").is_file():
108
+ refuse("config.missing", f"no ade.toml in the repository at {cwd}",
109
+ "run `ade init` in the repository root (add --dry-run to preview)")
110
+ return load_at(root)
111
+
112
+
113
+ def matches(path, globs):
114
+ # fnmatch's * crosses '/', so 'src/*' covers the whole subtree; that is the intended reading.
115
+ return any(g == path or fnmatch.fnmatchcase(path, g) for g in globs)
116
+
117
+
118
+ def rigour(paths, cfg):
119
+ return "proof" if any(matches(p, cfg["rigour"]["proof_grade"]) for p in paths) else "orchestration"