From 32540955a95d4dbe95b14fe302170aa886b7ac70 Mon Sep 17 00:00:00 2001 From: leather147 <139921639+lumenpearson@users.noreply.github.com> Date: Sun, 29 Nov 2026 00:19:02 +0300 Subject: [PATCH] Let the console retain transport APKs and own local hosts. --- .claude/skills/gates/SKILL.md | 11 +- .github/workflows/ci.yml | 2 +- CLAUDE.md | 2 + HANDOVER.md | 95 +++++- android/app/build.gradle.kts | 26 ++ docs/architecture.md | 8 + docs/build.md | 23 +- .../specs/2026-11-26-build-console-6c-plan.md | 72 ++++ tools/console/README.md | 44 ++- tools/console/lessons_console/app.py | 135 +++++++- tools/console/lessons_console/artifacts.py | 55 +++ .../console/lessons_console/ci_contract.json | 7 +- tools/console/lessons_console/device.py | 17 +- tools/console/lessons_console/environment.py | 2 +- tools/console/lessons_console/host.py | 280 +++++++++++++++ tools/console/lessons_console/locking.py | 17 + tools/console/lessons_console/operations.py | 29 +- tools/console/lessons_console/panels.py | 12 +- tools/console/lessons_console/parity.py | 22 +- tools/console/lessons_console/runner.py | 23 ++ tools/console/lessons_console/tasks.py | 20 +- tools/console/tests/test_console_6c.py | 318 ++++++++++++++++++ tools/console/tests/test_contract.py | 3 +- 23 files changed, 1187 insertions(+), 36 deletions(-) create mode 100644 docs/specs/2026-11-26-build-console-6c-plan.md create mode 100644 tools/console/lessons_console/artifacts.py create mode 100644 tools/console/lessons_console/host.py create mode 100644 tools/console/tests/test_console_6c.py diff --git a/.claude/skills/gates/SKILL.md b/.claude/skills/gates/SKILL.md index f90c380f..9bf2f84c 100644 --- a/.claude/skills/gates/SKILL.md +++ b/.claude/skills/gates/SKILL.md @@ -83,8 +83,15 @@ count check above; «Contract (Buf)» when the contract changed; and «Host», under pyvoy and hypercorn, whenever the server job runs: the host started on SQLite, and `pytest -m host` asking it over native gRPC — tests the ordinary run skips, and which need a Linux runner, the host's lock and a network; and last «CI», which -passes only when every job before it succeeded or was skipped, the one check `main` requires -(#424). Nothing else. +passes only when every job before it succeeded or was skipped, the one check `master` requires +(#424). «Console» is the path-filtered Linux/Windows matrix for the separate +`tools/console/` project. Its locked Ruff and pytest gates cover the console and +its reviewed external CI/build/host inputs; see `.claude/agents/build-ci.md`. + +From `tools/console/`, run `uv run --locked ruff check lessons_console tests` +and `uv run --locked pytest -q`. Console fixtures do not run the Android/server +product gates. A changed Android build script still requires the Android gates +above; a changed server implementation still requires its own gates. ## Updating measured counts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bbdb68bc..a706212a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -116,7 +116,7 @@ jobs: proto/*|buf.yaml|buf.gen.yaml|buf.lock|server/app/contract/*|android/core/data/src/main/contract/*|.github/workflows/*) contract=true ;; esac case "$file" in - tools/console/*|.github/workflows/*|.github/dependabot.yml|docs/build.md|server/app/config.py|server/app/db.py|server/.env.example|android/app/build.gradle.kts|.gitignore) console=true ;; + tools/console/*|.github/workflows/*|.github/dependabot.yml|docs/build.md|server/app/config.py|server/app/db.py|server/app/host.py|server/pyproject.toml|server/requirements-host.txt|requirements.txt|server/.env.example|android/app/build.gradle.kts|.gitignore) console=true ;; esac done <<< "$files" diff --git a/CLAUDE.md b/CLAUDE.md index 75a1a01f..d8c595ce 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -158,6 +158,8 @@ From `tools/console/`, its independent gates are `uv run --locked ruff check les and `uv run --locked pytest -q`; fake processes and a headless pilot require no SDK. See [its README](tools/console/README.md) for preparation, cancellation and scope. +- Serialize Host startup with queued/running preparation or generation, and guard the post-queue/prelaunch boundary too (`test_console_6c.py`, #784). + CI (`.github/workflows/ci.yml`) is: ruff, mypy, pytest (`-n auto`), `./gradlew test`, both assembles, and `./gradlew detekt` after them; and, when `proto/`, `buf.*` or `server/app/contract/` changed, the «Contract» job: `buf lint`, `buf breaking` against the base, diff --git a/HANDOVER.md b/HANDOVER.md index cdca91ad..6b1ac606 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -43,7 +43,100 @@ The original 6a local/first-CI notes below are historical, superseded by these delivery receipts. 5c #770 and standalone store #777 proceed independently; their written code does not establish runtime acceptance or permit v1 retirement. -**26 November 2026 — Console 6a (#771) and programme continuation.** +**29 November 2026 — Console 6c local gates passed; publication next.** +The one admitted Android controller completed all eight serial steps, without a +retry. Actual signing presence states, configuration-cache reuse and invalidation +after moving a synthetic keystore file all passed. The complete REST/non-streaming +`test assembleDebug assembleRelease` command passed in 15m12s: 341 tasks, +271 executed and 70 from cache. Separate Detekt passed in 28s with five executed +tasks; completed reports validate 2202 unique cases in five modules. All 1520 +frozen Android inputs still matched after execution. The existing console result +remains 57 passed/locked Ruff green, with one independent review and bounded +correction readback; no extra product-suite repeat was needed. + +Own process identities and completed-report hashes were retained. The coordinator +independently qualified the outcome and actually released the SDK slot, with zero +pending operations. The former commit block in the dated preparation notes below +is superseded. Publication uses the coordinated `work/console-6c` working ref from +dev `438ea369…`; Main's 5c/Room candidates stay detached and unchanged. Existing +Dependabot #768 and its dependency ref remain with their owner; do not fold its +different dependency pins into this accepted candidate. + +The actual ordinary debug/release APKs and AGP metadata were retained through the +console snapshot function and independently re-read with matching identities and +hashes. This was file processing only, with no SDK tool or device call. It proves +artifact retention, not cryptographic production signing, installation or runtime +transport acceptance. Live Host, device/Home-reopen, exact-head/dev/master CI, +production and Project acceptance remain separate. Root holds #783 until 6a's +missing runtime observation is accepted; do not move persistent dev/master yet. + +**28 November 2026 — Production runtime observation remains incomplete.** +Master `3ffcc33c…` and dev `438ea369…` were freshly re-read unchanged; promotion +#783 is still open and unmerged. The prior read-only v3 observation qualified +the exact source and all four alias bindings, then passed all eight health/warmup +GETs with the reviewed same-response-body decoder. Preserve their actual +26 November timestamps; they do not prove continuously current health. + +The first runtime-count response was not recognized. Its second query was not +executed. The coordinator independently qualified the sanitized partial and +actually released that consumed pass on 28 November. A separate runtime-only v4 +pass freshly requalified the five source/alias metadata reads, repeated no GETs +and made no write. Its first query likewise returned an unsupported formatted +text response; no zero-error count is inferred, and no second query ran. +That pass is also actually released with pending operations zero. Do not launch +another live request to guess the format. Resume runtime only from a confirmed +response contract or suitable structured counter; #783 remains separate until +6a production is accepted. All failed projections and original requests remain. + +Console 6c's frozen Android request waits after the active Source 5c check and +the local Room-store check. No 6c SDK execution or resource reservation has +occurred. No Project UI action is authorized by this remote-only continuation. + +**27 November 2026 — Console 6c (#782), source reviewed; Android gates pending.** +The [6c plan](docs/specs/2026-11-26-build-console-6c-plan.md) implements selected +REST/Connect APKs with retained metadata/hashes, an owned local Host occupant and +safe signing presence status. This detached candidate starts from accepted dev +`438ea369c56e3bd0056155e5d19a48da09b84de9`; it holds no working branch or +resource reservation. Native gRPC/streaming remains unavailable until accepted +5c source is integrated. The server/API/proto implementations are unchanged. + +One independent review found #784 (Host startup overlapping environment/source +mutation) and #785 (a generic selected-APK row missing required parameters). +Both were corrected in one pass: three focused witnesses observed RED then +GREEN; the complete locked console suite passed 57 cases in 24.45 seconds and +Ruff passed. The same reviewer accepted the bounded correction readback. +Host guards cover submission, queued work, preflight and launch; preparation or +generation cannot overlap a starting/running Host. The parameterized APK row +uses its dedicated selectors. Both defects remain open until delivery. + +Actual Android test/debug/release, separate Detekt, completed-report count and +the signing-status configuration-cache/moved-file fixture remain **unrun**. +No commit is permitted until the changed Android half's gates pass. The prepared +one-shot request uses direct Java wrapper argv, offline/one-worker/no-daemon, +private F-drive outputs and synthetic signing values; it waits behind Source's +5c/core checks and requires fresh admission. No SDK, device, port, backend or +production operation has established 6c runtime acceptance. Fake/headless results +do not establish a live Host or installed product result. + +Predecessors: 6a #771 merged through #772/#780 to master +`3ffcc33c7f6cde30f55639a3628b697c719a77e9`; exact working/dev/promotion/master +CI passed. 6b #776 merged through #781 to dev `438ea369…`; its exact working/dev +and promotion #783 CI passed, but #783 is not yet merged. Fresh 6a production +verification found the owned legacy alias still on an older deployment. One +admitted assignment and an independent post-read confirmed its correction; +public health/warmup passed. The first protected helper returned HTTP 200 but +the client did not recognize the API body, so that pass stopped without retries +or runtime queries. Complete production and Project 6 acceptance remain open; +do not promote #783 until the observation is resolved and actually released. + +Source #770 continues 5c foreground WatchClass. #409 and #777 continue the shared +core and Room store; the owner's one-based part 8 means this documented part 7. +Their real Gradle/KSP/integration results remain pending. Existing 5b APK 54 was +not installed: its retained emulator attempt failed before boot completion. +Preserve the accepted 5a/APK 50 evidence, all failed receipts and foreign WIP. +Family rollout and v1 retirement still require their actual acceptance. + +**26 November 2026 — Console 6a (#771) and programme continuation (historical batch notes).** The [approved console design](docs/specs/2026-10-05-build-console-design.md), decision #308 and [6a implementation plan](docs/specs/2026-11-26-build-console-6a-plan.md) govern this batch, isolated from the retained Android acceptance checkout. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 9992d73f..3f3100ec 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -91,6 +91,32 @@ val hasReleaseSigning: Boolean = keystoreKeyPassword != null && File(keystorePath).exists() +val releaseSigningMissingNames = buildList { + if (keystorePath == null || !File(keystorePath).exists()) add("LESSONS_KEYSTORE_FILE") + if (keystorePassword == null) add("LESSONS_KEYSTORE_PASSWORD") + if (keystoreKeyAlias == null) add("LESSONS_KEY_ALIAS") + if (keystoreKeyPassword == null) add("LESSONS_KEY_PASSWORD") +} +val releaseSigningStatusText = when { + hasReleaseSigning -> "configured" + keystorePath == null && + keystorePassword == null && + keystoreKeyAlias == null && + keystoreKeyPassword == null -> + "not configured" + else -> "partly configured" +} + if (releaseSigningMissingNames.isEmpty()) { + "" +} else { + "; missing=" + releaseSigningMissingNames.joinToString(",") +} + +tasks.register("releaseSigningStatus") { + // A safe immutable value keeps secrets and Project references out of the action. + val report = releaseSigningStatusText + doLast { println("LESSONS_SIGNING_STATUS $report") } +} + // Version identity can be overridden per build so a tagged release APK is // distinguishable from a nightly one. Both fall back to the values below. val appVersionName = signingSecret("LESSONS_VERSION_NAME", "lessons.versionName") ?: "0.1.0" diff --git a/docs/architecture.md b/docs/architecture.md index 30334091..98d8134f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -9,6 +9,14 @@ lessons/ └── docs/ ``` +`tools/console/` is a separate Python 3.12/Textual development tool, with its own +lock and environment. It coordinates owned build/client processes across +checkouts and retains selected APK snapshots. Its local Host is an explicit +session occupant using a verified checkout-local server installation, disposable +SQLite and an isolated environment; it is not the production deployment. Host +preparation and contract generation are exclusive with Host startup/lifetime. +Device operations retain the installed product's signature/version safeguards. + ## Why the bot is the backend The requirement was "admin panel in Telegram". Rather than build a web panel and diff --git a/docs/build.md b/docs/build.md index 4e6e31f2..e76ec083 100644 --- a/docs/build.md +++ b/docs/build.md @@ -29,8 +29,27 @@ Deploy reads the HTTPS origin in `LESSONS_PRODUCTION_ORIGIN` on explicit refresh It shows production's reported condition separately from whether its schema matches this checkout's expected revision. An unavailable database, a missing schema or a refused request remains visible as such. This tab does not deploy, -migrate, sign in to Vercel or follow redirects. Host controls and selected -transport builds remain the next console stage. +migrate, sign in to Vercel or follow redirects. + +Build also offers an explicit REST/Connect debug/release APK selection. The +selected build forces streaming off and retains the APK, AGP metadata and hashes +before releasing the build queue. Device can select that retained result. Native +gRPC and streaming remain unavailable until the foreground 5c lifecycle is +accepted in the console's source revision. + +Prepare Host installs CI's current host locks and extras in this checkout's +verified server environment. Start launches one chosen backend from a private +session directory against disposable SQLite on loopback port 8000, with no +production environment inherited. A visible Host occupant persists until Stop or +quit. Starting while Prepare or Generate is queued/running is refused; those +mutations likewise cannot overlap a starting/running Host. Other heavy work needs +an explicit Stop / Run alongside / Cancel choice. The backend marker row checks +the selected owned listener; one backend result is not the two-backend CI matrix. + +The explicit signing-status action runs `:app:releaseSigningStatus` and caches +its safe answer for the console session: configured, partly configured or not +configured, plus missing setting names. It neither prints values/paths nor proves +that an APK carries a valid production signature. ## From a clone to a working pair diff --git a/docs/specs/2026-11-26-build-console-6c-plan.md b/docs/specs/2026-11-26-build-console-6c-plan.md new file mode 100644 index 00000000..3c153ee5 --- /dev/null +++ b/docs/specs/2026-11-26-build-console-6c-plan.md @@ -0,0 +1,72 @@ +# Build console 6c: selected APKs, owned Host and safe signing status + +This implements #782 under approved #308 and programme #273, from the reviewed +6b tree delivered through #781. Source preparation is detached and reserves no +working ref or shared resource. Integrate only after its predecessor's protected +delivery. Keep 5c's frozen compiler inputs and every other owner's work untouched. + +## Current contract + +The Android build already reads LESSONS_TRANSPORT before lessons.transport and +LESSONS_APP_STREAMING before lessons.streaming. REST, Connect and gRPC enum/codegen +exist, but this checkout does not contain the accepted foreground 5c lifecycle. +Offer REST/Connect debug/release choices now and keep streaming off; explain why +gRPC/streaming selection is unavailable until accepted 5c source is integrated. + +Host CI installs root requirements, requirements-host.txt and the server's +dev/host-check extras, launches pyvoy or hypercorn against SQLite and tests each +through pytest host markers. It deliberately sets no LESSONS_TARGET. The console +must represent this real contract rather than calling startup the complete gate. + +## Implementation sequence + +1. Add a separate closed selected-APK build, without altering CI-equivalent + Android gates. Validate transport/variant, explicitly override both environment + flags, preserve no-daemon/one-worker/nonparallel ownership, assemble only the + selected variant and snapshot/hash its APK plus AGP metadata before releasing + the heavy queue. Let Device select that immutable output as well as ordinary + AGP outputs; retain all 6b signature/version guards. +2. Prepare Host in the verified checkout-local server environment with current + CI's two locks and extras. Do not create a borrowed venv or install backends + implicitly. Discover missing/unsupported backends with a clear reason. +3. Start one selected backend through that interpreter in isolated mode from a + private session directory containing no dotenv. Construct an explicit inert + local environment, absolute disposable SQLite path, loopback8000, RUN_BOT=false, + CI's dummy token/secrets and streaming server flag. Inherit no production DB, + bot/proxy configuration or deployment marker. Use bounded health readiness; + an un-stamped local SQLite schema is not a production schema failure. +4. Treat Host as a visible, non-heavy persistent occupant using existing runner + ownership, logs and safe shutdown. Do not hold the heavy lock for its lifetime. + Offer meaningful Stop Host then run / Run alongside / Cancel choices for heavy + overlap, and analogous consent when starting beside an active heavy run. Stop + before Prepare changes its environment or Generate changes imported sources. + Unexpected exit updates the occupant; do not silently start a second Host. +5. Add the selected owned Host's actual host-marker test row and prepare/start/ + readiness environment parity. A single backend result is labelled as such; + both backends are required for a matrix claim. Keep routes and disposable DB + bound to that owned session rather than any server already on the port. +6. Add :app:releaseSigningStatus using only the four existing resolved signing + values and hasReleaseSigning. Capture safe status/missing-name values for the + task action; print no secret or path and add no signingSecret call. An absent + keystore counts as a missing file setting. Expose an explicit heavy console + request and session-cached answer; presence is not cryptographic APK proof. + +## Verification and handback + +Use a small fake-command/headless set for selected artifact ownership, Host +environment/occupancy/shutdown, current CI mapping and status parsing. Reuse the +existing process-tree matrix. These fixtures perform no SDK, backend, HTTP, +port, device or production operation. Run locked Ruff and the complete small +console candidate once, with focused repeats only for real changes/failures. + +The Android build script change additionally needs actual local Android gates +and a bounded signing-status/configuration-cache fixture, including a moved +keystore path, under fresh admission. Written source or a mocked response cannot +close that requirement. Do not commit while the changed half's required checks +remain unrun. Live Host and 5c Host/device acceptance stay separate proof; never +enable gRPC/streaming merely because its build property exists. + +One independent review precedes delivery. Update consuming CI paths and the +reviewed inventory with changed external readers; update build/architecture +guidance and HANDOVER inside the same open batch. Working -> dev -> pinned master, +exact CI and fresh bounded production readback retain their separate meanings. diff --git a/tools/console/README.md b/tools/console/README.md index 530279ef..38919aff 100644 --- a/tools/console/README.md +++ b/tools/console/README.md @@ -44,7 +44,7 @@ scrubbed too. Values shorter than eight characters cannot safely be matched with ordinary text; the run displays that limitation. Server dotenv files contribute names only to Environment, never values to either the table or transcript. The console never opens the machine's Gradle properties or signing files. Signing -status remains unknown until the separate safe Gradle status task is available. +status is requested explicitly from Build and cached for this console session. The default cache and conventional lock live under the user's local application data directory on Windows or cache directory elsewhere. `LESSONS_CONSOLE_CACHE` @@ -57,9 +57,49 @@ The console lock serializes console jobs across worktrees. External terminals an agents must still follow their resource coordinator. An idle console lock is not permission to start work beside somebody else's build or device session. -Host execution and transport selectors belong to 6c. The represented gates do not establish full CI, signed-device or production +The represented gates do not establish full CI, signed-device or production acceptance. Tests never execute Gradle, Buf or adb. +6c adds a separate selected-APK build for REST or Connect and debug or release. +It assembles only that variant, explicitly overrides both app transport/streaming +environment flags, and captures the APK, AGP metadata and hashes before releasing +the heavy queue. Device's Refresh includes those retained snapshots with their +transport/variant labels, alongside ordinary AGP outputs. Later builds do not +retarget a selected snapshot. gRPC and app streaming remain unavailable until the +accepted 5c lifecycle source is integrated; the existence of their build flags is +not acceptance. The existing CI-equivalent Android gate task is unchanged. + +Deploy also has Prepare/Start/Stop Host and backend marker controls. Prepare Host +is an explicit heavy install of CI's two locks and dev/host-check extras into the +verified checkout-local server environment. It does not silently install a backend +on Start. Each Host uses isolated Python from that environment, a private session +directory without dotenv, loopback:8000 and a disposable SQLite file. Production +DB/bot/proxy settings and deployment markers are not inherited. Readiness requires +the actual loopback listener to belong to the current owned process job/group, +then a bounded health response. An existing service is never adopted or stopped. +The un-stamped local SQLite schema is not treated as a production schema failure. + +The Host is a visible persistent occupant rather than a heavy job holding the +queue. Heavy overlap offers Stop Host then run, Run alongside, or Cancel. Prepare +and source-generating tasks require stopping it first. Starting beside queued or +running heavy work offers waiting, explicit overlap or cancellation. The console +excludes Host startup from queued/running preparation or generation in both +directions: preflight counts as an occupant, and admission is checked again before +launch. Those mutations never offer Run alongside. Stop/quit +drain the owned process tree, and unexpected exit updates the occupant. The marker +row targets only that owned session and its disposable DB, with separate results +for pyvoy and hypercorn; a single backend is not a matrix pass. Local isolated cwd, +absolute test/config paths and private reports replace CI's background process and +log-file shell mechanics. The CI inventory records those equivalents explicitly. + +Signing status runs only the safe `:app:releaseSigningStatus` task through the heavy +queue. It reports presence and missing setting names, never credentials or paths. +The action captures a safe immutable string from the already-resolved four signing +settings; there is no additional signingSecret read. Its answer is cached for the +console session and is not cryptographic APK evidence. Actual Android gates and a +configuration-cache fixture with a moved keystore remain required before committing +this Android-script change. Pure tests do not establish those results. + Device and Deploy are implemented in 6b. Device's Refresh lists only online serials and recognized single-APK AGP outputs from this checkout. Select both before Check install or Install APK. Installation copies the selected hash into a private diff --git a/tools/console/lessons_console/app.py b/tools/console/lessons_console/app.py index 801a1e6a..b852d79b 100644 --- a/tools/console/lessons_console/app.py +++ b/tools/console/lessons_console/app.py @@ -31,6 +31,7 @@ setting_status, tools_summary, ) +from lessons_console.host import Host from lessons_console.panels import DeployPanel, DevicePanel from lessons_console.runner import Runner from lessons_console.tasks import BATCHES, BY_KEY, TASKS, bind, disabled_reason @@ -56,6 +57,25 @@ def on_button_pressed(self, event: Button.Pressed) -> None: self.dismiss(event.button.id == "admit") +class HostOverlap(ModalScreen[str]): + def __init__(self, message: str, stop_required: bool = False, starting: bool = False): + super().__init__() + self.message, self.stop_required, self.starting = message, stop_required, starting + + def compose(self) -> ComposeResult: + with VerticalScroll(id="admission"): + yield Label(self.message) + yield Static("These console workloads share memory and files. Choose how to proceed.") + with Horizontal(): + yield Button("Wait for heavy job" if self.starting else "Stop Host then run", id="overlap-stop") + if not self.stop_required: + yield Button("Run alongside", id="overlap-alongside", variant="warning") + yield Button("Cancel", id="overlap-cancel") + + def on_button_pressed(self, event: Button.Pressed) -> None: + self.dismiss((event.button.id or "").removeprefix("overlap-")) + + class Console(App): TITLE = "Lessons console — local developer tools" BINDINGS: ClassVar = [("q", "quit", "Quit safely"), ("r", "refresh", "Refresh"), ("c", "cancel", "Cancel active jobs")] @@ -66,7 +86,7 @@ class Console(App): RichLog { height: 1fr; min-height: 8; } #queue { height: auto; max-height: 8; } #admission { width: 75%; height: auto; max-height: 80%; border: thick $warning; padding: 2; background: $surface; } - Admission { align: center middle; background: $background 70%; } + Admission, HostOverlap { align: center middle; background: $background 70%; } #environment-info { height: auto; padding: 1; } #settings { height: auto; padding: 1; } #deploy-origin { width: 1fr; } @@ -89,12 +109,14 @@ def __init__(self, root: Path | None = None, runner: Runner | None = None, self._device_busy = False self._deploy_run = None self._candidates = {} + self.host = Host(self.root, self.runner, self.render_runs) + self._signing_cache = None def compose(self) -> ComposeResult: yield Header() yield Static( "One heavy console job runs at a time, with live logs and a visible queue. " - "Host execution / transport selectors: 6c. " + "REST/Connect selected APKs and local owned Host are available. gRPC/streaming await accepted 5c. " "Local represented gates do not establish complete CI, signed-device or production acceptance.", id="boundary", ) @@ -103,7 +125,7 @@ def compose(self) -> ComposeResult: for tab in ("Build", "Contract"): with TabPane(tab, id=tab.lower()): with Horizontal(): - yield Select([(task.name, task.key) for task in TASKS if task.tab == tab], + yield Select([(task.name, task.key) for task in TASKS if task.tab == tab and task.key != "android.selected"], allow_blank=False, id=tab.lower() + "-task") yield Button("Run", id="run-" + tab.lower(), variant="primary") if tab == "Build": @@ -111,6 +133,11 @@ def compose(self) -> ComposeResult: yield Button("Server gates", id="batch-server") yield Button("Android gates", id="batch-android") yield Button("Cancel jobs", id="cancel") + with Horizontal(): + yield Select([("REST", "rest"), ("Connect", "connect")], value="connect", allow_blank=False, id="apk-transport") + yield Select([("Debug", "debug"), ("Release", "release")], value="debug", allow_blank=False, id="apk-variant") + yield Button("Build selected APK", id="selected-apk") + yield Button("Signing status", id="signing-status-request") yield Select(self.history_options(), value="current", allow_blank=False, id="history") else: @@ -129,6 +156,7 @@ def compose(self) -> ComposeResult: yield Static("Discovering tools…", id="environment-info", markup=False) yield Static("", id="settings", markup=False) yield Static("", id="policy", markup=False) + yield Static("Signing status: not requested. Presence only; no certificate proof.", id="signing-status", markup=False) with TabPane("Docs", id="docs"): documents = [self.root / "CLAUDE.md", self.root / "HANDOVER.md"] documents.extend(sorted((self.root / "docs").rglob("*.md"))) @@ -209,6 +237,17 @@ async def on_button_pressed(self, event: Button.Pressed) -> None: self._operations.append(asyncio.create_task(self.device_action(identifier))) elif identifier == "deploy-warmup": self._operations.append(asyncio.create_task(self.deploy_action())) + elif identifier == "selected-apk": + task = bind("android.selected", {"transport": self.query_one("#apk-transport", Select).value, + "variant": self.query_one("#apk-variant", Select).value}) + await self.request_tasks((task,)) + elif identifier == "signing-status-request": + if self._signing_cache: + self.notify("Cached signing presence: " + self._signing_cache["status"] + ". Restart the console to refresh.") + else: + await self.request_start(("android.signing",)) + elif identifier.startswith("host-"): + self._operations.append(asyncio.create_task(self.host_action(identifier))) elif identifier.startswith("run-"): tab = identifier.removeprefix("run-") key = self.query_one("#" + tab + "-task", Select).value @@ -218,16 +257,72 @@ async def on_button_pressed(self, event: Button.Pressed) -> None: await self.request_start(BATCHES[identifier.removeprefix("batch-") + ".all"]) async def request_start(self, keys: tuple[str, ...]) -> None: - if any(BY_KEY[key].heavy for key in keys): + if keys == ("android.signing",) and self._signing_cache: + self.notify("Cached signing presence: " + self._signing_cache["status"] + ". Restart to refresh.") + return + await self.request_tasks(tuple(BY_KEY[key] for key in keys)) + + async def request_tasks(self, tasks: tuple) -> None: + if (self.host.active or self.host.starting) and any(task.heavy for task in tasks): + stop_required = any(task.key in {"prepare", "host.prepare", "contract.generate"} for task in tasks) + def choice(answer): + async def apply(): + if answer == "stop": + await self.host.stop() + await self.admit_tasks(tasks) + elif answer == "alongside" and not stop_required: + await self.admit_tasks(tasks) + self._operations.append(asyncio.create_task(apply())) + self.push_screen(HostOverlap("A local Host is running or starting" + ("; this task must stop it first." if stop_required else "."), stop_required), choice) + return + await self.admit_tasks(tasks) + + async def admit_tasks(self, tasks: tuple) -> None: + if any(task.heavy for task in tasks): try: occupants = await asyncio.to_thread(self.emulator_detector) except (OSError, RuntimeError, TimeoutError): occupants = [] self.notify("Emulator detection unavailable; check whether an emulator is running.", severity="warning") if occupants: - self.push_screen(Admission(occupants), lambda admitted: self.start(keys) if admitted else None) + self.push_screen(Admission(occupants), lambda admitted: self.start_tasks(tasks) if admitted else None) return - self.start(keys) + self.start_tasks(tasks) + + async def host_action(self, identifier: str) -> None: + try: + if identifier == "host-stop": + await self.host.stop() + elif identifier == "host-prepare": + await self.request_start(("host.prepare",)) + elif identifier == "host-check": + await self.host.check() + elif identifier == "host-start": + backend = self.query_one("#host-backend", Select).value + if any(run.task.heavy and not run.finished.is_set() for run in self.runner.runs): + epoch = self._cancel_epoch + stop_required = self.host.mutation_pending + def choice(answer): + async def apply(): + if answer == "stop": + await asyncio.gather(*(run.finished.wait() for run in self.runner.runs if run.task.heavy)) + await self.launch_host(backend, epoch) + elif answer == "alongside" and not stop_required: + await self.launch_host(backend, epoch) + self._operations.append(asyncio.create_task(apply())) + self.push_screen(HostOverlap("Preparation/generation must finish before Host startup." if stop_required else "A heavy console job is active.", stop_required=stop_required, starting=True), choice) + else: + await self.host.start(backend) + except (Refusal, OSError, TimeoutError) as error: + self.notify(str(error) if isinstance(error, Refusal) else "The local Host could not be prepared or started.", severity="warning") + + async def launch_host(self, backend: str, epoch: int) -> None: + if epoch != self._cancel_epoch: + return + try: + await self.host.start(backend) + except (Refusal, OSError, TimeoutError) as error: + self.notify(str(error) if isinstance(error, Refusal) else "The local Host could not be started.", severity="warning") async def device_action(self, identifier: str) -> None: if identifier == "device-stop": @@ -275,7 +370,7 @@ async def device_action(self, identifier: str) -> None: if identifier == "device-refresh": self._candidates = {item.metadata: item for item in found} self.query_one("#device-apk", Select).set_options([ - (f"{item.package} · {item.version} · {item.metadata}", item.metadata) for item in found]) + (f"{item.selection or 'AGP'} · {item.package} · {item.version} · {item.metadata}", item.metadata) for item in found]) online = owned.result.get("devices", []) if not isinstance(online, list) or any(not isinstance(item, str) for item in online): raise Refusal("Device discovery returned an unsupported result.") @@ -319,13 +414,15 @@ async def deploy_action(self) -> None: self.query_one("#checkout-status", Static).update("Ready for this checkout: not checked.") def start(self, keys: tuple[str, ...]) -> None: + self.start_tasks(tuple(BY_KEY[key] for key in keys)) + + def start_tasks(self, tasks: tuple) -> None: epoch = self._cancel_epoch async def execute_batch() -> None: failed = False - for key in keys: + for task in tasks: if epoch != self._cancel_epoch: break - task = BY_KEY[key] if failed and not task.always: continue reason = await asyncio.to_thread(disabled_reason, task, self.root) @@ -335,8 +432,17 @@ async def execute_batch() -> None: self.notify(reason, severity="warning", timeout=10) failed = True continue - run = self.runner.submit(task) + try: + run = self.runner.submit(task) + except Refusal as error: + self.notify(str(error), severity="warning") + break await run.finished.wait() + if run.state == "passed" and task.key == "android.signing" and run.result: + self._signing_cache = run.result + self.query_one("#signing-status", Static).update( + "Signing presence (cached this session): " + run.result["status"] + "; missing: " + + (run.result["missing"] or "none") + ". This is not certificate proof.") if run.state == "cancelled": break if run.state != "passed": @@ -346,6 +452,12 @@ async def execute_batch() -> None: def render_runs(self) -> None: if not self.is_mounted: return + if self.host.session: + current = self.host.session + self.query_one("#host-status", Static).update("Local Host: " + current.backend + " " + current.status + "; loopback:8000; disposable SQLite.") + self.query_one("#host-backend", Select).disabled = self.host.active or self.host.starting + self.query_one("#host-check-status", Static).update("Host marker results: " + "; ".join( + name + " " + self.host.results.get(name, "not checked") for name in ("pyvoy", "hypercorn")) + ". Both backends are required for a matrix claim.") self.query_one("#queue", Static).update("\n".join( f"{run.task.name}: {run.state}" for run in self.runner.runs[-8:] ) or "No console jobs. External occupants remain unknown.") @@ -369,6 +481,7 @@ def action_cancel(self) -> None: self._cancel_epoch += 1 self._device_epoch += 1 self._deploy_epoch += 1 + self.host.generation += 1 for run in self.runner.runs: if not run.finished.is_set(): run.cancel.set() @@ -378,6 +491,7 @@ async def action_quit(self) -> None: await asyncio.gather(*self._batches, return_exceptions=True) await asyncio.gather(*self._operations, return_exceptions=True) await self.runner.close() + await self.host.stop() self.exit() async def on_unmount(self) -> None: @@ -385,6 +499,7 @@ async def on_unmount(self) -> None: await asyncio.gather(*self._batches, return_exceptions=True) await asyncio.gather(*self._operations, return_exceptions=True) await self.runner.close() + await self.host.stop() def main() -> None: diff --git a/tools/console/lessons_console/artifacts.py b/tools/console/lessons_console/artifacts.py new file mode 100644 index 00000000..0cffcd50 --- /dev/null +++ b/tools/console/lessons_console/artifacts.py @@ -0,0 +1,55 @@ +"""Selected builds retain their own bytes; later builds cannot retarget Device.""" + +import hashlib +import json +import re +import shutil +from pathlib import Path +from uuid import uuid4 + +from lessons_console.deploy import Refusal + +TRANSPORTS = ("rest", "connect") +VARIANTS = ("debug", "release") +SIGNING_NAMES = frozenset({"LESSONS_KEYSTORE_FILE", "LESSONS_KEYSTORE_PASSWORD", "LESSONS_KEY_ALIAS", "LESSONS_KEY_PASSWORD"}) + + +def selection(transport: str, variant: str) -> None: + if transport not in TRANSPORTS or variant not in VARIANTS: + raise Refusal("Select REST or Connect and debug or release; gRPC/streaming await accepted 5c source.") + + +def snapshot(root: Path, transport: str, variant: str) -> dict[str, str]: + from lessons_console.device import candidate + selection(transport, variant) + source = candidate(root, f"android/app/build/outputs/apk/{variant}/output-metadata.json") + folder = root / "tools/console/.runs/artifacts" / uuid4().hex + folder.mkdir(parents=True) + shutil.copyfile(source.apk, folder / source.apk.name) + metadata = root / source.metadata + shutil.copyfile(metadata, folder / "output-metadata.json") + digest = hashlib.sha256((folder / source.apk.name).read_bytes()).hexdigest() + if digest != source.digest: + raise Refusal("APK output changed while it was being captured.") + receipt = {"transport": transport, "variant": variant, "sha256": digest, + "metadata_sha256": hashlib.sha256((folder / "output-metadata.json").read_bytes()).hexdigest()} + (folder / "selection.json").write_text(json.dumps(receipt, sort_keys=True), encoding="utf-8") + captured = candidate(root, (folder / "output-metadata.json").relative_to(root).as_posix()) + if (captured.package, captured.version, captured.digest) != (source.package, source.version, source.digest): + raise Refusal("AGP metadata changed while the selected APK was being captured.") + print(f"Captured {transport}/{variant} APK: {captured.metadata}; SHA-256 {captured.digest}", flush=True) + return {**captured.parameters(), "transport": transport, "variant": variant} + + +def signing_status(lines: list[str]) -> dict[str, str]: + reports = [line.removeprefix("LESSONS_SIGNING_STATUS ") for line in lines if line.startswith("LESSONS_SIGNING_STATUS ")] + if len(reports) != 1: + raise Refusal("Signing status did not return one safe report.") + match = re.fullmatch(r"(configured|not configured|partly configured)(?:; missing=([A-Z_,]+))?", reports[0]) + if not match: + raise Refusal("Signing status returned an unsupported report.") + state, missing = match.groups() + names = missing.split(",") if missing else [] + if len(names) != len(set(names)) or set(names) - SIGNING_NAMES or (state == "configured") == bool(names): + raise Refusal("Signing status has inconsistent missing-setting names.") + return {"status": state, "missing": ", ".join(names)} diff --git a/tools/console/lessons_console/ci_contract.json b/tools/console/lessons_console/ci_contract.json index 17fe990e..45e38ef2 100644 --- a/tools/console/lessons_console/ci_contract.json +++ b/tools/console/lessons_console/ci_contract.json @@ -26,7 +26,7 @@ }, { "identity": "filter", - "run_sha256": "450da37380cc18c05ed66d5cc16a9fabee7fb3430d46f7a54c3ebfe369475c82", + "run_sha256": "70f802a7854ac57cd2ea20a1c7e82c2b6caf2610f539c6b0d80398f72a2dbecb", "if": "success()", "cwd": ".", "env": { @@ -178,7 +178,7 @@ ] }, "host": { - "reason": "Host lifecycle and live gRPC matrix belong to 6c; 6a does not claim complete CI.", + "reason": "Represented gates and reviewed setup/artifact steps.", "job": { "name": "Host (${{ matrix.server }})", "needs": "changes", @@ -265,7 +265,8 @@ "if": "always()", "cwd": "server", "env": {}, - "continue-on-error": false + "continue-on-error": false, + "reason": "Owned Runner streams the Host output instead of reading CI's background log file." } ] }, diff --git a/tools/console/lessons_console/device.py b/tools/console/lessons_console/device.py index bb4f1a1e..28c6c06b 100644 --- a/tools/console/lessons_console/device.py +++ b/tools/console/lessons_console/device.py @@ -58,6 +58,7 @@ class Candidate: package: str version: int digest: str + selection: str = "" def parameters(self) -> dict[str, str]: return {"metadata": self.metadata, "package": self.package, @@ -68,8 +69,10 @@ def candidate(root: Path, relative: str) -> Candidate: base = (root / "android/app/build/outputs/apk").resolve() supplied = root / relative metadata = supplied.resolve() + captured = re.fullmatch(r"tools/console/\.runs/artifacts/[0-9a-f]{32}/output-metadata\.json", relative) is not None + allowed = metadata.is_relative_to((root / "tools/console/.runs/artifacts").resolve()) if captured else metadata.is_relative_to(base) if (Path(relative).is_absolute() or metadata.name != "output-metadata.json" - or not metadata.is_relative_to(base) or metadata != Path(os.path.abspath(supplied))): + or not allowed or metadata != Path(os.path.abspath(supplied))): raise Refusal("Select recognized AGP output metadata inside this checkout.") try: data = json.loads(metadata.read_text(encoding="utf-8")) @@ -89,16 +92,24 @@ def candidate(root: Path, relative: str) -> Candidate: raise Refusal("AGP APK output is missing or escapes its directory.") application = package(data["applicationId"]) digest = hashlib.sha256(apk.read_bytes()).hexdigest() + if captured: + receipt = json.loads((metadata.parent / "selection.json").read_text(encoding="utf-8")) + if (receipt.get("transport") not in {"rest", "connect"} or receipt.get("variant") not in {"debug", "release"} + or receipt.get("sha256") != digest or receipt.get("metadata_sha256") != hashlib.sha256(metadata.read_bytes()).hexdigest()): + raise Refusal("Selected APK snapshot no longer matches its capture receipt.") except (OSError, KeyError, TypeError, ValueError) as error: if isinstance(error, Refusal): raise raise Refusal("Could not read a recognized AGP APK output.") from None - return Candidate(metadata.relative_to(root.resolve()).as_posix(), apk, application, version, digest) + label = receipt["transport"] + "/" + receipt["variant"] if captured else "" + return Candidate(metadata.relative_to(root.resolve()).as_posix(), apk, application, version, digest, label) def candidates(root: Path) -> list[Candidate]: result = [] - for path in sorted((root / "android/app/build/outputs/apk").rglob("output-metadata.json")): + paths = list((root / "android/app/build/outputs/apk").rglob("output-metadata.json")) + paths.extend((root / "tools/console/.runs/artifacts").glob("*/output-metadata.json")) + for path in sorted(paths): try: result.append(candidate(root, path.relative_to(root).as_posix())) except Refusal: diff --git a/tools/console/lessons_console/environment.py b/tools/console/lessons_console/environment.py index 2b96def2..060e4fb6 100644 --- a/tools/console/lessons_console/environment.py +++ b/tools/console/lessons_console/environment.py @@ -152,7 +152,7 @@ def tools_summary(root: Path) -> str: "JDK 21: " + (str(jdk21(root)) if jdk21(root) else "missing; Android tasks disabled"), "uv: " + ("available" if shutil.which("uv") else "missing; Prepare disabled"), "Buf: " + buf_release(root)[0] + " (verified cache; fetch on first Contract run)", - "Signing: unknown; no passwords or Gradle properties are read.", + "Signing: request its session-cached presence report explicitly from Build; no passwords are read.", ]) diff --git a/tools/console/lessons_console/host.py b/tools/console/lessons_console/host.py new file mode 100644 index 00000000..fe48a127 --- /dev/null +++ b/tools/console/lessons_console/host.py @@ -0,0 +1,280 @@ +"""One inert local Host, owned from launch through listener checks and shutdown.""" + +import ast +import asyncio +import json +import os +import re +import shutil +import socket +import subprocess +from dataclasses import dataclass +from pathlib import Path +from urllib.request import ProxyHandler, build_opener +from uuid import uuid4 + +import yaml + +from lessons_console.deploy import NoRedirect, Refusal +from lessons_console.environment import server_problem, server_python + +BACKENDS = ("pyvoy", "hypercorn") +MUTATORS = frozenset({"prepare", "host.prepare", "contract.generate"}) +URL = "http://127.0.0.1:8000" + + +def ci_contract(root: Path) -> dict: + jobs = yaml.safe_load((root / ".github/workflows/ci.yml").read_text(encoding="utf-8"))["jobs"] + host = jobs["host"] + declared = ast.parse((root / "server/app/host.py").read_text(encoding="utf-8")) + values = [ast.literal_eval(node.value) for node in declared.body if isinstance(node, ast.Assign) + and any(isinstance(target, ast.Name) and target.id == "SERVERS" for target in node.targets)] + if host["strategy"]["matrix"]["server"] != list(BACKENDS) or values != [BACKENDS]: + raise Refusal("CI/server Host backend choices changed; review the console binding.") + return host + + +def session_directory(root: Path, session: str) -> Path: + if not re.fullmatch(r"[0-9a-f]{32}", session): + raise Refusal("Host session identity is malformed.") + directory = root / "tools/console/.runs/host" / session + if directory.resolve() != Path(os.path.abspath(directory)): + raise Refusal("Host session storage must not redirect to another directory.") + return directory + + +def environment(root: Path, session: str) -> dict[str, str]: + directory = session_directory(root, session) + # No production settings, proxy, user Python path, dotenv or deployment marker. + env = {name: os.environ[name] for name in ("SYSTEMROOT", "WINDIR", "COMSPEC", "PATHEXT") if name in os.environ} + env.update({"PATH": str(server_python(root).parent) + os.pathsep + os.defpath, + "TEMP": str(directory), "TMP": str(directory), "TMPDIR": str(directory), + "DATABASE_URL": "sqlite+aiosqlite:///" + (directory / "host.db").as_posix(), + "HOST": "127.0.0.1", "PORT": "8000", "RUN_BOT": "false", + "BOT_TOKEN": "123456:not-a-real-token", "WEBHOOK_SECRET": "ci-webhook-secret", + "CRON_SECRET": "ci-cron-secret", "LESSONS_STREAMING": "true", + "PYTHONIOENCODING": "utf-8"}) + return env + + +def problem(root: Path, backend: str, checks: bool = False) -> str | None: + if backend not in BACKENDS: + return "Select pyvoy or hypercorn." + issue = server_problem(root) + if issue: + return issue + code = ("import importlib.util; print('ready' if all(importlib.util.find_spec(n) is not None " + "for n in " + repr((backend, "grpc") if checks else (backend,)) + ") else 'missing')") + answer = subprocess.run([str(server_python(root)), "-I", "-c", code], cwd=root / "server", + env={name: os.environ[name] for name in ("SYSTEMROOT", "WINDIR") if name in os.environ}, + capture_output=True, text=True, timeout=10, check=False) + if answer.returncode or answer.stdout.strip() != "ready": + return "Host backend/client is missing or unsupported; run Prepare Host explicitly." + return None + + +def prepare(root: Path) -> None: + issue = server_problem(root) + if issue: + raise Refusal(issue + " Prepare the server first.") + uv = shutil.which("uv") + if not uv: + raise Refusal("uv is missing; install it outside the console.") + subprocess.run([uv, "pip", "install", "--python", str(server_python(root)), + "-r", "../requirements.txt", "-r", "requirements-host.txt", "-e", ".[dev,host-check]"], + cwd=root / "server", check=True) + + +def resolve(root: Path, values: dict[str, str], check: bool) -> tuple[list[str], Path, dict[str, str]]: + backend, identity = values["backend"], values["session"] + issue = problem(root, backend, checks=check) + if issue: + raise Refusal(issue) + directory = session_directory(root, identity) + if check and not directory.is_dir(): + raise Refusal("The owned Host session no longer exists.") + directory.mkdir(parents=True, exist_ok=True, mode=0o700) + if (directory / ".env").exists(): + raise Refusal("The private Host session contains a dotenv file; refusing to read it.") + env = environment(root, identity) + if check: + env.update(LESSONS_HOST_URL=URL, LESSONS_HOST_DATABASE_URL=env["DATABASE_URL"]) + pytest = server_python(root).parent / ("pytest.exe" if os.name == "nt" else "pytest") + argv = [str(pytest), "-q", "-p", "no:xdist", "-m", "host", "-c", str(root / "server/pyproject.toml"), + str(root / "server/tests"), "--junitxml=" + str(directory / "host-check.xml"), + "--basetemp=" + str(directory / "check-temp")] + else: + argv = [str(server_python(root)), "-I", "-m", "app.host", "--server", backend] + return argv, directory, env + + +def port_available() -> bool: + try: + with socket.socket() as probe: + if os.name == "nt": + probe.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1) + probe.bind(("127.0.0.1", 8000)) + return True + except OSError: + return False + + +def listener_owned(run) -> bool: + if not run.owns_pid: + return False + if os.name == "nt": + import ctypes + from ctypes import wintypes + class Row(ctypes.Structure): + _fields_ = [(name, wintypes.DWORD) for name in ("state", "address", "port", "remote", "remote_port", "pid")] + size = wintypes.DWORD() + api = ctypes.WinDLL("iphlpapi").GetExtendedTcpTable + api.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.DWORD), wintypes.BOOL, wintypes.ULONG, ctypes.c_int, wintypes.ULONG] + api(None, ctypes.byref(size), False, 2, 3, 0) + data = ctypes.create_string_buffer(size.value) + if api(data, ctypes.byref(size), False, 2, 3, 0): + return False + count = wintypes.DWORD.from_buffer(data).value + for index in range(count): + row = Row.from_buffer(data, ctypes.sizeof(wintypes.DWORD) + index * ctypes.sizeof(Row)) + if socket.ntohs(row.port & 0xffff) == 8000 and row.address == 0x0100007f and run.owns_pid(row.pid): + return True + return False + if not Path("/proc/net/tcp").is_file(): + return False + inodes = set() + for line in Path("/proc/net/tcp").read_text().splitlines()[1:]: + parts = line.split() + if parts[1] == "0100007F:1F40" and parts[3] == "0A": + inodes.add("socket:[" + parts[9] + "]") + for process in Path("/proc").iterdir(): + if not process.name.isdigit() or not run.owns_pid(int(process.name)): + continue + try: + if any(os.readlink(fd) in inodes for fd in (process / "fd").iterdir()): + return True + except OSError: + continue + return False + + +def health() -> bool: + try: + with build_opener(ProxyHandler({}), NoRedirect()).open(URL + "/api/v1/health", timeout=1) as response: + data = response.read(4097) + return response.status == 200 and len(data) <= 4096 and json.loads(data).get("status") == "ok" + except (OSError, ValueError, AttributeError): + return False + + +@dataclass +class Session: + identity: str + backend: str + run: object + ready: bool = False + status: str = "starting" + monitor: asyncio.Task | None = None + + +class Host: + def __init__(self, root: Path, runner, changed=lambda: None, backend_probe=problem, + port_probe=port_available, listener_probe=listener_owned, health_probe=health): + self.root, self.runner, self.changed = root, runner, changed + self.backend_probe, self.port_probe = backend_probe, port_probe + self.listener_probe, self.health_probe = listener_probe, health_probe + self.session: Session | None = None + self.check_run = None + self.results: dict[str, str] = {} + self.starting = False + self.generation = 0 + self._start_finished = asyncio.Event() + self._start_finished.set() + self.runner.guards.append(self.guard) + + @property + def mutation_pending(self) -> bool: + return any(run.task.key in MUTATORS and not run.finished.is_set() for run in self.runner.runs) + + def guard(self, task) -> None: + if task.key in MUTATORS and (self.active or self.starting): + raise Refusal("Stop the Host, including its startup, before preparation or generation.") + if task.key == "host.start" and self.mutation_pending: + raise Refusal("Wait for queued/running preparation or generation before starting the Host.") + + @property + def active(self) -> bool: + return bool(self.session and not self.session.run.finished.is_set()) + + async def start(self, backend: str) -> Session: + from lessons_console.tasks import BY_KEY, bind + if self.active or self.starting or (self.check_run and not self.check_run.finished.is_set()): + raise Refusal("Stop the current Host before starting another.") + self.guard(BY_KEY["host.start"]) + self.starting = True + self._start_finished.clear() + generation = self.generation + try: + issue = await asyncio.to_thread(self.backend_probe, self.root, backend) + if issue: + raise Refusal(issue) + if generation != self.generation: + raise Refusal("Host start was cancelled.") + self.guard(BY_KEY["host.start"]) + if not await asyncio.to_thread(self.port_probe): + raise Refusal("Loopback port 8000 is occupied; no existing service was stopped or adopted.") + if generation != self.generation: + raise Refusal("Host start was cancelled.") + identity = uuid4().hex + run = self.runner.submit(bind("host.start", {"backend": backend, "session": identity})) + self.session = Session(identity, backend, run) + self.session.monitor = asyncio.create_task(self._monitor(self.session)) + self.changed() + return self.session + finally: + self.starting = False + self._start_finished.set() + + async def _monitor(self, session: Session) -> None: + deadline = asyncio.get_running_loop().time() + 60 + while not session.run.finished.is_set() and asyncio.get_running_loop().time() < deadline: + if await asyncio.to_thread(self.listener_probe, session.run) and await asyncio.to_thread(self.health_probe): + session.ready, session.status = True, "ready" + self.changed() + break + await asyncio.sleep(0.1) + if not session.ready and not session.run.finished.is_set(): + session.status = "readiness timed out" + session.run.cancel.set() + await session.run.finished.wait() + if self.check_run and not self.check_run.finished.is_set(): + self.check_run.cancel.set() + session.ready = False + session.status = "stopped" if session.run.cancel.is_set() else "exited unexpectedly" + self.changed() + + async def stop(self) -> None: + self.generation += 1 + if self.starting: + await self._start_finished.wait() + if self.check_run and not self.check_run.finished.is_set(): + self.check_run.cancel.set() + await self.check_run.finished.wait() + if self.active: + self.session.run.cancel.set() + await self.session.run.finished.wait() + if self.session and self.session.monitor: + await self.session.monitor + + async def check(self): + from lessons_console.tasks import bind + current = self.session + if not self.active or not current.ready or not await asyncio.to_thread(self.listener_probe, current.run): + raise Refusal("Start a ready owned Host before its backend's marker checks.") + if self.check_run and not self.check_run.finished.is_set(): + raise Refusal("This Host already has marker checks running.") + self.check_run = self.runner.submit(bind("host.check", {"backend": current.backend, "session": current.identity})) + await self.check_run.finished.wait() + self.results[current.backend] = self.check_run.state + self.changed() + return self.check_run diff --git a/tools/console/lessons_console/locking.py b/tools/console/lessons_console/locking.py index 22e773a0..aba2a10d 100644 --- a/tools/console/lessons_console/locking.py +++ b/tools/console/lessons_console/locking.py @@ -120,3 +120,20 @@ def close(self) -> None: if self.handle: self.kernel.CloseHandle(self.handle) self.handle = None + + def contains(self, pid: int) -> bool: + if not self.handle: + return False + from ctypes import wintypes + kernel, ctypes = self.kernel, self.ctypes + kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + kernel.OpenProcess.restype = wintypes.HANDLE + kernel.IsProcessInJob.argtypes = [wintypes.HANDLE, wintypes.HANDLE, ctypes.POINTER(wintypes.BOOL)] + process = kernel.OpenProcess(0x1000, False, pid) + if not process: + return False + try: + owned = wintypes.BOOL() + return bool(kernel.IsProcessInJob(process, self.handle, ctypes.byref(owned)) and owned.value) + finally: + kernel.CloseHandle(process) diff --git a/tools/console/lessons_console/operations.py b/tools/console/lessons_console/operations.py index 9cad5b50..114043d3 100644 --- a/tools/console/lessons_console/operations.py +++ b/tools/console/lessons_console/operations.py @@ -13,6 +13,10 @@ from lessons_console.device import Device, candidate, package, serial FIELDS = { + "android.selected": frozenset({"transport", "variant"}), + "host.prepare": frozenset(), + "host.start": frozenset({"backend", "session"}), + "host.check": frozenset({"backend", "session"}), "device.refresh": frozenset(), "device.check": frozenset({"serial", "metadata", "package", "version", "sha256"}), "device.install": frozenset({"serial", "metadata", "package", "version", "sha256"}), @@ -38,10 +42,18 @@ def parameters(key: str, values: dict) -> tuple[tuple[str, str], ...]: raise Refusal("The selected APK version is malformed.") if "metadata" in values and (Path(values["metadata"]).is_absolute() or ".." in Path(values["metadata"]).parts or "\\" in values["metadata"] - or not values["metadata"].startswith("android/app/build/outputs/apk/") + or not (values["metadata"].startswith("android/app/build/outputs/apk/") + or re.fullmatch(r"tools/console/\.runs/artifacts/[0-9a-f]{32}/output-metadata\.json", values["metadata"])) or not values["metadata"].endswith("/output-metadata.json")): raise Refusal("The selected AGP output metadata path is malformed.") result = dict(values) + if key == "android.selected": + from lessons_console.artifacts import selection + selection(result["transport"], result["variant"]) + if key in {"host.start", "host.check"} and ( + result["backend"] not in {"pyvoy", "hypercorn"} or not re.fullmatch(r"[0-9a-f]{32}", result["session"]) + ): + raise Refusal("Select one supported Host backend and its owned session.") if "origin" in result: result["origin"] = origin(result["origin"]) return tuple(sorted(result.items())) @@ -95,6 +107,21 @@ def read() -> None: def operate(key: str, root: Path, supplied: dict, device=None, fetch=None) -> dict: values = dict(parameters(key, supplied)) + if key == "android.selected": + from dataclasses import replace + + from lessons_console.artifacts import snapshot + from lessons_console.tasks import BY_KEY, resolve + variant = values["variant"] + task = replace(BY_KEY["android.build"], argv=("./gradlew", ":app:assemble" + variant.title())) + argv, cwd, env = resolve(task, root) + env.update(LESSONS_TRANSPORT=values["transport"], LESSONS_APP_STREAMING="false") + subprocess.run(argv, cwd=cwd, env=env, check=True) + return snapshot(root, values["transport"], variant) + if key == "host.prepare": + from lessons_console.host import prepare + prepare(root) + return {"status": "prepared"} if key == "deploy.warmup": return warmup(root, values["origin"], **({"fetch": fetch} if fetch else {})) target = device or Device(root) diff --git a/tools/console/lessons_console/panels.py b/tools/console/lessons_console/panels.py index 82956f8e..580069b4 100644 --- a/tools/console/lessons_console/panels.py +++ b/tools/console/lessons_console/panels.py @@ -1,7 +1,7 @@ """Device and deployment surfaces; operations remain in the closed task registry.""" from textual.app import ComposeResult -from textual.containers import Horizontal, Vertical +from textual.containers import Horizontal, Vertical, VerticalScroll from textual.widgets import Button, Input, RichLog, Select, Static @@ -24,7 +24,7 @@ def compose(self) -> ComposeResult: yield RichLog(markup=False, highlight=False, wrap=True, id="device-output") -class DeployPanel(Vertical): +class DeployPanel(VerticalScroll): def __init__(self, configured: str): super().__init__() self.configured = configured @@ -36,4 +36,12 @@ def compose(self) -> ComposeResult: yield Button("Read warmup", id="deploy-warmup") yield Static("Production condition: not checked.", id="production-status", markup=False) yield Static("Ready for this checkout: not checked.", id="checkout-status", markup=False) + with Horizontal(): + yield Select([("pyvoy", "pyvoy"), ("hypercorn", "hypercorn")], value="pyvoy", allow_blank=False, id="host-backend") + yield Button("Prepare Host", id="host-prepare") + yield Button("Start Host", id="host-start") + yield Button("Stop Host", id="host-stop") + yield Button("Host markers", id="host-check") + yield Static("Local Host: stopped. This never starts or tests production.", id="host-status", markup=False) + yield Static("Host matrix: neither backend checked; both are required.", id="host-check-status", markup=False) yield RichLog(markup=False, highlight=False, wrap=True, id="deploy-output") diff --git a/tools/console/lessons_console/parity.py b/tools/console/lessons_console/parity.py index 798f002c..deadf607 100644 --- a/tools/console/lessons_console/parity.py +++ b/tools/console/lessons_console/parity.py @@ -13,10 +13,10 @@ CONTRACT = Path(__file__).with_name("ci_contract.json") SKIPPED_JOBS = { "changes": "Routing only; does not test the checkout.", - "host": "Host lifecycle and live gRPC matrix belong to 6c; 6a does not claim complete CI.", "ci": "Aggregates remote job results; there is no equivalent local remote-results gate.", "console": "The console's own tests; never recursively launch the console suite.", } +SKIPPED_STEPS = {("host", "The host's log"): "Owned Runner streams the Host output instead of reading CI's background log file."} def inventory(root: Path) -> dict: @@ -37,6 +37,8 @@ def inventory(root: Path) -> dict: # Environments and failure behavior are part of the equivalent, not comments. row["env"] = step.get("env", {}) row["continue-on-error"] = step.get("continue-on-error", False) + if (job_name, step.get("name")) in SKIPPED_STEPS: + row["reason"] = SKIPPED_STEPS[(job_name, step["name"])] rows.append(row) jobs[job_name] = {"reason": SKIPPED_JOBS.get(job_name, "Represented gates and reviewed setup/artifact steps."), "job": {key: value for key, value in job.items() if key != "steps"}, @@ -61,7 +63,7 @@ def validate_ci(root: Path) -> None: step = next((step for step in jobs[job_name]["steps"] if step.get("name") == name), None) if step is None: raise AssertionError(f"Gate {task.key} has no CI step") - if task.key not in {"prepare", "contract.fresh"} and tuple(shlex.split(step["run"])) != task.argv: + if task.key not in {"prepare", "contract.fresh", "host.prepare", "host.start"} and tuple(shlex.split(step["run"])) != task.argv: raise AssertionError(f"Gate argv drift: {task.key}") condition = step.get("if", "success()") if (condition == "success() || failure()") != task.always: @@ -70,13 +72,23 @@ def validate_ci(root: Path) -> None: if cwd != task.cwd: raise AssertionError(f"Gate cwd drift: {task.key}") # Nothing executable can disappear under an unclassified new job or action. - if set(jobs) - {"server", "android", "contract"} - set(SKIPPED_JOBS): + if set(jobs) - {"server", "android", "contract", "host"} - set(SKIPPED_JOBS): raise AssertionError("Unclassified CI job") - for job_name in ("server", "android", "contract"): + for job_name in ("server", "android", "contract", "host"): for step in jobs[job_name]["steps"]: if ("run" in step and "\n" not in step["run"] and step.get("name") - and (job_name, step["name"]) not in declared): + and (job_name, step["name"]) not in declared and (job_name, step["name"]) not in SKIPPED_STEPS): raise AssertionError("Unrepresented single-line gate") + for job, name in SKIPPED_STEPS: + assert any(step.get("name") == name for step in jobs[job]["steps"]), "Stale CI step exception" + from lessons_console.host import ci_contract, environment + contract = ci_contract(root) + start = next(step for step in contract["steps"] if step.get("name") == "Start the host") + local = environment(root, "0" * 32) + assert all(local[name] == value for name, value in start["env"].items() if name != "DATABASE_URL") + assert "LESSONS_TARGET" not in local and local["DATABASE_URL"].startswith("sqlite+aiosqlite:///") + install = next(step["run"] for step in contract["steps"] if step.get("name") == "Install") + assert shlex.split(install) == ["pip", "install", "-r", "../requirements.txt", "-r", "requirements-host.txt", "-e", ".[dev,host-check]"] buf_step = next(step for step in jobs["contract"]["steps"] if step.get("uses", "").startswith("bufbuild/buf-action@")) assert buf_step["with"]["lint"] is True assert buf_step["with"]["breaking"] is not False diff --git a/tools/console/lessons_console/runner.py b/tools/console/lessons_console/runner.py index 43dca897..c6b7f100 100644 --- a/tools/console/lessons_console/runner.py +++ b/tools/console/lessons_console/runner.py @@ -23,6 +23,8 @@ class Run: lines: list[str] = field(default_factory=list) path: Path | None = None result: dict | None = None + process_id: int | None = None + owns_pid: Callable[[int], bool] | None = field(default=None, repr=False) cancel: asyncio.Event = field(default_factory=asyncio.Event) finished: asyncio.Event = field(default_factory=asyncio.Event) worker: asyncio.Task | None = field(default=None, repr=False) @@ -39,8 +41,14 @@ def __init__(self, root: Path, changed: Callable[[], None] = lambda: None, self.resolver = resolver self.runs: list[Run] = [] self._heavy = asyncio.Lock() + self.guards: list[Callable[[Task], None]] = [] + + def ensure_admitted(self, task: Task) -> None: + for guard in self.guards: + guard(task) def submit(self, task: Task) -> Run: + self.ensure_admitted(task) run = Run(task) self.runs.append(run) run.worker = asyncio.create_task(self._execute(run)) @@ -80,6 +88,8 @@ async def _execute(self, run: Run) -> None: await asyncio.sleep(0.1) if run.cancel.is_set(): return + # Admission may have changed while this job waited in the queue. + self.ensure_admitted(run.task) run.state = "running" if not run.task.volatile: directory = self.root / "tools/console/.runs" @@ -116,6 +126,8 @@ async def _execute(self, run: Run) -> None: process.kill() await asyncio.to_thread(process.wait) raise + run.process_id = process.pid + run.owns_pid = windows.contains if windows else lambda pid: self._pid_in_group(pid, process.pid) self.changed() async def consume() -> None: @@ -167,6 +179,9 @@ async def consume() -> None: run.state = "failed" else: run.state = "passed" + if run.state == "passed" and run.task.key == "android.signing": + from lessons_console.artifacts import signing_status + run.result = signing_status(run.lines) self.emit(run, "Result: " + run.state, stream) except asyncio.CancelledError: run.cancel.set() @@ -217,12 +232,20 @@ async def cleanup() -> None: if run.task.volatile: run.lines.clear() run.result = None + run.owns_pid = None lock.release() if local_held: self._heavy.release() run.finished.set() self.changed() + @staticmethod + def _pid_in_group(pid: int, group: int) -> bool: + try: + return os.getpgid(pid) == group + except ProcessLookupError: + return False + @staticmethod def _group_exists(pid: int) -> bool: if Path("/proc").is_dir(): diff --git a/tools/console/lessons_console/tasks.py b/tools/console/lessons_console/tasks.py index f1f56a62..4993b51a 100644 --- a/tools/console/lessons_console/tasks.py +++ b/tools/console/lessons_console/tasks.py @@ -53,6 +53,16 @@ class Task: Task("android.count", "Android: report count", "Build", "server", ("python", "../server/scripts/check_test_counts.py", "android", "--root", "."), "android", False, "Compare completed JVM reports with the published count.", ("android", "Check Android test count")), + Task("android.selected", "Build selected APK snapshot", "Build", "operation", (), ".", True, + "Build only the selected REST/Connect variant and retain its own APK and metadata."), + Task("android.signing", "Read release signing status", "Build", "gradle", ("./gradlew", ":app:releaseSigningStatus"), + "android", True, "Read only safe presence/missing names; this is not certificate proof."), + Task("host.prepare", "Prepare Host", "Deploy", "operation", (), "server", True, + "Install CI's two locks and dev/host-check extras in the verified server environment.", ("host", "Install")), + Task("host.start", "Owned local Host", "Deploy", "host", (), "server", False, + "Run the selected backend in an inert private session; a persistent occupant, not a heavy job.", ("host", "Start the host")), + Task("host.check", "Host backend marker checks", "Deploy", "hostcheck", ("pytest", "-q", "-p", "no:xdist", "-m", "host"), + "server", True, "Run CI's host markers against the selected owned session only.", ("host", "Test against it")), Task("contract.lint", "Contract: lint", "Contract", "console", ("buf-lint",), ".", False, "Run Buf STANDARD lint at CI's verified version.", ("contract", "buf:lint")), Task("contract.generate", "Contract: generate (writes sources)", "Contract", "console", ("buf-generate",), @@ -79,7 +89,7 @@ class Task: def bind(key: str, values: dict) -> Task: from lessons_console.operations import parameters - if key not in BY_KEY or BY_KEY[key].tool != "operation": + if key not in BY_KEY or BY_KEY[key].tool not in {"operation", "host", "hostcheck"}: raise ValueError("Only a declared device/deploy operation accepts parameters") return replace(BY_KEY[key], parameters=parameters(key, values)) @@ -87,7 +97,7 @@ def bind(key: str, values: dict) -> Task: def disabled_reason(task: Task, root: Path) -> str | None: if task.tool == "server": return server_problem(root) - if task.tool == "gradle": + if task.tool == "gradle" or task.key == "android.selected": if not jdk21(root): return "No verified JDK 21. Set JAVA_HOME or android/.gradle/config.properties." if not (os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT")): @@ -111,10 +121,16 @@ def resolve(task: Task, root: Path) -> tuple[list[str], Path, dict[str, str]]: if not java: raise ValueError("JDK 21 is required") env["JAVA_HOME"] = str(java) + if task.key == "android.signing": + env.update(LESSONS_TRANSPORT="connect", LESSONS_APP_STREAMING="false") env["PATH"] = str(java / "bin") + os.pathsep + env.get("PATH", "") wrapper = str(root / "android" / ("gradlew.bat" if os.name == "nt" else "gradlew")) # A persistent daemon would outlive the wrapper and retain our owned job lock. argv = [wrapper, *task.argv[1:], "--max-workers=1", "--no-parallel", "--console=plain", "--no-daemon"] + elif task.tool in {"host", "hostcheck"}: + from lessons_console.host import resolve as resolve_host + from lessons_console.operations import parameters + return resolve_host(root, dict(parameters(task.key, dict(task.parameters))), check=task.tool == "hostcheck") elif task.tool == "operation": from lessons_console.operations import parameters values = dict(parameters(task.key, dict(task.parameters))) diff --git a/tools/console/tests/test_console_6c.py b/tools/console/tests/test_console_6c.py new file mode 100644 index 00000000..1b9faa63 --- /dev/null +++ b/tools/console/tests/test_console_6c.py @@ -0,0 +1,318 @@ +import asyncio +import json +import os +import sys +import threading +from dataclasses import replace +from typing import ClassVar + +import pytest +from textual.widgets import Select, TabbedContent + +from lessons_console.app import Console, HostOverlap +from lessons_console.artifacts import signing_status +from lessons_console.deploy import Refusal +from lessons_console.device import candidate +from lessons_console.host import Host, ci_contract, environment, prepare, resolve, session_directory +from lessons_console.operations import operate +from lessons_console.runner import Run, Runner +from lessons_console.tasks import BY_KEY, bind + + +def agp(root): + directory = root / "android/app/build/outputs/apk/release" + directory.mkdir(parents=True) + (directory / "app.apk").write_bytes(b"selected-apk-bytes") + (directory / "output-metadata.json").write_text(json.dumps({"artifactType": {"type": "APK"}, + "applicationId": "com.example.lessons", "elements": [{"outputFile": "app.apk", "filters": [], "versionCode": 9}]})) + + +def test_selected_build_overrides_both_flags_and_retains_own_snapshot(tmp_path, monkeypatch): + agp(tmp_path) + monkeypatch.setenv("LESSONS_TRANSPORT", "grpc") + monkeypatch.setenv("LESSONS_APP_STREAMING", "true") + monkeypatch.setattr("lessons_console.tasks.jdk21", lambda root: tmp_path / "jdk") + calls = [] + monkeypatch.setattr("lessons_console.operations.subprocess.run", lambda argv, **kwargs: calls.append((argv, kwargs))) + result = operate("android.selected", tmp_path, {"transport": "rest", "variant": "release"}) + argv, arguments = calls[0] + assert ":app:assembleRelease" in argv and "test" not in argv and "--no-daemon" in argv + assert arguments["env"]["LESSONS_TRANSPORT"] == "rest" + assert arguments["env"]["LESSONS_APP_STREAMING"] == "false" + original = tmp_path / "android/app/build/outputs/apk/release/app.apk" + original.write_bytes(b"later-build") + retained = candidate(tmp_path, result["metadata"]) + assert retained.apk.read_bytes() == b"selected-apk-bytes" + retained.apk.write_bytes(b"changed-snapshot") + with pytest.raises(Refusal, match="capture receipt"): + candidate(tmp_path, result["metadata"]) + + +def test_grpc_streaming_and_unknown_selected_variant_stay_disabled(): + for values in ({"transport": "grpc", "variant": "debug"}, + {"transport": "connect", "variant": "debug", "streaming": "true"}, + {"transport": "rest", "variant": "release --debug"}): + with pytest.raises(Refusal): + bind("android.selected", values) + + +def test_safe_signing_report_parser_and_gradle_capture(root): + assert signing_status(["LESSONS_SIGNING_STATUS configured"])["status"] == "configured" + answer = signing_status(["LESSONS_SIGNING_STATUS partly configured; missing=LESSONS_KEYSTORE_FILE"]) + assert answer["missing"] == "LESSONS_KEYSTORE_FILE" + for line in ("configured; missing=LESSONS_KEY_PASSWORD", "not configured; missing=SECRET_VALUE", "configured; password=anything"): + with pytest.raises(Refusal): + signing_status(["LESSONS_SIGNING_STATUS " + line]) + source = (root / "android/app/build.gradle.kts").read_text(encoding="utf-8") + action = source.split('tasks.register("releaseSigningStatus")', 1)[1].split("\n}", 1)[0] + assert "val report = releaseSigningStatusText" in action + assert "signingSecret(" not in action and "keystorePassword" not in action + assert 'println("LESSONS_SIGNING_STATUS $report")' in action + + +def test_host_environment_matches_ci_but_drops_production_state(root, monkeypatch): + for name in ("DATABASE_URL", "BOT_TOKEN", "HTTPS_PROXY", "DIARY_PROXY_URL", "SENTRY_DSN", "LESSONS_TARGET", "VERCEL", "PYTHONPATH"): + monkeypatch.setenv(name, "poison-production-value") + env = environment(root, "a" * 32) + start = next(step for step in ci_contract(root)["steps"] if step.get("name") == "Start the host") + assert all(env[name] == value for name, value in start["env"].items() if name != "DATABASE_URL") + assert all("poison" not in value for value in env.values()) + assert "LESSONS_TARGET" not in env and "VERCEL" not in env and "HTTPS_PROXY" not in env + assert env["DATABASE_URL"].endswith("/" + "a" * 32 + "/host.db") + + +def test_host_resolver_uses_private_no_dotenv_session_and_owned_marker_paths(tmp_path, monkeypatch): + monkeypatch.setattr("lessons_console.host.problem", lambda *args, **kwargs: None) + values = {"backend": "hypercorn", "session": "b" * 32} + argv, cwd, env = resolve(tmp_path, values, check=False) + assert argv[1:] == ["-I", "-m", "app.host", "--server", "hypercorn"] + assert cwd == session_directory(tmp_path, values["session"]) and not (cwd / ".env").exists() + argv, test_cwd, test_env = resolve(tmp_path, values, check=True) + assert argv[1:6] == ["-q", "-p", "no:xdist", "-m", "host"] + assert test_cwd == cwd and test_env["LESSONS_HOST_DATABASE_URL"] == env["DATABASE_URL"] + assert test_env["LESSONS_HOST_URL"] == "http://127.0.0.1:8000" + (cwd / ".env").write_text("DATABASE_URL=do-not-read") + with pytest.raises(Refusal, match="dotenv"): + resolve(tmp_path, values, check=False) + + +def test_host_prepare_is_explicit_and_mirrors_ci_two_locks(tmp_path, monkeypatch): + monkeypatch.setattr("lessons_console.host.server_problem", lambda root: None) + monkeypatch.setattr("lessons_console.host.shutil.which", lambda name: "fake-uv") + seen = [] + monkeypatch.setattr("lessons_console.host.subprocess.run", lambda argv, **kwargs: seen.append((argv, kwargs))) + prepare(tmp_path) + assert seen[0][0][-6:] == ["-r", "../requirements.txt", "-r", "requirements-host.txt", "-e", ".[dev,host-check]"] + assert seen[0][1]["cwd"] == tmp_path / "server" + + +async def test_owned_host_does_not_hold_heavy_queue_and_marker_is_backend_scoped(tmp_path): + def fake(task, root): + code = "import time; print('host-ready',flush=True); time.sleep(60)" if task.key == "host.start" else "print('fake-check-complete')" + return [sys.executable, "-u", "-c", code], root, dict(os.environ) + runner = Runner(tmp_path, resolver=fake, lock_path=tmp_path / "queue.lock") + ownership = {"owned": True} + host = Host(tmp_path, runner, backend_probe=lambda *args: None, port_probe=lambda: True, + listener_probe=lambda run: ownership["owned"] and run.process_id is not None, + health_probe=lambda: True) + try: + current = await host.start("pyvoy") + async with asyncio.timeout(5): + while not current.ready: + await asyncio.sleep(0.02) + heavy = runner.submit(replace(BY_KEY["android.build"], key="fake-heavy", tool="fake")) + await asyncio.wait_for(heavy.finished.wait(), 5) + assert heavy.state == "passed" and host.active and not current.run.task.heavy + checks = await host.check() + assert checks.state == "passed" and host.results == {"pyvoy": "passed"} + assert dict(checks.task.parameters)["session"] == current.identity + ownership["owned"] = False + with pytest.raises(Refusal, match="ready owned Host"): + await host.check() + await host.stop() + assert not host.active and current.run.state == "cancelled" + finally: + await host.stop() + await runner.close() + + +async def test_host_never_borrows_a_port_or_reads_health_without_pid_ownership(tmp_path): + runner = Runner(tmp_path, resolver=lambda task, root: ([sys.executable, "-c", "import time;time.sleep(60)"], root, dict(os.environ))) + health_calls = [] + host = Host(tmp_path, runner, backend_probe=lambda *args: None, port_probe=lambda: False, + listener_probe=lambda run: False, health_probe=lambda: health_calls.append(True)) + with pytest.raises(Refusal, match="occupied"): + await host.start("pyvoy") + assert runner.runs == [] + host.port_probe = lambda: True + try: + await host.start("hypercorn") + await asyncio.sleep(0.05) + assert not host.session.ready and health_calls == [] + with pytest.raises(Refusal, match="Stop the current"): + await host.start("pyvoy") + finally: + await host.stop() + await runner.close() + + +async def test_cancel_during_host_preflight_cannot_launch_late(tmp_path): + runner = Runner(tmp_path) + host = Host(tmp_path, runner, backend_probe=lambda *args: None, port_probe=lambda: True) + starting = asyncio.create_task(host.start("pyvoy")) + await asyncio.sleep(0) + await host.stop() + with pytest.raises(Refusal, match="cancelled"): + await starting + assert runner.runs == [] + + +async def test_host_overlap_requires_stop_before_prepare_and_allows_explicit_other_overlap(root, monkeypatch): + monkeypatch.setattr("lessons_console.app.tools_summary", lambda root: "Fake tools") + app = Console(root, emulator_detector=list) + class Occupant: + active = True + session = None + results: ClassVar = {} + starting = False + mutation_pending = False + generation = 0 + async def stop(self): + self.active = False + app.host = Occupant() + async with app.run_test(size=(130, 48)) as pilot: + assert "android.selected" not in app.query_one("#build-task", Select)._legal_values + await pilot.click("#run-build") + async with asyncio.timeout(4): + while not isinstance(app.screen, HostOverlap) or not app.screen.query("#overlap-cancel"): + await pilot.pause(0.01) + await pilot.pause() + assert not app.screen.query("#overlap-alongside") + assert await pilot.click("#overlap-cancel") + app.query_one("#build-task", Select).value = "android.build" + await pilot.pause() + assert await pilot.click("#run-build") + async with asyncio.timeout(4): + while not isinstance(app.screen, HostOverlap) or not app.screen.query("#overlap-alongside"): + await pilot.pause(0.01) + await pilot.pause() + assert await pilot.click("#overlap-cancel") + assert not app.runner.runs + app.host.active = False + app.host.starting = True + app.query_one("#build-task", Select).value = "prepare" + await pilot.pause() + assert await pilot.click("#run-build") + async with asyncio.timeout(4): + while not isinstance(app.screen, HostOverlap) or not app.screen.query("#overlap-cancel"): + await pilot.pause(0.01) + await pilot.pause() + assert not app.screen.query("#overlap-alongside") + assert await pilot.click("#overlap-cancel") + app.host.starting = False + app.host.mutation_pending = True + queued = Run(BY_KEY["prepare"]) + app.runner.runs.append(queued) + await pilot.click("#--content-tab-deploy") + async with asyncio.timeout(4): + while app.query_one(TabbedContent).active != "deploy" or not app.query_one("#host-start").region.width: + await pilot.pause(0.01) + await pilot.pause() + assert await pilot.click("#host-start") + async with asyncio.timeout(4): + while not isinstance(app.screen, HostOverlap) or not app.screen.query("#overlap-cancel"): + await pilot.pause(0.01) + await pilot.pause() + assert not app.screen.query("#overlap-alongside") + assert await pilot.click("#overlap-cancel") + queued.finished.set() + app.runner.runs.remove(queued) + + +async def test_explicit_signing_presence_is_cached_for_session(root, monkeypatch): + monkeypatch.setattr("lessons_console.app.tools_summary", lambda root: "Fake tools") + monkeypatch.setattr("lessons_console.app.disabled_reason", lambda task, root: None) + class FakeRunner(Runner): + async def _execute(self, run): + run.result = {"status": "configured", "missing": ""} + run.state = "passed" + run.finished.set() + self.changed() + runner = FakeRunner(root) + app = Console(root, runner, emulator_detector=list) + async with app.run_test(size=(130, 48)) as pilot: + assert await pilot.click("#signing-status-request") + async with asyncio.timeout(4): + while app._signing_cache is None: + await pilot.pause(0.01) + assert await pilot.click("#signing-status-request") + await pilot.pause() + assert len(runner.runs) == 1 and app._signing_cache["status"] == "configured" + + +async def test_host_exclusion_covers_queued_mutators_and_rechecks_launch(tmp_path): + resolved = [] + def fake(task, root): + resolved.append(task.key) + return [sys.executable, "-c", "print('fake-host-only')"], root, dict(os.environ) + runner = Runner(tmp_path, resolver=fake) + probes = [] + host = Host(tmp_path, runner, backend_probe=lambda *args: probes.append(True), + port_probe=lambda: True, listener_probe=lambda run: False, health_probe=lambda: False) + try: + for key in ("prepare", "host.prepare", "contract.generate"): + queued = Run(BY_KEY[key]) + runner.runs.append(queued) + try: + with pytest.raises(Refusal, match="preparation or generation"): + await host.start("pyvoy") + assert probes == [] + finally: + queued.finished.set() + runner.runs.remove(queued) + current = await host.start("pyvoy") + # Insert work after admission but before the worker can launch its process. + queued = Run(BY_KEY["prepare"]) + runner.runs.append(queued) + await asyncio.wait_for(current.run.finished.wait(), 3) + assert current.run.state == "failed" and resolved == [] + queued.finished.set() + runner.runs.remove(queued) + finally: + for run in runner.runs: + if run.worker is None: + run.finished.set() + await host.stop() + await runner.close() + + +async def test_host_starting_preflight_excludes_mutators_until_stopped(tmp_path): + entered, released = threading.Event(), threading.Event() + def probe(*args): + entered.set() + released.wait(1) + runner = Runner(tmp_path, resolver=lambda task, root: ([sys.executable, "-c", "print('fake-only')"], root, dict(os.environ))) + host = Host(tmp_path, runner, backend_probe=probe, port_probe=lambda: True, + listener_probe=lambda run: False, health_probe=lambda: False) + starting = asyncio.create_task(host.start("pyvoy")) + try: + async with asyncio.timeout(2): + while not entered.is_set(): + await asyncio.sleep(0) + for key in ("prepare", "host.prepare", "contract.generate"): + with pytest.raises(Refusal, match="Stop the Host"): + runner.submit(BY_KEY[key]) + stopping = asyncio.create_task(host.stop()) + await asyncio.sleep(0) + assert not stopping.done() + released.set() + await stopping + with pytest.raises(Refusal, match="cancelled"): + await starting + assert runner.runs == [] + finally: + host.generation += 1 + released.set() + await asyncio.gather(starting, return_exceptions=True) + await host.stop() + await runner.close() diff --git a/tools/console/tests/test_contract.py b/tools/console/tests/test_contract.py index a2f65e3a..73ebbf7e 100644 --- a/tools/console/tests/test_contract.py +++ b/tools/console/tests/test_contract.py @@ -149,7 +149,8 @@ def test_console_ci_filter_covers_every_external_reader(root): assert len(arms) == 1 inputs = ("tools/console/lessons_console/new_module.py", ".github/workflows/ci.yml", ".github/dependabot.yml", "docs/build.md", "server/app/config.py", "server/app/db.py", - "server/.env.example", "android/app/build.gradle.kts", ".gitignore") + "server/.env.example", "android/app/build.gradle.kts", ".gitignore", + "server/app/host.py", "server/pyproject.toml", "server/requirements-host.txt", "requirements.txt") assert all(any(fnmatch.fnmatchcase(path, pattern) for pattern in arms[0].split("|")) for path in inputs) assert 'echo "console=true"' in script