Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(paths): collapse all MachinaOs files under DATA_DIR + drop empty daemon dirs
trohitg79570c904c0d
diff --git a/CLAUDE.md b/CLAUDE.mdindex d526fb48..818c4a93 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5300,7 +5300,7 @@ This function:- **Telegram owner detection — three layers** (f746ddf): the bot owner is captured by THREE independent paths so the realistic setup flows all converge to a working state. (1) **Explicit field**: secondary `FieldDef` in the credentials modal lets the user paste their Telegram user ID directly (recommended; works without DM'ing the bot). (2) **Pre-poll peek** in `connect()` via `_capture_owner_from_pending_updates()` — calls `bot.get_updates(timeout=0)` BEFORE `start_polling(drop_pending_updates=True)` discards the queue, scans for any historical private DM, captures + persists atomically. (3) **Atomic write-through in `_on_message_received`** — persists FIRST, sets in-memory ONLY on success. Invariant: "in-memory has owner ⇒ DB has owner" so a process restart can re-capture cleanly. Failure logged at `ERROR` with `exc_info=True` (was `WARNING` previously, masking persist failures). The lazy fallback in `telegram_send.py` (read DB → `service.set_owner`) sits on top of all three.- **Supervisor Job Object loud-failure (cli/tree.py + cli/supervisor.py)** (8a64eb9): the Windows process-tree mechanism depends entirely on a Job Object with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` (no fallback — `start_new_session` is POSIX-only). `pywin32>=308` is a hard supervisor dependency on Windows; the declaration in the root `pyproject.toml` (where `machinaos-cli` lives — `cli/pyproject.toml` was removed as a stale duplicate) carries an inline comment so future maintainers don't drop it. `_JobObject.__init__` splits failures into explicit `ImportError` (with reinstall command) and `Exception` (with `repr`) branches — both write to `stderr` instead of swallowing. `_JobObject.add()` verifies enrollment via `win32job.IsProcessInJob(handle, self._handle)` after assignment; on mismatch it queries `IsProcessInJob(handle, None)` so the warning explicitly names the wrapper-job hypothesis (npm / pnpm / conhost wrappers occasionally place us in their own non-nesting Job). `supervisor._spawn_once` checks `add_to_job` return value and emits a yellow `WARN: pid=N not enrolled in Job Object` per child if False. Without these guards, a stale pywin32 install or a wrapping Job Object silently leaks orphan Python processes on every Ctrl-C and they accumulate to the point of holding SQLite locks that block subsequent backend startup.- **Credentials envelope-shape invariant** (dc94cde): the `useCredentialPanel` query stores `{values: CredentialFormValues, hadStored: boolean}` (an envelope, NOT a flat dict). The earlier `writeValues` called `setQueryData<CredentialFormValues>` with a spread `(prev) => ({...prev, [key]: value})`, which at runtime merged the typed character at the envelope level next to `values` and `hadStored` instead of inside `.values` — the input selector `panel.values[field.key]` re-rendered with the original (server) value on every keystroke and the input felt frozen. Fix: `writeValues` now preserves the envelope shape and updates only the inner `values` dict; `hadStored` is preserved verbatim (it reflects real server state, not local edits). When introducing other queries shaped as `{data, meta}` envelopes, follow the same pattern — never spread `prev` as if it were the inner payload.-- **`core.paths` is the SSOT for on-disk locations**: state vs. install split — `machina_root()` (= `~/.machina/`) holds *state* (workspaces, whatsapp session DB, `credentials.db`, `workflow.db`, claude OAuth+binary at `~/.machina/claude/`, supervised daemon cwds at `~/.machina/daemons/<namespace>/`); `packages_dir()` (= `platformdirs.user_cache_path("MachinaOs")` → `~/.cache/MachinaOs/` on Linux, `~/Library/Caches/MachinaOs/` on macOS, `%LOCALAPPDATA%\MachinaOs\Cache\` on Windows) holds *downloaded binaries* via `package_dir(name)` per service (`stripe`, `browser`). Wiping `packages_dir` forces a fresh redownload without dropping auth state. **Claude is the deliberate exception** — its npm tree lives at `<DATA_DIR>/claude/npm/` (via `claude_npm_dir()`) alongside `CLAUDE_CONFIG_DIR` state, so the entire claude footprint sits under one operator-visible subtree. **`daemons_dir()`** (sibling of `workspaces_dir()`) is where `DaemonEventSource.workdir()` places cwds — pre-fix it placed them under `workspaces_dir() / namespace` and the `stripe listen` daemon polluted per-workflow scratch with framework state. Out of scope: globally-installed binaries (`temporal`, Himalaya) and npm `package.json` deps (`edgymeow`). Shipped seed workflows are the lone exception — `example_workflows_dir()` is hardcoded to `<repo>/.machina/workflows/` (git-tracked seeds, NOT under `DATA_DIR`) so they survive `machina clean` and stay at the same path across `DATA_DIR=~/.machina` vs `DATA_DIR=.machina` configs.+- **`core.paths` is the SSOT for on-disk locations**: everything MachinaOs owns lives under `machina_root()` (= `~/.machina/` per default `DATA_DIR`). Subtree map: `workspaces/<slug>/` (per-workflow scratch), `daemons/` (supervised event-source daemon cwds — `stripe listen` etc.; shared root by default, no per-namespace subdir), `claude/` (Claude Code's `CLAUDE_CONFIG_DIR` state + `claude/npm/` binary install via `claude_npm_dir()`), `packages/<service>/` (downloaded binaries via `package_dir(name)` — `stripe`, `browser`, `temporal`), `whatsapp/` (WhatsApp session DB), `credentials.db` / `workflow.db` / `temporal.db`. Pre-fix `packages_dir()` routed through `platformdirs.user_cache_path("MachinaOs")` (`~/.cache/MachinaOs/` etc.) and the Temporal CLI sat in its own `pooch.os_cache("machinaos-temporal")` namespace — operators reported both as "not local" and the binary-vs-state split bought nothing in practice. Daemon cwds also used to live under `workspaces/_<namespace>/` and polluted per-workflow scratch with framework state. Out of scope: globally-installed binaries (Himalaya) and npm `package.json` deps (`edgymeow`). Shipped seed workflows are the lone exception — `example_workflows_dir()` is hardcoded to `<repo>/.machina/workflows/` (git-tracked seeds, NOT under `DATA_DIR`) so they survive `machina clean` and stay at the same path across `DATA_DIR=~/.machina` vs `DATA_DIR=.machina` configs.- **`machina clean` preserves `.machina/workflows/`**: `cli/commands/clean.py` iterates `<repo>/.machina/` children and skips anything in `_MACHINA_KEEP = frozenset({"workflows"})`. Wipes `claude/`, `workspaces/`, `*.db` as before; preserves the shipped seed JSONs so a fresh clone + clean doesn't lose user-importable examples. Test `cli/tests/test_clean.py::test_machina_keep_preserves_workflows` locks the keep-list.- **No raw `print()` outside three sanctioned helpers**: `main._startup_log` (pre-logger boot markers), `core.container._clog` (DI-bootstrap markers), and `nodes.code.python_executor.captured_print` (the sandbox builtin handed to user code). Everything else goes through `logger = get_logger(__name__)`. The supervisor prefixes every aggregated line with `[HH:MM:SS.fff]` so no inner `TimeStamper` is needed; structlog console mode is deliberately timestamp-less. Test `server/tests/test_no_raw_prints.py` AST-walks the tree and flags any unsanctioned `print(...)` call.- **`configure_logging(settings)` must run BEFORE plugin self-registration imports**: in `main.py`, `Settings()` + `configure_logging(settings)` + `init_tracing()` + `get_logger(__name__)` happen ahead of `from core.container import container` and `from routers import …`. Otherwise plugin folders that register on import call `logger.debug(...)` while structlog is still on its default processor chain (which includes `TimeStamper` + no `filter_by_level`) — symptom is double timestamps + debug records leaking despite `LOG_LEVEL=INFO`.diff --git a/server/core/paths.py b/server/core/paths.pyindex 21ba9c0d..fdba0e9f 100644--- a/server/core/paths.py+++ b/server/core/paths.py@@ -14,45 +14,53 @@ ngrok's ``~/.ngrok2/``, and claude code's own ``~/.claude/``.State layout under ``~/.machina/`` (flat, no redundant nesting):- - ``~/.machina/claude/`` OAuth state for spawned claude subprocesses- - ``~/.machina/workspaces/`` per-workflow scratch dirs+ - ``~/.machina/claude/`` Claude Code's CLAUDE_CONFIG_DIR+ state + ``claude/npm/`` binary install+ - ``~/.machina/workspaces/`` per-workflow scratch dirs (one+ subdir per ``Workflow.slug``)+ - ``~/.machina/daemons/`` cwd root for supervised event-source+ daemons (``stripe listen``, …);+ shared across all daemons by+ default to avoid empty per-namespace+ subdirs+ - ``~/.machina/packages/`` downloaded service binaries+ (``stripe``, ``browser``)- ``~/.machina/whatsapp/`` persistent WhatsApp session DB- - ``~/.machina/temporal/`` temporal-server cwd + SQLite db when persist=true- ``~/.machina/credentials.db`` Fernet-encrypted secrets- ``~/.machina/workflow.db`` SQLite app DB+ - ``~/.machina/temporal.db`` Temporal server SQLite (flat under+ DATA_DIR like the other ``*.db``)Binaries that MachinaOs downloads on first use (Stripe CLI,-``agent-browser``'s npm tree) live separately, under the-OS-conventional cache dir (see :func:`packages_dir`). Resolved via-:func:`platformdirs.user_cache_path` — the standard cross-platform-resolver every XDG-aware tool already uses:-- - Linux: ``~/.cache/MachinaOs/<service>/``- - macOS: ``~/Library/Caches/MachinaOs/<service>/``- - Windows: ``%LOCALAPPDATA%\\MachinaOs\\Cache\\<service>\\``--Claude Code is the deliberate exception: its npm tree lives at-``<DATA_DIR>/claude/npm/`` (see :func:`claude_npm_dir`) alongside the-``CLAUDE_CONFIG_DIR`` auth state at ``<DATA_DIR>/claude/``. Keeping-the entire claude footprint (binary + tokens + IDE lockfiles + session-JSONL) under one operator-visible subtree means a single-``mv ~/.machina/claude /backup`` carries everything claude needs;-every operation requires both anyway, so the binary-vs-state split-that's useful for Stripe / browser hurts here. Supervised-event-source daemons (``stripe listen``, future plugins) keep their-cwd under :func:`daemons_dir` — a sibling of :func:`workspaces_dir`-so per-workflow scratch (workspaces) is never mixed with framework-state (daemons).--Out of scope here: the downloaded Temporal CLI binary (pooch cache-under :func:`packages_dir`, see ``services/temporal/_install.py``),-Himalaya (``cargo``/``brew`` system install), and npm packages-declared in ``package.json`` whose binaries pnpm manages directly-under ``node_modules/`` (e.g. ``whatsapp-rpc``'s ``edgymeow``).--The split keeps ``machina clean`` semantics clear: wiping-:func:`packages_dir` forces a fresh redownload of MachinaOs-managed-binaries without touching auth tokens, session DBs, or workspaces.+``agent-browser``'s npm tree, ``@anthropic-ai/claude-code``) all+live under ``<DATA_DIR>/`` — the same operator-visible tree as+auth state, workspaces, and daemon cwds:++ - Stripe CLI: ``<DATA_DIR>/packages/stripe/bin/stripe[.exe]``+ - agent-browser: ``<DATA_DIR>/packages/browser/npm/``+ - Claude Code: ``<DATA_DIR>/claude/npm/`` (sibling of+ ``CLAUDE_CONFIG_DIR`` at ``<DATA_DIR>/claude/`` — see+ :func:`claude_npm_dir`)++Supervised event-source daemons (``stripe listen``, future plugins)+keep their cwd under :func:`daemons_dir` (``<DATA_DIR>/daemons/+<namespace>/``) — a sibling of :func:`workspaces_dir` so per-workflow+scratch (workspaces) is never mixed with framework state (daemons).++The split that pre-fix routed binaries through+:func:`platformdirs.user_cache_path` (``~/.cache/MachinaOs/`` etc.)+turned out to confuse operators ("not local") without buying anything+in practice — both ``machina clean`` and a manual cache wipe are+operator-driven anyway. Single subtree wins for inspection,+backup, and reasoning about disk usage.++The Temporal CLI binary lands at ``<DATA_DIR>/packages/temporal/``+too (pooch-managed; see ``services/temporal/_install.py``).++Out of scope: Himalaya (``cargo`` / ``brew`` system install) and+npm packages declared in ``package.json`` whose binaries pnpm+manages directly under ``node_modules/`` (e.g. ``whatsapp-rpc``'s+``edgymeow``).Shipped example workflows live at ``<repo>/.machina/workflows/`` —git-tracked seed JSONs auto-imported on first launch by@@ -89,8 +97,6 @@ from __future__ import annotationsfrom pathlib import Path-import platformdirs-from core.logging import get_loggerlogger = get_logger(__name__)@@ -155,39 +161,37 @@ def machina_root() -> Path:def packages_dir() -> Path:- """OS-conventional cache root for binaries we download on first use.-- Delegates to :func:`platformdirs.user_cache_path` — the standard- cross-platform resolver (used internally by ``pooch.os_cache``,- which is how the Temporal binary downloader already finds its- cache). Resolves to:-- - Linux: ``$XDG_CACHE_HOME/MachinaOs/`` or ``~/.cache/MachinaOs/``- - macOS: ``~/Library/Caches/MachinaOs/``- - Windows: ``%LOCALAPPDATA%\\MachinaOs\\Cache``-- Why OS cache (not :func:`machina_root`): downloaded binaries are- pure cache — wiping them forces a clean redownload, never- drops auth tokens or session state. The OS-conventional cache- location is the standard place tools like Stripe CLI, Temporal,- and Claude Code expect their binaries to land; matches every- XDG-aware system installer.+ """Root for binaries MachinaOs downloads on first use.++ Resolves to ``<DATA_DIR>/packages/`` — under the same operator-+ visible tree as auth state, workspaces, and daemon cwds. One+ ``mv ~/.machina`` carries every MachinaOs-managed file together,+ and one glance at ``~/.machina/`` shows the operator everything+ the app owns.++ Pre-fix this used :func:`platformdirs.user_cache_path` so binaries+ landed at ``~/.cache/MachinaOs/`` (Linux) / ``~/Library/Caches/+ MachinaOs/`` (macOS) / ``%LOCALAPPDATA%\\MachinaOs\\Cache\\``+ (Windows). Operators reported it as "not local" — the split+ between binaries (OS cache) and state (DATA_DIR) was confusing+ and the OS-cache rationale (machina clean keeps auth, cache+ wipe drops binaries) didn't matter in practice since both wipe+ operations are operator-driven anyway.See :func:`package_dir` for the per-service accessor."""- return platformdirs.user_cache_path("MachinaOs", appauthor=False)+ return data_path("packages")def package_dir(name: str) -> Path:"""Per-service install folder under :func:`packages_dir`.Canonical layout — each plugin's installer (``ensure_stripe_cli``,- ``ensure_temporal_binaries``, ``ensure_local_claude_install``, …)+ ``ensure_temporal_binaries``, ``agent_browser_binary_path``, …)drops its tree here. Examples::- package_dir("stripe") -> ~/.cache/MachinaOs/stripe/ (Linux)- package_dir("temporal") -> ~/Library/Caches/MachinaOs/temporal/ (macOS)- package_dir("claude") -> %LOCALAPPDATA%\\MachinaOs\\Cache\\claude\\ (Windows)+ package_dir("stripe") -> ~/.machina/packages/stripe/+ package_dir("browser") -> ~/.machina/packages/browser/Caller is responsible for ``mkdir(parents=True, exist_ok=True)``so this helper stays side-effect-free and safe to call duringdiff --git a/server/nodes/stripe/_install.py b/server/nodes/stripe/_install.pyindex fb02ba07..309d4459 100644--- a/server/nodes/stripe/_install.py+++ b/server/nodes/stripe/_install.py@@ -1,19 +1,17 @@"""Stripe CLI auto-installer.On first use, downloads the official Stripe CLI binary from GitHub-releases (https://github.com/stripe/stripe-cli/releases) and caches-it under :func:`core.paths.package_dir` (``<OS cache>/MachinaOs/stripe/-bin/stripe[.exe]``). A system install on PATH (brew / scoop / apt /-direct binary) is preferred — the download path only fires when no-system binary is found.--Note: the cache directory above is the *binary* install location and-is separate from the ``stripe listen`` daemon's working directory,-which lives at ``<DATA_DIR>/daemons/_stripe/`` (see-:func:`core.paths.daemons_dir`). The two were not always separate —-prior to the daemon-cwd cleanup, the daemon ran from-``<DATA_DIR>/workspaces/_stripe/`` and polluted per-workflow scratch-space with framework state.+releases (https://github.com/stripe/stripe-cli/releases) and stores+it at ``<DATA_DIR>/packages/stripe/bin/stripe[.exe]`` (resolved via+:func:`core.paths.package_dir`). A system install on PATH (brew /+scoop / apt / direct binary) is preferred — the download path only+fires when no system binary is found.++The ``stripe listen`` daemon's working directory is a separate+location at ``<DATA_DIR>/daemons/_stripe/`` (see+:func:`core.paths.daemons_dir`). The binary install and the daemon+cwd are intentionally split — binaries are install state, daemon+cwds hold runtime log/state files.Pin a version here when bumping; pre-built archives are signed byStripe and served over GitHub's CDN.diff --git a/server/services/events/daemon.py b/server/services/events/daemon.pyindex 88b63dbc..c7de89bc 100644--- a/server/services/events/daemon.py+++ b/server/services/events/daemon.py@@ -70,9 +70,16 @@ class DaemonEventSource(EventSource):return Nonedef workdir(self) -> Path:+ """Subprocess cwd for the supervised daemon. Default returns the+ shared :func:`core.paths.daemons_dir` root — most daemons+ (``stripe listen``, future plugins) don't write anything to+ their cwd, so giving each a per-namespace subdir just leaves+ empty directories behind. Override in a subclass that genuinely+ needs scratch space (and ``mkdir`` the per-namespace tree+ yourself)."""from core.paths import daemons_dir- cwd = daemons_dir() / self.workflow_namespace+ cwd = daemons_dir()cwd.mkdir(parents=True, exist_ok=True)return cwddiff --git a/server/services/process_service.py b/server/services/process_service.pyindex e7a703c4..04dc41cd 100644--- a/server/services/process_service.py+++ b/server/services/process_service.py@@ -146,23 +146,37 @@ class ProcessService:argv[0] = resolvedenv = {**os.environ, "PYTHONUNBUFFERED": "1"}from core.config import Settings+ from core.paths import daemons_dirworkspace_base = Path(Settings().workspace_base_resolved).resolve()+ daemon_base = daemons_dir().resolve()if not working_directory:working_directory = str(workspace_base / "default")os.makedirs(working_directory, exist_ok=True)cwd = working_directory- # Guardrail: cwd must resolve inside workspace base- if not Path(cwd).resolve().is_relative_to(workspace_base):+ # Guardrail: cwd must resolve inside one of the MachinaOs-controlled+ # state roots — workspaces (per-workflow scratch for workflow nodes+ # like processManager / code executors) OR daemons (framework event+ # sources like `stripe listen`). Both are siblings under DATA_DIR.+ cwd_resolved = Path(cwd).resolve()+ is_under_workspace = cwd_resolved.is_relative_to(workspace_base)+ is_under_daemons = cwd_resolved.is_relative_to(daemon_base)+ if not (is_under_workspace or is_under_daemons):return {"success": False,- "error": f"Working directory must be inside workspace ({workspace_base}).",+ "error": (+ f"Working directory must be inside workspace ({workspace_base}) "+ f"or daemons ({daemon_base})."+ ),}- # Create log directory inside the workflow workspace- # Layout: {workspace}/.processes/{name}/stdout.log, stderr.log+ # Per-process log directory. For workflow-scoped processes this+ # lands at ``{workspace}/.processes/{name}/`` (operator can find+ # logs alongside the workflow's other files); for daemons it+ # lands at ``{daemons_dir}/.processes/{name}/``. Either way it+ # holds stdout.log + stderr.log.log_dir = Path(cwd) / ".processes" / namelog_dir.mkdir(parents=True, exist_ok=True)# Clear old logs if restartingdiff --git a/server/services/temporal/_install.py b/server/services/temporal/_install.pyindex e62029d3..b9216186 100644--- a/server/services/temporal/_install.py+++ b/server/services/temporal/_install.py@@ -4,11 +4,20 @@ Downloads the official ``temporal`` CLI from the URL documented athttps://docs.temporal.io/develop/python/set-up-your-local-python(``temporal.download/cli/archive/latest?platform=<os>&arch=<arch>``).-Pooch handles XDG-aware cross-platform caching and archive extraction-(zip on Windows, tar.gz elsewhere). The ``latest`` URL rotates as new-CLI versions ship, so the download is unverified (TLS gives transport-integrity); pooch caches by local filename, not URL contents, so-re-runs after the first fetch are instant cache hits.+The binary lands at ``<DATA_DIR>/packages/temporal/`` — the same root+that holds the Stripe and agent-browser binaries (see+:func:`core.paths.package_dir`). Pre-fix this used+``pooch.os_cache("machinaos-temporal")`` which landed the binary+under a separate ``%LOCALAPPDATA%\\machinaos-temporal\\Cache\\``+(Windows) / ``~/.cache/machinaos-temporal/`` (Linux) tree outside+the operator-visible ``~/.machina/`` root.++Pooch still drives archive extraction (zip on Windows, tar.gz+elsewhere); we just point its cache at our DATA_DIR-rooted package+dir. The ``latest`` URL rotates as new CLI versions ship, so the+download is unverified (TLS gives transport integrity); pooch caches+by local filename, not URL contents, so re-runs after the first+fetch are instant cache hits.The downloaded ``temporal`` CLI powers ``temporal server start-dev``(the SQLite/in-memory dev server) and ad-hoc workflow / operator@@ -45,9 +54,21 @@ _CLI_PLATFORM_MAP: dict[tuple[str, str], tuple[str, str]] = {("Windows", "ARM64"): ("windows", "arm64"),}-# pooch cache namespace. Pooch's own cache layout includes the asset-# URL so versions don't collide.-_CACHE_NAMESPACE = "machinaos-temporal"+def _cache_dir() -> Path:+ """Per-service install dir under :func:`core.paths.package_dir`.++ Lands at ``<DATA_DIR>/packages/temporal/`` — same root that+ holds ``stripe`` and ``browser`` binaries. Pre-fix this used+ ``pooch.os_cache("machinaos-temporal")`` which landed the binary+ at ``%LOCALAPPDATA%\\machinaos-temporal\\Cache\\`` (Windows) /+ ``~/.cache/machinaos-temporal/`` (Linux) — outside the+ operator-visible ``~/.machina/`` tree.+ """+ from core.paths import package_dir++ p = package_dir("temporal")+ p.mkdir(parents=True, exist_ok=True)+ return p_cached: dict[str, Path] | None = None@@ -104,7 +125,7 @@ def _fetch_cli_sync() -> Path:extracted = pooch.retrieve(url=url,known_hash=None,- path=pooch.os_cache(_CACHE_NAMESPACE),+ path=_cache_dir(),fname=fname,processor=processor,progressbar=True,