feat: add dev update channel

This commit is contained in:
Peter Steinberger
2026-01-20 13:33:31 +00:00
parent cc24ede586
commit 4ebf55f1db
14 changed files with 378 additions and 123 deletions

View File

@@ -120,7 +120,7 @@ describe("update-cli", () => {
expect(defaultRuntime.log).toHaveBeenCalled();
});
it("defaults to stable channel when unset", async () => {
it("defaults to dev channel for git installs when unset", async () => {
const { runGatewayUpdate } = await import("../infra/update-runner.js");
const { updateCommand } = await import("./update-cli.js");
@@ -134,7 +134,38 @@ describe("update-cli", () => {
await updateCommand({});
const call = vi.mocked(runGatewayUpdate).mock.calls[0]?.[0];
expect(call?.tag).toBe("latest");
expect(call?.channel).toBe("dev");
});
it("defaults to stable channel for package installs when unset", async () => {
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-update-"));
try {
await fs.writeFile(
path.join(tempDir, "package.json"),
JSON.stringify({ name: "clawdbot", version: "1.0.0" }),
"utf-8",
);
const { resolveClawdbotPackageRoot } = await import("../infra/clawdbot-root.js");
const { runGatewayUpdate } = await import("../infra/update-runner.js");
const { updateCommand } = await import("./update-cli.js");
vi.mocked(resolveClawdbotPackageRoot).mockResolvedValue(tempDir);
vi.mocked(runGatewayUpdate).mockResolvedValue({
status: "ok",
mode: "npm",
steps: [],
durationMs: 100,
});
await updateCommand({});
const call = vi.mocked(runGatewayUpdate).mock.calls[0]?.[0];
expect(call?.channel).toBe("stable");
expect(call?.tag).toBe("latest");
} finally {
await fs.rm(tempDir, { recursive: true, force: true });
}
});
it("uses stored beta channel when configured", async () => {
@@ -156,24 +187,37 @@ describe("update-cli", () => {
await updateCommand({});
const call = vi.mocked(runGatewayUpdate).mock.calls[0]?.[0];
expect(call?.tag).toBe("beta");
expect(call?.channel).toBe("beta");
});
it("honors --tag override", async () => {
const { runGatewayUpdate } = await import("../infra/update-runner.js");
const { updateCommand } = await import("./update-cli.js");
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "clawdbot-update-"));
try {
await fs.writeFile(
path.join(tempDir, "package.json"),
JSON.stringify({ name: "clawdbot", version: "1.0.0" }),
"utf-8",
);
vi.mocked(runGatewayUpdate).mockResolvedValue({
status: "ok",
mode: "git",
steps: [],
durationMs: 100,
});
const { resolveClawdbotPackageRoot } = await import("../infra/clawdbot-root.js");
const { runGatewayUpdate } = await import("../infra/update-runner.js");
const { updateCommand } = await import("./update-cli.js");
await updateCommand({ tag: "next" });
vi.mocked(resolveClawdbotPackageRoot).mockResolvedValue(tempDir);
vi.mocked(runGatewayUpdate).mockResolvedValue({
status: "ok",
mode: "npm",
steps: [],
durationMs: 100,
});
const call = vi.mocked(runGatewayUpdate).mock.calls[0]?.[0];
expect(call?.tag).toBe("next");
await updateCommand({ tag: "next" });
const call = vi.mocked(runGatewayUpdate).mock.calls[0]?.[0];
expect(call?.tag).toBe("next");
} finally {
await fs.rm(tempDir, { recursive: true, force: true });
}
});
it("updateCommand outputs JSON when --json is set", async () => {

View File

@@ -13,6 +13,13 @@ import {
type UpdateStepInfo,
type UpdateStepProgress,
} from "../infra/update-runner.js";
import {
channelToNpmTag,
DEFAULT_GIT_CHANNEL,
DEFAULT_PACKAGE_CHANNEL,
normalizeUpdateChannel,
type UpdateChannel,
} from "../infra/update-channels.js";
import { defaultRuntime } from "../runtime.js";
import { formatDocsLink } from "../terminal/links.js";
import { formatCliCommand } from "./command-format.js";
@@ -40,9 +47,6 @@ const STEP_LABELS: Record<string, string> = {
"global update": "Updating via package manager",
};
type UpdateChannel = "stable" | "beta";
const DEFAULT_UPDATE_CHANNEL: UpdateChannel = "stable";
const UPDATE_QUIPS = [
"Leveled up! New skills unlocked. You're welcome.",
"Fresh code, same lobster. Miss me?",
@@ -66,13 +70,6 @@ const UPDATE_QUIPS = [
"Version bump! Same chaos energy, fewer crashes (probably).",
];
function normalizeChannel(value?: string | null): UpdateChannel | null {
if (!value) return null;
const normalized = value.trim().toLowerCase();
if (normalized === "stable" || normalized === "beta") return normalized;
return null;
}
function normalizeTag(value?: string | null): string | null {
if (!value) return null;
const trimmed = value.trim();
@@ -80,10 +77,6 @@ function normalizeTag(value?: string | null): string | null {
return trimmed.startsWith("clawdbot@") ? trimmed.slice("clawdbot@".length) : trimmed;
}
function channelToTag(channel: UpdateChannel): string {
return channel === "beta" ? "beta" : "latest";
}
function pickUpdateQuip(): string {
return UPDATE_QUIPS[Math.floor(Math.random() * UPDATE_QUIPS.length)] ?? "Update complete.";
}
@@ -263,12 +256,12 @@ export async function updateCommand(opts: UpdateCommandOptions): Promise<void> {
const configSnapshot = await readConfigFileSnapshot();
const storedChannel = configSnapshot.valid
? normalizeChannel(configSnapshot.config.update?.channel)
? normalizeUpdateChannel(configSnapshot.config.update?.channel)
: null;
const requestedChannel = normalizeChannel(opts.channel);
const requestedChannel = normalizeUpdateChannel(opts.channel);
if (opts.channel && !requestedChannel) {
defaultRuntime.error(`--channel must be "stable" or "beta" (got "${opts.channel}")`);
defaultRuntime.error(`--channel must be "stable", "beta", or "dev" (got "${opts.channel}")`);
defaultRuntime.exit(1);
return;
}
@@ -279,10 +272,10 @@ export async function updateCommand(opts: UpdateCommandOptions): Promise<void> {
return;
}
const channel = requestedChannel ?? storedChannel ?? DEFAULT_UPDATE_CHANNEL;
const tag = normalizeTag(opts.tag) ?? channelToTag(channel);
const gitCheckout = await isGitCheckout(root);
const defaultChannel = gitCheckout ? DEFAULT_GIT_CHANNEL : DEFAULT_PACKAGE_CHANNEL;
const channel = requestedChannel ?? storedChannel ?? defaultChannel;
const tag = normalizeTag(opts.tag) ?? channelToNpmTag(channel);
if (!gitCheckout) {
const currentVersion = await readPackageVersion(root);
const targetVersion = await resolveTargetVersion(tag, timeoutMs);
@@ -317,9 +310,9 @@ export async function updateCommand(opts: UpdateCommandOptions): Promise<void> {
return;
}
}
} else if ((opts.channel || opts.tag) && !opts.json) {
} else if (opts.tag && !opts.json) {
defaultRuntime.log(
theme.muted("Note: --channel/--tag apply to npm installs only; git updates ignore them."),
theme.muted("Note: --tag applies to npm installs only; git updates ignore it."),
);
}
@@ -351,6 +344,7 @@ export async function updateCommand(opts: UpdateCommandOptions): Promise<void> {
argv1: process.argv[1],
timeoutMs,
progress,
channel,
tag,
});
@@ -445,7 +439,7 @@ export function registerUpdateCli(program: Command) {
.description("Update Clawdbot to the latest version")
.option("--json", "Output result as JSON", false)
.option("--restart", "Restart the gateway daemon after a successful update", false)
.option("--channel <stable|beta>", "Persist update channel (npm installs only)")
.option("--channel <stable|beta|dev>", "Persist update channel (git + npm)")
.option("--tag <dist-tag|version>", "Override npm dist-tag or version for this update")
.option("--timeout <seconds>", "Timeout for each update step in seconds (default: 1200)")
.addHelpText(
@@ -454,7 +448,8 @@ export function registerUpdateCli(program: Command) {
`
Examples:
clawdbot update # Update a source checkout (git)
clawdbot update --channel beta # Switch to the beta channel (npm installs)
clawdbot update --channel beta # Switch to beta channel (git + npm)
clawdbot update --channel dev # Switch to dev channel (git + npm)
clawdbot update --tag beta # One-off update to a dist-tag or version
clawdbot update --restart # Update and restart the daemon
clawdbot update --json # Output result as JSON

View File

@@ -309,7 +309,7 @@ const FIELD_LABELS: Record<string, string> = {
const FIELD_HELP: Record<string, string> = {
"meta.lastTouchedVersion": "Auto-set when Clawdbot writes the config.",
"meta.lastTouchedAt": "ISO timestamp of the last config write (auto-set).",
"update.channel": 'Update channel for npm installs ("stable" or "beta").',
"update.channel": 'Update channel for git + npm installs ("stable", "beta", or "dev").',
"update.checkOnStart": "Check for npm updates when the gateway starts (default: true).",
"gateway.remote.url": "Remote Gateway WebSocket URL (ws:// or wss://).",
"gateway.remote.tlsFingerprint":

View File

@@ -55,8 +55,8 @@ export type ClawdbotConfig = {
};
logging?: LoggingConfig;
update?: {
/** Update channel for npm installs ("stable" or "beta"). */
channel?: "stable" | "beta";
/** Update channel for git + npm installs ("stable", "beta", or "dev"). */
channel?: "stable" | "beta" | "dev";
/** Check for updates on gateway start (npm installs only). */
checkOnStart?: boolean;
};

View File

@@ -73,7 +73,7 @@ export const ClawdbotSchema = z
.optional(),
update: z
.object({
channel: z.union([z.literal("stable"), z.literal("beta")]).optional(),
channel: z.union([z.literal("stable"), z.literal("beta"), z.literal("dev")]).optional(),
checkOnStart: z.boolean().optional(),
})
.strict()

View File

@@ -0,0 +1,26 @@
export type UpdateChannel = "stable" | "beta" | "dev";
export const DEFAULT_PACKAGE_CHANNEL: UpdateChannel = "stable";
export const DEFAULT_GIT_CHANNEL: UpdateChannel = "dev";
export const DEV_BRANCH = "main";
export function normalizeUpdateChannel(value?: string | null): UpdateChannel | null {
if (!value) return null;
const normalized = value.trim().toLowerCase();
if (normalized === "stable" || normalized === "beta" || normalized === "dev") return normalized;
return null;
}
export function channelToNpmTag(channel: UpdateChannel): string {
if (channel === "beta") return "beta";
if (channel === "dev") return "dev";
return "latest";
}
export function isBetaTag(tag: string): boolean {
return tag.toLowerCase().includes("-beta");
}
export function isStableTag(tag: string): boolean {
return !isBetaTag(tag);
}

View File

@@ -43,6 +43,7 @@ describe("runGatewayUpdate", () => {
const { runner, calls } = createRunner({
[`git -C ${tempDir} rev-parse --show-toplevel`]: { stdout: tempDir },
[`git -C ${tempDir} rev-parse HEAD`]: { stdout: "abc123" },
[`git -C ${tempDir} rev-parse --abbrev-ref HEAD`]: { stdout: "main" },
[`git -C ${tempDir} status --porcelain`]: { stdout: " M README.md" },
});
@@ -67,11 +68,12 @@ describe("runGatewayUpdate", () => {
const { runner, calls } = createRunner({
[`git -C ${tempDir} rev-parse --show-toplevel`]: { stdout: tempDir },
[`git -C ${tempDir} rev-parse HEAD`]: { stdout: "abc123" },
[`git -C ${tempDir} rev-parse --abbrev-ref HEAD`]: { stdout: "main" },
[`git -C ${tempDir} status --porcelain`]: { stdout: "" },
[`git -C ${tempDir} rev-parse --abbrev-ref --symbolic-full-name @{upstream}`]: {
stdout: "origin/main",
},
[`git -C ${tempDir} fetch --all --prune`]: { stdout: "" },
[`git -C ${tempDir} fetch --all --prune --tags`]: { stdout: "" },
[`git -C ${tempDir} rebase @{upstream}`]: { code: 1, stderr: "conflict" },
[`git -C ${tempDir} rebase --abort`]: { stdout: "" },
});

View File

@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
import path from "node:path";
import { type CommandOptions, runCommandWithTimeout } from "../process/exec.js";
import { DEV_BRANCH, isBetaTag, isStableTag, type UpdateChannel } from "./update-channels.js";
import { trimLogTail } from "./restart-sentinel.js";
export type UpdateStepResult = {
@@ -53,6 +54,7 @@ type UpdateRunnerOptions = {
cwd?: string;
argv1?: string;
tag?: string;
channel?: UpdateChannel;
timeoutMs?: number;
runCommand?: CommandRunner;
progress?: UpdateStepProgress;
@@ -60,7 +62,6 @@ type UpdateRunnerOptions = {
const DEFAULT_TIMEOUT_MS = 20 * 60_000;
const MAX_LOG_CHARS = 8000;
const START_DIRS = ["cwd", "argv1", "process"];
function normalizeDir(value?: string | null) {
@@ -106,6 +107,46 @@ async function readPackageVersion(root: string) {
}
}
async function readBranchName(
runCommand: CommandRunner,
root: string,
timeoutMs: number,
): Promise<string | null> {
const res = await runCommand(["git", "-C", root, "rev-parse", "--abbrev-ref", "HEAD"], {
timeoutMs,
}).catch(() => null);
if (!res || res.code !== 0) return null;
const branch = res.stdout.trim();
return branch || null;
}
async function listGitTags(
runCommand: CommandRunner,
root: string,
timeoutMs: number,
pattern = "v*",
): Promise<string[]> {
const res = await runCommand(["git", "-C", root, "tag", "--list", pattern, "--sort=-v:refname"], {
timeoutMs,
}).catch(() => null);
if (!res || res.code !== 0) return [];
return res.stdout
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
}
async function resolveChannelTag(
runCommand: CommandRunner,
root: string,
timeoutMs: number,
channel: Exclude<UpdateChannel, "dev">,
): Promise<string | null> {
const tags = await listGitTags(runCommand, root, timeoutMs);
const predicate = channel === "beta" ? isBetaTag : isStableTag;
return tags.find((tag) => predicate(tag)) ?? null;
}
async function resolveGitRoot(
runCommand: CommandRunner,
candidates: string[],
@@ -281,9 +322,6 @@ function globalUpdateArgs(manager: "pnpm" | "npm" | "bun", tag?: string) {
return ["npm", "i", "-g", spec];
}
// Total number of visible steps in a successful git update flow
const GIT_UPDATE_TOTAL_STEPS = 9;
export async function runGatewayUpdate(opts: UpdateRunnerOptions = {}): Promise<UpdateRunResult> {
const startedAt = Date.now();
const runCommand =
@@ -298,6 +336,7 @@ export async function runGatewayUpdate(opts: UpdateRunnerOptions = {}): Promise<
const candidates = buildStartDirs(opts);
let stepIndex = 0;
let gitTotalSteps = 0;
const step = (
name: string,
@@ -316,7 +355,7 @@ export async function runGatewayUpdate(opts: UpdateRunnerOptions = {}): Promise<
env,
progress,
stepIndex: currentIndex,
totalSteps: GIT_UPDATE_TOTAL_STEPS,
totalSteps: gitTotalSteps,
};
};
@@ -346,6 +385,10 @@ export async function runGatewayUpdate(opts: UpdateRunnerOptions = {}): Promise<
});
const beforeSha = beforeShaResult.stdout.trim() || null;
const beforeVersion = await readPackageVersion(gitRoot);
const channel: UpdateChannel = opts.channel ?? "dev";
const branch = channel === "dev" ? await readBranchName(runCommand, gitRoot, timeoutMs) : null;
const needsCheckoutMain = channel === "dev" && branch !== DEV_BRANCH;
gitTotalSteps = channel === "dev" ? (needsCheckoutMain ? 10 : 9) : 8;
const statusCheck = await runStep(
step("clean check", ["git", "-C", gitRoot, "status", "--porcelain"], gitRoot),
@@ -365,58 +408,135 @@ export async function runGatewayUpdate(opts: UpdateRunnerOptions = {}): Promise<
};
}
const upstreamStep = await runStep(
step(
"upstream check",
["git", "-C", gitRoot, "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
gitRoot,
),
);
steps.push(upstreamStep);
if (upstreamStep.exitCode !== 0) {
return {
status: "skipped",
mode: "git",
root: gitRoot,
reason: "no-upstream",
before: { sha: beforeSha, version: beforeVersion },
steps,
durationMs: Date.now() - startedAt,
};
}
if (channel === "dev") {
if (needsCheckoutMain) {
const checkoutStep = await runStep(
step(
`git checkout ${DEV_BRANCH}`,
["git", "-C", gitRoot, "checkout", DEV_BRANCH],
gitRoot,
),
);
steps.push(checkoutStep);
if (checkoutStep.exitCode !== 0) {
return {
status: "error",
mode: "git",
root: gitRoot,
reason: "checkout-failed",
before: { sha: beforeSha, version: beforeVersion },
steps,
durationMs: Date.now() - startedAt,
};
}
}
const fetchStep = await runStep(
step("git fetch", ["git", "-C", gitRoot, "fetch", "--all", "--prune"], gitRoot),
);
steps.push(fetchStep);
const upstreamStep = await runStep(
step(
"upstream check",
[
"git",
"-C",
gitRoot,
"rev-parse",
"--abbrev-ref",
"--symbolic-full-name",
"@{upstream}",
],
gitRoot,
),
);
steps.push(upstreamStep);
if (upstreamStep.exitCode !== 0) {
return {
status: "skipped",
mode: "git",
root: gitRoot,
reason: "no-upstream",
before: { sha: beforeSha, version: beforeVersion },
steps,
durationMs: Date.now() - startedAt,
};
}
const rebaseStep = await runStep(
step("git rebase", ["git", "-C", gitRoot, "rebase", "@{upstream}"], gitRoot),
);
steps.push(rebaseStep);
if (rebaseStep.exitCode !== 0) {
const abortResult = await runCommand(["git", "-C", gitRoot, "rebase", "--abort"], {
cwd: gitRoot,
timeoutMs,
});
steps.push({
name: "git rebase --abort",
command: "git rebase --abort",
cwd: gitRoot,
durationMs: 0,
exitCode: abortResult.code,
stdoutTail: trimLogTail(abortResult.stdout, MAX_LOG_CHARS),
stderrTail: trimLogTail(abortResult.stderr, MAX_LOG_CHARS),
});
return {
status: "error",
mode: "git",
root: gitRoot,
reason: "rebase-failed",
before: { sha: beforeSha, version: beforeVersion },
steps,
durationMs: Date.now() - startedAt,
};
const fetchStep = await runStep(
step("git fetch", ["git", "-C", gitRoot, "fetch", "--all", "--prune", "--tags"], gitRoot),
);
steps.push(fetchStep);
const rebaseStep = await runStep(
step("git rebase", ["git", "-C", gitRoot, "rebase", "@{upstream}"], gitRoot),
);
steps.push(rebaseStep);
if (rebaseStep.exitCode !== 0) {
const abortResult = await runCommand(["git", "-C", gitRoot, "rebase", "--abort"], {
cwd: gitRoot,
timeoutMs,
});
steps.push({
name: "git rebase --abort",
command: "git rebase --abort",
cwd: gitRoot,
durationMs: 0,
exitCode: abortResult.code,
stdoutTail: trimLogTail(abortResult.stdout, MAX_LOG_CHARS),
stderrTail: trimLogTail(abortResult.stderr, MAX_LOG_CHARS),
});
return {
status: "error",
mode: "git",
root: gitRoot,
reason: "rebase-failed",
before: { sha: beforeSha, version: beforeVersion },
steps,
durationMs: Date.now() - startedAt,
};
}
} else {
const fetchStep = await runStep(
step("git fetch", ["git", "-C", gitRoot, "fetch", "--all", "--prune", "--tags"], gitRoot),
);
steps.push(fetchStep);
if (fetchStep.exitCode !== 0) {
return {
status: "error",
mode: "git",
root: gitRoot,
reason: "fetch-failed",
before: { sha: beforeSha, version: beforeVersion },
steps,
durationMs: Date.now() - startedAt,
};
}
const tag = await resolveChannelTag(runCommand, gitRoot, timeoutMs, channel);
if (!tag) {
return {
status: "error",
mode: "git",
root: gitRoot,
reason: "no-release-tag",
before: { sha: beforeSha, version: beforeVersion },
steps,
durationMs: Date.now() - startedAt,
};
}
const checkoutStep = await runStep(
step(`git checkout ${tag}`, ["git", "-C", gitRoot, "checkout", "--detach", tag], gitRoot),
);
steps.push(checkoutStep);
if (checkoutStep.exitCode !== 0) {
return {
status: "error",
mode: "git",
root: gitRoot,
reason: "checkout-failed",
before: { sha: beforeSha, version: beforeVersion },
steps,
durationMs: Date.now() - startedAt,
};
}
}
const manager = await detectPackageManager(gitRoot);

View File

@@ -5,6 +5,11 @@ import type { loadConfig } from "../config/config.js";
import { resolveStateDir } from "../config/paths.js";
import { resolveClawdbotPackageRoot } from "./clawdbot-root.js";
import { compareSemverStrings, fetchNpmTagVersion, checkUpdateStatus } from "./update-check.js";
import {
channelToNpmTag,
normalizeUpdateChannel,
DEFAULT_PACKAGE_CHANNEL,
} from "./update-channels.js";
import { VERSION } from "../version.js";
import { formatCliCommand } from "../cli/command-format.js";
@@ -17,17 +22,6 @@ type UpdateCheckState = {
const UPDATE_CHECK_FILENAME = "update-check.json";
const UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
function normalizeChannel(value?: string | null): "stable" | "beta" | null {
if (!value) return null;
const normalized = value.trim().toLowerCase();
if (normalized === "stable" || normalized === "beta") return normalized;
return null;
}
function channelToTag(channel: "stable" | "beta"): string {
return channel === "beta" ? "beta" : "latest";
}
function shouldSkipCheck(allowInTests: boolean): boolean {
if (allowInTests) return false;
if (process.env.VITEST || process.env.NODE_ENV === "test") return true;
@@ -89,8 +83,8 @@ export async function runGatewayUpdateCheck(params: {
return;
}
const channel = normalizeChannel(params.cfg.update?.channel) ?? "stable";
const tag = channelToTag(channel);
const channel = normalizeUpdateChannel(params.cfg.update?.channel) ?? DEFAULT_PACKAGE_CHANNEL;
const tag = channelToNpmTag(channel);
const tagStatus = await fetchNpmTagVersion({ tag, timeoutMs: 2500 });
if (!tagStatus.version) {
await writeState(statePath, nextState);