"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/
Python
fix(joplin): fix benign-warning masking, backend config precedence, and nested session save path handling
27494539a-hub19840276622d
diff --git a/joplin/agent-harness/cli_anything/joplin/core/session.py b/joplin/agent-harness/cli_anything/joplin/core/session.pyindex bf1b5b217..0d6ce9044 100644--- a/joplin/agent-harness/cli_anything/joplin/core/session.py+++ b/joplin/agent-harness/cli_anything/joplin/core/session.py@@ -78,6 +78,14 @@ class Session:}def _locked_save_json(self, path: str, data: dict) -> None:+ # Ensure the parent directory exists before touching the lock or tmp+ # files. `project save nested/sub/file.json` (or any first save to a+ # not-yet-created directory) would otherwise fail with FileNotFoundError+ # at the lock open, before the data write even gets a chance to run.+ parent = os.path.dirname(os.path.abspath(path))+ if parent:+ os.makedirs(parent, exist_ok=True)+lock_path = f"{path}.lock"lock_fd = os.open(lock_path, os.O_CREAT | os.O_RDWR)try:diff --git a/joplin/agent-harness/cli_anything/joplin/joplin_cli.py b/joplin/agent-harness/cli_anything/joplin/joplin_cli.pyindex 2f46c4181..4175dbee7 100644--- a/joplin/agent-harness/cli_anything/joplin/joplin_cli.py+++ b/joplin/agent-harness/cli_anything/joplin/joplin_cli.py@@ -88,19 +88,37 @@ def handle_error(func):return wrapper-def _backend_config(binary: str, profile: Optional[str]) -> BackendConfig:+def _backend_config(binary: Optional[str], profile: Optional[str]) -> BackendConfig:+ """Resolve the backend config for the current command.++ Resolution precedence:+ 1. Explicit CLI flags (`--binary`, `--profile`) when the user passed them.+ 2. Values persisted in the loaded harness project's `backend` section.+ 3. Built-in defaults (`joplin` binary, no profile).++ The CLI options use sentinel `None` defaults so we can distinguish "user+ omitted the flag" from "user explicitly passed --binary joplin"; passing+ the default would otherwise silently override the project's saved binary.+ """sess = get_session()if sess.has_project():proj = sess.get_project()- backend = proj.get("backend", {})- return BackendConfig(binary=binary or backend.get("binary", "joplin"), profile=profile if profile is not None else backend.get("profile"))- return BackendConfig(binary=binary, profile=profile)+ backend = proj.get("backend", {}) or {}+ resolved_binary = binary if binary is not None else backend.get("binary") or "joplin"+ resolved_profile = profile if profile is not None else backend.get("profile")+ return BackendConfig(binary=resolved_binary, profile=resolved_profile)+ return BackendConfig(binary=binary or "joplin", profile=profile)@click.group(invoke_without_command=True)@click.option("--json", "use_json", is_flag=True, help="Output as JSON")@click.option("--project", "project_path", type=str, default=None, help="Harness project JSON path")[email protected]("--binary", type=str, default="joplin", help="Joplin CLI binary name/path")+ "--binary",+ type=str,+ default=None,+ help="Joplin CLI binary name/path (defaults to the project's saved binary or 'joplin')",+)@click.option("--profile", type=str, default=None, help="Joplin profile path")@click.option("--dry-run", "dry_run", is_flag=True, default=False, help="Run command without saving harness project")@click.pass_context@@ -150,7 +168,11 @@ def project():@click.pass_context@handle_errordef project_new(ctx, name, output_path):- proj = project_mod.create_project(name=name, backend_binary=ctx.obj["binary"], backend_profile=ctx.obj["profile"])+ proj = project_mod.create_project(+ name=name,+ backend_binary=ctx.obj["binary"] or "joplin",+ backend_profile=ctx.obj["profile"],+ )sess = get_session()sess.set_project(proj, output_path)if output_path:diff --git a/joplin/agent-harness/cli_anything/joplin/tests/test_core.py b/joplin/agent-harness/cli_anything/joplin/tests/test_core.pyindex 3f8fb2518..8550bc9ad 100644--- a/joplin/agent-harness/cli_anything/joplin/tests/test_core.py+++ b/joplin/agent-harness/cli_anything/joplin/tests/test_core.py@@ -180,6 +180,17 @@ def test_session_save_with_path(tmp_path):assert os.path.exists(saved)+def test_session_save_creates_missing_parent_directories(tmp_path):+ """Regression: saving to a not-yet-created nested path must not fail at+ the lock open before the data write runs."""+ sess = Session()+ nested = tmp_path / "deep" / "subdir" / "newly_created.json"+ sess.set_project(project_mod.create_project(name="nested"), str(nested))+ saved = sess.save_session()+ assert os.path.exists(saved)+ assert nested.parent.is_dir()++def test_session_set_project_clears_undo_redo():sess = Session()sess.set_project(project_mod.create_project(name="a"))@@ -295,6 +306,47 @@ def test_backend_run_command_node_warning_passes(monkeypatch):cfg = joplin_backend.BackendConfig(binary="joplin", profile=None)result = joplin_backend.run_joplin_command(["ls"], cfg)assert result["returncode"] == 1+ # Stripped stdout/stderr should be empty so JSON callers don't see warning lines.+ assert result["stdout"] == ""+ assert result["stderr"] == ""+++def test_backend_run_command_real_error_alongside_warning_raises(monkeypatch):+ """Regression: a real Joplin error must surface even when stderr also+ contains the benign DEP0040 punycode deprecation warning."""++ class Proc:+ returncode = 1+ stdout = ""+ stderr = (+ "(node:1234) [DEP0040] DeprecationWarning: The `punycode` module is deprecated.\n"+ "Error: Cannot find \"missing-note\"."+ )++ monkeypatch.setattr(joplin_backend, "find_joplin", lambda _: "joplin")+ monkeypatch.setattr(joplin_backend.subprocess, "run", lambda *a, **k: Proc())+ cfg = joplin_backend.BackendConfig(binary="joplin", profile=None)+ with pytest.raises(RuntimeError) as excinfo:+ joplin_backend.run_joplin_command(["cat", "missing-note"], cfg)+ assert "Cannot find" in str(excinfo.value)+ # The benign warning line should be stripped from the surfaced error text.+ assert "DEP0040" not in str(excinfo.value)+++def test_backend_run_command_strips_warning_from_stdout(monkeypatch):+ class Proc:+ returncode = 0+ stdout = (+ "(node:7) [DEP0040] DeprecationWarning: The `punycode` module is deprecated.\n"+ "[{\"title\":\"NoteA\"}]"+ )+ stderr = ""++ monkeypatch.setattr(joplin_backend, "find_joplin", lambda _: "joplin")+ monkeypatch.setattr(joplin_backend.subprocess, "run", lambda *a, **k: Proc())+ cfg = joplin_backend.BackendConfig(binary="joplin", profile=None)+ result = joplin_backend.run_joplin_command(["ls", "--format", "json"], cfg)+ assert result["stdout"] == "[{\"title\":\"NoteA\"}]"def test_backend_run_command_timeout(monkeypatch):@@ -565,6 +617,70 @@ def test_sync_import_config_and_backend_args(monkeypatch):assert captured[6] == ["e2ee", "decrypt-file", "encrypted.bin", "--output", "out"]+# ---------------------------------------------------------------------------+# Backend config resolution precedence+# ---------------------------------------------------------------------------+++def test_backend_config_without_project_uses_defaults():+ joplin_cli._session = None+ cfg = joplin_cli._backend_config(None, None)+ assert cfg.binary == "joplin"+ assert cfg.profile is None+++def test_backend_config_without_project_respects_cli_overrides():+ joplin_cli._session = None+ cfg = joplin_cli._backend_config("/custom/joplin", "/tmp/prof")+ assert cfg.binary == "/custom/joplin"+ assert cfg.profile == "/tmp/prof"+++def test_backend_config_uses_project_backend_when_cli_omitted():+ """Regression: a project that persisted a custom backend binary and+ profile must keep using them when the user does not pass --binary /+ --profile explicitly."""+ joplin_cli._session = None+ sess = joplin_cli.get_session()+ proj = project_mod.create_project(+ name="custom",+ backend_binary="/opt/joplin-custom",+ backend_profile="/var/joplin-profile",+ )+ sess.set_project(proj)++ cfg = joplin_cli._backend_config(None, None)+ assert cfg.binary == "/opt/joplin-custom"+ assert cfg.profile == "/var/joplin-profile"+++def test_backend_config_cli_overrides_beat_project_values():+ joplin_cli._session = None+ sess = joplin_cli.get_session()+ proj = project_mod.create_project(+ name="overridable",+ backend_binary="/opt/joplin-custom",+ backend_profile="/var/joplin-profile",+ )+ sess.set_project(proj)++ cfg = joplin_cli._backend_config("/usr/local/bin/joplin", "/tmp/other")+ assert cfg.binary == "/usr/local/bin/joplin"+ assert cfg.profile == "/tmp/other"+++def test_backend_config_falls_back_to_default_binary_when_project_missing_backend():+ joplin_cli._session = None+ sess = joplin_cli.get_session()+ proj = project_mod.create_project(name="empty")+ proj["backend"] = {}+ sess.set_project(proj)++ cfg = joplin_cli._backend_config(None, None)+ assert cfg.binary == "joplin"+ assert cfg.profile is None++# ---------------------------------------------------------------------------# JSON envelope shape# ---------------------------------------------------------------------------diff --git a/joplin/agent-harness/cli_anything/joplin/utils/joplin_backend.py b/joplin/agent-harness/cli_anything/joplin/utils/joplin_backend.pyindex 51165d021..983f906a8 100644--- a/joplin/agent-harness/cli_anything/joplin/utils/joplin_backend.py+++ b/joplin/agent-harness/cli_anything/joplin/utils/joplin_backend.py@@ -20,9 +20,38 @@ def find_joplin(binary: str = "joplin") -> str:)-def _is_benign_node_warning(stderr: str, stdout: str = "") -> bool:- text = f"{stderr}\n{stdout}".strip().lower()- return bool(text) and "dep0040" in text and "punycode" in text+_BENIGN_NODE_WARNING_MARKERS = (+ ("dep0040", "punycode"),+ ("dep0169", "url.parse"),+)+++def _line_is_benign_node_warning(line: str) -> bool:+ """Return True for Node.js deprecation warnings that Joplin emits on stderr.++ These warnings are emitted on every invocation by Node 20+ when Joplin's+ dependencies still use the deprecated builtin modules. They never indicate+ a real Joplin failure, but they are noisy on stderr.+ """+ lowered = line.lower()+ if "deprecationwarning" not in lowered and "experimentalwarning" not in lowered:+ return False+ return any(all(marker in lowered for marker in markers) for markers in _BENIGN_NODE_WARNING_MARKERS)+++def _strip_benign_node_warnings(text: str) -> str:+ """Drop benign Node warning lines while preserving any real diagnostic text."""+ if not text:+ return ""+ kept = []+ for raw_line in text.splitlines():+ line = raw_line.strip()+ if not line:+ continue+ if _line_is_benign_node_warning(line):+ continue+ kept.append(raw_line)+ return "\n".join(kept).strip()def run_joplin_command(args: list[str], config: BackendConfig, timeout: int = 120) -> dict:@@ -43,8 +72,11 @@ def run_joplin_command(args: list[str], config: BackendConfig, timeout: int = 12except subprocess.TimeoutExpired as e:raise RuntimeError(f"Joplin command timed out after {timeout}s") from e- stdout = (proc.stdout or "").strip()- stderr = (proc.stderr or "").strip()+ stdout_raw = proc.stdout or ""+ stderr_raw = proc.stderr or ""+ stdout = _strip_benign_node_warnings(stdout_raw)+ stderr = _strip_benign_node_warnings(stderr_raw)+result = {"command": cmd,"returncode": proc.returncode,@@ -52,8 +84,12 @@ def run_joplin_command(args: list[str], config: BackendConfig, timeout: int = 12"stderr": stderr,}- if proc.returncode != 0 and not _is_benign_node_warning(stderr, stdout):- raise RuntimeError(stderr or stdout or "Joplin command failed")+ if proc.returncode != 0:+ # After stripping known-benign Node warnings, anything left on stderr or+ # stdout is a real Joplin error and must surface as a failure. We only+ # treat the exit as success when there is no remaining diagnostic text.+ if stderr or stdout:+ raise RuntimeError(stderr or stdout)return result