From e62be68e0cf32f918f859c537f9e658db4a3c8f7 Mon Sep 17 00:00:00 2001 From: Daniil Pokrovsky Date: Fri, 4 Dec 2026 21:15:35 +0700 Subject: [PATCH] =?UTF-8?q?feat:=20implement=20local-test-e2e-worker-daemo?= =?UTF-8?q?n-idle-auto-update=20-=20test(e2e):=20worker-daemon=20=E2=80=94?= =?UTF-8?q?=20idle=20auto-update=20installs=20a=20newer=20release=20and=20?= =?UTF-8?q?hands=20over?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/e2e/docs/coverage/worker-daemon.md | 14 +- packages/e2e/helpers/auto-update-fixture.ts | 99 +++++++++++++ .../helpers/npm-registry-redirect-preload.cjs | 21 +++ packages/e2e/helpers/worker.ts | 27 +++- .../tests/local/worker-auto-update.test.ts | 130 ++++++++++++++++++ 5 files changed, 279 insertions(+), 12 deletions(-) create mode 100644 packages/e2e/helpers/auto-update-fixture.ts create mode 100644 packages/e2e/helpers/npm-registry-redirect-preload.cjs create mode 100644 packages/e2e/tests/local/worker-auto-update.test.ts diff --git a/packages/e2e/docs/coverage/worker-daemon.md b/packages/e2e/docs/coverage/worker-daemon.md index 1ff3f737a..f1a63b54d 100644 --- a/packages/e2e/docs/coverage/worker-daemon.md +++ b/packages/e2e/docs/coverage/worker-daemon.md @@ -97,10 +97,10 @@ Status values are defined in the [coverage index](../coverage-matrix.md#status-l ### Auto-update - Surface: `devintern worker` surface -- Status: `gap` -- Evidence: — -- Missing: Disabled in tests; simulate an available update safely. -- Last reviewed: 2026-11-17 +- Status: `default` +- Evidence: `tests/local/worker-auto-update.test.ts` (`bun run --filter @devintern/e2e test`). The built bundle is copied to `/prefix/lib/node_modules/@getdevintern/code` so install detection is real (`npm-global`); a loopback fake serves the registry `latest` document, and a `PATH` shim stands in for `npm`. (a) An idle worker with a newer `latest` calls the shim exactly once with `install -g @getdevintern/code@99.0.0` and logs the update, then exits 1 (service-manager path). (b) A worker running a slow agent task logs "waiting for idle" and makes no install until the task settles. (c) `[worker] auto_update = false` and `--no-update` install nothing and send no further registry requests across ticks. (d) A failing install logs the failure, is not retried on the next ticks, and the worker keeps serving an injected task. +- Missing: The successor-spawn path (no service manager; tests set `DEVINTERN_SERVICE=1`). Re-exec onto the new binary (the shim installs nothing). Real `bun-global` layout. Observed (unconfirmed intent): with `[worker] auto_update = false` the CLI startup notice still reads the registry once (it never installs); `--no-update` sends no request. +- Last reviewed: 2026-12-04 ### Team routing, `env_file`, per-repo env @@ -140,7 +140,7 @@ Priority numbers are the global ranking from the [index](../coverage-matrix.md#priority-backlog); lower runs first. - Priority 13: Quiet hours, concurrency, and orphan recovery on a deterministic local workspace. Scheduled automations are implemented by `tests/local/worker-automations.test.ts`. Scheduled estimations are implemented by `tests/local/worker-scheduled-estimation.test.ts`. -- Priority 18: Native service install and auto-update in a sandboxed user-scope fixture. The systemd install is covered by `tests/service/systemd-service.test.ts`; launchd and auto-update remain. +- Priority 18: Native service install and auto-update in a sandboxed user-scope fixture. The systemd install is covered by `tests/service/systemd-service.test.ts`; launchd remains. ~~Auto-update~~ is covered by `tests/local/worker-auto-update.test.ts`. ## Test notes @@ -248,3 +248,7 @@ bun run --filter @devintern/e2e test - How: `WorkerFixture` with the deterministic fake agent, a loopback `FakeGitlabForge` (optional `ci` failure), and git fetch/push rewritten onto the local bare repository by `helpers/gitlab-worker-follow-up.ts` (shared with `worker-conflict-failover.test.ts` and `worker-relay-gitlab-events.test.ts`), which also registers MR !1 in `agent_prs`. The poll cases use `poll_interval = 1` and count `merge_requests/1/discussions` reads as completed ticks, not sleeps. The relay case uses `FakeRelay` with `poll_interval = 3600` and waits for the cursor to move past each envelope. The forge and relay tokens are random per test. A refusing recording proxy is set as `HTTP(S)_PROXY`, and the test asserts it saw no request, and that no token (raw or URL-encoded) appears in worker output, `worker runs --json`, forge notes, or files under the fixture root. Assertions read the forge request and mutation logs, the git argv log, the bare repository, `processed_events`, the run table, and `worker runs --json`. - Run: `bun run --filter @getdevintern/code build`, then `bun run --filter @devintern/e2e test` (or `bun test tests/local/worker-gitlab-follow-up-opt-outs.test.ts` from `packages/e2e`). - Prerequisites: the built CLI and `git`. No network or credentials. About 20 s for the three tests. + +### `tests/local/worker-auto-update.test.ts` + +Run: `bun run --filter @devintern/e2e test` (needs `bun run --filter @getdevintern/code build` first; skipped when `packages/code/dist/index.js` is absent). No other prerequisites, and no request leaves loopback. The daemon preloads `helpers/npm-registry-redirect-preload.cjs`, which redirects `https://registry.npmjs.org` to the fake and shortens the 60 s update tick to 1 s; `helpers/auto-update-fixture.ts` builds the fake global install, registry, and `npm` shim. Takes about 20 s. diff --git a/packages/e2e/helpers/auto-update-fixture.ts b/packages/e2e/helpers/auto-update-fixture.ts new file mode 100644 index 000000000..3381b5aae --- /dev/null +++ b/packages/e2e/helpers/auto-update-fixture.ts @@ -0,0 +1,99 @@ +/** + * Idle auto-update fixture: a fake global npm install, a loopback registry + * that serves the `latest` document, and an `npm` shim that records its argv + * instead of installing anything. + */ + +import { + chmodSync, + cpSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { cliPath } from "./fixture-workspace"; +import { WorkerFixture } from "./worker"; +import type { WorkerFixtureOptions } from "./worker"; + +const preload = resolve(import.meta.dir, "npm-registry-redirect-preload.cjs"); + +/** Version the fake registry advertises as `latest`. */ +export const NEWER_VERSION = "99.0.0"; + +/** Loopback stand-in for `https://registry.npmjs.org`. */ +export class FakeNpmRegistry { + /** Request paths received, in order. */ + readonly requests: string[] = []; + private readonly server = Bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch: (request) => { + this.requests.push(new URL(request.url).pathname); + return Response.json({ name: "@getdevintern/code", version: NEWER_VERSION }); + }, + }); + + get url(): string { + return `http://127.0.0.1:${this.server.port}`; + } + + async stop(): Promise { + await this.server.stop(true); + } +} + +/** + * A worker running from a copy of the built bundle laid out as an npm global + * install (`/prefix/lib/node_modules/@getdevintern/code`), so install-kind + * detection is real, with the registry and `npm` faked. + */ +export class AutoUpdateWorker extends WorkerFixture { + readonly registry = new FakeNpmRegistry(); + private readonly argvLog: string; + + constructor(options: WorkerFixtureOptions & { npmExitCode?: number } = {}) { + const { npmExitCode, ...rest } = options; + const root = mkdtempSync(join(tmpdir(), "devintern-e2e-auto-update-")); + const pkgDir = join(root, "prefix/lib/node_modules/@getdevintern/code"); + // A copy, not a symlink: detection follows realpath, which would land in + // `packages/code` and classify the install as local. + mkdirSync(pkgDir, { recursive: true }); + cpSync(dirname(cliPath), join(pkgDir, "dist"), { recursive: true }); + super({ + ...rest, + root, + daemonEntry: join(pkgDir, "dist/index.js"), + daemonBunArgs: ["--preload", preload], + env: { DEVINTERN_SERVICE: "1", ...rest.env }, + }); + this.argvLog = join(root, "npm-argv.log"); + const bin = join(root, "bin"); + mkdirSync(bin, { recursive: true }); + writeFileSync( + join(bin, "npm"), + `#!/bin/sh\necho "$*" >> ${JSON.stringify(this.argvLog)}\nexit ${npmExitCode ?? 0}\n`, + ); + chmodSync(join(bin, "npm"), 0o755); + this.env.PATH = `${bin}:${this.env.PATH}`; + this.env.E2E_NPM_REGISTRY_URL = this.registry.url; + delete this.env.DEVINTERN_NO_UPDATE; + } + + /** Argument lines the `npm` shim was called with. */ + npmCalls(): string[] { + if (!existsSync(this.argvLog)) return []; + return readFileSync(this.argvLog, "utf8").trim().split("\n").filter(Boolean); + } + + override async dispose(): Promise { + try { + await super.dispose(); + } finally { + await this.registry.stop(); + } + } +} diff --git a/packages/e2e/helpers/npm-registry-redirect-preload.cjs b/packages/e2e/helpers/npm-registry-redirect-preload.cjs new file mode 100644 index 000000000..6695b572a --- /dev/null +++ b/packages/e2e/helpers/npm-registry-redirect-preload.cjs @@ -0,0 +1,21 @@ +// Bun `--preload` for a worker daemon: sends every request for +// https://registry.npmjs.org to the loopback fake named by E2E_NPM_REGISTRY_URL +// and shortens the 60 s idle auto-update tick (`WORKER_AUTO_UPDATE_TICK_MS`) to +// 1 s. Only processes started with `--preload` load this file. +const target = process.env.E2E_NPM_REGISTRY_URL; +if (target) { + const fetchOriginal = globalThis.fetch; + const redirect = (url) => url.replace(/^https:\/\/registry\.npmjs\.org/, target); + globalThis.fetch = function (input, init) { + if (typeof input === "string") return fetchOriginal.call(this, redirect(input), init); + if (input instanceof URL) return fetchOriginal.call(this, redirect(input.href), init); + if (input instanceof Request && input.url.startsWith("https://registry.npmjs.org")) { + return fetchOriginal.call(this, new Request(redirect(input.url), input), init); + } + return fetchOriginal.call(this, input, init); + }; + const setIntervalOriginal = globalThis.setInterval; + globalThis.setInterval = function (callback, delay, ...args) { + return setIntervalOriginal.call(this, callback, delay === 60_000 ? 1_000 : delay, ...args); + }; +} diff --git a/packages/e2e/helpers/worker.ts b/packages/e2e/helpers/worker.ts index b8c58e831..85dfea7a2 100644 --- a/packages/e2e/helpers/worker.ts +++ b/packages/e2e/helpers/worker.ts @@ -267,6 +267,10 @@ export interface WorkerFixtureOptions { env?: Record; /** Bun runtime flags for the daemon only, placed before the CLI path (e.g. `--preload`). */ daemonBunArgs?: string[]; + /** Built CLI entry the daemon runs; defaults to `packages/code/dist/index.js`. */ + daemonEntry?: string; + /** Extra CLI arguments appended after `worker` for the daemon (e.g. `--no-update`). */ + daemonArgs?: string[]; /** Repo names to seed; defaults to one fixture repo. */ repos?: string[]; /** Prefix for the isolated temporary directory. */ @@ -535,13 +539,22 @@ export class WorkerFixture { start(): void { if (this.child) throw new Error("Worker fixture is already started"); const bunArgs = this.options.daemonBunArgs ?? []; - const child = Bun.spawn([process.execPath, ...bunArgs, cliPath, "worker"], { - cwd: this.workspaceDir, - env: this.env, - stdout: "pipe", - stderr: "pipe", - detached: true, - }); + const child = Bun.spawn( + [ + process.execPath, + ...bunArgs, + this.options.daemonEntry ?? cliPath, + "worker", + ...(this.options.daemonArgs ?? []), + ], + { + cwd: this.workspaceDir, + env: this.env, + stdout: "pipe", + stderr: "pipe", + detached: true, + }, + ); this.child = child; this.exitCode = undefined; this.output = ""; diff --git a/packages/e2e/tests/local/worker-auto-update.test.ts b/packages/e2e/tests/local/worker-auto-update.test.ts new file mode 100644 index 000000000..82c139066 --- /dev/null +++ b/packages/e2e/tests/local/worker-auto-update.test.ts @@ -0,0 +1,130 @@ +import { expect, test } from "bun:test"; +import { existsSync, mkdirSync } from "node:fs"; +import { join } from "node:path"; + +import { AutoUpdateWorker, NEWER_VERSION } from "../../helpers/auto-update-fixture"; +import { cliPath } from "../../helpers/worker"; +import type { WorkerFixtureOptions } from "../../helpers/worker"; + +const installCall = `install -g @getdevintern/code@${NEWER_VERSION}`; +const workerTable = (autoUpdate: boolean) => `\n[worker]\nauto_update = ${autoUpdate}`; + +/** A worker with an empty markdown task source, so it stays up idle. */ +function idleWorker( + options: WorkerFixtureOptions & { npmExitCode?: number } = {}, +): AutoUpdateWorker { + const { workspaceTomlExtra, ...rest } = options; + return new AutoUpdateWorker({ + ...rest, + workspaceTomlExtra: ['task_query = "status=todo"', workspaceTomlExtra] + .filter(Boolean) + .join("\n"), + }); +} + +async function boot(worker: AutoUpdateWorker): Promise { + await worker.prepare(); + const tasksDir = join(worker.root, "markdown-tasks"); + mkdirSync(tasksDir, { recursive: true }); + worker.env.MARKDOWN_TASKS_DIR = tasksDir; +} + +test.skipIf(!existsSync(cliPath))( + "an idle worker installs a newer release, then exits for the service manager", + async () => { + const worker = idleWorker(); + try { + await boot(worker); + worker.start(); + const deadline = Date.now() + 40_000; + while (worker.exitStatus === undefined && Date.now() < deadline) await Bun.sleep(100); + await worker.stop(); + expect(worker.logs).toMatch(/Updated devintern to 99\.0\.0/); + expect(worker.npmCalls(), worker.tail()).toEqual([installCall]); + expect(worker.registry.requests).toEqual(["/@getdevintern/code/latest"]); + expect(worker.exitStatus, worker.tail()).toBe(1); + expect(worker.logs).toContain("restart-requested status"); + } finally { + await worker.dispose(); + } + }, + 90_000, +); + +test.skipIf(!existsSync(cliPath))( + "a busy worker installs only after its task settles", + async () => { + const worker = idleWorker({ env: { E2E_AGENT_DELAY_MS: "6000" } }); + try { + await boot(worker); + const task = await worker.addTask({ title: "Stay busy", body: "Change the greeting." }); + worker.start(); + await worker.waitForOutput( + /agent work is in progress; waiting for idle/, + 40_000, + "busy wait", + ); + expect(worker.npmCalls()).toEqual([]); + await worker.waitForSettled(task.id); + await worker.waitForOutput(/Updated devintern to 99\.0\.0/, 40_000, "the update"); + expect(worker.npmCalls(), worker.tail()).toEqual([installCall]); + } finally { + await worker.dispose(); + } + }, + 120_000, +); + +test.skipIf(!existsSync(cliPath))( + "[worker] auto_update = false and --no-update install nothing and poll no further", + async () => { + const configOff = idleWorker({ workspaceTomlExtra: workerTable(false) }); + const flagOff = idleWorker({ daemonArgs: ["--no-update"] }); + try { + for (const [worker, pattern] of [ + [configOff, /disabled by \[worker\] auto_update = false/], + [flagOff, /disabled by DEVINTERN_NO_UPDATE\/--no-update/], + ] as const) { + await boot(worker); + worker.start(); + await worker.waitForOutput(pattern, 40_000, "opt-out notice"); + } + // Observed: the CLI's startup notice (non-installing) still reads the + // registry once before the worker starts, even with auto_update = false. + const startupRequests = configOff.registry.requests.length; + expect(startupRequests).toBeLessThanOrEqual(1); + // Several more 1 s ticks must stay quiet. + await Bun.sleep(3_000); + expect(configOff.registry.requests).toHaveLength(startupRequests); + expect(flagOff.registry.requests, flagOff.tail()).toEqual([]); + for (const worker of [configOff, flagOff]) { + expect(worker.npmCalls()).toEqual([]); + expect(worker.running, worker.tail()).toBe(true); + } + } finally { + await Promise.allSettled([configOff.dispose(), flagOff.dispose()]); + } + }, + 90_000, +); + +test.skipIf(!existsSync(cliPath))( + "a failed install is non-fatal and is not retried on the next ticks", + async () => { + const worker = idleWorker({ npmExitCode: 1 }); + try { + await boot(worker); + worker.start(); + await worker.waitForOutput(/Failed to update devintern/, 40_000, "install failure"); + await Bun.sleep(3_000); + expect(worker.npmCalls()).toEqual([installCall]); + expect(worker.running, worker.tail()).toBe(true); + const task = await worker.addTask({ title: "Still served", body: "Change the greeting." }); + const settled = await worker.waitForSettled(task.id); + expect(settled.task.status).toBe("done"); + } finally { + await worker.dispose(); + } + }, + 120_000, +);