From 7e760e4ecfd75883d81f7c91774c51b28af58a3f Mon Sep 17 00:00:00 2001 From: Tom Softreck Date: Mon, 23 Nov 2026 17:34:43 +0100 Subject: [PATCH] fix(cli,dns): respect --yes in single-service cleanup and avoid non-TTY hangs in fixos dns --fix (ticket-186) --- fixos/cli/cleanup_cmd.py | 10 ++-- fixos/cli/dns_cmd.py | 16 +++++- fixos/plugins/builtin/dns.py | 36 ++++++++++---- project/TICKETS.md | 1 + project/ticket-186/README.md | 19 +++++++ project/ticket-186/intent.json | 82 +++++++++++++++++++++++++++++++ tests/unit/test_cleanup_cmd.py | 28 +++++++++++ tests/unit/test_dns.py | 90 ++++++++++++++++++++++++++++++++++ 8 files changed, 267 insertions(+), 15 deletions(-) create mode 100644 project/ticket-186/README.md create mode 100644 project/ticket-186/intent.json create mode 100644 tests/unit/test_dns.py diff --git a/fixos/cli/cleanup_cmd.py b/fixos/cli/cleanup_cmd.py index 2363f28..bb4bfdc 100644 --- a/fixos/cli/cleanup_cmd.py +++ b/fixos/cli/cleanup_cmd.py @@ -581,7 +581,7 @@ def _single_service_target(service_name: str, scanner) -> dict | None: def _cleanup_single_service( - service_name: str, scanner, json_output: bool, dry_run: bool + service_name: str, scanner, json_output: bool, dry_run: bool, yes: bool = False ) -> None: """Handle cleanup of a single specific service.""" target = _single_service_target(service_name, scanner) @@ -630,7 +630,9 @@ def _cleanup_single_service( ) ) click.echo(f" {target['cleanup_command']}") - if not click.confirm(f"Wykonać ograniczone czyszczenie {target['name']}?"): + if not yes and not click.confirm( + f"Wykonać ograniczone czyszczenie {target['name']}?" + ): click.echo("Anulowano.") return @@ -2460,7 +2462,9 @@ def _dispatch_scanner_route(req: CleanupCliRequest, route: CleanupRouteDecision) if route.action_name == "flatpak": _cleanup_flatpak_detailed(scanner, req.json_output, req.dry_run) else: - _cleanup_single_service(route.action_name, scanner, req.json_output, req.dry_run) + _cleanup_single_service( + route.action_name, scanner, req.json_output, req.dry_run, yes=req.yes + ) else: _run_service_plan_route(req, route, scanner) diff --git a/fixos/cli/dns_cmd.py b/fixos/cli/dns_cmd.py index d9d21b9..79d4ef3 100644 --- a/fixos/cli/dns_cmd.py +++ b/fixos/cli/dns_cmd.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import sys import click @@ -89,9 +90,20 @@ def dns( click.echo(click.style("\nPlan naprawy DNS:", fg="cyan", bold=True)) for item in plan: click.echo(f" - {item['description']}") - should_execute = click.confirm("Wykonać powyższy plan naprawy DNS?", default=True) + if not sys.stdin.isatty(): + click.echo( + click.style( + "Tryb nieinteraktywny wymaga flagi --yes do wykonania naprawy DNS.", + fg="yellow", + ) + ) + should_execute = False + else: + should_execute = click.confirm("Wykonać powyższy plan naprawy DNS?", default=True) if should_execute: - repair_results = apply_dns_repair(plan, dry_run=dry_run) + repair_results = apply_dns_repair( + plan, dry_run=dry_run, non_interactive=yes or not sys.stdin.isatty() + ) if as_json: payload = result.to_dict() diff --git a/fixos/plugins/builtin/dns.py b/fixos/plugins/builtin/dns.py index 12d577b..3abc860 100644 --- a/fixos/plugins/builtin/dns.py +++ b/fixos/plugins/builtin/dns.py @@ -7,6 +7,7 @@ import shutil import socket import subprocess +import sys import time from collections.abc import Sequence from pathlib import Path @@ -276,20 +277,32 @@ def build_repair_plan( return plan +def _with_non_interactive_sudo(cmd: list[str], *, non_interactive: bool) -> list[str]: + """Add ``-n`` to ``sudo`` invocations in non-interactive mode so sudo fails fast.""" + if non_interactive and cmd and cmd[0] == "sudo" and "-n" not in cmd[1:3]: + return ["sudo", "-n", *cmd[1:]] + return list(cmd) + + def apply_dns_repair( - plan: Sequence[dict[str, Any]], dry_run: bool = False + plan: Sequence[dict[str, Any]], + dry_run: bool = False, + *, + non_interactive: bool | None = None, ) -> list[dict[str, Any]]: """Execute or simulate a DNS repair plan built by ``build_repair_plan``.""" + is_non_interactive = (not sys.stdin.isatty()) if non_interactive is None else bool(non_interactive) results: list[dict[str, Any]] = [] for item in plan: step = str(item.get("step", "unknown")) - cmd = [str(part) for part in item.get("command", [])] + raw_cmd = [str(part) for part in item.get("command", [])] + cmd = _with_non_interactive_sudo(raw_cmd, non_interactive=is_non_interactive) if dry_run: results.append( { "step": step, "description": item.get("description", ""), - "command": " ".join(cmd), + "command": " ".join(raw_cmd), "ok": True, "dry_run": True, "output": "dry-run", @@ -311,9 +324,12 @@ def apply_dns_repair( } ) continue + tee_cmd = _with_non_interactive_sudo( + ["sudo", "tee", str(item["path"])], non_interactive=is_non_interactive + ) try: proc = subprocess.run( - ["sudo", "tee", str(item["path"])], + tee_cmd, input=str(item["content"]), capture_output=True, text=True, @@ -329,7 +345,7 @@ def apply_dns_repair( { "step": step, "description": item.get("description", ""), - "command": f"sudo tee {item['path']}", + "command": " ".join(tee_cmd), "ok": ok, "dry_run": False, "output": output, @@ -388,7 +404,7 @@ def diagnose(self) -> DiagnosticResult: f"Plik {self.resolv_conf_path} nie zawiera żadnego wpisu nameserver." ), suggestion="Uruchom deterministyczną naprawę DNS przez `fixos dns --fix`.", - command="fixos dns --fix", + command="fixos dns --fix --yes", ) ) @@ -408,7 +424,7 @@ def diagnose(self) -> DiagnosticResult: "Dodaj niezawodne serwery DNS (1.1.1.1, 8.8.8.8) z zachowaniem " "lokalnej domeny przez `fixos dns --fix`." ), - command="fixos dns --fix", + command="fixos dns --fix --yes", data={"total_timeouts": total_timeouts}, ) ) @@ -448,7 +464,7 @@ def diagnose(self) -> DiagnosticResult: "Skonfiguruj 1.1.1.1 i 8.8.8.8 przed DNS routera, zachowując " "rozwiązywanie domeny lokalnej: `fixos dns --fix`." ), - command="fixos dns --fix", + command="fixos dns --fix --yes", data={"devices": [link["device"] for link in router_only_links]}, ) ) @@ -463,7 +479,7 @@ def diagnose(self) -> DiagnosticResult: severity=Severity.CRITICAL, description=f"Błąd rozwiązywania nazwy {probe['host']}: {probe['error']}", suggestion="Uruchom `fixos dns --fix` aby odświeżyć i naprawić konfigurację DNS.", - command="fixos dns --fix", + command="fixos dns --fix --yes", data=probe, ) ) @@ -480,7 +496,7 @@ def diagnose(self) -> DiagnosticResult: f"(próg ostrzeżenia: {LATENCY_WARNING_MS:.0f} ms)." ), suggestion="Przełącz DNS na 1.1.1.1 / 8.8.8.8 przez `fixos dns --fix`.", - command="fixos dns --fix", + command="fixos dns --fix --yes", data=probe, ) ) diff --git a/project/TICKETS.md b/project/TICKETS.md index bff0dc4..292a879 100644 --- a/project/TICKETS.md +++ b/project/TICKETS.md @@ -181,4 +181,5 @@ This file indexes governance tickets without taking ownership of | **ticket-183** | [`README.md`](./ticket-183/README.md) | - | - | - | - | - | | **ticket-184** | [`README.md`](./ticket-184/README.md) | - | - | - | - | - | | **ticket-185** | [`README.md`](./ticket-185/README.md) | - | - | - | - | - | +| **ticket-186** | [`README.md`](./ticket-186/README.md) | - | - | - | - | - | diff --git a/project/ticket-186/README.md b/project/ticket-186/README.md new file mode 100644 index 0000000..75e9d34 --- /dev/null +++ b/project/ticket-186/README.md @@ -0,0 +1,19 @@ +# Ticket 186: Fix non-interactive --yes handling in cleanup_cmd and dns_cmd/dns plugin + +- **ID**: ticket-186 +- **Owner**: agent:antigravity (SESSION_EXECUTION_AUTHORIZATION from user request) +- **Status**: IN_PROGRESS +- **Workflow state**: EDIT +- **Created**: 2026-11-23 + +## Goal and scope + +Fix two live non-interactive hangs observed during autonomous `fixos` execution: +1. Pass `yes=req.yes` to `_cleanup_single_service` in `fixos/cli/cleanup_cmd.py` so `fixos cleanup -c docker --yes` skips `click.confirm(...)`. +2. Guard `fixos dns --fix` against hanging in non-TTY / `fixos auto --yes` mode by refusing interactive `click.confirm` without `--yes`, injecting `sudo -n` in `apply_dns_repair` when non-interactive, and emitting `fixos dns --fix --yes` from `fixos/plugins/builtin/dns.py`. + +## Acceptance criteria + +- [x] AC-01: `fixos cleanup -c docker --yes` executes without prompting `click.confirm`. +- [x] AC-02: `fixos dns --fix` in non-TTY without `--yes` fails fast without blocking, and `apply_dns_repair(..., non_interactive=True)` uses `sudo -n`. +- [x] AC-03: Unit tests in `tests/unit/test_cleanup_cmd.py`, `tests/unit/test_dns.py`, and `tests/unit/test_dns_plugin.py` pass alongside `./project/governance-check.sh`. diff --git a/project/ticket-186/intent.json b/project/ticket-186/intent.json new file mode 100644 index 0000000..b978961 --- /dev/null +++ b/project/ticket-186/intent.json @@ -0,0 +1,82 @@ +{ + "schema": "new-project.intent/v3", + "ticket": "ticket-186", + "summary": "Fix non-interactive --yes handling in cleanup_cmd and dns_cmd/dns plugin", + "workstream": "application", + "classification": { + "kind": "BUG", + "priority": "P1", + "origin": "regression" + }, + "allowedPaths": [ + "project/ticket-186/**", + "TODO.md", + "project/TICKETS.md", + "fixos/cli/cleanup_cmd.py", + "fixos/cli/dns_cmd.py", + "fixos/plugins/builtin/dns.py", + "tests/unit/test_cleanup_cmd.py", + "tests/unit/test_dns.py" + ], + "forbiddenPaths": [ + "project/ticket-*/user-*.md" + ], + "stacks": [], + "dependsOn": [], + "conflictsWith": [], + "integrationTicket": null, + "delivery": { + "targetBranch": "main", + "acceptedBaseSha": "510fb86517ba9fd39020268249a72613b34c99cd", + "outcome": "Prevent non-interactive hangs in fixos cleanup -c docker --yes and fixos dns --fix when executed by fixos auto or systemd.", + "complexity": "S", + "estimatedMinutes": 20, + "budgets": { + "maxImplementationFiles": 5, + "maxAffectedComponents": 2, + "maxPublicInterfaceChanges": 1, + "maxRuntimeDependencies": 0 + }, + "runtimeDependencies": [], + "nonGoals": [ + "Changing fixos/cli/fix_cmd.py or altering interactive prompts when running on a TTY without --yes." + ], + "architecture": { + "status": "accepted", + "decision": "Forward req.yes to _cleanup_single_service in cleanup_cmd.py, guard click.confirm on sys.stdin.isatty() in dns_cmd.py, and inject sudo -n in apply_dns_repair when non_interactive is true.", + "components": [ + { + "name": "non-interactive cleanup and dns execution", + "paths": [ + "fixos/cli/cleanup_cmd.py", + "fixos/cli/dns_cmd.py", + "fixos/plugins/builtin/dns.py", + "tests/unit/test_cleanup_cmd.py", + "tests/unit/test_dns.py" + ] + } + ], + "responsibilityChanges": false, + "interfaceChanges": [ + "Add optional yes=False to _cleanup_single_service and non_interactive=None to apply_dns_repair" + ], + "dataChanges": [], + "ui": { + "impact": "none", + "states": [], + "evidence": [] + }, + "rollback": "Revert the commit touching cleanup_cmd.py, dns_cmd.py, and dns.py." + }, + "validation": [ + { + "criterion": "AC-01", + "commands": [ + "python -m pytest -q tests/unit/test_cleanup_cmd.py tests/unit/test_dns.py tests/unit/test_dns_plugin.py", + "./project/governance-check.sh" + ], + "evidence": "All cleanup_cmd and DNS unit tests pass and governance-check passes." + } + ] + } +} diff --git a/tests/unit/test_cleanup_cmd.py b/tests/unit/test_cleanup_cmd.py index d08d8fc..c5264c8 100644 --- a/tests/unit/test_cleanup_cmd.py +++ b/tests/unit/test_cleanup_cmd.py @@ -799,6 +799,34 @@ def cleanup(self, **kwargs): assert "brak zmian w Dockerze i procesach" in result.output +def test_single_service_cleanup_respects_yes_for_dangerous_service(monkeypatch): + cleaned = [] + + class FakeScanner: + def cleanup_service(self, service_name, *, dry_run=False, planned_service=None): + cleaned.append((service_name, dry_run)) + return {"success": True, "space_freed_gb": 0.0, "output": "ok"} + + monkeypatch.setattr( + cleanup_cmd, + "_single_service_target", + lambda _name, _scanner: { + "name": "Docker", + "can_cleanup": True, + "risk_level": "dangerous", + "cleanup_command": "docker builder prune --force --filter until=168h", + }, + ) + monkeypatch.setattr( + cleanup_cmd.click, + "confirm", + lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("must not prompt when yes=True")), + ) + + cleanup_cmd._cleanup_single_service("docker", FakeScanner(), json_output=False, dry_run=False, yes=True) + assert cleaned == [("docker", False)] + + def test_orphaned_projects_applies_only_exact_selected_identities(monkeypatch): captured = {} diff --git a/tests/unit/test_dns.py b/tests/unit/test_dns.py new file mode 100644 index 0000000..8f90d6c --- /dev/null +++ b/tests/unit/test_dns.py @@ -0,0 +1,90 @@ +"""Unit tests for non-interactive DNS CLI and sudo -n safety in fixos dns.""" + +from __future__ import annotations + +import subprocess +from types import SimpleNamespace + +from click.testing import CliRunner + +from fixos.cli import dns_cmd +from fixos.plugins.builtin import dns as dns_plugin + + +def test_apply_dns_repair_uses_sudo_n_in_non_interactive_mode(monkeypatch): + seen_cmds: list[list[str]] = [] + + def _fake_run_text(cmd: list[str], timeout: int = 10): + seen_cmds.append(list(cmd)) + return True, "ok", "" + + def _fake_subprocess_run(cmd, **_kwargs): + seen_cmds.append(list(cmd)) + return subprocess.CompletedProcess(cmd, 0, stdout="ok", stderr="") + + monkeypatch.setattr(dns_plugin, "_run_text_command", _fake_run_text) + monkeypatch.setattr(dns_plugin.subprocess, "run", _fake_subprocess_run) + + plan = [ + { + "step": "write_resolved_dropin", + "description": "Write drop-in", + "command": ["sudo", "mkdir", "-p", "/etc/systemd/resolved.conf.d"], + "path": "/etc/systemd/resolved.conf.d/90-fixos.conf", + "content": "[Resolve]\nDNS=1.1.1.1\n", + }, + { + "step": "restart_resolved", + "description": "Restart systemd-resolved", + "command": ["sudo", "systemctl", "restart", "systemd-resolved"], + }, + ] + + results = dns_plugin.apply_dns_repair(plan, dry_run=False, non_interactive=True) + assert len(results) == 2 + assert all(r["ok"] for r in results) + assert seen_cmds[0][:2] == ["sudo", "-n"] + assert seen_cmds[1][:3] == ["sudo", "-n", "tee"] + assert seen_cmds[2][:2] == ["sudo", "-n"] + + +def test_dns_cli_non_tty_without_yes_does_not_prompt_or_apply(monkeypatch): + called_apply = [] + + class _FakePlugin: + def __init__(self, **_kwargs): + pass + + def diagnose(self): + from fixos.plugins.base import DiagnosticResult, Severity + + return DiagnosticResult( + plugin_name="dns", + status=Severity.WARNING, + findings=[], + raw_data={"status": {}, "nm_connections": {}}, + duration_ms=1.0, + ) + + monkeypatch.setattr(dns_plugin, "Plugin", _FakePlugin) + monkeypatch.setattr( + dns_plugin, + "build_repair_plan", + lambda **_k: [{"step": "restart", "description": "Restart", "command": ["sudo", "true"]}], + ) + monkeypatch.setattr( + dns_plugin, + "apply_dns_repair", + lambda *a, **k: called_apply.append((a, k)) or [], + ) + monkeypatch.setattr( + dns_cmd.click, + "confirm", + lambda *_a, **_k: (_ for _ in ()).throw(AssertionError("must not prompt in non-TTY")), + ) + monkeypatch.setattr(dns_cmd, "sys", SimpleNamespace(stdin=SimpleNamespace(isatty=lambda: False))) + + res = CliRunner().invoke(dns_cmd.dns, ["--fix"]) + assert res.exit_code == 0, res.output + assert "wymaga flagi --yes" in res.output + assert called_apply == []