beyondbabel 0.3.0__tar.gz → 0.5.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 (28) hide show
  1. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/PKG-INFO +39 -30
  2. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/README.md +38 -29
  3. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/bb.py +183 -71
  4. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/beyondbabel.egg-info/PKG-INFO +39 -30
  5. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/pyproject.toml +1 -1
  6. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_edit_new.py +1 -1
  7. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_internals.py +72 -22
  8. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_scratchpad.py +16 -4
  9. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/beyondbabel.egg-info/SOURCES.txt +0 -0
  10. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/beyondbabel.egg-info/dependency_links.txt +0 -0
  11. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/beyondbabel.egg-info/entry_points.txt +0 -0
  12. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/beyondbabel.egg-info/requires.txt +0 -0
  13. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/beyondbabel.egg-info/top_level.txt +0 -0
  14. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/setup.cfg +0 -0
  15. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_compile.py +0 -0
  16. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_edit_file.py +0 -0
  17. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_edit_refactor.py +0 -0
  18. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_import_by_name.py +0 -0
  19. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_lineage_v2.py +0 -0
  20. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_pool_refs.py +0 -0
  21. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_positional.py +0 -0
  22. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_refactor_stale.py +0 -0
  23. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_restore.py +0 -0
  24. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_storage.py +0 -0
  25. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_translate_file.py +0 -0
  26. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_translate_tree.py +0 -0
  27. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_undefined_names.py +0 -0
  28. {beyondbabel-0.3.0 → beyondbabel-0.5.0}/tests/test_update.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: beyondbabel
3
- Version: 0.3.0
3
+ Version: 0.5.0
4
4
  Summary: A function pool manager for Python that enables multilingual function sharing through AST normalization
5
5
  Author: Amirouche Boubekki
6
6
  License-Expression: MIT
@@ -28,50 +28,53 @@ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
28
28
 
29
29
  ![Tests](https://github.com/amirouche/bb.py/actions/workflows/test.yml/badge.svg)
30
30
 
31
- **Nurturing a society that recognizes diversity as strength through verifiable knowledge sharing.**
31
+ **Diversity as strength, made verifiable.**
32
32
 
33
- > **Experimental**: This is research software under active development.
34
-
35
- Every programmer who thinks in Wolof, Tamil, Vietnamese, or Tamazight and codes in English pays a cognitive tax. Every variable named in a second language is a thought translated before it's expressed. This overhead is invisible to the people who don't pay it — and universal for everyone who does.
33
+ Write a function in your language; if someone else, human or machine, had the same thought, the hash will show it.
36
34
 
37
- bb.py makes that tax optional. Write functions in your language — name variables, write documentation, think natively. The tool separates what your code *does* from what you *called* things. Same logic, same hash, regardless of tongue.
38
-
39
- Content-addressing gives every function a unique fingerprint. Authorship is preserved. Lineage is traceable. Knowledge is shared without losing track of who made what.
35
+ > **Experimental**: This is research software under active development.
40
36
 
41
- ## Same logic, three languages, one hash
37
+ Convergence is detected, divergence is preserved. When two minds write the same logic, they get the same hash, and no shared language was needed to find each other. When they write different logic, they get different hashes, and both are kept. Nothing is flattened into a single English version.
42
38
 
43
39
  ```python
44
- # English
45
- def calculate_sum(first_number, second_number):
46
- """Calculate the sum of two numbers."""
47
- result = first_number + second_number
48
- return result
40
+ # Français
41
+ def additionner(premier, second):
42
+ """Additionner deux nombres."""
43
+ somme = premier + second
44
+ return somme
49
45
  ```
50
46
 
51
47
  ```python
52
- # Français
53
- def calculer_somme(premier_nombre, deuxieme_nombre):
54
- """Calculer la somme de deux nombres."""
55
- sortie = premier_nombre + deuxieme_nombre
56
- return sortie
48
+ # العربية
49
+ def اجمع(الأول, الثاني):
50
+ """اجمع عددين."""
51
+ الناتج = الأول + الثاني
52
+ return الناتج
57
53
  ```
58
54
 
59
55
  ```python
60
56
  # Español
61
- def calcular_suma(primer_numero, segundo_numero):
62
- """Calcular la suma de dos números."""
63
- resultado = primer_numero + segundo_numero
64
- return resultado
57
+ def sumar(primero, segundo):
58
+ """Sumar dos números."""
59
+ suma = primero + segundo
60
+ return suma
65
61
  ```
66
62
 
67
63
  ```bash
68
- bb init
69
- bb add example_simple.py@eng # → 9f86d0...
70
- bb add example_simple_french.py@fra # → 9f86d0... ← same hash
71
- bb add example_simple_spanish.py@spa # → 9f86d0... ← same hash again
64
+ bb add additionner.py@fra # → one hash
65
+ bb add اجمع.py@ara # → the same hash
66
+ bb add sumar.py@spa # → the same hash again
72
67
  ```
73
68
 
74
- Three languages. One identity. No one translated — they wrote originals.
69
+ Three people, or two people and a model prompted in Arabic. Nobody translated; each wrote an original. The names and the docstring stay in their own language, and the hash is computed from the logic alone.
70
+
71
+ ## Why
72
+
73
+ Students learn to code in English while thinking in their own language, and every name they choose is a thought translated before it is written. Languages in Arabic script also tend to cost more tokens on LLMs for the same meaning, a quiet tax on the people who already pay one.
74
+
75
+ The machine side is the same question seen from outside. When several LLM agents work on one problem, someone has to know whether two of them really agree, or only sound alike. A shared hash is a cheap, honest answer for the case where the logic is identical, and an honest "no" when it is not.
76
+
77
+ The project is early. Exact matching is the foundation; near-matches are still a research question (see `LIMITS.md`).
75
78
 
76
79
  ## What it enables
77
80
 
@@ -100,14 +103,20 @@ Exact matching is the foundation — the clean case where two people write the s
100
103
 
101
104
  ```bash
102
105
  # Using pip
103
- pip install git+https://github.com/amirouche/bb.py.git
106
+ pip install beyondbabel
104
107
 
105
108
  # Using uv
106
- uv tool install git+https://github.com/amirouche/bb.py.git
109
+ uv tool install beyondbabel
107
110
  ```
108
111
 
109
112
  Requires Python 3.11+. No runtime dependencies.
110
113
 
114
+ ## About
115
+
116
+ Nurturing a society that recognizes diversity as strength through verifiable knowledge sharing.
117
+
118
+ Content-addressing gives every function a fingerprint. Authorship is preserved. Lineage is traceable. Knowledge is shared without losing track of who made what.
119
+
111
120
  ## Vision
112
121
 
113
122
  bb.py is a step toward Möbius — a content-addressed language where timestamps make lineage visible, and names are views into a multilingual registry. Who made what, who built on whom, who absorbed whose work without credit. The mirror doesn't prescribe norms or enforce justice. It refuses amnesia.
@@ -2,50 +2,53 @@
2
2
 
3
3
  ![Tests](https://github.com/amirouche/bb.py/actions/workflows/test.yml/badge.svg)
4
4
 
5
- **Nurturing a society that recognizes diversity as strength through verifiable knowledge sharing.**
5
+ **Diversity as strength, made verifiable.**
6
6
 
7
- > **Experimental**: This is research software under active development.
8
-
9
- Every programmer who thinks in Wolof, Tamil, Vietnamese, or Tamazight and codes in English pays a cognitive tax. Every variable named in a second language is a thought translated before it's expressed. This overhead is invisible to the people who don't pay it — and universal for everyone who does.
7
+ Write a function in your language; if someone else, human or machine, had the same thought, the hash will show it.
10
8
 
11
- bb.py makes that tax optional. Write functions in your language — name variables, write documentation, think natively. The tool separates what your code *does* from what you *called* things. Same logic, same hash, regardless of tongue.
12
-
13
- Content-addressing gives every function a unique fingerprint. Authorship is preserved. Lineage is traceable. Knowledge is shared without losing track of who made what.
9
+ > **Experimental**: This is research software under active development.
14
10
 
15
- ## Same logic, three languages, one hash
11
+ Convergence is detected, divergence is preserved. When two minds write the same logic, they get the same hash, and no shared language was needed to find each other. When they write different logic, they get different hashes, and both are kept. Nothing is flattened into a single English version.
16
12
 
17
13
  ```python
18
- # English
19
- def calculate_sum(first_number, second_number):
20
- """Calculate the sum of two numbers."""
21
- result = first_number + second_number
22
- return result
14
+ # Français
15
+ def additionner(premier, second):
16
+ """Additionner deux nombres."""
17
+ somme = premier + second
18
+ return somme
23
19
  ```
24
20
 
25
21
  ```python
26
- # Français
27
- def calculer_somme(premier_nombre, deuxieme_nombre):
28
- """Calculer la somme de deux nombres."""
29
- sortie = premier_nombre + deuxieme_nombre
30
- return sortie
22
+ # العربية
23
+ def اجمع(الأول, الثاني):
24
+ """اجمع عددين."""
25
+ الناتج = الأول + الثاني
26
+ return الناتج
31
27
  ```
32
28
 
33
29
  ```python
34
30
  # Español
35
- def calcular_suma(primer_numero, segundo_numero):
36
- """Calcular la suma de dos números."""
37
- resultado = primer_numero + segundo_numero
38
- return resultado
31
+ def sumar(primero, segundo):
32
+ """Sumar dos números."""
33
+ suma = primero + segundo
34
+ return suma
39
35
  ```
40
36
 
41
37
  ```bash
42
- bb init
43
- bb add example_simple.py@eng # → 9f86d0...
44
- bb add example_simple_french.py@fra # → 9f86d0... ← same hash
45
- bb add example_simple_spanish.py@spa # → 9f86d0... ← same hash again
38
+ bb add additionner.py@fra # → one hash
39
+ bb add اجمع.py@ara # → the same hash
40
+ bb add sumar.py@spa # → the same hash again
46
41
  ```
47
42
 
48
- Three languages. One identity. No one translated — they wrote originals.
43
+ Three people, or two people and a model prompted in Arabic. Nobody translated; each wrote an original. The names and the docstring stay in their own language, and the hash is computed from the logic alone.
44
+
45
+ ## Why
46
+
47
+ Students learn to code in English while thinking in their own language, and every name they choose is a thought translated before it is written. Languages in Arabic script also tend to cost more tokens on LLMs for the same meaning, a quiet tax on the people who already pay one.
48
+
49
+ The machine side is the same question seen from outside. When several LLM agents work on one problem, someone has to know whether two of them really agree, or only sound alike. A shared hash is a cheap, honest answer for the case where the logic is identical, and an honest "no" when it is not.
50
+
51
+ The project is early. Exact matching is the foundation; near-matches are still a research question (see `LIMITS.md`).
49
52
 
50
53
  ## What it enables
51
54
 
@@ -74,14 +77,20 @@ Exact matching is the foundation — the clean case where two people write the s
74
77
 
75
78
  ```bash
76
79
  # Using pip
77
- pip install git+https://github.com/amirouche/bb.py.git
80
+ pip install beyondbabel
78
81
 
79
82
  # Using uv
80
- uv tool install git+https://github.com/amirouche/bb.py.git
83
+ uv tool install beyondbabel
81
84
  ```
82
85
 
83
86
  Requires Python 3.11+. No runtime dependencies.
84
87
 
88
+ ## About
89
+
90
+ Nurturing a society that recognizes diversity as strength through verifiable knowledge sharing.
91
+
92
+ Content-addressing gives every function a fingerprint. Authorship is preserved. Lineage is traceable. Knowledge is shared without losing track of who made what.
93
+
85
94
  ## Vision
86
95
 
87
96
  bb.py is a step toward Möbius — a content-addressed language where timestamps make lineage visible, and names are views into a multilingual registry. Who made what, who built on whom, who absorbed whose work without credit. The mirror doesn't prescribe norms or enforce justice. It refuses amnesia.
@@ -70,7 +70,10 @@ Writing functions for the pool:
70
70
  `bb edit name@lang --refactor app@lang` saves the change and updates
71
71
  everything between app and it, and lists what it rewrote (or run
72
72
  `bb update app@lang` later: it brings app and everything it uses to
73
- their current versions in one step, keeping pins).
73
+ their current versions in one step, keeping pins). An update is saved
74
+ only when the checks of what it rewrites pass, as in bb edit: one that
75
+ fails stays on its version, the rest is updated, the failure is printed
76
+ and the exit status is 1.
74
77
  - Finding functions: `bb search` alone lists every current function;
75
78
  `bb search WORDS` searches names, docs and code; `bb latest
76
79
  name@lang --hash` prints only the current hash (for scripts); `bb log`
@@ -113,8 +116,10 @@ Writing functions for the pool:
113
116
  - The documentation is the prose under `## Implementation`, before the
114
117
  code (per language, outside the hash). Each check is a `###` section
115
118
  whose function takes the implementation as its only argument and
116
- returns True when it passes; checks run when you save and are part of
117
- the definition (changing them forks the function). A check does not
119
+ states what must hold with assert (at least one; it passes when it
120
+ runs without raising, its return value is ignored); checks run when
121
+ you save and are part of the definition (changing them forks the
122
+ function). A check does not
118
123
  import what it tests, so the same check can test a fork or another
119
124
  function with the same contract. Checks are worth it for central
120
125
  functions (many callers, see `bb caller`) and tricky logic, less for
@@ -149,7 +154,7 @@ Writing functions for the pool:
149
154
  ```python def
150
155
  def check_rejects_garbage(parse):
151
156
  \"\"\"Anything that is not an amount gives None instead of raising.\"\"\"
152
- return all((parse(text) is None for text in ['', 'abc', '1.2.3', '-5', '1.999']))
157
+ assert all((parse(text) is None for text in ['', 'abc', '1.2.3', '-5', '1.999']))
153
158
  ```
154
159
 
155
160
  ### check_reads_common_forms
@@ -157,7 +162,10 @@ Writing functions for the pool:
157
162
  ```python def
158
163
  def check_reads_common_forms(parse):
159
164
  \"\"\"Whole, decimal point, decimal comma and spaced thousands all read right.\"\"\"
160
- return parse('12') == 1200 and parse('12.5') == 1250 and (parse('12,50') == 1250) and (parse(' 1 200.00 ') == 120000)
165
+ assert parse('12') == 1200
166
+ assert parse('12.5') == 1250
167
+ assert parse('12,50') == 1250
168
+ assert parse(' 1 200.00 ') == 120000
161
169
  ```
162
170
 
163
171
  - `bb scratchpad a@lang b@lang FILE` does the same for several functions
@@ -198,6 +206,7 @@ import ast
198
206
  import argparse
199
207
  import builtins
200
208
  import contextlib
209
+ import copy
201
210
  import hashlib
202
211
  import io
203
212
  import itertools
@@ -5262,7 +5271,7 @@ EDIT_DEFINITION_INFO = 'python def'
5262
5271
  EDIT_IMPLEMENTATION_HEADING = 'Implementation'
5263
5272
  EDIT_CHECKS_HEADING = 'Checks'
5264
5273
  EDIT_CHECKS_HINT = ('<!-- bb: add checks as ### subsections. Each one needs a ```python def block '
5265
- 'whose function takes the implementation as its only argument and returns True when it passes. -->')
5274
+ 'whose function takes the implementation as its only argument and states what must hold with assert. -->')
5266
5275
 
5267
5276
  _EDIT_FENCE_RE = re.compile(r'^(`{3,}|~{3,})\s*(.*?)\s*$')
5268
5277
  _EDIT_MARKER_RE = re.compile(r'^<!--\s*bb:(.*?)\s*-->$')
@@ -6091,7 +6100,8 @@ def helper_identifier_name(identifier: str) -> Optional[str]:
6091
6100
  # ============================================================================
6092
6101
  #
6093
6102
  # A check is an ordinary pool function that takes the implementation as its
6094
- # only argument and returns a truthy value when it passes. Checks do not
6103
+ # only argument and states what must hold with assert: it passes when it
6104
+ # runs without raising, and needs at least one assert. Checks do not
6095
6105
  # import the function they test, so one check can run against every fork.
6096
6106
  # They are part of an implementation's definition: object.json lists their
6097
6107
  # hashes under 'checks', and they enter the function hash, so changing the
@@ -6154,90 +6164,113 @@ def code_execute_source(source_code: str, lang: str) -> Callable:
6154
6164
  tree.body = body
6155
6165
 
6156
6166
  try:
6157
- exec(compile(tree, f'<bb edit {function_def.name}>', 'exec'), namespace)
6167
+ exec(compile(tree, f'<bb edit {function_def.name}>', 'exec', optimize=0), namespace)
6158
6168
  except Exception as e:
6159
6169
  raise ValueError(f"{function_def.name} failed to load: {type(e).__name__}: {e}")
6160
6170
 
6161
6171
  return namespace[function_def.name]
6162
6172
 
6163
6173
 
6164
- def check_explain(source: str, captured: Dict[str, Any], result: Any) -> str:
6174
+ CHECK_NO_ASSERT = ("no assert: a check passes when it runs without raising, so it needs at least one "
6175
+ "assert (assert f(2) == 4); rewrite it with bb edit")
6176
+
6177
+
6178
+ def check_has_assert(code: str) -> bool:
6179
+ """True when the code of a check holds at least one assert statement."""
6180
+ try:
6181
+ tree = ast.parse(code)
6182
+ except SyntaxError:
6183
+ return True # not this function's business: running it says what is wrong
6184
+ return any(isinstance(node, ast.Assert) for node in ast.walk(tree))
6185
+
6186
+
6187
+ def check_explain(source: str, check: Callable, error: AssertionError,
6188
+ names: Dict[str, str] = None) -> str:
6165
6189
  """
6166
- Say why a check failed, from the expression it returned.
6190
+ Say why a check failed, from the assert that raised.
6167
6191
 
6168
- captured holds the check's frame at its return (locals, globals, line).
6169
- The return statement on that line is evaluated again piece by piece:
6170
- the first false part of an `and` chain, and for a comparison both of
6171
- its sides, so `parse('12,50') == 1250` shows `1200 == 1250`. Anything
6172
- that cannot be evaluated is left out; the returned value is always shown.
6192
+ The assert statement is found in source, the check's code, by the line
6193
+ the traceback reaches in the check, and evaluated again piece by piece
6194
+ with the values the check had: the first false part of an `and` chain,
6195
+ and for a comparison both of its sides, so `assert parse('12,50') ==
6196
+ 1250` shows `1200 == 1250`. The assert's own message, when it has one,
6197
+ heads the line. Anything that cannot be evaluated is left out. names
6198
+ maps the normalized names of stored code (_bb_v_1) back to the ones
6199
+ its author wrote, for display only.
6173
6200
  """
6174
- detail = f"returned {result!r}"
6175
- if not source or not captured:
6201
+ detail = str(error) or "assertion failed"
6202
+ code = getattr(check, '__code__', None)
6203
+ tb, found = error.__traceback__, None
6204
+ while tb is not None:
6205
+ if tb.tb_frame.f_code is code:
6206
+ found = tb
6207
+ tb = tb.tb_next
6208
+ if not source or found is None:
6176
6209
  return detail
6177
6210
  try:
6178
6211
  tree = ast.parse(source)
6179
6212
  except SyntaxError:
6180
6213
  return detail
6181
- returns = [node for node in ast.walk(tree) if isinstance(node, ast.Return) and node.value is not None]
6182
- on_line = [node for node in returns if node.lineno <= captured['line'] <= node.end_lineno]
6183
- node = (on_line or returns[-1:] or [None])[0]
6214
+ line, scope = found.tb_lineno, found.tb_frame
6215
+ node = next((n for n in ast.walk(tree)
6216
+ if isinstance(n, ast.Assert) and n.lineno <= line <= n.end_lineno), None)
6184
6217
  if node is None:
6185
- return detail
6218
+ return detail # raised by something the check called
6186
6219
 
6187
6220
  def evaluate(expression: ast.expr):
6188
- code = compile(ast.fix_missing_locations(ast.Expression(expression)), '<check>', 'eval')
6189
- return eval(code, captured['globals'], captured['locals'])
6221
+ compiled = compile(ast.fix_missing_locations(ast.Expression(expression)), '<check>', 'eval')
6222
+ return eval(compiled, scope.f_globals, scope.f_locals)
6223
+
6224
+ def show(expression: ast.expr) -> str:
6225
+ shown = copy.deepcopy(expression)
6226
+ for name in ast.walk(shown):
6227
+ if isinstance(name, ast.Name) and name.id in (names or {}):
6228
+ name.id = names[name.id]
6229
+ return ast.unparse(shown)
6190
6230
 
6191
6231
  try:
6192
- part = node.value
6232
+ part = node.test
6193
6233
  while isinstance(part, ast.BoolOp) and isinstance(part.op, ast.And):
6194
6234
  part = next((value for value in part.values if not evaluate(value)), None)
6195
6235
  if part is None:
6196
6236
  return detail
6237
+ detail += f": {show(part)}"
6197
6238
  if isinstance(part, ast.Call) and getattr(part.func, 'id', None) == 'all' and len(part.args) == 1:
6198
- return f"{detail}: {ast.unparse(part)} is False"
6199
- if part is not node.value:
6200
- detail += f": {ast.unparse(part)} is false"
6239
+ return f"{detail} is False"
6201
6240
  if isinstance(part, ast.Compare) and len(part.ops) == 1:
6202
6241
  left, right = evaluate(part.left), evaluate(part.comparators[0])
6203
6242
  operator = ast.unparse(ast.Compare(left=ast.Name('a'), ops=part.ops, comparators=[ast.Name('b')]))[2:-2]
6204
6243
  detail += f" ({left!r} {operator} {right!r})"
6244
+ elif part is not node.test:
6245
+ detail += " is false"
6205
6246
  except Exception:
6206
6247
  pass
6207
6248
  return detail
6208
6249
 
6209
6250
 
6210
- def check_run(check: Callable, implementation: Callable, source: str = None) -> Tuple[str, str]:
6251
+ def check_run(check: Callable, implementation: Callable, source: str = None,
6252
+ names: Dict[str, str] = None) -> Tuple[str, str]:
6211
6253
  """
6212
6254
  Run one check against an implementation.
6213
6255
 
6214
- source, the check's code as it was compiled, lets a failure say which
6215
- part of the returned expression was false and what it compared
6216
- (check_explain).
6256
+ A check passes when it runs without raising: it states what must hold
6257
+ with assert, and its return value is ignored. A failed assert is FAIL
6258
+ and says which one (check_explain); any other exception is ERROR. With
6259
+ source, the check's code as it was compiled, a check without any
6260
+ assert is an ERROR, since nothing could ever fail it.
6217
6261
 
6218
6262
  Returns:
6219
6263
  (status, detail) where status is PASS, FAIL or ERROR
6220
6264
  """
6221
- captured: Dict[str, Any] = {}
6222
- code = getattr(check, '__code__', None)
6223
-
6224
- def watch(frame, event, arg):
6225
- if event == 'return':
6226
- captured.update(locals=dict(frame.f_locals), globals=frame.f_globals, line=frame.f_lineno)
6227
- return watch
6228
-
6229
- def calls(frame, event, arg):
6230
- return watch if frame.f_code is code else None
6231
-
6232
- previous = sys.gettrace()
6233
- sys.settrace(calls if code is not None and source else previous)
6265
+ if source and not check_has_assert(source):
6266
+ return 'ERROR', CHECK_NO_ASSERT
6234
6267
  try:
6235
- result = check(implementation)
6268
+ check(implementation)
6269
+ except AssertionError as e:
6270
+ return 'FAIL', check_explain(source, check, e, names)
6236
6271
  except Exception as e:
6237
6272
  return 'ERROR', f"{type(e).__name__}: {e}"
6238
- finally:
6239
- sys.settrace(previous)
6240
- return ('PASS', '') if result else ('FAIL', check_explain(source, captured, result))
6273
+ return 'PASS', ''
6241
6274
 
6242
6275
 
6243
6276
  def check_report(results: List[Tuple[str, str, str]], indent: str = "") -> bool:
@@ -6319,14 +6352,16 @@ def code_load_refs(tree: ast.AST, cache: Dict[str, Callable]) -> types.SimpleNam
6319
6352
  return types.SimpleNamespace(ref=loaded.__getitem__)
6320
6353
 
6321
6354
 
6322
- def code_load_normalized(func_hash: str, cache: Dict[str, Callable] = None) -> Callable:
6355
+ def code_load_normalized(func_hash: str, cache: Dict[str, Callable] = None,
6356
+ source: str = None, like: str = None) -> Callable:
6323
6357
  """
6324
6358
  Load a pool function from its normalized code, exactly as hashed.
6325
6359
 
6326
6360
  No language mapping is applied, so what runs is the code that was
6327
6361
  hashed and reviewed, whatever names a mapping displays. Each function
6328
6362
  runs in its own namespace, with its bb imports bound to their own
6329
- loaded functions.
6363
+ loaded functions. With source (and like, the function it rewrites),
6364
+ code that is not in the pool yet is loaded under func_hash.
6330
6365
 
6331
6366
  Raises:
6332
6367
  ValueError: If the function or a dependency is missing or fails to load
@@ -6336,12 +6371,16 @@ def code_load_normalized(func_hash: str, cache: Dict[str, Callable] = None) -> C
6336
6371
  if func_hash in cache:
6337
6372
  return cache[func_hash]
6338
6373
 
6339
- if code_detect_schema(func_hash) is None:
6340
- raise ValueError(f"Function not in the local pool: {func_hash}")
6341
- data = object_load(func_hash)
6342
- tree = ast.parse(data['normalized_code'])
6374
+ if source is None:
6375
+ if code_detect_schema(func_hash) is None:
6376
+ raise ValueError(f"Function not in the local pool: {func_hash}")
6377
+ data = object_load(func_hash)
6378
+ source, like = data['normalized_code'], func_hash
6379
+ else:
6380
+ data = object_load(like) # a version not saved yet, loaded like the one it rewrites
6381
+ tree = ast.parse(source)
6343
6382
  if data.get('normalization', 1) < 2:
6344
- code_restore_inner_imports(tree, func_hash)
6383
+ code_restore_inner_imports(tree, like)
6345
6384
 
6346
6385
  namespace: Dict[str, Any] = {'bb': code_load_refs(tree, cache)}
6347
6386
  body = []
@@ -6355,7 +6394,7 @@ def code_load_normalized(func_hash: str, cache: Dict[str, Callable] = None) -> C
6355
6394
  tree.body = body
6356
6395
 
6357
6396
  try:
6358
- exec(compile(tree, f'<bb {func_hash[:12]}>', 'exec'), namespace)
6397
+ exec(compile(tree, f'<bb {func_hash[:12]}>', 'exec', optimize=0), namespace)
6359
6398
  except Exception as e:
6360
6399
  raise ValueError(f"{func_hash[:12]}... failed to load: {type(e).__name__}: {e}")
6361
6400
 
@@ -6389,25 +6428,45 @@ def check_run_reviewed(func_hash: str, reviewed: set) -> Tuple[Optional[List[Tup
6389
6428
  if missing:
6390
6429
  return None, missing
6391
6430
 
6431
+ return check_run_all(func_hash, object_load_checks(func_hash)), []
6432
+
6433
+
6434
+ def helper_display_names(func_hash: str) -> Dict[str, str]:
6435
+ """The names a function's author wrote, by normalized name, in the language you read it in."""
6436
+ lang = helper_pick_language(func_hash)
6437
+ if lang is None:
6438
+ return {}
6439
+ return mapping_load_json(func_hash, lang, mapping_select(func_hash, lang)).get('name_mapping', {})
6440
+
6441
+
6442
+ def check_run_all(func_hash: str, checks: List[str], source: str = None,
6443
+ like: str = None) -> List[Tuple[str, str, str]]:
6444
+ """
6445
+ Run checks against a function, already approved: results for check_report.
6446
+
6447
+ With source and like, the function is code not saved yet (see
6448
+ code_load_normalized). Callers make sure everything that runs was approved.
6449
+ """
6392
6450
  cache: Dict[str, Callable] = {}
6393
6451
  try:
6394
- implementation = code_load_normalized(func_hash, cache)
6452
+ implementation = code_load_normalized(func_hash, cache, source=source, like=like)
6395
6453
  except ValueError as e:
6396
- return [('ERROR', helper_function_label(func_hash), str(e))], []
6454
+ return [('ERROR', helper_function_label(like or func_hash), str(e))]
6397
6455
 
6398
6456
  results = []
6399
- for check_hash in object_load_checks(func_hash):
6457
+ for check_hash in checks:
6400
6458
  name = helper_function_label(check_hash)
6401
6459
  try:
6402
6460
  check = code_load_normalized(check_hash, cache)
6403
6461
  except ValueError as e:
6404
6462
  results.append(('ERROR', name, str(e)))
6405
6463
  continue
6406
- status, detail = check_run(check, implementation, object_load(check_hash).get('normalized_code'))
6464
+ status, detail = check_run(check, implementation, object_load(check_hash).get('normalized_code'),
6465
+ helper_display_names(check_hash))
6407
6466
  results.append((status, name, detail))
6408
6467
 
6409
6468
  results.sort(key=lambda r: r[1])
6410
- return results, []
6469
+ return results
6411
6470
 
6412
6471
 
6413
6472
  def command_validate_checks(identifier: str = None, unreviewed: bool = False):
@@ -6589,6 +6648,9 @@ def edit_prepare(text: str, lang: str, unreviewed: bool = False) -> Dict[str, An
6589
6648
  section['source'], names = code_resolve_pool_names(section['source'], lang, where=where)
6590
6649
  resolved.update(names)
6591
6650
  prepared_implementation = code_prepare_source(implementation['source'], lang, where="Implementation")
6651
+ for check in parsed['checks']:
6652
+ if not check_has_assert(check['source']):
6653
+ raise ValueError(f"check '{check['title']}' has {CHECK_NO_ASSERT}")
6592
6654
  checks = [(check, code_prepare_source(check['source'], lang, where=f"check '{check['title']}'"))
6593
6655
  for check in parsed['checks']]
6594
6656
  for section, prepared in [(implementation, prepared_implementation)] + checks:
@@ -6714,8 +6776,9 @@ def command_edit(identifier: str, comment: str = None, unreviewed: bool = False,
6714
6776
  Opens $EDITOR on a file with an Implementation section and a Checks
6715
6777
  section. Each section holds prose and examples, and exactly one code
6716
6778
  block fenced as `python def`: the function that is hashed. Each check
6717
- takes the implementation as its only argument and returns True when it
6718
- passes.
6779
+ takes the implementation as its only argument and states what must hold
6780
+ with assert (at least one: a check passes when it runs without raising;
6781
+ one without an assert is refused).
6719
6782
 
6720
6783
  Saving requires the file to parse and every check to pass. Only checks
6721
6784
  run the code: a function without checks is saved without running it,
@@ -7229,7 +7292,7 @@ def command_scratchpad(identifiers: List[str], file: str, comment: str = None, t
7229
7292
  finally:
7230
7293
  shutil.rmtree(work, ignore_errors=True)
7231
7294
  if refactor:
7232
- command_update(refactor, comment)
7295
+ command_update(refactor, comment, unreviewed)
7233
7296
 
7234
7297
 
7235
7298
  def refactor_save(old_hash: str, new_hash: str, new_code: str, checks: List[str], comment: str,
@@ -7269,7 +7332,29 @@ def code_hash_rewritten(new_code: str, checks: List[str]) -> str:
7269
7332
  raise ValueError("no function in code")
7270
7333
 
7271
7334
 
7272
- def command_update(identifier: str, comment: str = None):
7335
+ def update_check_rewritten(base: str, new_hash: str, new_code: str, checks: List[str],
7336
+ unreviewed: bool = False) -> List[str]:
7337
+ """
7338
+ Run the checks of a rewrite before it is saved; the failures, one line each.
7339
+
7340
+ Like bb edit, nothing runs that you have not approved: the rewrite
7341
+ imports pool functions and so do its checks. Those not approved are
7342
+ reported as failures (bb review them), unless unreviewed.
7343
+ """
7344
+ needed = set()
7345
+ for dep in code_extract_dependencies(new_code):
7346
+ needed.update(code_resolve_dependencies(dep))
7347
+ for check_hash in checks:
7348
+ needed.update(code_resolve_dependencies(check_hash))
7349
+ missing = sorted(needed - review_approvals(list(needed)) - review_load_authored())
7350
+ if missing and not unreviewed:
7351
+ return ["not run, review first: " + ', '.join(f"bb review {h}" for h in missing)]
7352
+ results = check_run_all(new_hash, checks, source=new_code, like=base)
7353
+ return [f"{status} {name}: {detail}" if detail else f"{status} {name}"
7354
+ for status, name, detail in results if status != 'PASS']
7355
+
7356
+
7357
+ def command_update(identifier: str, comment: str = None, unreviewed: bool = False):
7273
7358
  """
7274
7359
  Bring a function and everything it uses up to date, in one step.
7275
7360
 
@@ -7282,6 +7367,12 @@ def command_update(identifier: str, comment: str = None):
7282
7367
  (written as bb.ref) are kept. A fork (several current versions) is
7283
7368
  left as it is, with a warning. One comment goes on every new version.
7284
7369
 
7370
+ Like bb edit, a rewrite is saved only when the checks of the function
7371
+ pass with the new versions it uses. One that fails is not saved: it
7372
+ stays on the version it has, its callers stay as they were, and the
7373
+ rest is updated anyway. What failed is printed, and bb update exits
7374
+ with status 1; bb edit the function to adapt it, then update again.
7375
+
7285
7376
  ```
7286
7377
  bb update app@eng -m "use the new layout everywhere"
7287
7378
  ```
@@ -7295,6 +7386,7 @@ def command_update(identifier: str, comment: str = None):
7295
7386
  comment = ""
7296
7387
  done: Dict[Tuple[str, Optional[str]], str] = {}
7297
7388
  rewritten: List[Tuple[str, str]] = []
7389
+ failed: List[Tuple[str, str, List[str]]] = []
7298
7390
 
7299
7391
  def update(func_hash: str, name: Optional[str], stack: Tuple[str, ...] = ()) -> str:
7300
7392
  """The up-to-date hash for func_hash, used by name (itself when nothing changes)."""
@@ -7323,6 +7415,11 @@ def command_update(identifier: str, comment: str = None):
7323
7415
  checks = object_load_checks(base)
7324
7416
  result = code_hash_rewritten(new_code, checks)
7325
7417
  followed = {dep: lineage_name_for(dep, lang, aliases.get(dep)) for dep in swaps}
7418
+ problems = update_check_rewritten(base, result, new_code, checks, unreviewed) if checks else []
7419
+ if problems and result != base:
7420
+ failed.append((base, result, problems))
7421
+ done[(func_hash, name)] = done[(base, name)] = base
7422
+ return base
7326
7423
 
7327
7424
  def keep(record):
7328
7425
  """Names of base that use the swapped functions by other names stay (two names, one code)."""
@@ -7339,14 +7436,27 @@ def command_update(identifier: str, comment: str = None):
7339
7436
  return result
7340
7437
 
7341
7438
  new_root = update(root, helper_identifier_name(identifier) or lineage_name_for(root, lang))
7342
- if not rewritten:
7439
+ if not rewritten and not failed:
7343
7440
  print(f"{helper_function_label(root)} is up to date: nothing to save")
7344
7441
  return
7345
- print(f"Updated {len(rewritten)} function(s), deepest first:")
7346
- for old, new in rewritten:
7347
- print(f" {helper_function_label(new)}: {old[:12]}... -> {new[:12]}...")
7348
- print("Drafts open on these functions are now stale: write them again.")
7442
+ if rewritten:
7443
+ print(f"Updated {len(rewritten)} function(s), deepest first:")
7444
+ for old, new in rewritten:
7445
+ print(f" {helper_function_label(new)}: {old[:12]}... -> {new[:12]}...")
7446
+ print("Drafts open on these functions are now stale: write them again.")
7447
+ else:
7448
+ print("Nothing updated.")
7349
7449
  print(f"Hash: {new_root}")
7450
+ if failed:
7451
+ sys.stdout.flush() # what was updated comes before what was not
7452
+ print(f"Not updated, a check failed ({len(failed)}):", file=sys.stderr)
7453
+ for old, new, problems in failed:
7454
+ print(f" {helper_function_label(old)}: {old[:12]}... stays; its update would be {new[:12]}...",
7455
+ file=sys.stderr)
7456
+ for problem in problems:
7457
+ print(f" {problem}", file=sys.stderr)
7458
+ print("Edit them to adapt (bb edit NAME@lang), then update again.", file=sys.stderr)
7459
+ sys.exit(1)
7350
7460
 
7351
7461
 
7352
7462
  def command_refactor(what_hash: str, from_hash: str, to_hash: str, at_hash: str = None, comment: str = None):
@@ -8439,6 +8549,8 @@ def _build_parser():
8439
8549
  update_parser = subparsers.add_parser('update', help='Bring a function and everything it uses up to date')
8440
8550
  update_parser.add_argument('identifier', help='Function to update (name@lang or hash)')
8441
8551
  update_parser.add_argument('--comment', '-m', default=None, help='Comment for the new versions (asked when omitted)')
8552
+ update_parser.add_argument('--dangerously-unreviewed', action='store_true',
8553
+ help='Run checks even on unreviewed functions they import')
8442
8554
 
8443
8555
  refactor_parser = subparsers.add_parser('refactor', help='Replace a dependency in a function')
8444
8556
  refactor_parser.add_argument('what', help='Function hash to modify')
@@ -8583,7 +8695,7 @@ def main():
8583
8695
  elif args.command == 'tree':
8584
8696
  command_tree(args.identifier, as_json=args.as_json)
8585
8697
  elif args.command == 'update':
8586
- command_update(args.identifier, comment=args.comment)
8698
+ command_update(args.identifier, comment=args.comment, unreviewed=args.dangerously_unreviewed)
8587
8699
  elif args.command == 'refactor':
8588
8700
  command_refactor(args.what, args.from_hash, args.to_hash, args.at_hash if hasattr(args, 'at_hash') else None,
8589
8701
  comment=args.comment)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: beyondbabel
3
- Version: 0.3.0
3
+ Version: 0.5.0
4
4
  Summary: A function pool manager for Python that enables multilingual function sharing through AST normalization
5
5
  Author: Amirouche Boubekki
6
6
  License-Expression: MIT
@@ -28,50 +28,53 @@ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
28
28
 
29
29
  ![Tests](https://github.com/amirouche/bb.py/actions/workflows/test.yml/badge.svg)
30
30
 
31
- **Nurturing a society that recognizes diversity as strength through verifiable knowledge sharing.**
31
+ **Diversity as strength, made verifiable.**
32
32
 
33
- > **Experimental**: This is research software under active development.
34
-
35
- Every programmer who thinks in Wolof, Tamil, Vietnamese, or Tamazight and codes in English pays a cognitive tax. Every variable named in a second language is a thought translated before it's expressed. This overhead is invisible to the people who don't pay it — and universal for everyone who does.
33
+ Write a function in your language; if someone else, human or machine, had the same thought, the hash will show it.
36
34
 
37
- bb.py makes that tax optional. Write functions in your language — name variables, write documentation, think natively. The tool separates what your code *does* from what you *called* things. Same logic, same hash, regardless of tongue.
38
-
39
- Content-addressing gives every function a unique fingerprint. Authorship is preserved. Lineage is traceable. Knowledge is shared without losing track of who made what.
35
+ > **Experimental**: This is research software under active development.
40
36
 
41
- ## Same logic, three languages, one hash
37
+ Convergence is detected, divergence is preserved. When two minds write the same logic, they get the same hash, and no shared language was needed to find each other. When they write different logic, they get different hashes, and both are kept. Nothing is flattened into a single English version.
42
38
 
43
39
  ```python
44
- # English
45
- def calculate_sum(first_number, second_number):
46
- """Calculate the sum of two numbers."""
47
- result = first_number + second_number
48
- return result
40
+ # Français
41
+ def additionner(premier, second):
42
+ """Additionner deux nombres."""
43
+ somme = premier + second
44
+ return somme
49
45
  ```
50
46
 
51
47
  ```python
52
- # Français
53
- def calculer_somme(premier_nombre, deuxieme_nombre):
54
- """Calculer la somme de deux nombres."""
55
- sortie = premier_nombre + deuxieme_nombre
56
- return sortie
48
+ # العربية
49
+ def اجمع(الأول, الثاني):
50
+ """اجمع عددين."""
51
+ الناتج = الأول + الثاني
52
+ return الناتج
57
53
  ```
58
54
 
59
55
  ```python
60
56
  # Español
61
- def calcular_suma(primer_numero, segundo_numero):
62
- """Calcular la suma de dos números."""
63
- resultado = primer_numero + segundo_numero
64
- return resultado
57
+ def sumar(primero, segundo):
58
+ """Sumar dos números."""
59
+ suma = primero + segundo
60
+ return suma
65
61
  ```
66
62
 
67
63
  ```bash
68
- bb init
69
- bb add example_simple.py@eng # → 9f86d0...
70
- bb add example_simple_french.py@fra # → 9f86d0... ← same hash
71
- bb add example_simple_spanish.py@spa # → 9f86d0... ← same hash again
64
+ bb add additionner.py@fra # → one hash
65
+ bb add اجمع.py@ara # → the same hash
66
+ bb add sumar.py@spa # → the same hash again
72
67
  ```
73
68
 
74
- Three languages. One identity. No one translated — they wrote originals.
69
+ Three people, or two people and a model prompted in Arabic. Nobody translated; each wrote an original. The names and the docstring stay in their own language, and the hash is computed from the logic alone.
70
+
71
+ ## Why
72
+
73
+ Students learn to code in English while thinking in their own language, and every name they choose is a thought translated before it is written. Languages in Arabic script also tend to cost more tokens on LLMs for the same meaning, a quiet tax on the people who already pay one.
74
+
75
+ The machine side is the same question seen from outside. When several LLM agents work on one problem, someone has to know whether two of them really agree, or only sound alike. A shared hash is a cheap, honest answer for the case where the logic is identical, and an honest "no" when it is not.
76
+
77
+ The project is early. Exact matching is the foundation; near-matches are still a research question (see `LIMITS.md`).
75
78
 
76
79
  ## What it enables
77
80
 
@@ -100,14 +103,20 @@ Exact matching is the foundation — the clean case where two people write the s
100
103
 
101
104
  ```bash
102
105
  # Using pip
103
- pip install git+https://github.com/amirouche/bb.py.git
106
+ pip install beyondbabel
104
107
 
105
108
  # Using uv
106
- uv tool install git+https://github.com/amirouche/bb.py.git
109
+ uv tool install beyondbabel
107
110
  ```
108
111
 
109
112
  Requires Python 3.11+. No runtime dependencies.
110
113
 
114
+ ## About
115
+
116
+ Nurturing a society that recognizes diversity as strength through verifiable knowledge sharing.
117
+
118
+ Content-addressing gives every function a fingerprint. Authorship is preserved. Lineage is traceable. Knowledge is shared without losing track of who made what.
119
+
111
120
  ## Vision
112
121
 
113
122
  bb.py is a step toward Möbius — a content-addressed language where timestamps make lineage visible, and names are views into a multilingual registry. Who made what, who built on whom, who absorbed whose work without credit. The mirror doesn't prescribe norms or enforce justice. It refuses amnesia.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "beyondbabel"
7
- version = "0.3.0"
7
+ version = "0.5.0"
8
8
  description = "A function pool manager for Python that enables multilingual function sharing through AST normalization"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -73,7 +73,7 @@ def test_saving_runs_nothing_without_checks_and_checks_need_reviewed_imports(tmp
73
73
  bb(read, 'edit', 'quadruple@eng')
74
74
  with_check = draft.read_text().rstrip('\n') + ('\n\n### check_quadruple\n\n```python def\n'
75
75
  'def check_quadruple(quadruple):\n """Four times one."""\n'
76
- ' return quadruple(1) == 4\n```\n')
76
+ ' assert quadruple(1) == 4\n```\n')
77
77
  draft.write_text(with_check)
78
78
  ran = bb(write, 'edit', 'quadruple@eng', '-m', 'with a check')
79
79
  assert ran.returncode == 0 and 'PASS check_quadruple' in ran.stdout, ran.stderr
@@ -973,7 +973,7 @@ EDIT_IMPLEMENTATION = {
973
973
  }
974
974
  EDIT_CHECK = {
975
975
  'title': 'check_small',
976
- 'source': 'def check_small(double):\n return double(3) == 6\n',
976
+ 'source': 'def check_small(double):\n assert double(3) == 6\n',
977
977
  'markdown': 'Small integers.',
978
978
  'parent': 'b' * 64,
979
979
  }
@@ -1043,18 +1043,41 @@ def test_edit_format_errors(text, message):
1043
1043
  # Tests for functor checks
1044
1044
  # ============================================================================
1045
1045
 
1046
+ def _check_function(source: str):
1047
+ """The function a check's source defines, compiled the way bb compiles checks."""
1048
+ namespace = {}
1049
+ exec(compile(source, '<check>', 'exec', optimize=0), namespace)
1050
+ return namespace[next(name for name in namespace if name.startswith('check_'))]
1051
+
1052
+
1046
1053
  def test_check_run_statuses():
1047
- """A check passes on a truthy result, fails on a falsy one, errors on an exception"""
1054
+ """A check passes when it runs, fails on a failed assert, errors on another exception"""
1048
1055
  def double(x):
1049
1056
  return x * 2
1050
1057
 
1051
- assert bb.check_run(lambda f: f(3) == 6, double) == ('PASS', '')
1052
- assert bb.check_run(lambda f: f(3) == 7, double) == ('FAIL', 'returned False')
1053
- status, detail = bb.check_run(lambda f: f(), double)
1058
+ six = _check_function('def check_six(f):\n assert f(3) == 6\n')
1059
+ seven = _check_function('def check_seven(f):\n assert f(3) == 7\n')
1060
+ arity = _check_function('def check_arity(f):\n f()\n assert True\n')
1061
+ assert bb.check_run(six, double) == ('PASS', '')
1062
+ assert bb.check_run(seven, double) == ('FAIL', 'assertion failed')
1063
+ status, detail = bb.check_run(arity, double)
1054
1064
  assert status == 'ERROR'
1055
1065
  assert detail.startswith('TypeError:')
1056
1066
 
1057
1067
 
1068
+ def test_a_check_ignores_what_it_returns():
1069
+ check = _check_function('def check_false(f):\n assert f(1) == 1\n return False\n')
1070
+ assert bb.check_run(check, lambda n: n) == ('PASS', '')
1071
+
1072
+
1073
+ def test_a_check_without_assert_is_an_error_when_run():
1074
+ source = 'def check_none(f):\n return f(1) == 2\n'
1075
+ status, detail = bb.check_run(_check_function(source), lambda n: n, source)
1076
+ assert (status, detail) == ('ERROR', bb.CHECK_NO_ASSERT)
1077
+ assert bb.check_has_assert('def check_one(f):\n assert f(1)\n')
1078
+ assert not bb.check_has_assert(source)
1079
+
1080
+
1058
1081
  def test_check_report_summary(capsys):
1059
1082
  """check_report prints one line per check and returns whether all passed"""
1060
1083
  assert bb.check_report([]) is True
@@ -1131,7 +1154,7 @@ def test_review_state_lives_outside_the_shared_directory(mock_bb_dir):
1131
1154
  def test_checks_do_not_run_until_everything_is_approved(mock_bb_dir, tmp_path):
1132
1155
  """An unapproved check never executes, even when the function is approved"""
1133
1156
  marker = tmp_path / 'ran'
1134
- check = _pool_add(f"def check_side_effect(f):\n open({str(marker)!r}, 'w').close()\n return True\n")
1157
+ check = _pool_add(f"def check_side_effect(f):\n open({str(marker)!r}, 'w').close()\n assert True\n")
1135
1158
  func = _pool_add("def one():\n return 1\n", checks=[check])
1136
1159
 
1137
1160
  results, missing = bb.check_run_reviewed(func, {func})
@@ -1143,11 +1166,19 @@ def test_checks_do_not_run_until_everything_is_approved(mock_bb_dir, tmp_path):
1143
1166
  assert marker.exists()
1144
1167
 
1145
1168
 
1169
+ def test_a_stored_check_without_assert_is_an_error_when_its_checks_run(mock_bb_dir):
1170
+ """Checks saved before the assert protocol return a value: nothing could fail them, so they do not pass"""
1171
+ check = _pool_add("def check_old(f):\n return f() == 2\n")
1172
+ func = _pool_add("def one():\n return 1\n", checks=[check])
1173
+ results, missing = bb.check_run_reviewed(func, {func, check})
1174
+ assert missing == [] and results == [('ERROR', 'check_old', bb.CHECK_NO_ASSERT)]
1175
+
1176
+
1146
1177
  def test_review_closure_includes_check_dependencies(mock_bb_dir):
1147
1178
  """A check's own imports must be approved too"""
1148
1179
  helper = _pool_add("def six():\n return 6\n")
1149
1180
  check = _pool_add(f"import bb\nsix = bb.ref('{helper}')\n\n"
1150
- f"def check_double(f):\n return f(3) == six()\n")
1181
+ f"def check_double(f):\n assert f(3) == six()\n")
1151
1182
  func = _pool_add("def double(x):\n return x * 2\n", checks=[check])
1152
1183
  assert set(bb.review_closure(func)) == {func, helper, check}
1153
1184
  results, _ = bb.check_run_reviewed(func, {func, helper, check})
@@ -1170,7 +1201,7 @@ def test_edit_runs_nothing_without_checks_and_checks_need_reviewed_imports(mock_
1170
1201
  assert bb.edit_prepare(implementation, 'eng')['results'] == [] # saved without running
1171
1202
 
1172
1203
  with_check = implementation + ("\n## Checks\n\n### check_twelve\n\n```python def\n"
1173
- "def check_twelve(twelve):\n return twelve() == 12\n```\n")
1204
+ "def check_twelve(twelve):\n assert twelve() == 12\n```\n")
1174
1205
  with pytest.raises(ValueError, match=f"bb review {helper}"):
1175
1206
  bb.edit_prepare(with_check, 'eng')
1176
1207
 
@@ -1182,7 +1213,7 @@ def test_review_order_puts_dependencies_and_checks_first(mock_bb_dir):
1182
1213
  """Levels follow the dependency order; a function's checks come before it"""
1183
1214
  helper = _pool_add("def six():\n return 6\n")
1184
1215
  check = _pool_add(f"import bb\nsix = bb.ref('{helper}')\n\n"
1185
- f"def check_double(f):\n return f(3) == six()\n")
1216
+ f"def check_double(f):\n assert f(3) == six()\n")
1186
1217
  leaf = _pool_add("def two():\n return 2\n")
1187
1218
  func = _pool_add(f"import bb\ntwo = bb.ref('{leaf}')\n\n"
1188
1219
  f"def double(x):\n return x * two()\n", checks=[check])
@@ -1209,7 +1240,7 @@ def test_review_require_refuses_unreviewed_code(mock_bb_dir, capsys):
1209
1240
 
1210
1241
  def test_validate_dangerously_unreviewed_runs_everything(mock_bb_dir, capsys):
1211
1242
  """--dangerously-unreviewed runs unapproved checks, warns, and approves nothing"""
1212
- check = _pool_add("def check_one(f):\n return f() == 1\n")
1243
+ check = _pool_add("def check_one(f):\n assert f() == 1\n")
1213
1244
  func = _pool_add("def one():\n return 1\n", checks=[check])
1214
1245
 
1215
1246
  bb.command_validate_checks()
@@ -1473,21 +1504,40 @@ def test_code_pretty_leaves_short_code_and_lone_tuple_children_alone():
1473
1504
 
1474
1505
  def test_a_failing_check_says_which_part_was_false_and_what_it_compared():
1475
1506
  source = ('def check_double(double):\n """Doubles."""\n expected = 4\n'
1476
- ' return double(1) == 2 and double(2) == expected\n')
1477
- namespace = {}
1478
- exec(compile(source, '<check>', 'exec'), namespace)
1479
- status, detail = bb.check_run(namespace['check_double'], lambda n: n * 3, source)
1507
+ ' assert double(1) == 2 and double(2) == expected\n')
1508
+ status, detail = bb.check_run(_check_function(source), lambda n: n * 3, source)
1480
1509
  assert status == 'FAIL'
1481
- assert detail == 'returned False: double(1) == 2 is false (3 == 2)'
1510
+ assert detail == 'assertion failed: double(1) == 2 (3 == 2)'
1482
1511
 
1483
1512
 
1484
- def test_a_failing_check_without_source_still_shows_what_it_returned():
1485
- assert bb.check_run(lambda f: f(0), lambda n: n) == ('FAIL', 'returned 0')
1486
- source = 'def check_all(f):\n """All."""\n return all(f(x) for x in [1, 2])\n'
1487
- namespace = {}
1488
- exec(compile(source, '<check>', 'exec'), namespace)
1489
- assert bb.check_run(namespace['check_all'], lambda n: n > 1, source) == \
1490
- ('FAIL', 'returned False: all((f(x) for x in [1, 2])) is False')
1513
+ def test_a_failing_assert_shows_its_message_first():
1514
+ source = 'def check_keep(f):\n assert f([2, 1, 2]) == [1, 2, 2], "duplicates are kept"\n'
1515
+ assert bb.check_run(_check_function(source), lambda numbers: sorted(set(numbers)), source) == \
1516
+ ('FAIL', 'duplicates are kept: f([2, 1, 2]) == [1, 2, 2] ([1, 2] == [1, 2, 2])')
1517
+
1518
+
1519
+ def test_a_failing_check_without_source_only_says_the_assert_failed():
1520
+ zero = _check_function('def check_zero(f):\n assert f(0)\n')
1521
+ assert bb.check_run(zero, lambda n: n) == ('FAIL', 'assertion failed')
1522
+ source = 'def check_all(f):\n """All."""\n assert all(f(x) for x in [1, 2])\n'
1523
+ assert bb.check_run(_check_function(source), lambda n: n > 1, source) == \
1524
+ ('FAIL', 'assertion failed: all((f(x) for x in [1, 2])) is False')
1525
+
1526
+
1527
+ def test_an_assert_raised_by_a_helper_is_reported_without_guessing():
1528
+ source = ('def check_helper(f):\n def inner():\n assert False, "inner broke"\n'
1529
+ ' assert True\n inner()\n')
1530
+ assert bb.check_run(_check_function(source), lambda n: n, source) == ('FAIL', 'inner broke')
1531
+
1532
+
1533
+ def test_asserts_in_a_check_survive_python_optimization():
1534
+ """python -O removes asserts it compiles; bb compiles checks with optimize=0"""
1535
+ code = ("import bb\nsource = 'def check_f(f):\\n assert f(1) == 2\\n'\n"
1536
+ "namespace = {}\nexec(compile(source, '<c>', 'exec', optimize=0), namespace)\n"
1537
+ "print(bb.check_run(namespace['check_f'], lambda n: n, source)[0])")
1538
+ result = subprocess.run([sys.executable, '-O', '-c', code], cwd=Path(bb.__file__).parent,
1539
+ capture_output=True, text=True)
1540
+ assert result.stdout.strip() == 'FAIL', result.stderr
1491
1541
 
1492
1542
 
1493
1543
  def test_a_class_defined_inside_a_function_is_renamed_with_its_uses(mock_bb_dir):
@@ -58,16 +58,28 @@ def test_a_stale_section_stops_the_save_and_keeps_the_rest_as_written(tmp_path):
58
58
  assert "'Due: '" in pad.read_text() # the refused section keeps the text written
59
59
 
60
60
 
61
+ def test_a_check_without_assert_is_refused(tmp_path):
62
+ pool = Pool(tmp_path)
63
+ pad = tmp_path / 'pad.md'
64
+ check = ('\n## Checks\n\n### check_money\n\n```python def\ndef check_money(money):\n'
65
+ ' """Two decimals."""\n return money(150) == "$1.50"\n```\n')
66
+ pad.write_text(f'# money\n\n## Implementation\n\n```python def\n{MONEY}```\n{check}')
67
+ result = pool.bb('scratchpad', 'money@eng', str(pad), '-m', 'try')
68
+ assert result.returncode == 1
69
+ assert "check 'check_money' has no assert" in result.stderr
70
+ assert not latest(pool, 'money')
71
+
72
+
61
73
  def test_a_failing_check_stops_and_names_the_section(tmp_path):
62
74
  pool = Pool(tmp_path)
63
75
  pad = tmp_path / 'pad.md'
64
76
  check = ('\n## Checks\n\n### check_money\n\n```python def\ndef check_money(money):\n'
65
- ' """Two decimals."""\n return money(150) == "$1.5"\n```\n')
77
+ ' """Two decimals."""\n assert money(150) == "$1.5"\n```\n')
66
78
  pad.write_text(f'# money\n\n## Implementation\n\n```python def\n{MONEY}```\n{check}\n'
67
79
  f'# badge\n\n## Implementation\n\n```python def\n{BADGE}```\n')
68
80
  result = pool.bb('scratchpad', 'money@eng', 'badge@eng', str(pad), '-m', 'try')
69
81
  assert result.returncode == 1 and 'Stopped at money' in result.stderr
70
- assert "FAIL check_money: returned False ('$1.50' == '$1.5')" in result.stdout
82
+ assert "FAIL check_money: assertion failed: money(150) == '$1.5' ('$1.50' == '$1.5')" in result.stdout
71
83
  assert not latest(pool, 'badge') # not tried
72
84
  # The reason is the failing check: no "unchanged" line contradicts it
73
85
  assert 'unchanged' not in result.stderr and 'Not saved: fix' not in result.stderr
@@ -138,7 +150,7 @@ def test_refactor_brings_the_root_up_to_date_after_the_save(tmp_path):
138
150
 
139
151
 
140
152
  CHECKED = ('# money\n\n## Implementation\n\n```python def\n' + MONEY + '```\n\n## Checks\n\n### check_money\n\n'
141
- '```python def\ndef check_money(money):\n """Two decimals."""\n return money(150) == "$1.50"\n```\n')
153
+ '```python def\ndef check_money(money):\n """Two decimals."""\n assert money(150) == "$1.50"\n```\n')
142
154
 
143
155
 
144
156
  def test_a_check_is_written_under_its_function_only(tmp_path):
@@ -169,7 +181,7 @@ def test_a_check_also_written_as_its_own_section_is_saved_once(tmp_path):
169
181
  # Two copies that differ are refused before anything is saved
170
182
  pad.write_text(pad.read_text().replace('Cents shown as dollars', 'Cents in dollars')
171
183
  + '\n# check_money\n\n## Implementation\n\n```python def\ndef check_money(money):\n'
172
- ' """Other."""\n return money(1) == "$0.01"\n```\n')
184
+ ' """Other."""\n assert money(1) == "$0.01"\n```\n')
173
185
  refused = pool.bb('scratchpad', 'money@eng', str(pad), '-m', 'two copies')
174
186
  assert refused.returncode == 1 and 'the two differ' in refused.stderr
175
187
  assert 'Cents shown as dollars' in pool.bb('show', 'money@eng').stdout # nothing saved
File without changes