fromscratch-pystack 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. fromscratch_pystack-0.5.0.dist-info/METADATA +510 -0
  2. fromscratch_pystack-0.5.0.dist-info/RECORD +43 -0
  3. fromscratch_pystack-0.5.0.dist-info/WHEEL +4 -0
  4. fromscratch_pystack-0.5.0.dist-info/entry_points.txt +3 -0
  5. fromscratch_pystack-0.5.0.dist-info/licenses/LICENSE +21 -0
  6. pystack/__init__.py +1 -0
  7. pystack/_version.py +24 -0
  8. pystack/adapters/__init__.py +1 -0
  9. pystack/adapters/db_storage.py +157 -0
  10. pystack/adapters/os_pebble.py +118 -0
  11. pystack/adapters/pebble_db.py +85 -0
  12. pystack/cli.py +127 -0
  13. pystack/environment.py +272 -0
  14. pystack/plugins/__init__.py +1 -0
  15. pystack/plugins/_dbcrash_child.py +56 -0
  16. pystack/plugins/_schedagents.py +37 -0
  17. pystack/plugins/_schedalerts.py +103 -0
  18. pystack/plugins/_schedweb.py +79 -0
  19. pystack/plugins/_shared.py +26 -0
  20. pystack/plugins/_webdemo.py +171 -0
  21. pystack/plugins/base.py +201 -0
  22. pystack/plugins/coldb_plugin.py +165 -0
  23. pystack/plugins/crypto_plugin.py +115 -0
  24. pystack/plugins/docdb_plugin.py +172 -0
  25. pystack/plugins/git_plugin.py +94 -0
  26. pystack/plugins/graphdb_plugin.py +206 -0
  27. pystack/plugins/kv_plugin.py +156 -0
  28. pystack/plugins/llm_plugin.py +102 -0
  29. pystack/plugins/mq_plugin.py +290 -0
  30. pystack/plugins/net_plugin.py +247 -0
  31. pystack/plugins/pydb_plugin.py +111 -0
  32. pystack/plugins/registry.py +150 -0
  33. pystack/plugins/sched_plugin.py +235 -0
  34. pystack/plugins/search_plugin.py +151 -0
  35. pystack/plugins/tsdb_plugin.py +175 -0
  36. pystack/plugins/vecdb_plugin.py +168 -0
  37. pystack/plugins/web_plugin.py +95 -0
  38. pystack/py.typed +0 -0
  39. pystack/web/__init__.py +1 -0
  40. pystack/web/app.py +138 -0
  41. pystack/web/static/app.js +105 -0
  42. pystack/web/static/style.css +158 -0
  43. pystack/web/templates/index.html +59 -0
@@ -0,0 +1,157 @@
1
+ """PyDB ↔ PyOS filesystem adapter.
2
+
3
+ A storage engine that saves PyDB tables inside the PyOS virtual
4
+ filesystem instead of the real disk. This means database files live
5
+ alongside OS files in the simulated world.
6
+
7
+ Think of it like keeping your card binder inside the school building
8
+ (PyOS) instead of at home (the real filesystem).
9
+ """
10
+
11
+ import contextlib
12
+
13
+ from py_os.kernel import Kernel
14
+ from py_os.syscalls import SyscallError, SyscallNumber
15
+ from pydb.record import Record
16
+ from pydb.schema import Schema
17
+ from pydb.serializer import SerializationError, deserialize_table_data, serialize_table_data
18
+ from pydb.storage import StorageError
19
+
20
+ TABLE_FILE_SUFFIX = ".json"
21
+ DEFAULT_DB_DIR = "/data"
22
+
23
+
24
+ class PyOSStorageEngine:
25
+ """Store PyDB tables in the PyOS virtual filesystem.
26
+
27
+ Implements the same interface as ``pydb.storage.StorageEngine``
28
+ but delegates all I/O to PyOS kernel syscalls.
29
+
30
+ Args:
31
+ kernel: The running PyOS kernel.
32
+ db_dir: Directory in the PyOS filesystem for table files.
33
+
34
+ """
35
+
36
+ __slots__ = ("_db_dir", "_kernel")
37
+
38
+ def __init__(self, kernel: Kernel, db_dir: str = DEFAULT_DB_DIR) -> None:
39
+ """Create a storage engine backed by the PyOS filesystem."""
40
+ self._kernel = kernel
41
+ self._db_dir = db_dir
42
+ self._ensure_dir()
43
+
44
+ def _ensure_dir(self) -> None:
45
+ """Create the database directory if it doesn't exist."""
46
+ with contextlib.suppress(SyscallError):
47
+ self._kernel.syscall(SyscallNumber.SYS_CREATE_DIR, path=self._db_dir)
48
+
49
+ def _table_path(self, table_name: str) -> str:
50
+ """Return the virtual filesystem path for a table."""
51
+ return f"{self._db_dir}/{table_name}{TABLE_FILE_SUFFIX}"
52
+
53
+ @property
54
+ def data_dir(self) -> str:
55
+ """Return the database directory path."""
56
+ return self._db_dir
57
+
58
+ def save_table(
59
+ self,
60
+ name: str,
61
+ schema: Schema,
62
+ records: list[Record],
63
+ next_id: int,
64
+ ) -> None:
65
+ """Save a table to the PyOS filesystem.
66
+
67
+ Args:
68
+ name: The table name.
69
+ schema: The table's schema.
70
+ records: All records in the table.
71
+ next_id: The next auto-increment ID.
72
+
73
+ Raises:
74
+ StorageError: If the write fails.
75
+
76
+ """
77
+ json_str = serialize_table_data(name, schema, records, next_id)
78
+ path = self._table_path(name)
79
+ try:
80
+ # Create file if it doesn't exist, then write.
81
+ with contextlib.suppress(SyscallError):
82
+ self._kernel.syscall(SyscallNumber.SYS_CREATE_FILE, path=path)
83
+ self._kernel.syscall(
84
+ SyscallNumber.SYS_WRITE_FILE,
85
+ path=path,
86
+ data=json_str.encode("utf-8"),
87
+ )
88
+ except SyscallError as exc:
89
+ msg = f"Failed to save table {name!r}: {exc}"
90
+ raise StorageError(msg) from exc
91
+
92
+ def load_table(self, name: str) -> tuple[str, Schema, list[Record], int]:
93
+ """Load a table from the PyOS filesystem.
94
+
95
+ Args:
96
+ name: The table name.
97
+
98
+ Returns:
99
+ A tuple of (name, schema, records, next_id).
100
+
101
+ Raises:
102
+ StorageError: If the file doesn't exist or is corrupted.
103
+
104
+ """
105
+ path = self._table_path(name)
106
+ try:
107
+ data: bytes = self._kernel.syscall(SyscallNumber.SYS_READ_FILE, path=path)
108
+ except SyscallError as exc:
109
+ msg = f"No data file for table {name!r} at {path}"
110
+ raise StorageError(msg) from exc
111
+
112
+ try:
113
+ return deserialize_table_data(data.decode("utf-8"))
114
+ except SerializationError as exc:
115
+ msg = f"Corrupted data file for table {name!r}: {exc}"
116
+ raise StorageError(msg) from exc
117
+
118
+ def delete_table(self, name: str) -> None:
119
+ """Remove a table's data file from the PyOS filesystem.
120
+
121
+ Args:
122
+ name: The table name.
123
+
124
+ Raises:
125
+ StorageError: If the file doesn't exist.
126
+
127
+ """
128
+ path = self._table_path(name)
129
+ try:
130
+ self._kernel.syscall(SyscallNumber.SYS_DELETE_FILE, path=path)
131
+ except SyscallError as exc:
132
+ msg = f"No data file for table {name!r} at {path}"
133
+ raise StorageError(msg) from exc
134
+
135
+ def table_exists(self, name: str) -> bool:
136
+ """Check whether a data file exists for the given table name."""
137
+ path = self._table_path(name)
138
+ try:
139
+ self._kernel.syscall(SyscallNumber.SYS_READ_FILE, path=path)
140
+ except SyscallError:
141
+ return False
142
+ return True
143
+
144
+ def list_tables(self) -> list[str]:
145
+ """Return the names of all tables in the PyOS filesystem."""
146
+ try:
147
+ entries: list[str] = self._kernel.syscall(
148
+ SyscallNumber.SYS_LIST_DIR,
149
+ path=self._db_dir,
150
+ )
151
+ except SyscallError:
152
+ return []
153
+ return sorted(
154
+ entry.removesuffix(TABLE_FILE_SUFFIX)
155
+ for entry in entries
156
+ if entry.endswith(TABLE_FILE_SUFFIX)
157
+ )
@@ -0,0 +1,118 @@
1
+ """PyOS ↔ Pebble adapter.
2
+
3
+ Register a ``pebble`` command in the PyOS shell so users can run
4
+ Pebble programs from the OS command line. Programs run with full
5
+ database access via the ``db`` stdlib module.
6
+
7
+ Usage from the PyOS shell::
8
+
9
+ pebble run /programs/hello.pbl
10
+ pebble eval 'print(1 + 2)'
11
+ """
12
+
13
+ from collections.abc import Callable
14
+
15
+ from py_os.kernel import Kernel
16
+ from py_os.shell import Shell
17
+ from py_os.syscalls import SyscallError, SyscallNumber
18
+
19
+ MIN_QUOTED_LENGTH = 2
20
+ PEBBLE_USAGE = "Usage: pebble run <file.pbl> | pebble eval '<code>'"
21
+
22
+
23
+ def _run_file(
24
+ kernel: Kernel,
25
+ run_source: Callable[[str], str],
26
+ file_path: str,
27
+ ) -> str:
28
+ """Run a .pbl file from the PyOS filesystem."""
29
+ try:
30
+ data: bytes = kernel.syscall(SyscallNumber.SYS_READ_FILE, path=file_path)
31
+ except SyscallError as exc:
32
+ return f"Error: {exc}"
33
+ try:
34
+ return run_source(data.decode("utf-8")).rstrip("\n")
35
+ except Exception as exc: # noqa: BLE001
36
+ return f"Error: {exc}"
37
+
38
+
39
+ def _eval_code(run_source: Callable[[str], str], source: str) -> str:
40
+ """Evaluate a Pebble expression."""
41
+ try:
42
+ return run_source(source).rstrip("\n")
43
+ except Exception as exc: # noqa: BLE001
44
+ return f"Error: {exc}"
45
+
46
+
47
+ def register_pebble_command(
48
+ shell: Shell,
49
+ kernel: Kernel,
50
+ run_source: Callable[[str], str],
51
+ ) -> None:
52
+ """Register the ``pebble`` command in a PyOS shell.
53
+
54
+ Args:
55
+ shell: The PyOS shell to extend.
56
+ kernel: The running kernel (for filesystem access).
57
+ run_source: A callable that compiles and runs Pebble source code.
58
+
59
+ """
60
+
61
+ def handler(args: list[str]) -> str:
62
+ if not args:
63
+ return PEBBLE_USAGE
64
+ subcommand = args[0]
65
+ if subcommand == "run" and len(args) > 1:
66
+ return _run_file(kernel, run_source, args[1])
67
+ if subcommand == "eval" and len(args) > 1:
68
+ source = " ".join(args[1:])
69
+ # Remove matching outer quotes if present.
70
+ if len(source) >= MIN_QUOTED_LENGTH and source[0] == source[-1] and source[0] in "'\"":
71
+ source = source[1:-1]
72
+ return _eval_code(run_source, source)
73
+ return PEBBLE_USAGE
74
+
75
+ shell._commands["pebble"] = handler # noqa: SLF001
76
+
77
+
78
+ def register_sql_command(
79
+ shell: Shell,
80
+ run_sql: Callable[[str], str],
81
+ ) -> None:
82
+ """Register a ``sql`` command in the PyOS shell.
83
+
84
+ Args:
85
+ shell: The PyOS shell to extend.
86
+ run_sql: A callable that executes SQL and returns formatted results.
87
+
88
+ """
89
+
90
+ def handler(args: list[str]) -> str:
91
+ if not args:
92
+ return "Usage: sql '<query>'"
93
+ sql = " ".join(args)
94
+ try:
95
+ return run_sql(sql)
96
+ except Exception as exc: # noqa: BLE001
97
+ return f"Error: {exc}"
98
+
99
+ shell._commands["sql"] = handler # noqa: SLF001
100
+
101
+
102
+ def register_save_command(shell: Shell, save: Callable[[], None]) -> None:
103
+ """Register a ``save`` command that saves the database and every plugin.
104
+
105
+ Args:
106
+ shell: The PyOS shell to extend.
107
+ save: The environment's save method.
108
+
109
+ """
110
+
111
+ def handler(_args: list[str]) -> str:
112
+ try:
113
+ save()
114
+ except Exception as exc: # noqa: BLE001 -- shown to the user
115
+ return f"Error: {exc}"
116
+ return "Saved."
117
+
118
+ shell._commands["save"] = handler # noqa: SLF001
@@ -0,0 +1,85 @@
1
+ """Pebble ↔ PyDB adapter.
2
+
3
+ Build a ``db`` module for Pebble so that Pebble programs can
4
+ query and modify a PyDB database using functions like ``db_query()``
5
+ and ``db_execute()``.
6
+
7
+ This is the bridge between a programming language and a database --
8
+ just like how Python programs talk to SQLite or PostgreSQL.
9
+ """
10
+
11
+ from datetime import date
12
+
13
+ from pebble import StdlibModule
14
+ from pebble import Value as PebbleValue
15
+ from pydb.database import Database
16
+ from pydb.executor import execute
17
+ from pydb.record import Value as PyDBValue
18
+ from pydb.sql_parser import parse_sql
19
+ from pydb.types import to_iso
20
+
21
+
22
+ def _pydb_to_pebble(value: PyDBValue) -> PebbleValue:
23
+ """Convert a PyDB value to a Pebble value.
24
+
25
+ Text, numbers and booleans pass straight through. Dates and timestamps
26
+ become readable ISO text (``2026-10-17`` or ``2026-10-17T07:30:00Z``),
27
+ because Pebble has no date type of its own.
28
+ """
29
+ return to_iso(value) if isinstance(value, date) else value
30
+
31
+
32
+ def _row_to_pebble_dict(row: dict[str, PyDBValue]) -> dict[str, PebbleValue]:
33
+ """Convert a PyDB result row to a Pebble dict."""
34
+ return {k: _pydb_to_pebble(v) for k, v in row.items()}
35
+
36
+
37
+ def _make_db_query(database: Database) -> StdlibModule:
38
+ """Build the handler functions that wrap PyDB operations.
39
+
40
+ Args:
41
+ database: The PyDB database instance to query.
42
+
43
+ Returns:
44
+ A Pebble StdlibModule with db_query, db_execute, and db_tables.
45
+
46
+ """
47
+
48
+ def _db_query(args: list[PebbleValue]) -> PebbleValue:
49
+ """Execute a SQL SELECT and return results as a list of dicts."""
50
+ sql = str(args[0])
51
+ parsed = parse_sql(sql)
52
+ results = execute(parsed, database)
53
+ return [_row_to_pebble_dict(row) for row in results]
54
+
55
+ def _db_execute(args: list[PebbleValue]) -> PebbleValue:
56
+ """Execute a SQL write statement and return a status message."""
57
+ sql = str(args[0])
58
+ parsed = parse_sql(sql)
59
+ results = execute(parsed, database)
60
+ if results and "result" in results[0]:
61
+ return str(results[0]["result"])
62
+ return f"{len(results)} rows returned"
63
+
64
+ def _db_tables(_args: list[PebbleValue]) -> PebbleValue:
65
+ """Return a list of all table names in the database."""
66
+ names: list[PebbleValue] = list(database.table_names())
67
+ return names
68
+
69
+ return StdlibModule(
70
+ functions={
71
+ "db_query": (1, _db_query),
72
+ "db_execute": (1, _db_execute),
73
+ "db_tables": (0, _db_tables),
74
+ },
75
+ constants={},
76
+ )
77
+
78
+
79
+ def make_db_module(database: Database) -> StdlibModule:
80
+ """Build a ``db`` module wired to one particular database.
81
+
82
+ Each environment keeps its own copy, so two environments never end up
83
+ reading (or deleting) each other's tables.
84
+ """
85
+ return _make_db_query(database)
pystack/cli.py ADDED
@@ -0,0 +1,127 @@
1
+ """PyStack command-line interface.
2
+
3
+ Launch the integrated environment with Pebble + PyDB, run Pebble
4
+ programs that query databases, or start an interactive SQL session.
5
+ """
6
+
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from py_os.shell import Shell
11
+ from pydb.cli import repl
12
+
13
+ from pystack.environment import PyStackEnvironment
14
+
15
+
16
+ def _run_web() -> None:
17
+ """Launch the browser UI -- the only command that needs Flask.
18
+
19
+ Flask is an optional extra, so we only import it when you actually ask
20
+ for the web UI. Everything else works on a plain install.
21
+ """
22
+ try:
23
+ from pystack.web.app import main as web_main # noqa: PLC0415 -- optional extra
24
+ except ImportError:
25
+ sys.stderr.write("pystack web needs Flask. Install it with: pip install 'pystack[web]'\n")
26
+ sys.exit(1)
27
+ web_main()
28
+
29
+
30
+ def main() -> None:
31
+ """Entry point for the ``pystack`` command."""
32
+ args = sys.argv[1:]
33
+
34
+ if not args or args[0] in ("--help", "-h"):
35
+ _print_help()
36
+ return
37
+
38
+ command = args[0]
39
+
40
+ match command:
41
+ case "pebble":
42
+ _run_pebble(args[1:])
43
+ case "sql":
44
+ _run_sql()
45
+ case "os":
46
+ _run_os()
47
+ case "web":
48
+ _run_web()
49
+ case _:
50
+ if command.endswith(".pbl"):
51
+ _run_pebble([command])
52
+ else:
53
+ sys.stderr.write(f"Unknown command: {command}\n")
54
+ _print_help()
55
+ sys.exit(1)
56
+
57
+
58
+ def _print_help() -> None:
59
+ """Print usage information."""
60
+ sys.stdout.write(
61
+ "PyStack -- the full stack, from scratch\n\n"
62
+ "Usage:\n"
63
+ " pystack pebble <file.pbl> Run a Pebble program with database access\n"
64
+ " pystack sql Launch interactive SQL REPL\n"
65
+ " pystack os Launch PyOS shell with Pebble + DB integration\n"
66
+ " pystack web Launch browser UI at http://localhost:8080\n"
67
+ " pystack <file.pbl> Shortcut for pystack pebble <file.pbl>\n"
68
+ " pystack --help Show this help\n"
69
+ )
70
+
71
+
72
+ def _run_pebble(args: list[str]) -> None:
73
+ """Run a Pebble program with database access."""
74
+ if not args:
75
+ sys.stderr.write("Usage: pystack pebble <file.pbl>\n")
76
+ sys.exit(1)
77
+
78
+ file_path = Path(args[0])
79
+ if not file_path.exists():
80
+ sys.stderr.write(f"Error: file not found: {file_path}\n")
81
+ sys.exit(1)
82
+
83
+ env = PyStackEnvironment()
84
+ try:
85
+ output = env.run_pebble_file(file_path)
86
+ if output:
87
+ sys.stdout.write(output)
88
+ except Exception as exc: # noqa: BLE001
89
+ sys.stderr.write(f"Error: {exc}\n")
90
+ sys.exit(1)
91
+ finally:
92
+ env.shutdown()
93
+
94
+
95
+ def _run_sql() -> None:
96
+ """Launch an interactive SQL REPL with the integrated database."""
97
+ env = PyStackEnvironment()
98
+ try:
99
+ repl(env.database)
100
+ finally:
101
+ env.shutdown()
102
+
103
+
104
+ def _run_os() -> None:
105
+ """Launch the PyOS shell with Pebble and SQL integration."""
106
+ env = PyStackEnvironment(os_mode=True)
107
+ sys.stdout.write("PyStack OS -- type 'help' for commands, 'pebble' or 'sql' for integrations\n")
108
+ shell = env.shell
109
+ if not isinstance(shell, Shell):
110
+ sys.stderr.write("Error: OS mode failed to boot\n")
111
+ sys.exit(1)
112
+ try:
113
+ while True:
114
+ try:
115
+ line = input("pystack-os> ").strip()
116
+ except (EOFError, KeyboardInterrupt): # fmt: skip
117
+ sys.stdout.write("\nGoodbye!\n")
118
+ break
119
+ if not line:
120
+ continue
121
+ output = shell.execute(line)
122
+ if output == Shell.EXIT_SENTINEL:
123
+ break
124
+ if output:
125
+ sys.stdout.write(output + "\n")
126
+ finally:
127
+ env.shutdown()