Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257"""Every SQLite table the daemon creates has one transfer classification.
A session move copies only the tables owner `transfer.gleam` modules declare.A new table that holds session or workspace rows but has no `transfer.Table`or `transfer.Excluded` declaration would silently stay behind on the sourcedaemon. No end-to-end run installs and fills every owner's schema, so thisreads the schema from the production Marmot snapshot, without a build or daemon."""
from __future__ import annotations
import reimport sqlite3import unittestfrom contextlib import closingfrom functools import cachefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[2]# Albedo's own sources and each workspace package's, where the SDK lives.SOURCES = [ ROOT / "apps/albedo/src", *sorted(ROOT.glob("packages/*/src")), *sorted(ROOT.glob("extensions/*/src")),]
def gleam_sources() -> list[Path]: return sorted(path for root in SOURCES for path in root.rglob("*.gleam"))
def schemas() -> set[str]: """Compare declarations with actual user tables, excluding SQLite internals.""" with closing(sqlite3.connect(":memory:")) as db: db.executescript((ROOT / "tools/marmot/schema.sql").read_text()) return { name for _, name, kind, *_ in db.execute("PRAGMA main.table_list") if kind == "table" and not name.startswith("sqlite_") }
_TOKEN = re.compile( r'\s+|//[^\n]*|"(?:[^"\\]|\\.)*"|<>|\d+|[A-Za-z_][\w]*(?:/[A-Za-z_]\w*)*|.', re.S)_TYPES = ROOT / "packages/albedo_sdk/src/albedo_sdk/transfer.gleam"
def _tokens(source: str) -> list[str]: return [ token for token in _TOKEN.findall(source) if token.strip() and not token.startswith("//") ]
def _imported(tokens: list[str]) -> set[str]: """Constructors `import albedo_sdk/transfer.{...}` brings in unqualified.""" names: set[str] = set() for index, token in enumerate(tokens): if token == "albedo_sdk/transfer" and tokens[index - 1] == "import": if tokens[index + 1 : index + 3] == [".", "{"]: at = index + 3 while tokens[at] != "}": if tokens[at] in ("Table", "Excluded") and tokens[at - 1] != "type": names.add(tokens[at]) at += 1 return names
@cachedef imported_string(module: str, name: str) -> str: path = next( root / f"{module}.gleam" for root in SOURCES if (root / f"{module}.gleam").is_file() ) reader = _Declarations(path) if name not in reader.consts: raise AssertionError(f"{module}.{name} is not a string constant") return reader.consts[name]
class _Declarations: """Resolve literal and imported constants in transfer declarations."""
def __init__(self, path: Path): self.path = str(path.relative_to(ROOT)) self.tokens = _tokens(path.read_text()) self.consts: dict[str, str] = {} self.at = 0 self.modules = { module.rsplit("/", 1)[-1]: module for idx, module in enumerate(self.tokens) if idx and self.tokens[idx - 1] == "import" } starts = { self.tokens[index + 1]: index + 2 for index, token in enumerate(self.tokens) if token == "const" } # Passes until nothing new resolves: a const may name a later one. while True: resolved = len(self.consts) for name, start in starts.items(): self.at = start + 2 if self.tokens[start] == ":" else start if name in self.consts or self.tokens[self.at] != "=": continue self.at += 1 try: self.consts[name] = self._string() except AssertionError: continue if len(self.consts) == resolved: break
def _fail(self, wanted: str) -> AssertionError: found = " ".join(self.tokens[self.at : self.at + 6]) return AssertionError(f"{self.path}: expected {wanted}, found {found!r}")
def _take(self, token: str) -> None: if self.tokens[self.at] != token: raise self._fail(repr(token)) self.at += 1
def _string(self) -> str: parts = [] while True: token = self.tokens[self.at] if token.startswith('"'): parts.append(token[1:-1].replace('\\"', '"').replace("\\\\", "\\")) elif token in self.modules and self.tokens[self.at + 1] == ".": parts.append( imported_string(self.modules[token], self.tokens[self.at + 2]) ) self.at += 2 elif token in self.consts: parts.append(self.consts[token]) else: raise self._fail("a string literal or string constant") self.at += 1 if self.tokens[self.at : self.at + 1] != ["<>"]: return "".join(parts) self.at += 1
def _label(self, name: str) -> None: if self.tokens[self.at] == name and self.tokens[self.at + 1] == ":": self.at += 2
def _argument(self, name: str, read): self._label(name) value = read() if self.tokens[self.at] == ",": self.at += 1 return value
def _int(self) -> int: token = self.tokens[self.at] if not token.isdigit(): raise self._fail("an int literal") self.at += 1 return int(token)
def calls(self): unqualified = _imported(self.tokens) for index, token in enumerate(self.tokens): if token not in ("Table", "Excluded") or self.tokens[index + 1] != "(": continue qualified = self.tokens[index - 2 : index] == ["transfer", "."] if not qualified and token not in unqualified: raise AssertionError( f"{self.path}: {token}( is not albedo_sdk/transfer's" ) self.at = index + 2 if token == "Table": entry = ( self._argument("name", self._string), self._argument("version", self._int), self._argument("filter_sql", self._string), ) else: entry = ( self._argument("name", self._string), self._argument("reason", self._string), ) self._take(")") yield token, entry
def declarations() -> tuple[dict[str, list], dict[str, list]]: tables: dict[str, list] = {} excluded: dict[str, list] = {} for path in gleam_sources(): if path == _TYPES: continue if path.name != "transfer.gleam": tokens = _tokens(path.read_text()) built = any( tokens[index : index + 3] == ["transfer", "."] + [name] and tokens[index + 3 : index + 4] == ["("] for index in range(len(tokens)) for name in ("Table", "Excluded") ) if built or _imported(tokens): raise AssertionError( f"{path.relative_to(ROOT)} declares transfer tables outside a transfer.gleam" ) continue reader = _Declarations(path) for kind, entry in reader.calls(): if kind == "Table": name, version, filter_sql = entry tables.setdefault(name, []).append((version, filter_sql, reader.path)) else: excluded.setdefault(entry[0], []).append((entry[1], reader.path)) return tables, excluded
class TransferCoverageTest(unittest.TestCase): def test_every_table_is_declared_once(self): schema = schemas() tables, excluded = declarations() declared = list(tables) + list(excluded) twice = sorted( name for name in set(declared) if len(tables.get(name, [])) + len(excluded.get(name, [])) > 1 ) self.assertEqual(twice, [], "tables declared more than once") missing = sorted(set(schema) - set(declared)) self.assertEqual( missing, [], "tables with no transfer.Table or transfer.Excluded" ) unknown = sorted(set(declared) - set(schema)) self.assertEqual( unknown, [], "transfer declarations for tables nothing creates" )
def test_filters_are_scoped(self): tables, _ = declarations() for name, entries in tables.items(): _, filter_sql, source = entries[0] with self.subTest(table=name, source=source): self.assertRegex(filter_sql, r"\btransfer_(?:scope|workspace)\b") self.assertNotRegex(filter_sql, r"'[0-9a-f]{8,}'", "literal ids")
def test_reasons_are_given(self): _, excluded = declarations() for name, entries in excluded.items(): self.assertTrue( entries[0][0].strip(), f"{name} is excluded without a reason" )
if __name__ == "__main__": unittest.main()