Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(machina): Phase D.1 -- migrate `version:sync` and `docs:nodes[:check]`
trohitg55dc8c0fd578
diff --git a/machina/cli.py b/machina/cli.pyindex f13131d8..771de8e3 100644--- a/machina/cli.py+++ b/machina/cli.py@@ -11,8 +11,10 @@ import typerfrom machina.commands.build import build_commandfrom machina.commands.clean import clean_commandfrom machina.commands.dev import dev_command+from machina.commands.docs import app as docs_appfrom machina.commands.start import start_commandfrom machina.commands.stop import stop_command+from machina.commands.version import app as version_appapp = typer.Typer(@@ -43,6 +45,8 @@ app.command("clean", help="Stop services then remove build artefacts and venvs."app.command("build", help="Install toolchain + build client + sync Python + verify deps.")(build_command)+app.add_typer(version_app, name="version")+app.add_typer(docs_app, name="docs")if __name__ == "__main__":diff --git a/machina/commands/docs.py b/machina/commands/docs.pynew file mode 100644index 00000000..36e59b29--- /dev/null+++ b/machina/commands/docs.py@@ -0,0 +1,154 @@+"""``machina docs nodes`` -- replaces ``scripts/build-node-docs-index.js``.++Walks ``docs-internal/node-logic-flows/<category>/<node>.md``, scrapes+each doc's first H1, and rewrites the AUTO-GENERATED-INDEX block in+``docs-internal/node-logic-flows/README.md``. With ``--check`` instead+of rewriting, cross-references against the plugin tree under+``server/nodes/`` and exits non-zero if any registered node lacks a+doc.+"""++from __future__ import annotations++import re+from pathlib import Path++import typer++from machina.colors import console+from machina.platform_ import project_root+++app = typer.Typer(+ name="docs",+ help="Documentation-tooling subcommands.",+ no_args_is_help=True,+ add_completion=False,+)+++_START = "<!-- AUTO-GENERATED-INDEX-START -->"+_END = "<!-- AUTO-GENERATED-INDEX-END -->"+_H1 = re.compile(r"^#\s+(.+)$", re.MULTILINE)+# Mirror the existing JS regex: `` type[: str] = "<nodeType>"`` at+# class-attribute indentation.+_TYPE_ATTR = re.compile(+ r"^\s{4}type\s*(?::\s*str\s*)?=\s*['\"]([A-Za-z_][\w]*)['\"]",+ re.MULTILINE,+)+++def _docs_dir(root: Path) -> Path:+ return root / "docs-internal" / "node-logic-flows"+++def _read_h1(path: Path) -> str:+ text = path.read_text(encoding="utf-8")+ match = _H1.search(text)+ return match.group(1).strip() if match else path.stem+++def _list_categories(docs_dir: Path) -> list[str]:+ if not docs_dir.exists():+ return []+ return sorted(+ d.name for d in docs_dir.iterdir()+ if d.is_dir() and not d.name.startswith("_")+ )+++def _list_docs(docs_dir: Path, category: str) -> list[dict]:+ cat_dir = docs_dir / category+ out: list[dict] = []+ for path in sorted(cat_dir.iterdir()):+ if path.suffix != ".md":+ continue+ if path.name.startswith("_") or path.name == "README.md":+ continue+ out.append({+ "rel_path": f"{category}/{path.name}",+ "title": _read_h1(path),+ "node_key": path.stem,+ })+ return out+++def _build_index_block(docs_dir: Path) -> str:+ lines = [_START]+ for cat in _list_categories(docs_dir):+ docs = _list_docs(docs_dir, cat)+ if not docs:+ continue+ lines.extend(["", f"### {cat}", ""])+ for doc in docs:+ lines.append(f"- [{doc['title']}](./{doc['rel_path']})")+ lines.extend(["", _END])+ return "\n".join(lines)+++def _collect_documented_keys(docs_dir: Path) -> set[str]:+ return {+ doc["node_key"]+ for cat in _list_categories(docs_dir)+ for doc in _list_docs(docs_dir, cat)+ }+++def _collect_registry_keys(plugins_dir: Path) -> set[str]:+ """Scrape ``type = "<nodeType>"`` from every plugin file."""+ keys: set[str] = set()+ if not plugins_dir.exists():+ return keys+ for path in plugins_dir.rglob("*.py"):+ if path.name == "__init__.py" or path.name.startswith("_"):+ continue+ match = _TYPE_ATTR.search(path.read_text(encoding="utf-8"))+ if match:+ keys.add(match.group(1))+ return keys+++def _rewrite_index(root: Path) -> None:+ docs_dir = _docs_dir(root)+ index_file = docs_dir / "README.md"+ original = index_file.read_text(encoding="utf-8")+ block = _build_index_block(docs_dir)+ pattern = re.compile(re.escape(_START) + r".*?" + re.escape(_END), re.DOTALL)+ if not pattern.search(original):+ console.print(+ f"[red]error: {index_file} is missing the AUTO-GENERATED-INDEX markers[/]"+ )+ raise typer.Exit(code=2)+ index_file.write_text(pattern.sub(block, original), encoding="utf-8")+ console.print(f"wrote index to {index_file.relative_to(root)}")+++def _check_completeness(root: Path) -> int:+ documented = _collect_documented_keys(_docs_dir(root))+ registered = _collect_registry_keys(root / "server" / "nodes")+ missing = sorted(k for k in registered if k not in documented)+ if not missing:+ console.print(+ f"OK: every registered node has a logic-flow doc ({len(registered)} total)"+ )+ return 0+ console.print(f"[red]MISSING DOCS for {len(missing)}/{len(registered)} nodes:[/]")+ for key in missing:+ console.print(f" - {key}")+ return 1++[email protected]("nodes", help="Rebuild (or --check) the per-node documentation index.")+def nodes(+ check: bool = typer.Option(+ False, "--check",+ help="Instead of rewriting, exit 1 if any registered node lacks a doc.",+ ),+) -> None:+ root = project_root()+ if check:+ rc = _check_completeness(root)+ if rc != 0:+ raise typer.Exit(code=rc)+ else:+ _rewrite_index(root)diff --git a/machina/commands/version.py b/machina/commands/version.pynew file mode 100644index 00000000..90cf602d--- /dev/null+++ b/machina/commands/version.py@@ -0,0 +1,109 @@+"""``machina version sync`` -- replaces ``scripts/sync-version.js``.++Reads the latest git tag (or one supplied on the command line), strips+the ``v`` prefix, and writes the resulting semver into both+``package.json`` files (root + client).+"""++from __future__ import annotations++import json+import re+import subprocess+from pathlib import Path++import typer++from machina.colors import console+from machina.platform_ import project_root+++app = typer.Typer(+ name="version",+ help="Version-management subcommands.",+ no_args_is_help=True,+ add_completion=False,+)+++_VALID_VERSION = re.compile(r"^\d+\.\d+\.\d+")+++def _git_describe(root: Path) -> str | None:+ """``git describe --tags --abbrev=0``; falls back to sorted ``git tag -l``."""+ try:+ out = subprocess.run(+ ["git", "describe", "--tags", "--abbrev=0"],+ cwd=str(root),+ capture_output=True,+ text=True,+ check=True,+ )+ tag = out.stdout.strip()+ if tag:+ return tag+ except (FileNotFoundError, subprocess.CalledProcessError):+ pass+ try:+ out = subprocess.run(+ ["git", "tag", "-l", "--sort=-version:refname"],+ cwd=str(root),+ capture_output=True,+ text=True,+ check=True,+ )+ for line in out.stdout.splitlines():+ tag = line.strip()+ if tag:+ return tag+ except (FileNotFoundError, subprocess.CalledProcessError):+ pass+ return None+++def _tag_to_version(tag: str) -> str:+ return tag.lstrip("v")+++def _update_package_json(path: Path, new_version: str) -> bool:+ pkg = json.loads(path.read_text(encoding="utf-8"))+ old = pkg.get("version")+ if old == new_version:+ console.print(f" {path}: already at {new_version}")+ return False+ pkg["version"] = new_version+ # Match the existing 2-space indent + trailing newline of the JS writer.+ path.write_text(json.dumps(pkg, indent=2) + "\n", encoding="utf-8")+ console.print(f" {path}: {old} -> {new_version}")+ return True++[email protected]("sync", help="Sync package.json versions from latest git tag.")+def sync(tag: str | None = typer.Argument(None, help="Git tag to use (defaults to latest).")) -> None:+ root = project_root()+ resolved_tag = tag or _git_describe(root)+ if not resolved_tag:+ console.print("[red]Error: No git tags found and no tag provided.[/]")+ raise typer.Exit(code=1)++ version = _tag_to_version(resolved_tag)+ if not _VALID_VERSION.match(version):+ console.print(f"[red]Error: Invalid version from tag {resolved_tag!r}: {version!r}[/]")+ console.print("Expected semver format (e.g. v0.0.11 or 0.0.11).")+ raise typer.Exit(code=1)++ console.print(f"Syncing version from tag: {resolved_tag} -> {version}\n")++ updated = 0+ for pkg_path in (root / "package.json", root / "client" / "package.json"):+ try:+ if _update_package_json(pkg_path, version):+ updated += 1+ except (OSError, json.JSONDecodeError) as exc:+ console.print(f"[red] Error updating {pkg_path}: {exc}[/]")++ console.print()+ if updated:+ console.print(f"Updated {updated} file(s). Don't forget to commit the changes.")+ else:+ console.print("All package.json files already at correct version.")diff --git a/machina/tests/test_docs.py b/machina/tests/test_docs.pynew file mode 100644index 00000000..c7b7c4ef--- /dev/null+++ b/machina/tests/test_docs.py@@ -0,0 +1,77 @@+"""Smoke tests for ``machina.commands.docs``."""++from __future__ import annotations++from pathlib import Path++from machina.commands import docs+++def test_read_h1_extracts_first_h1(tmp_path: Path):+ f = tmp_path / "x.md"+ f.write_text("# My Title\n\nbody\n## sub\n", encoding="utf-8")+ assert docs._read_h1(f) == "My Title"+++def test_read_h1_falls_back_to_stem(tmp_path: Path):+ f = tmp_path / "fallback.md"+ f.write_text("no heading here", encoding="utf-8")+ assert docs._read_h1(f) == "fallback"+++def test_list_categories_skips_underscore_and_returns_sorted(tmp_path: Path):+ docs_dir = tmp_path / "docs-internal" / "node-logic-flows"+ (docs_dir / "z_cat").mkdir(parents=True)+ (docs_dir / "a_cat").mkdir()+ (docs_dir / "_skipped").mkdir()+ (docs_dir / "not-a-dir.md").write_text("")+ assert docs._list_categories(docs_dir) == ["a_cat", "z_cat"]+++def test_list_docs_excludes_readme_and_underscore_files(tmp_path: Path):+ docs_dir = tmp_path / "x"+ cat = docs_dir / "cat"+ cat.mkdir(parents=True)+ (cat / "node1.md").write_text("# Node One\n")+ (cat / "_helper.md").write_text("")+ (cat / "README.md").write_text("")+ (cat / "ignore.txt").write_text("")+ out = docs._list_docs(docs_dir, "cat")+ assert [d["node_key"] for d in out] == ["node1"]+ assert out[0]["title"] == "Node One"+++def test_build_index_block_omits_empty_categories(tmp_path: Path):+ docs_dir = tmp_path / "x"+ full = docs_dir / "full"+ full.mkdir(parents=True)+ (full / "node.md").write_text("# Heading\n")+ empty = docs_dir / "empty"+ empty.mkdir()+ block = docs._build_index_block(docs_dir)+ assert "### full" in block+ assert "### empty" not in block+ assert block.startswith(docs._START)+ assert block.endswith(docs._END)+++def test_collect_registry_keys_scrapes_type_attribute(tmp_path: Path):+ plugin = tmp_path / "category" / "node.py"+ plugin.parent.mkdir(parents=True)+ plugin.write_text(+ 'class FooNode:\n'+ ' type: str = "fooNode"\n'+ ' other = "ignored"\n',+ encoding="utf-8",+ )+ keys = docs._collect_registry_keys(tmp_path)+ assert keys == {"fooNode"}+++def test_collect_registry_keys_skips_underscore_and_init(tmp_path: Path):+ cat = tmp_path / "category"+ cat.mkdir(parents=True)+ (cat / "_base.py").write_text(' type = "skipMe"\n')+ (cat / "__init__.py").write_text(' type = "alsoSkip"\n')+ (cat / "good.py").write_text(' type = "goodNode"\n')+ assert docs._collect_registry_keys(tmp_path) == {"goodNode"}diff --git a/machina/tests/test_version.py b/machina/tests/test_version.pynew file mode 100644index 00000000..595254c9--- /dev/null+++ b/machina/tests/test_version.py@@ -0,0 +1,43 @@+"""Smoke tests for ``machina.commands.version``."""++from __future__ import annotations++import json+from pathlib import Path+from unittest.mock import patch++import pytest+import typer++from machina.commands import version+++def test_tag_to_version_strips_v_prefix():+ assert version._tag_to_version("v1.2.3") == "1.2.3"+ assert version._tag_to_version("0.0.11") == "0.0.11"+++def test_update_package_json_writes_new_version(tmp_path: Path):+ pkg = tmp_path / "package.json"+ pkg.write_text(json.dumps({"name": "x", "version": "0.0.1"}, indent=2) + "\n")+ assert version._update_package_json(pkg, "0.0.2") is True+ contents = json.loads(pkg.read_text())+ assert contents["version"] == "0.0.2"+++def test_update_package_json_no_op_when_already_correct(tmp_path: Path):+ pkg = tmp_path / "package.json"+ pkg.write_text(json.dumps({"name": "x", "version": "1.0.0"}) + "\n")+ assert version._update_package_json(pkg, "1.0.0") is False+++def test_update_package_json_preserves_trailing_newline(tmp_path: Path):+ pkg = tmp_path / "package.json"+ pkg.write_text(json.dumps({"name": "x", "version": "0.0.1"}) + "\n")+ version._update_package_json(pkg, "0.0.2")+ assert pkg.read_text(encoding="utf-8").endswith("\n")+++def test_git_describe_returns_none_without_git():+ with patch.object(version.subprocess, "run", side_effect=FileNotFoundError):+ assert version._git_describe(Path(".")) is Nonediff --git a/package.json b/package.jsonindex 0bf1571e..ec12a5d2 100644--- a/package.json+++ b/package.json@@ -77,8 +77,8 @@"test:backend": "cd server && uv run pytest tests/ -v","test:frontend": "cd client && npm run test","test:nodes": "cd server && uv run pytest tests/nodes/ -v --cov=services.handlers --cov-report=term-missing",- "docs:nodes": "node scripts/build-node-docs-index.js",- "docs:nodes:check": "node scripts/build-node-docs-index.js --check",+ "docs:nodes": "python -m machina docs nodes",+ "docs:nodes:check": "python -m machina docs nodes --check","deploy": "bash deploy.sh","deploy:gcp": "bash deploy.sh","daemon:install": "node scripts/daemon.js install",@@ -87,8 +87,8 @@"daemon:start": "node scripts/daemon.js start","daemon:stop": "node scripts/daemon.js stop","daemon:restart": "node scripts/daemon.js restart",- "version:sync": "node scripts/sync-version.js",- "prepublishOnly": "node scripts/sync-version.js && node -e \"const p=require('./package.json'); if(!p.bin||!p.version){process.exit(1)}\"",+ "version:sync": "python -m machina version sync",+ "prepublishOnly": "python -m machina version sync && node -e \"const p=require('./package.json'); if(!p.bin||!p.version){process.exit(1)}\"","preinstall": "node scripts/preinstall.js","postinstall": "node scripts/postinstall.js","preuninstall": "node scripts/preinstall.js"diff --git a/scripts/build-node-docs-index.js b/scripts/build-node-docs-index.jsdeleted file mode 100644index c6184e88..00000000--- a/scripts/build-node-docs-index.js+++ /dev/null@@ -1,153 +0,0 @@-#!/usr/bin/env node-/**- * Build / verify the per-node documentation index.- *- * Usage:- * node scripts/build-node-docs-index.js # rewrite README index- * node scripts/build-node-docs-index.js --check # exit 1 if any registry node is undocumented- *- * Walks `docs-internal/node-logic-flows/<category>/<node>.md`, scrapes the- * first H1 of each doc, and rewrites the AUTO-GENERATED-INDEX block in- * README.md. With --check, also cross-references against- * `server/nodes/` (the plugin tree, post-Wave-11 source of truth) to- * catch missing docs after a new plugin lands. Pre-Wave-11 this- * scraped `client/src/nodeDefinitions/`; that folder is gone.- */--import fs from 'node:fs';-import path from 'node:path';-import { fileURLToPath } from 'node:url';--const __filename = fileURLToPath(import.meta.url);-const __dirname = path.dirname(__filename);--const ROOT = path.resolve(__dirname, '..');-const DOCS_DIR = path.join(ROOT, 'docs-internal', 'node-logic-flows');-const INDEX_FILE = path.join(DOCS_DIR, 'README.md');-// The plugin tree at server/nodes/<category>/<file>.py is the canonical-// list of node types (post-Wave-11). Each plugin class declares-// ``type = "<nodeType>"`` at class scope — we scrape those.-const REGISTRY_GLOB = path.join(ROOT, 'server', 'nodes');--const START_MARKER = '<!-- AUTO-GENERATED-INDEX-START -->';-const END_MARKER = '<!-- AUTO-GENERATED-INDEX-END -->';--function readH1(filePath) {- const content = fs.readFileSync(filePath, 'utf8');- const match = content.match(/^#\s+(.+)$/m);- return match ? match[1].trim() : path.basename(filePath, '.md');-}--function listCategories() {- if (!fs.existsSync(DOCS_DIR)) return [];- return fs- .readdirSync(DOCS_DIR, { withFileTypes: true })- .filter((d) => d.isDirectory() && !d.name.startsWith('_'))- .map((d) => d.name)- .sort();-}--function listDocs(category) {- const dir = path.join(DOCS_DIR, category);- return fs- .readdirSync(dir)- .filter((f) => f.endsWith('.md') && !f.startsWith('_') && f !== 'README.md')- .sort()- .map((f) => ({- file: f,- relPath: path.posix.join(category, f),- title: readH1(path.join(dir, f)),- nodeKey: path.basename(f, '.md'),- }));-}--function buildIndexBlock() {- const cats = listCategories();- const lines = [START_MARKER];- for (const cat of cats) {- const docs = listDocs(cat);- if (docs.length === 0) continue;- lines.push('', `### ${cat}`, '');- for (const doc of docs) {- lines.push(`- [${doc.title}](./${doc.relPath})`);- }- }- lines.push('', END_MARKER);- return lines.join('\n');-}--function rewriteIndex() {- const original = fs.readFileSync(INDEX_FILE, 'utf8');- const block = buildIndexBlock();- const re = new RegExp(`${START_MARKER}[\\s\\S]*?${END_MARKER}`, 'm');- if (!re.test(original)) {- console.error(`error: ${INDEX_FILE} is missing the AUTO-GENERATED-INDEX markers`);- process.exit(2);- }- const next = original.replace(re, block);- fs.writeFileSync(INDEX_FILE, next);- console.log(`wrote index to ${path.relative(ROOT, INDEX_FILE)}`);-}--function collectDocumentedKeys() {- const keys = new Set();- for (const cat of listCategories()) {- for (const doc of listDocs(cat)) {- keys.add(doc.nodeKey);- }- }- return keys;-}--function collectRegistryKeys() {- // Scrape the plugin ``type = "<nodeType>"`` class attribute from every- // Python file under server/nodes/. Skips ``_*.py`` helpers (``_base``,- // ``_credentials``, ``_inline``) and ``__init__.py``. Each plugin class- // declares this once at class scope, so a simple line-anchored regex- // is enough — no full AST parse.- const keys = new Set();- const files = walk(REGISTRY_GLOB).filter(- (f) =>- f.endsWith('.py') &&- !path.basename(f).startsWith('_') &&- path.basename(f) !== '__init__.py',- );- const typeRe = /^\s{4}type\s*(?::\s*str\s*)?=\s*['"]([a-zA-Z_][\w]*)['"]/m;- for (const f of files) {- const text = fs.readFileSync(f, 'utf8');- const m = text.match(typeRe);- if (m) keys.add(m[1]);- }- return keys;-}--function walk(dir) {- if (!fs.existsSync(dir)) return [];- const out = [];- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {- const full = path.join(dir, entry.name);- if (entry.isDirectory()) out.push(...walk(full));- else out.push(full);- }- return out;-}--function checkCompleteness() {- const documented = collectDocumentedKeys();- const registered = collectRegistryKeys();- const missing = [...registered].filter((k) => !documented.has(k)).sort();- if (missing.length === 0) {- console.log(`OK: every registered node has a logic-flow doc (${registered.size} total)`);- return 0;- }- console.error(`MISSING DOCS for ${missing.length}/${registered.size} nodes:`);- for (const k of missing) console.error(` - ${k}`);- return 1;-}--const args = process.argv.slice(2);-if (args.includes('--check')) {- process.exit(checkCompleteness());-} else {- rewriteIndex();-}diff --git a/scripts/sync-version.js b/scripts/sync-version.jsdeleted file mode 100755index 6ba45e01..00000000--- a/scripts/sync-version.js+++ /dev/null@@ -1,108 +0,0 @@-#!/usr/bin/env node-/**- * Syncs package.json version from the latest git tag.- *- * Usage:- * node scripts/sync-version.js # Sync from latest tag- * node scripts/sync-version.js v0.0.11 # Sync from specific tag- *- * This script:- * 1. Gets the latest git tag (or uses provided tag)- * 2. Strips the 'v' prefix to get semver version- * 3. Updates root package.json and client/package.json- */-import { execSync } from 'child_process';-import { readFileSync, writeFileSync } from 'fs';-import { resolve, dirname } from 'path';-import { fileURLToPath } from 'url';--const __dirname = dirname(fileURLToPath(import.meta.url));-const ROOT = resolve(__dirname, '..');--function getLatestTag() {- try {- // Get the latest tag sorted by version- const tag = execSync('git describe --tags --abbrev=0', {- encoding: 'utf-8',- stdio: ['pipe', 'pipe', 'pipe'],- cwd: ROOT- }).trim();- return tag;- } catch {- // Fallback: list tags and get the latest by version sort- try {- const tags = execSync('git tag -l --sort=-version:refname', {- encoding: 'utf-8',- stdio: ['pipe', 'pipe', 'pipe'],- cwd: ROOT- }).trim().split('\n');- return tags[0] || null;- } catch {- return null;- }- }-}--function tagToVersion(tag) {- // Strip 'v' prefix if present: v0.0.11 -> 0.0.11- return tag.replace(/^v/, '');-}--function updatePackageJson(filePath, newVersion) {- const content = readFileSync(filePath, 'utf-8');- const pkg = JSON.parse(content);- const oldVersion = pkg.version;-- if (oldVersion === newVersion) {- console.log(` ${filePath}: already at ${newVersion}`);- return false;- }-- pkg.version = newVersion;- // Preserve formatting (2-space indent)- writeFileSync(filePath, JSON.stringify(pkg, null, 2) + '\n');- console.log(` ${filePath}: ${oldVersion} -> ${newVersion}`);- return true;-}--// Main-const providedTag = process.argv[2];-const tag = providedTag || getLatestTag();--if (!tag) {- console.error('Error: No git tags found and no tag provided.');- console.error('Usage: node scripts/sync-version.js [tag]');- process.exit(1);-}--const version = tagToVersion(tag);--if (!/^\d+\.\d+\.\d+/.test(version)) {- console.error(`Error: Invalid version format from tag "${tag}": "${version}"`);- console.error('Expected semver format like v0.0.11 or 0.0.11');- process.exit(1);-}--console.log(`Syncing version from tag: ${tag} -> ${version}\n`);--const packageFiles = [- resolve(ROOT, 'package.json'),- resolve(ROOT, 'client', 'package.json'),-];--let updated = 0;-for (const file of packageFiles) {- try {- if (updatePackageJson(file, version)) {- updated++;- }- } catch (err) {- console.error(` Error updating ${file}: ${err.message}`);- }-}--if (updated > 0) {- console.log(`\nUpdated ${updated} file(s). Don't forget to commit the changes.`);-} else {- console.log('\nAll package.json files already at correct version.');-}