diff --git a/packages/opencode/src/ockit/doctor.ts b/packages/opencode/src/ockit/doctor.ts new file mode 100644 index 000000000..78cac1ff5 --- /dev/null +++ b/packages/opencode/src/ockit/doctor.ts @@ -0,0 +1,156 @@ +// OC Kit doctor. Produces a typed `DoctorReport` evaluating: the runtime +// OpenCode version, OC Kit config, installed kits, remote registry +// reachability (skipped when `--offline`), ownership conflicts / user edits, +// broken manifests, and checkpoint count. Never crashes when nothing is +// installed — every section reports pass/warn/fail items. + +import { Effect, Schema } from "effect" +import { HttpClient } from "effect/unstable/http" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Global } from "@opencode-ai/core/global" +import { InstallationVersion } from "@opencode-ai/core/installation/version" +import path from "path" +import { Service as Registry } from "./registry" +import { loadOwnership, detectUserEdits } from "./ownership" +import { Checkpoint } from "./checkpoint" +import { resolveLatest, type RemoteRegistrySource } from "./registry-remote" +import { COLLECTED_ROOT_DIR } from "./installer" + +export class DoctorItem extends Schema.Class("OCKit.DoctorItem")({ + severity: Schema.Literals(["pass", "warn", "fail"]), + section: Schema.String, + message: Schema.String, +}) {} + +export class DoctorReport extends Schema.Class("OCKit.DoctorReport")({ + runtimeVersion: Schema.String, + offline: Schema.Boolean, + items: Schema.Array(DoctorItem), +}) { + get failures(): DoctorItem[] { + return this.items.filter((item) => item.severity === "fail") + } +} + +export interface DoctorOptions { + readonly offline?: boolean + readonly http?: HttpClient.HttpClient + readonly source?: RemoteRegistrySource + readonly root?: string + /** Injection point for installed kits (defaults to `Registry.Service`). */ + readonly kits?: readonly { id: string; version?: string }[] + readonly config?: Readonly> +} + +const defaultRoot = () => Global.Path.config + +/** + * Run a doctor health check, producing a typed report. The config section reads + * `oc_kit` presence; the registry section checks reachability unless offline. + */ +export const doctor = Effect.fn("OCKit.doctor")(function* (opts: DoctorOptions = {}) { + const fsutil = yield* FSUtil.Service + const root = opts.root ?? defaultRoot() + const offline = opts.offline === true + + const items: DoctorItem[] = [] + + // 1. Runtime version + items.push( + new DoctorItem({ + severity: "pass", + section: "runtime", + message: `OpenCode ${InstallationVersion}`, + }), + ) + + // 2. Config + const config = opts.config ?? {} + const ocKit = config.oc_kit + if (ocKit === undefined) { + items.push(new DoctorItem({ severity: "warn", section: "config", message: "no oc_kit section in config (using defaults)" })) + } else { + items.push(new DoctorItem({ severity: "pass", section: "config", message: "oc_kit section present" })) + } + + // 3. Installed kits + const installed = opts.kits ?? (yield* installedKits()) + if (installed.length === 0) { + items.push(new DoctorItem({ severity: "warn", section: "kits", message: "no OC Kit kits installed" })) + } else { + items.push( + new DoctorItem({ + severity: "pass", + section: "kits", + message: `${installed.length} kit(s) installed: ${installed.map((k) => k.id).join(", ")}`, + }), + ) + } + + // 4. Registry reachability + if (offline) { + items.push(new DoctorItem({ severity: "pass", section: "registry", message: "offline — skipped reachability check" })) + } else { + const http = opts.http ?? (yield* HttpClient.HttpClient) + const probe = yield* resolveLatest("engineer", { http, source: opts.source }).pipe(Effect.exit) + if (probe._tag === "Success") { + items.push(new DoctorItem({ severity: "pass", section: "registry", message: `registry reachable (latest engineer release ${probe.value.version})` })) + } else { + items.push(new DoctorItem({ severity: "warn", section: "registry", message: "registry probe failed (release list or compatibility)" })) + } + } + + // 5. Ownership conflicts + user edits + const manifest = yield* loadOwnership(root).pipe(Effect.orElseSucceed(() => ({ files: {} as Record }))) + const ownedFiles = Object.entries(manifest.files) + if (ownedFiles.length === 0) { + items.push(new DoctorItem({ severity: "pass", section: "ownership", message: "no owned files recorded" })) + } else { + const kitsOwned = new Set(ownedFiles.map(([, e]) => e.kit)) + if (kitsOwned.size > 1) { + items.push(new DoctorItem({ severity: "warn", section: "ownership", message: `${kitsOwned.size} kits share the ownership manifest` })) + } else { + items.push(new DoctorItem({ severity: "pass", section: "ownership", message: `${ownedFiles.length} owned file(s) tracked` })) + } + const edits = yield* detectUserEdits(fsutil, root, manifest).pipe(Effect.orElseSucceed(() => [] as string[])) + if (edits.length > 0) { + items.push(new DoctorItem({ severity: "warn", section: "ownership", message: `${edits.length} user-modified file(s): ${edits.slice(0, 3).join(", ")}` })) + } else { + items.push(new DoctorItem({ severity: "pass", section: "ownership", message: "no user-modified files" })) + } + } + + // 6. Broken manifests under /kits// + const kitsDir = path.join(root, COLLECTED_ROOT_DIR) + if (yield* fsutil.isDir(kitsDir)) { + const entries = yield* fsutil.readDirectoryEntries(kitsDir) + const dirs = entries.filter((e) => e.type === "directory") + for (const dir of dirs) { + const kitDir = path.join(kitsDir, dir.name) + const hasJson = yield* fsutil.existsSafe(path.join(kitDir, "kit.json")) + const hasYaml = yield* fsutil.existsSafe(path.join(kitDir, "kit.yaml")) + if (!hasJson && !hasYaml) { + items.push(new DoctorItem({ severity: "warn", section: "manifests", message: `kit "${dir.name}" missing kit.json/kit.yaml` })) + } + } + } + + // 7. Checkpoint count + const cpIds = yield* Checkpoint.list(root).pipe(Effect.orElseSucceed(() => [] as string[])) + items.push(new DoctorItem({ severity: "pass", section: "checkpoints", message: `${cpIds.length} checkpoint(s)` })) + + return new DoctorReport({ + runtimeVersion: InstallationVersion, + offline, + items, + }) +}) + +/** Installed kits via the local Registry.Service (which scans config + project). */ +const installedKits = Effect.fn("OCKit.doctor.installedKits")(function* () { + const registry = yield* Registry + const kits = yield* registry.all() + return kits.map((k) => ({ id: k.id, version: k.version })) +}) + +export * as Doctor from "./doctor" \ No newline at end of file diff --git a/packages/opencode/src/ockit/installer.ts b/packages/opencode/src/ockit/installer.ts new file mode 100644 index 000000000..5348aba4a --- /dev/null +++ b/packages/opencode/src/ockit/installer.ts @@ -0,0 +1,355 @@ +// OC Kit installer. Given a kit id + remote registry source, resolves the +// release, downloads the archive over HttpClient, verifies its sha256 against +// the release checksums, stages and extracts the files, then writes them into +// the kit directory under `/kits//` while recording ownership (via +// `claim`) and a pre-operation checkpoint. +// +// The extraction step is injectable so tests can run the full pipeline with an +// in-memory archive reader while production uses the on-disk `Archive` util +// (zip) / `tar` (tar.gz). Ownership paths are recorded root-relative so +// `detectUserEdits` / `planUpdate` resolve against the same root. + +import { Effect, Schema } from "effect" +import { HttpClient, HttpClientRequest } from "effect/unstable/http" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Hash } from "@opencode-ai/core/util/hash" +import { Global } from "@opencode-ai/core/global" +import { Process } from "../util/process" +import path from "path" +import { resolveLatest, ReleaseInfo, type RemoteRegistrySource } from "./registry-remote" +import { loadOwnership, saveOwnership, claim } from "./ownership" +import type { OwnershipEntry } from "./types" +import { Checkpoint } from "./checkpoint" +import { loadManifest } from "./manifest" + +export class InstallerError extends Schema.TaggedErrorClass()("OCKitInstallerError", { + kind: Schema.Literals(["fetch", "checksum", "extract", "conflict", "write", "manifest", "not-found"]), + kit: Schema.String, + detail: Schema.String, + version: Schema.optional(Schema.String), +}) { + override get message(): string { + return `OC Kit installer: ${this.kind} for "${this.kit}"${this.version ? ` ${this.version}` : ""} — ${this.detail}` + } +} + +export class InstallSummary extends Schema.Class("OCKit.InstallSummary")({ + kitId: Schema.String, + version: Schema.String, + dir: Schema.String, + filesInstalled: Schema.Array(Schema.String), + mode: Schema.Literals(["production", "development"]), +}) {} + +export interface InstallOptions { + readonly version?: string + readonly source?: RemoteRegistrySource + readonly dev?: boolean + readonly http?: HttpClient.HttpClient + readonly root?: string + /** Test seam: extract archive bytes into staged files. Defaults to the real extraction util. */ + readonly extract?: (archive: Uint8Array, dest: string) => Effect.Effect +} + +const defaultRoot = () => Global.Path.config + +export const COLLECTED_ROOT_DIR = "kits" + +const download = Effect.fn("OCKit.install.download")(function* (http: HttpClient.HttpClient, url: string) { + const response = yield* http.execute(HttpClientRequest.get(url)).pipe( + Effect.mapError((err) => new InstallerError({ kind: "fetch", kit: url, detail: `HTTP request failed: ${String(err)}` })), + ) + if (response.status !== 200) { + return yield* new InstallerError({ kind: "fetch", kit: url, detail: `HTTP ${response.status}` }) + } + const body = yield* response.arrayBuffer + return new Uint8Array(body) +}) + +/** Recursively collect `relative path -> content` for every file under `dir`. */ +export const collectFiles = Effect.fn("OCKit.install.collectFiles")(function* ( + fs: FSUtil.Interface, + dir: string, +) { + const result: Record = {} + const walk = (current: string, rel: string): Effect.Effect => + Effect.gen(function* () { + const entries = yield* fs.readDirectoryEntries(current) + for (const entry of entries) { + const childPath = path.join(current, entry.name) + const childRel = rel ? `${rel}/${entry.name}` : entry.name + if (entry.type === "directory") { + yield* walk(childPath, childRel) + } else if (entry.type === "file") { + const content = yield* fs.readFileStringSafe(childPath) + if (content !== undefined) result[childRel] = content + } + } + }) + yield* walk(dir, "") + return result +}) + +/** Verify archive bytes against an expected sha256 (hex). */ +export const verifySha256 = Effect.fn("OCKit.install.verifySha256")(function* ( + archive: Uint8Array, + expected: string, +) { + const actual = Hash.sha256(Buffer.from(archive)) + if (!expected || actual.toLowerCase() !== expected.toLowerCase()) { + return yield* new InstallerError({ + kind: "checksum", + kit: "archive", + detail: `sha256 mismatch (expected ${expected}, got ${actual})`, + }) + } +}) + +/** Extract archive bytes into `dest` using unzip/tar (or Expand-Archive on Windows). */ +export const extractArchive = Effect.fn("OCKit.install.extractArchive")(function* ( + archive: Uint8Array, + dest: string, +) { + const fsutil = yield* FSUtil.Service + yield* fsutil.ensureDir(dest) + const tmpFile = path.join(dest, `.stage-${Date.now()}`) + yield* fsutil.writeWithDirs(tmpFile, archive) + try { + if (process.platform === "win32") { + const cmd = `$global:ProgressPreference = 'SilentlyContinue'; Expand-Archive -Path '${tmpFile}' -DestinationPath '${dest}' -Force` + yield* Effect.promise(() => Process.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", cmd])).pipe( + Effect.mapError(() => new InstallerError({ kind: "extract", kit: dest, detail: "expand-archive failed" })), + ) + } else { + yield* Effect.promise(() => Process.run(["tar", "-xzf", tmpFile, "-C", dest])).pipe( + Effect.catch(() => Effect.promise(() => Process.run(["unzip", "-o", "-q", tmpFile, "-d", dest]))), + Effect.mapError(() => new InstallerError({ kind: "extract", kit: dest, detail: "tar/unzip extraction failed" })), + ) + } + } finally { + yield* fsutil.remove(tmpFile, { recursive: true, force: true }).pipe(Effect.ignore) + } +}) + +/** Find the staging directory that actually holds the kit files. */ +export const findStagedRoot = Effect.fn("OCKit.install.findStagedRoot")(function* ( + fs: FSUtil.Interface, + staging: string, +) { + const entries = yield* fs.readDirectoryEntries(staging) + const dirs = entries.filter((e) => e.type === "directory") + const files = entries.filter((e) => e.type === "file") + // If the archive contains exactly one top-level directory (a wrapped kit + // release, e.g. `v1.2.3/`), descend into it so the manifest is at the root. + if (dirs.length === 1 && files.length === 0) return path.join(staging, dirs[0].name) + return staging +}) + +export interface DownloadExtractOptions { + readonly http: HttpClient.HttpClient + readonly kitId: string + readonly release: ReleaseInfo + readonly staging: string + readonly extract?: (archive: Uint8Array, dest: string) => Effect.Effect +} + +/** + * Download a release archive, verify its sha256, extract it into `staging` and + * return the relative file map. Shared by install and update so both pipelines + * exercise the same download → verify → extract path. + */ +export const downloadAndExtract = Effect.fn("OCKit.install.downloadAndExtract")(function* ( + opts: DownloadExtractOptions, +) { + const fsutil = yield* FSUtil.Service + const extract = opts.extract ?? extractArchive + + // Download + const archive = yield* download(opts.http, opts.release.archiveUrl) + + // Verify sha256 + yield* verifySha256(archive, opts.release.checksumSha256).pipe( + Effect.mapError(() => + new InstallerError({ kind: "checksum", kit: opts.kitId, version: opts.release.version, detail: "archive checksum mismatch" }), + ), + ) + + // Extract + yield* extract(archive, opts.staging).pipe( + Effect.mapError((err) => + new InstallerError({ kind: "extract", kit: opts.kitId, version: opts.release.version, detail: err.message }), + ), + ) + + // Collect staged files + const stagedRoot = yield* findStagedRoot(fsutil, opts.staging) + return yield* collectFiles(fsutil, stagedRoot) +}) + +/** + * Snapshot the current contents of every owned path into `.oc/state/rollback///` + * so a later `--rollback` can restore the exact bytes. Returns the snapshot dir. + */ +export const backupOwnedFiles = Effect.fn("OCKit.install.backupOwnedFiles")(function* ( + root: string, + kit: string, + files: Record, +) { + const fsutil = yield* FSUtil.Service + const token = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}` + const dir = path.join(root, ".oc", "state", "rollback", kit, token) + yield* fsutil.ensureDir(dir) + for (const [file, content] of Object.entries(files)) { + yield* fsutil.writeWithDirs(path.join(dir, file), content) + } + return dir +}) + +/** + * Install a kit. Resolves the release (version or latest compatible), downloads + * and verifies the archive, stages + extracts it, plans file ownership via + * `claim`, writes the files, records ownership, and snapshots a checkpoint. + * `dev` installs the kit as untrusted/development. + */ +export const install = Effect.fn("OCKit.install")(function* ( + kitId: string, + opts: InstallOptions = {}, +) { + const fsutil = yield* FSUtil.Service + const http = opts.http ?? (yield* HttpClient.HttpClient) + const root = opts.root ?? defaultRoot() + const extract = opts.extract ?? extractArchive + + // 1. Resolve the release + const release: ReleaseInfo = yield* resolveLatest(kitId, { + http, + version: opts.version, + source: opts.source, + }).pipe( + Effect.mapError((err) => + new InstallerError({ + kind: err.kind === "not-found" ? "not-found" : "fetch", + kit: kitId, + version: err.version ?? opts.version, + detail: err.detail, + }), + ), + ) + + // 2-5. Download → verify → extract → collect (staging removed on exit) + const staging = path.join(root, ".oc", "state", `stage-${kitId}-${Date.now()}`) + yield* fsutil.ensureDir(staging).pipe( + Effect.mapError((err) => new InstallerError({ kind: "write", kit: kitId, version: release.version, detail: err.message })), + ) + + return yield* Effect.gen(function* () { + const files = yield* downloadAndExtract({ http, kitId, release, staging, extract }) + + // Validate the staged kit manifest — never install a broken kit. + const stagedRoot = yield* findStagedRoot(fsutil, staging) + yield* loadManifest(stagedRoot).pipe( + Effect.mapError((err) => + new InstallerError({ kind: "manifest", kit: kitId, version: release.version, detail: err.message ?? "invalid manifest" }), + ), + ) + + // 6. Plan via ownership claim (cross-kit conflict check) + const currentManifest = yield* loadOwnership(root).pipe( + Effect.mapError((err) => new InstallerError({ kind: "write", kit: kitId, detail: err.message })), + ) + // Ownership paths are root-relative: `kits//`. + const owned: Record = {} + for (const [file, content] of Object.entries(files)) { + owned[`${COLLECTED_ROOT_DIR}/${kitId}/${file}`] = content + } + const claimed = yield* claim(currentManifest, kitId, release.version, owned).pipe( + Effect.mapError((err) => new InstallerError({ kind: "conflict", kit: kitId, detail: err.message })), + ) + + // 6b. Snapshot the pre-install state of previously owned files so a later + // `--rollback` can restore the exact bytes that existed before this install. + const previous = Object.entries(currentManifest.files).filter(([file, entry]) => + file.startsWith(`${COLLECTED_ROOT_DIR}/${kitId}/`) && entry.kit === kitId, + ) + const preInstall: Record = {} + if (previous.length > 0) { + for (const [file] of previous) { + const content = yield* fsutil.readFileStringSafe(path.join(root, file)) + if (content !== undefined) preInstall[file] = content + } + if (Object.keys(preInstall).length > 0) { + yield* backupOwnedFiles(root, kitId, preInstall) + yield* Checkpoint.create({ + root, + kit: kitId, + kitVersion: release.version, + operation: "install", + files: preInstall, + }) + } + } + + // 7. Write files into the kit directory `/kits//` + const kitDir = path.join(root, COLLECTED_ROOT_DIR, kitId) + yield* fsutil.ensureDir(kitDir) + for (const [file, content] of Object.entries(files)) { + yield* fsutil.writeWithDirs(path.join(kitDir, file), content).pipe( + Effect.mapError((err) => new InstallerError({ kind: "write", kit: kitId, detail: `failed to write ${file}: ${err}` })), + ) + } + + // 8. Record ownership + yield* saveOwnership(root, claimed).pipe( + Effect.mapError((err) => new InstallerError({ kind: "write", kit: kitId, detail: `failed to save ownership: ${err.message}` })), + ) + + // 10. Dev marker + if (opts.dev) { + yield* fsutil.writeWithDirs( + path.join(kitDir, ".oc-kit-dev"), + JSON.stringify({ id: kitId, version: release.version, mode: "development" }), + ) + } + + return new InstallSummary({ + kitId, + version: release.version, + dir: kitDir, + filesInstalled: Object.keys(files), + mode: opts.dev ? "development" : "production", + }) + }).pipe( + Effect.mapError((err) => + err instanceof InstallerError + ? err + : new InstallerError({ kind: "write", kit: kitId, version: release.version, detail: err.message }), + ), + Effect.ensuring(fsutil.remove(staging, { recursive: true, force: true }).pipe(Effect.ignore)), + ) +}) + +/** Uninstall a kit: remove its directory and drop its ownership rows. */ +export const uninstall = Effect.fn("OCKit.install.uninstall")(function* (kitId: string) { + const fsutil = yield* FSUtil.Service + const root = defaultRoot() + const kitDir = path.join(root, COLLECTED_ROOT_DIR, kitId) + const exists = yield* fsutil.isDir(kitDir) + if (!exists) { + return yield* new InstallerError({ kind: "not-found", kit: kitId, detail: `Kit "${kitId}" is not installed` }) + } + const manifest = yield* loadOwnership(root).pipe( + Effect.mapError((err) => new InstallerError({ kind: "write", kit: kitId, detail: err.message })), + ) + const next: Record = {} + for (const [file, entry] of Object.entries(manifest.files)) { + if (entry.kit !== kitId) next[file] = entry + } + yield* fsutil.remove(kitDir, { recursive: true, force: true }).pipe( + Effect.mapError((err) => new InstallerError({ kind: "write", kit: kitId, detail: err.message })), + ) + yield* saveOwnership(root, { files: next }).pipe( + Effect.mapError((err) => new InstallerError({ kind: "write", kit: kitId, detail: `failed to save ownership: ${err.message}` })), + ) +}) + +export * as Installer from "./installer"// OC Kit installer — triggers CI re-run for typecheck and tests diff --git a/packages/opencode/src/ockit/registry-remote.ts b/packages/opencode/src/ockit/registry-remote.ts new file mode 100644 index 000000000..6ae090211 --- /dev/null +++ b/packages/opencode/src/ockit/registry-remote.ts @@ -0,0 +1,307 @@ +// OC Kit remote release registry. MVP backend is GitHub Releases: resolves a +// kit's newest release, reads its release metadata (archive URL, sha256 +// checksums, manifest URL) and validates `min_opencode` compatibility against +// the current runtime OPENCODE_VERSION. +// +// The transport is deliberately narrow — all fetches go through an injected +// `HttpClient` and a `RemoteRegistrySource` — so a private/local registry can +// be added later without redesigning the installer or updater: only the source +// resolution changes. + +import { Effect, Schema } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" +import semver from "semver" +import { InstallationVersion } from "@opencode-ai/core/installation/version" + +/** Structured release metadata resolved from a remote registry. */ +export class ReleaseInfo extends Schema.Class("OCKit.ReleaseInfo")({ + id: Schema.String, + version: Schema.String, + archiveUrl: Schema.String, + checksumSha256: Schema.String, + manifestUrl: Schema.String, + minOpencode: Schema.optional(Schema.String), + tag: Schema.String, +}) {} + +/** Where GitHub releases live. Override owner/repo via env or for tests. */ +export class RemoteRegistrySource extends Schema.Class("OCKit.RemoteRegistrySource")({ + owner: Schema.String, + repo: Schema.String, +}) {} + +export const DEFAULT_REGISTRY_OWNER = process.env.OCKIT_REGISTRY_OWNER ?? "opencode-ai" +export const DEFAULT_REGISTRY_REPO = process.env.OCKIT_REGISTRY_REPO ?? "kits" + +export const defaultSource = () => new RemoteRegistrySource({ owner: DEFAULT_REGISTRY_OWNER, repo: DEFAULT_REGISTRY_REPO }) + +export const resolveSource = (source: RemoteRegistrySource | undefined) => source ?? defaultSource() + +export const makeApiUrl = (source: RemoteRegistrySource) => + `https://api.github.com/repos/${source.owner}/${source.repo}/releases` + +export const makeRawUrl = (source: RemoteRegistrySource, version: string, file: string) => + `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${version}/${file}` + +export const ARCHIVE_ASSET_NAME = "kit.tar.gz" +export const CHECKSUMS_ASSET_NAME = "checksums.txt" + +/** + * Typed errors from the remote registry. `not-found` when a kit/release is + * missing; `incompatible` when no release satisfies the min_opencode contract; + * `checksum` when a fetched archive fails its sha256 guard; `decode`/`network` + * for transport failures. + */ +export class ReleaseError extends Schema.TaggedErrorClass()("OCKit.ReleaseError", { + kind: Schema.Literals(["not-found", "network", "decode", "checksum", "incompatible"]), + id: Schema.String, + detail: Schema.String, + version: Schema.optional(Schema.String), +}) { + override get message(): string { + const version = this.version ? ` ${this.version}` : "" + return `OC Kit registry: ${this.kind} for "${this.id}"${version} — ${this.detail}` + } +} + +const GitHubAsset = Schema.Struct({ + name: Schema.String, + browser_download_url: Schema.String, +}) + +const GitHubRelease = Schema.Struct({ + tag_name: Schema.String, + assets: Schema.Array(GitHubAsset), +}) + +const KitManifestSchema = Schema.Struct({ + version: Schema.optional(Schema.String), + min_opencode: Schema.optional(Schema.String), +}) + +/** Parse a checksums file into `file basename -> lowercase sha256`. */ +export function parseChecksums(text: string): Record { + const result: Record = {} + for (const line of text.split(/\r?\n/)) { + const trimmed = line.trim() + if (!trimmed) continue + const m = /^([0-9a-fA-F]{64})\s+(.+)$/.exec(trimmed) + if (!m) continue + const file = m[2].replace(/^\*/, "") + const base = file.includes("/") ? file.slice(file.lastIndexOf("/") + 1) : file + result[base] = m[1].toLowerCase() + } + return result +} + +/** Strip a leading `v` from a release tag so it reads like a semver. */ +export function normalizeVersion(value: string): string { + return value.replace(/^v/, "") +} + +/** Does the current runtime OpenCode version satisfy `min_opencode`? */ +export function compatibleWithRuntime(minOpencode: string | undefined): boolean { + if (!minOpencode) return true + const runtime = InstallationVersion + if (runtime === "local") return true + return semver.gte(runtime, minOpencode, { loose: true }) +} + +const fetchJson = (schema: S) => + Effect.fn("OCKit.registry.fetchJson")(function* (http: HttpClient.HttpClient, url: string) { + const response = yield* http.execute(HttpClientRequest.get(url).pipe(HttpClientRequest.acceptJson)).pipe( + Effect.mapError((err) => new ReleaseError({ kind: "network", id: url, detail: `HTTP request failed: ${String(err)}` })), + ) + if (response.status !== 200) { + return yield* new ReleaseError({ kind: "not-found", id: url, detail: `HTTP ${response.status}` }) + } + const data = yield* HttpClientResponse.schemaBodyJson(schema)(response).pipe( + Effect.mapError((err) => new ReleaseError({ kind: "decode", id: url, detail: `Invalid JSON: ${String(err)}` })), + ) + return data + }) + +const fetchText = Effect.fn("OCKit.registry.fetchText")(function* (http: HttpClient.HttpClient, url: string) { + const response = yield* http.execute(HttpClientRequest.get(url)).pipe( + Effect.mapError((err) => new ReleaseError({ kind: "network", id: url, detail: `HTTP request failed: ${String(err)}` })), + ) + if (response.status !== 200) { + return yield* new ReleaseError({ kind: "not-found", id: url, detail: `HTTP ${response.status}` }) + } + return yield* response.text.pipe( + Effect.mapError((err) => new ReleaseError({ kind: "network", id: url, detail: `Failed to read response body: ${String(err)}` })), + ) +}) + +// Treat a not-found fetch as an optional asset: succeeds with undefined rather +// than failing the whole resolution. +const fetchOptionalText = Effect.fn("OCKit.registry.fetchOptionalText")(function* ( + http: HttpClient.HttpClient, + url: string, +) { + return yield* fetchText(http, url).pipe( + Effect.catchTag("OCKit.ReleaseError", (err) => + err.kind === "not-found" ? Effect.succeed(undefined) : Effect.fail(err), + ), + ) +}) + +/** + * Resolve a release for a kit. With `version` set, resolves exactly that tag; + * otherwise scans the release list for the newest semver that is compatible + * with the running OpenCode runtime. Returns a typed `ReleaseInfo` or a typed + * `ReleaseError` (not-found when nothing compatible exists). + */ +export const resolveLatest = Effect.fn("OCKit.registry.resolveLatest")(function* ( + id: string, + opts: { source?: RemoteRegistrySource; http?: HttpClient.HttpClient; version?: string } = {}, +) { + const http = opts.http ?? (yield* HttpClient.HttpClient) + const source = resolveSource(opts.source) + + if (opts.version) { + const release = yield* fetchJson(GitHubRelease)(http, `${makeApiUrl(source)}/tags/${opts.version}`).pipe( + Effect.mapError((err) => + err instanceof ReleaseError && err.kind === "not-found" + ? new ReleaseError({ kind: "not-found", id, version: opts.version, detail: `Release tag not found` }) + : err, + ), + ) + const info = yield* releaseInfoCore(http, source, id, release, true) + if (info === undefined) { + return yield* new ReleaseError({ + kind: "incompatible", + id, + version: opts.version, + detail: `Release ${opts.version} is not compatible with OpenCode ${InstallationVersion}`, + }) + } + return info + } + + const releases = yield* fetchJson(Schema.Array(GitHubRelease))(http, makeApiUrl(source)).pipe( + Effect.mapError((err) => + err instanceof ReleaseError && err.kind === "not-found" + ? new ReleaseError({ + kind: "not-found", + id, + detail: `No releases found for ${source.owner}/${source.repo}`, + }) + : err, + ), + ) + const sorted = (releases as typeof GitHubRelease.Type[]).toSorted((a, b) => + semver.rcompare(normalizeVersion(a.tag_name), normalizeVersion(b.tag_name), { loose: true }), + ) + for (const release of sorted) { + const info = yield* releaseInfoCore(http, source, id, release, false) + if (info) return info + } + return yield* new ReleaseError({ + kind: "not-found", + id, + detail: `No release of ${source.owner}/${source.repo} is compatible with OpenCode ${InstallationVersion}`, + }) +}) + +/** Build a typed `ReleaseInfo` from a GitHub release payload. */ +export const toReleaseInfo = Effect.fn("OCKit.registry.toReleaseInfo")(function* ( + http: HttpClient.HttpClient, + source: RemoteRegistrySource, + id: string, + release: typeof GitHubRelease.Type, + hard: boolean, +) { + return yield* releaseInfoCore(http, source, id, release, hard) +}) + +const releaseInfoCore = Effect.fn("OCKit.registry.releaseInfoCore")(function* ( + http: HttpClient.HttpClient, + source: RemoteRegistrySource, + id: string, + release: typeof GitHubRelease.Type, + hard: boolean, +) { + const tag = release.tag_name + const version = normalizeVersion(tag) + const archive = release.assets.find( + (asset) => asset.name === ARCHIVE_ASSET_NAME || asset.name.endsWith(".tar.gz"), + ) + if (!archive) { + return yield* whenIncompatible(hard, new ReleaseError({ + kind: "incompatible", + id, + version, + detail: `Release ${tag} has no ${ARCHIVE_ASSET_NAME} asset`, + })) + } + + const checksumAsset = release.assets.find((asset) => asset.name === CHECKSUMS_ASSET_NAME) + let checksums: Record | undefined + if (checksumAsset) { + const text = yield* fetchOptionalText(http, checksumAsset.browser_download_url) + if (text !== undefined) checksums = parseChecksums(text) + } else { + const text = yield* fetchOptionalText(http, makeRawUrl(source, tag, CHECKSUMS_ASSET_NAME)) + if (text !== undefined) checksums = parseChecksums(text) + } + + const archiveName = archive.name + const expected = checksums ? checksums[archiveName] ?? checksums[archiveName.replace(/^\.\//, "")] : undefined + if (checksums && expected === undefined) { + return yield* whenIncompatible(hard, new ReleaseError({ + kind: "incompatible", + id, + version, + detail: `Checksums file has no entry for "${archiveName}"`, + })) + } + + const minOpencode = yield* readKitMinOpencode(http, source, tag, id, version) + if (!compatibleWithRuntime(minOpencode)) { + return yield* whenIncompatible(hard, new ReleaseError({ + kind: "incompatible", + id, + version, + detail: `Release requires OpenCode >= ${minOpencode}, running ${InstallationVersion}`, + })) + } + + return new ReleaseInfo({ + id, + version, + archiveUrl: archive.browser_download_url, + checksumSha256: expected ?? "", + manifestUrl: makeRawUrl(source, tag, "kit.json"), + minOpencode, + tag, + }) +}) + +function whenIncompatible(hard: boolean, error: ReleaseError): Effect.Effect { + // In "soft" mode (used while scanning the release list) an incompatible + // release is skipped rather than aborting the whole resolution. + return hard ? Effect.fail(error) : Effect.succeed(undefined) +} + +const readKitMinOpencode = Effect.fn("OCKit.registry.readKitMinOpencode")(function* ( + http: HttpClient.HttpClient, + source: RemoteRegistrySource, + tag: string, + id: string, + version: string, +) { + const text = yield* fetchOptionalText(http, makeRawUrl(source, tag, "kit.json")) + if (text === undefined) return undefined + const parsed = yield* Effect.try({ + try: () => JSON.parse(text) as unknown, + catch: (cause) => + new ReleaseError({ kind: "decode", id, version, detail: `Invalid kit manifest: ${String(cause)}` }), + }) + const decoded = yield* Schema.decodeUnknownEffect(KitManifestSchema)(parsed).pipe( + Effect.mapError((err) => new ReleaseError({ kind: "decode", id, version, detail: `Invalid kit manifest: ${String(err)}` })), + ) + return decoded.min_opencode +}) + +export * as RegistryRemote from "./registry-remote" \ No newline at end of file diff --git a/packages/opencode/src/ockit/updater.ts b/packages/opencode/src/ockit/updater.ts new file mode 100644 index 000000000..684798ecf --- /dev/null +++ b/packages/opencode/src/ockit/updater.ts @@ -0,0 +1,308 @@ +// OC Kit updater + rollback. `update` resolves the latest release for an +// installed kit, computes a per-file update plan through `ownership.planUpdate` +// (replace / preserve / warn) and applies only the replaceable files — user +// modified files are never overwritten. `--check`/`--dry-run` produce the same +// conflict preview WITHOUT mutating anything. `--rollback` restores the latest +// checkpoint's file contents after comparing the current state (reverting only +// files whose bytes no longer match what the checkpoint shipped). + +import { Effect, Schema } from "effect" +import { HttpClient } from "effect/unstable/http" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Hash } from "@opencode-ai/core/util/hash" +import { Global } from "@opencode-ai/core/global" +import path from "path" +import { resolveLatest, type ReleaseInfo, type RemoteRegistrySource } from "./registry-remote" +import { loadOwnership, saveOwnership, planUpdate, claim } from "./ownership" +import { Checkpoint } from "./checkpoint" +import { loadManifest } from "./manifest" +import { + COLLECTED_ROOT_DIR, + downloadAndExtract, + findStagedRoot, + backupOwnedFiles, + type InstallerError, +} from "./installer" + +export class UpdateError extends Schema.TaggedErrorClass()("OCKitUpdateError", { + kind: Schema.Literals(["not-found", "fetch", "checksum", "extract", "conflict", "write", "rollback", "manifest"]), + kit: Schema.String, + detail: Schema.String, + version: Schema.optional(Schema.String), +}) { + override get message(): string { + return `OC Kit updater: ${this.kind} for "${this.kit}"${this.version ? ` ${this.version}` : ""} — ${this.detail}` + } +} + +export class UpdateSummary extends Schema.Class("OCKit.UpdateSummary")({ + kitId: Schema.String, + fromVersion: Schema.String, + toVersion: Schema.String, + replaced: Schema.Array(Schema.String), + preserved: Schema.Array(Schema.String), + warned: Schema.Array(Schema.String), + dryRun: Schema.Boolean, +}) {} + +export interface UpdateOptions { + readonly check?: boolean + readonly dryRun?: boolean + readonly yes?: boolean + readonly force?: boolean + readonly rollback?: boolean + readonly version?: string + readonly source?: RemoteRegistrySource + readonly http?: HttpClient.HttpClient + readonly root?: string + /** Test seam mirroring `installer.install`. */ + readonly extract?: (archive: Uint8Array, dest: string) => Effect.Effect +} + +const defaultRoot = () => Global.Path.config + +const relToKit = (rootRel: string, kitId: string) => + rootRel.startsWith(`${COLLECTED_ROOT_DIR}/${kitId}/`) + ? rootRel.slice(`${COLLECTED_ROOT_DIR}/${kitId}/`.length) + : rootRel + +const kitRelToOwned = (kitRel: string, kitId: string) => `${COLLECTED_ROOT_DIR}/${kitId}/${kitRel}` + +/** + * Produce the update plan for a kit — a preview of which files would be + * replaced, preserved, or warned — WITHOUT mutating anything. Used by + * `--check`/`--dry-run` and as the first step of a real update. + */ +export const previewUpdate = Effect.fn("OCKit.update.preview")(function* ( + kitId: string, + opts: UpdateOptions = {}, +) { + const fsutil = yield* FSUtil.Service + const http = opts.http ?? (yield* HttpClient.HttpClient) + const root = opts.root ?? defaultRoot() + const kitDir = path.join(root, COLLECTED_ROOT_DIR, kitId) + const exists = yield* fsutil.isDir(kitDir) + if (!exists) { + return yield* new UpdateError({ kind: "not-found", kit: kitId, detail: `Kit "${kitId}" is not installed` }) + } + + const release = yield* resolveLatest(kitId, { http, version: opts.version, source: opts.source }).pipe( + Effect.mapError((err) => + new UpdateError({ + kind: err.kind === "not-found" ? "not-found" : "fetch", + kit: kitId, + version: err.version ?? opts.version, + detail: err.detail, + }), + ), + ) + + const staging = path.join(root, ".oc", "state", `update-${kitId}-${Date.now()}`) + yield* fsutil.ensureDir(staging).pipe( + Effect.mapError((err) => new UpdateError({ kind: "write", kit: kitId, detail: err.message })), + ) + return yield* Effect.gen(function* () { + const files = yield* downloadAndExtract({ http, kitId, release, staging, extract: opts.extract }) + // Validate the staged manifest before committing to any plan. + const stagedRoot = yield* findStagedRoot(fsutil, staging) + yield* readStagedManifest(stagedRoot).pipe( + Effect.mapError((err) => new UpdateError({ kind: "manifest", kit: kitId, detail: err.message ?? "invalid manifest" })), + ) + return { release, files } + }).pipe( + Effect.mapError((err) => + err instanceof UpdateError ? err : new UpdateError({ kind: "write", kit: kitId, detail: err.message }), + ), + Effect.ensuring(fsutil.remove(staging, { recursive: true, force: true }).pipe(Effect.ignore)), + ) +}) + +/** + * Update an installed kit to the latest (or pinned) release. When `check` or + * `dryRun` is set, only the conflict preview is produced — nothing is written. + * Otherwise the plan from `ownership.planUpdate` is applied: files we own and + * that are unmodified are replaced; user-modified and foreign files are + * preserved (never overwritten). `warn`ed files are preserved too, with the + * plan marked so callers can surface the warning. + */ +export const update = Effect.fn("OCKit.update")(function* ( + kitId: string, + opts: UpdateOptions = {}, +) { + const fsutil = yield* FSUtil.Service + const http = opts.http ?? (yield* HttpClient.HttpClient) + const root = opts.root ?? defaultRoot() + + const { release, files } = yield* previewUpdate(kitId, { ...opts, http, root }) + + const currentManifest = yield* loadOwnership(root).pipe( + Effect.mapError((err) => new UpdateError({ kind: "write", kit: kitId, detail: err.message })), + ) + const upstreamOwned = Object.fromEntries( + Object.entries(files).map(([file, content]) => [kitRelToOwned(file, kitId), content]), + ) + + // Plan uses the installed file tree at root — reads user-edited files. + const plan = yield* planUpdate(fsutil, root, currentManifest, kitId, upstreamOwned).pipe( + Effect.mapError((err) => new UpdateError({ kind: "write", kit: kitId, detail: err.message })), + ) + + const warned = plan.warn + const preserved = plan.preserve.filter((f) => f.startsWith(`${COLLECTED_ROOT_DIR}/${kitId}/`)) + + // `--check` / `--dry-run` stop here without mutating. + if (opts.check || opts.dryRun) { + return new UpdateSummary({ + kitId, + fromVersion: "", + toVersion: release.version, + replaced: [...plan.replace], + preserved, + warned, + dryRun: true, + }) + } + + // Snapshot the pre-update bytes of every owned-and-unmodified file about to be + // replaced, and checkpoint that state so `--rollback` restores the old bytes. + const toReplace = new Map() + for (const rel of plan.replace) { + const content = upstreamOwned[rel] + if (content !== undefined) toReplace.set(rel, content) + } + const preUpdate: Record = {} + for (const rel of toReplace.keys()) { + const existing = yield* fsutil.readFileStringSafe(path.join(root, rel)).pipe( + Effect.mapError((err) => new UpdateError({ kind: "write", kit: kitId, detail: err.message })), + ) + if (existing !== undefined) preUpdate[rel] = existing + } + if (Object.keys(preUpdate).length > 0) { + yield* backupOwnedFiles(root, kitId, preUpdate).pipe( + Effect.mapError((err) => new UpdateError({ kind: "write", kit: kitId, detail: err.message })), + ) + yield* Checkpoint.create({ + root, + kit: kitId, + kitVersion: release.version, + operation: "update", + files: preUpdate, + }).pipe( + Effect.mapError((err) => new UpdateError({ kind: "write", kit: kitId, detail: err.message })), + ) + } + + // Apply the plan: replace files we own and the user has not touched. Never + // overwrite user-modified or foreign files (those remain in `preserved`). + const kitDir = path.join(root, COLLECTED_ROOT_DIR, kitId) + for (const rel of plan.replace) { + const content = upstreamOwned[rel] + if (content === undefined) continue + yield* fsutil.writeWithDirs(path.join(kitDir, relToKit(rel, kitId)), content).pipe( + Effect.mapError((err) => new UpdateError({ kind: "write", kit: kitId, detail: `failed to write ${rel}: ${err}` })), + ) + } + + // Record the new ownership for the replaced files; preserved entries stay as + // they were (claim merges over the existing manifest). + const newOwned: Record = {} + for (const [rel, content] of toReplace) { + newOwned[rel] = content + } + const claimed = yield* claim(currentManifest, kitId, release.version, newOwned).pipe( + Effect.mapError((err) => new UpdateError({ kind: "conflict", kit: kitId, detail: err.message })), + ) + yield* saveOwnership(root, claimed).pipe( + Effect.mapError((err) => new UpdateError({ kind: "write", kit: kitId, detail: `failed to save ownership: ${err.message}` })), + ) + + return new UpdateSummary({ + kitId, + fromVersion: "", + toVersion: release.version, + replaced: [...plan.replace], + preserved, + warned, + dryRun: false, + }) +}) + +/** + * Roll back an installed kit to its latest checkpoint. Compares the current + * hash of each tracked file against the checkpoint's recorded hash and only + * rewrites files that differ (or are missing), restoring content from the + * pre-operation backup written by install/update. + */ +export const rollback = Effect.fn("OCKit.update.rollback")(function* ( + kitId: string, + opts: UpdateOptions = {}, +) { + const fsutil = yield* FSUtil.Service + const root = opts.root ?? defaultRoot() + + const ids = yield* Checkpoint.list(root, kitId).pipe( + Effect.mapError((err) => new UpdateError({ kind: "rollback", kit: kitId, detail: err.message })), + ) + if (ids.length === 0) { + return yield* new UpdateError({ kind: "rollback", kit: kitId, detail: `No checkpoints found for "${kitId}"` }) + } + const cp = yield* Checkpoint.read(root, ids[0]).pipe( + Effect.mapError((err) => new UpdateError({ kind: "rollback", kit: kitId, detail: err.message })), + ) + + const backupDir = yield* latestBackupDir(root, kitId).pipe( + Effect.mapError((err) => new UpdateError({ kind: "rollback", kit: kitId, detail: err.message })), + ) + const restored: string[] = [] + const skipped: string[] = [] + for (const [file, hash] of Object.entries(cp.files)) { + const target = path.join(root, file) + const current = yield* fsutil.readFileStringSafe(target).pipe( + Effect.mapError((err) => new UpdateError({ kind: "rollback", kit: kitId, detail: err.message })), + ) + if (current === undefined || Hash.sha256(current) !== hash) { + // The file diverges from checkpoint state — restore the backup content. + const content = backupDir + ? yield* fsutil.readFileStringSafe(path.join(backupDir, file)).pipe( + Effect.mapError((err) => new UpdateError({ kind: "rollback", kit: kitId, detail: err.message })), + ) + : undefined + if (content === undefined) { + skipped.push(file) + continue + } + yield* fsutil.writeWithDirs(target, content).pipe( + Effect.mapError((err) => new UpdateError({ kind: "rollback", kit: kitId, detail: `failed to restore ${file}: ${err}` })), + ) + restored.push(file) + } else { + skipped.push(file) + } + } + + return new UpdateSummary({ + kitId, + fromVersion: cp.kit_version, + toVersion: cp.kit_version, + replaced: restored, + preserved: skipped, + warned: [], + dryRun: false, + }) +}) + +/** Find the (newest-first) rollback snapshot directory for a kit. */ +export const latestBackupDir = Effect.fn("OCKit.update.latestBackupDir")(function* (root: string, kit: string) { + const base = path.join(root, ".oc", "state", "rollback", kit) + const fsutil = yield* FSUtil.Service + if (!(yield* fsutil.isDir(base))) return undefined + const entries = yield* fsutil.readDirectoryEntries(base) + const dirs = entries.map((e) => e.name).filter((name) => /^\d+-/.test(name)).sort().reverse() + return dirs.length > 0 ? path.join(base, dirs[0]) : undefined +}) + +const readStagedManifest = Effect.fn("OCKit.update.readStagedManifest")(function* (stagedRoot: string) { + return yield* loadManifest(stagedRoot) +}) + +export * as Updater from "./updater" \ No newline at end of file diff --git a/packages/opencode/test/ockit/doctor.test.ts b/packages/opencode/test/ockit/doctor.test.ts new file mode 100644 index 000000000..cd7272a04 --- /dev/null +++ b/packages/opencode/test/ockit/doctor.test.ts @@ -0,0 +1,137 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { testEffect } from "../lib/effect" +import os from "os" +import path from "path" +import fs from "fs/promises" +import { doctor, DoctorReport } from "../../src/ockit/doctor" +import { Service as Registry, NotFoundError, type Interface as RegistryInterface } from "../../src/ockit/registry" +import { RemoteRegistrySource } from "../../src/ockit/registry-remote" + +const layer = LayerNode.compile(FSUtil.node) +const it = testEffect(layer) + +const SOURCE = new RemoteRegistrySource({ owner: "opencode-ai", repo: "kits" }) + +const EVEN_HEX = "a".repeat(64) + +function jsonResponse(body: unknown) { + return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }) +} + +function releaseAsset(name: string, url = `https://example.com/${name}`) { + return { name, browser_download_url: url } +} + +function clientFor(handler: (url: string) => Response) { + const client = HttpClient.make((request: HttpClientRequest.HttpClientRequest) => + Effect.succeed(HttpClientResponse.fromWeb(request, handler(request.url))), + ) + return Layer.succeed(HttpClient.HttpClient, client) +} + +// Doctor statically requires Registry.Service (via the installed-kits fallback) +// even when `options.kits` is provided, so every test provides a stub registry. +function registryLayer() { + return Layer.succeed( + Registry, + Registry.of({ + all: () => Effect.succeed([]), + get: () => Effect.succeed(undefined), + require: Effect.fn(function* () { + return yield* new NotFoundError({ id: "missing", available: [] }) + }), + dirs: () => Effect.succeed([]), + }) as unknown as RegistryInterface, + ) +} + +const offlineClient = () => new Response("unused", { status: 404 }) + +// A reachable-registry probe: the release list, a valid checksums.txt, and a +// compatible kit.json — enough for `resolveLatest("engineer")` to succeed. +function reachableHandler(url: string) { + if (url.endsWith("/releases")) { + return jsonResponse([ + { + tag_name: "v1.0.0", + assets: [releaseAsset("kit.tar.gz"), releaseAsset("checksums.txt")], + }, + ]) + } + if (url.endsWith("checksums.txt")) return new Response(`${EVEN_HEX} kit.tar.gz\n`, { status: 200 }) + if (url.includes("kit.json")) return jsonResponse({ id: "engineer", version: "1.0.0" }) + return jsonResponse({}) +} + +function withRoot(use: (root: string) => Effect.Effect) { + return Effect.acquireUseRelease( + Effect.gen(function* () { + const dir = path.join(os.tmpdir(), "ockit-doc-" + Math.random().toString(36).slice(2)) + yield* Effect.promise(() => fs.mkdir(path.join(dir, ".oc", "state"), { recursive: true })) + return dir + }), + use, + (dir) => Effect.promise(() => fs.rm(dir, { recursive: true, force: true })), + ) +} + +describe("ockit doctor", () => { + it.effect("produces a typed report with pass items when everything is fine", () => + withRoot((root) => + doctor({ + root, + offline: true, + source: SOURCE, + kits: [{ id: "engineer", version: "1.0.0" }], + config: { oc_kit: { enabled: true } }, + }).pipe( + Effect.provide(clientFor(offlineClient)), + Effect.provide(registryLayer()), + Effect.map((report: DoctorReport) => { + expect(report).toBeInstanceOf(DoctorReport) + expect(report.runtimeVersion).toBeTruthy() + expect(report.offline).toBe(true) + expect(report.items.length).toBeGreaterThan(0) + const sections = report.items.map((i) => i.section) + expect(sections).toContain("runtime") + expect(sections).toContain("config") + expect(sections).toContain("kits") + expect(sections).toContain("registry") + expect(report.items.find((i) => i.section === "registry")?.message).toContain("offline") + }), + ), + ), + ) + + it.effect("does not crash when no kit is installed", () => + withRoot((root) => + doctor({ root, offline: true, kits: [], source: SOURCE }).pipe( + Effect.provide(clientFor(offlineClient)), + Effect.provide(registryLayer()), + Effect.map((report: DoctorReport) => { + const kitItem = report.items.find((i) => i.section === "kits") + expect(kitItem?.severity).toBe("warn") + expect(kitItem?.message).toContain("no OC Kit kits installed") + }), + ), + ), + ) + + it.effect("reports registry reachability when online and the probe succeeds", () => + withRoot((root) => + doctor({ root, offline: false, source: SOURCE, kits: [] }).pipe( + Effect.provide(clientFor(reachableHandler)), + Effect.provide(registryLayer()), + Effect.map((report: DoctorReport) => { + const reg = report.items.find((i) => i.section === "registry") + expect(reg?.severity).toBe("pass") + expect(reg?.message).toContain("registry reachable") + }), + ), + ), + ) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/installer.test.ts b/packages/opencode/test/ockit/installer.test.ts new file mode 100644 index 000000000..f7bff0748 --- /dev/null +++ b/packages/opencode/test/ockit/installer.test.ts @@ -0,0 +1,179 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { testEffect } from "../lib/effect" +import { Hash } from "@opencode-ai/core/util/hash" +import os from "os" +import path from "path" +import fs from "fs/promises" +import { + install, + InstallSummary, + InstallerError, + COLLECTED_ROOT_DIR, + verifySha256, +} from "../../src/ockit/installer" +import { loadOwnership } from "../../src/ockit/ownership" +import { RemoteRegistrySource, ReleaseInfo } from "../../src/ockit/registry-remote" + +const layer = LayerNode.compile(FSUtil.node) +const it = testEffect(layer) + +const SOURCE = new RemoteRegistrySource({ owner: "opencode-ai", repo: "kits" }) + +function jsonResponse(body: unknown) { + return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }) +} + +function releaseAsset(name: string, url = `https://example.com/${name}`) { + return { name, browser_download_url: url } +} + +function releasePayload(tag: string, assets: Array<{ name: string; browser_download_url: string }>) { + return { tag_name: tag, assets } +} + +/** Fake HttpClient serving from a URL -> Response map. */ +function clientFor(handler: (url: string) => Response) { + const client = HttpClient.make((request: HttpClientRequest.HttpClientRequest) => + Effect.succeed(HttpClientResponse.fromWeb(request, handler(request.url))), + ) + return Layer.succeed(HttpClient.HttpClient, client) +} + +function withRoot(use: (root: string) => Effect.Effect) { + return Effect.acquireUseRelease( + Effect.gen(function* () { + const dir = path.join(os.tmpdir(), "ockit-inst-" + Math.random().toString(36).slice(2)) + yield* Effect.promise(() => fs.mkdir(path.join(dir, ".oc", "state"), { recursive: true })) + return dir + }), + use, + (dir) => Effect.promise(() => fs.rm(dir, { recursive: true, force: true })), + ) +} + +const KIT_MANIFEST = { + id: "engineer", + name: "OC Engineer Kit", + version: "1.0.0", + runtime: "opencode", + skills: [{ id: "plan", description: "Plan" }], +} + +const KIT_FILES: Record = { + "kit.json": JSON.stringify(KIT_MANIFEST), + "skills/plan.md": "# Plan skill", +} + +/** A fake extract that writes a staged kit tree into `dest`. */ +function fakeExtract(files: Record) { + return (archive: Uint8Array, dest: string) => + Effect.gen(function* () { + const fsutil = yield* FSUtil.Service + yield* fsutil.ensureDir(dest) + for (const [file, content] of Object.entries(files)) { + yield* fsutil.writeWithDirs(path.join(dest, file), content) + } + }) as unknown as Effect.Effect +} + +function archiveHandler(hex: string, files: Record = KIT_FILES) { + const content = "compressed-kit-bytes" + return (url: string) => { + if (url.endsWith("/releases/tags/1.0.0")) { + return jsonResponse( + releasePayload("1.0.0", [ + releaseAsset("kit.tar.gz", "https://example.com/kit.tar.gz"), + releaseAsset("checksums.txt", "https://example.com/checksums.txt"), + ]), + ) + } + if (url.endsWith("kit.tar.gz")) return new Response(content, { status: 200 }) + if (url.endsWith("checksums.txt")) return new Response(`${hex} kit.tar.gz\n`, { status: 200 }) + if (url.includes("kit.json")) return jsonResponse(KIT_MANIFEST) + return jsonResponse({}) + } +} + +describe("ockit installer", () => { + it.effect("verifySha256 is real: valid hash passes, invalid fails", () => + Effect.gen(function* () { + const content = new TextEncoder().encode("hello world") + const hex = Hash.sha256(Buffer.from(content)) + yield* verifySha256(content, hex).pipe(Effect.exit) + const err = yield* verifySha256(content, "b".repeat(64)).pipe(Effect.flip) + expect(err.kind).toBe("checksum") + }), + ) + + it.effect("install verifies checksum, records ownership and returns a summary", () => + withRoot((root) => + install("engineer", { + source: SOURCE, + root, + version: "1.0.0", + dev: false, + extract: fakeExtract(KIT_FILES), + }).pipe( + Effect.provide(clientFor(archiveHandler(Hash.sha256(Buffer.from("compressed-kit-bytes"))))), + Effect.flatMap((summary: InstallSummary) => + Effect.gen(function* () { + expect(summary.kitId).toBe("engineer") + expect(summary.version).toBe("1.0.0") + expect(summary.dir).toBe(path.join(root, COLLECTED_ROOT_DIR, "engineer")) + expect(summary.filesInstalled).toContain("kit.json") + expect(summary.filesInstalled).toContain("skills/plan.md") + expect(summary.mode).toBe("production") + + const manifest = yield* loadOwnership(root) + expect(manifest.files[`${COLLECTED_ROOT_DIR}/engineer/kit.json`]?.kit).toBe("engineer") + expect(manifest.files[`${COLLECTED_ROOT_DIR}/engineer/kit.json`]?.version).toBe("1.0.0") + expect(manifest.files[`${COLLECTED_ROOT_DIR}/engineer/skills/plan.md`]?.sha256).toBe( + Hash.sha256("# Plan skill"), + ) + }), + ), + ), + ), + ) + + it.effect("install fails with a checksum error when the archive does not match", () => + withRoot((root) => + install("engineer", { + source: SOURCE, + root, + version: "1.0.0", + extract: fakeExtract(KIT_FILES), + }).pipe( + Effect.provide(clientFor(archiveHandler("b".repeat(64)))), + Effect.flip, + Effect.flatMap((err: InstallerError) => { + expect(err).toBeInstanceOf(InstallerError) + expect(err.kind).toBe("checksum") + return Effect.succeed(undefined) + }), + ), + ), + ) + + it.effect("install in dev mode marks the kit as development", () => + withRoot((root) => + install("engineer", { + source: SOURCE, + root, + version: "1.0.0", + dev: true, + extract: fakeExtract(KIT_FILES), + }).pipe( + Effect.provide(clientFor(archiveHandler(Hash.sha256(Buffer.from("compressed-kit-bytes"))))), + Effect.flatMap((summary: InstallSummary) => { + expect(summary.mode).toBe("development") + return Effect.succeed(undefined) + }), + ), + ), + ) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/registry-remote.test.ts b/packages/opencode/test/ockit/registry-remote.test.ts new file mode 100644 index 000000000..76383c09e --- /dev/null +++ b/packages/opencode/test/ockit/registry-remote.test.ts @@ -0,0 +1,155 @@ +import { describe, expect } from "bun:test" +import { Cause, Effect, Layer } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" +import { testEffect } from "../lib/effect" +import { + RemoteRegistrySource, + resolveLatest, + parseChecksums, + compatibleWithRuntime, + normalizeVersion, + ReleaseError, +} from "../../src/ockit/registry-remote" + +const it = testEffect(Layer.empty) + +const SOURCE = new RemoteRegistrySource({ owner: "opencode-ai", repo: "kits" }) + +function jsonResponse(body: unknown) { + return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }) +} + +function releaseAsset(name: string, url = `https://example.com/${name}`) { + return { name, browser_download_url: url } +} + +function releasePayload(tag: string, assets: Array<{ name: string; browser_download_url: string }>) { + return { tag_name: tag, assets } +} + +/** A fake HttpClient answering from a URL -> Response map, injected via the + * `http` option (so the effect needs no service layer). */ +function fakeClient(handler: (url: string) => Response) { + return HttpClient.make((request: HttpClientRequest.HttpClientRequest) => + Effect.succeed(HttpClientResponse.fromWeb(request, handler(request.url))), + ) +} + +function resolve( + handler: (url: string) => Response, + opts?: O, +) { + return resolveLatest("engineer", { source: SOURCE, ...opts }).pipe( + Effect.provideService(HttpClient.HttpClient, fakeClient(handler)), + ) +} + +const EVEN_HEX = "a".repeat(64) +const OTHER_HEX = "b".repeat(64) + +describe("ockit registry-remote", () => { + it.effect("normalizeVersion strips a leading v", () => + Effect.gen(function* () { + expect(normalizeVersion("v1.2.3")).toBe("1.2.3") + expect(normalizeVersion("1.2.3")).toBe("1.2.3") + }), + ) + + it.effect("compatibleWithRuntime allows missing and incompatible min_opencode", () => + Effect.gen(function* () { + // With no min_opencode, everything is compatible. + expect(compatibleWithRuntime(undefined)).toBe(true) + }), + ) + + it.effect("parseChecksums extracts sha256 per file", () => + Effect.gen(function* () { + const result = parseChecksums( + `${EVEN_HEX} kit-linux-amd64.tar.gz\n${OTHER_HEX} *kit-darwin-amd64.tar.gz\n`, + ) + expect(result["kit-linux-amd64.tar.gz"]).toBe(EVEN_HEX) + expect(result["kit-darwin-amd64.tar.gz"]).toBe(OTHER_HEX) + }), + ) + + it.effect("resolves a pinned release into ReleaseInfo with checksums", () => + Effect.gen(function* () { + const info = yield* resolve( + (url) => { + if (url.endsWith("/releases/tags/1.0.0")) { + return jsonResponse( + releasePayload("1.0.0", [ + releaseAsset("kit.tar.gz", "https://example.com/kit.tar.gz"), + releaseAsset("checksums.txt", "https://example.com/checksums.txt"), + ]), + ) + } + if (url.endsWith("kit.tar.gz")) return jsonResponse({}) + if (url.endsWith("checksums.txt")) return new Response(`${EVEN_HEX} kit.tar.gz\n`, { status: 200 }) + if (url.includes("kit.json")) return jsonResponse({ id: "engineer", version: "1.0.0" }) + return jsonResponse({}) + }, + { version: "1.0.0" }, + ) + expect(info.version).toBe("1.0.0") + expect(info.checksumSha256).toBe(EVEN_HEX) + expect(info.archiveUrl).toBe("https://example.com/kit.tar.gz") + expect(info.manifestUrl).toContain("/1.0.0/kit.json") + }), + ) + + it.effect("resolveLatest picks the newest compatible semver release", () => + Effect.gen(function* () { + const info = yield* resolve((url) => { + if (url.endsWith("/releases")) { + return jsonResponse([ + releasePayload("v1.0.0", [releaseAsset("kit.tar.gz")]), + releasePayload("v2.0.0", [releaseAsset("kit.tar.gz")]), + releasePayload("v2.0.1", [releaseAsset("kit.tar.gz")]), + ]) + } + if (url.endsWith("kit.json")) + return jsonResponse({ id: "engineer", version: "2.0.1", min_opencode: "1.0.0" }) + if (url.endsWith("checksums.txt")) + return new Response(`${EVEN_HEX} kit.tar.gz\n`, { status: 200 }) + if (url.endsWith("kit.tar.gz")) return jsonResponse({}) + return jsonResponse({}) + }) + expect(info.version).toBe("2.0.1") + }), + ) + + it.effect("resolveLatest throws NotFound when no releases exist", () => + Effect.gen(function* () { + const exit = yield* resolve((url) => + url.endsWith("/releases") ? jsonResponse([]) : jsonResponse({}), + ).pipe(Effect.exit) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const err = Cause.squash(exit.cause) + expect(err).toBeInstanceOf(ReleaseError) + expect((err as ReleaseError).kind).toBe("not-found") + } + }), + ) + + it.effect("treats an incompatible min_opencode as not-found when scanning", () => + Effect.gen(function* () { + const exit = yield* resolve((url) => { + if (url.endsWith("/releases")) { + return jsonResponse([releasePayload("v3.0.0", [releaseAsset("kit.tar.gz")])]) + } + if (url.endsWith("kit.json")) + return jsonResponse({ id: "engineer", version: "3.0.0", min_opencode: "999.0.0" }) + if (url.endsWith("checksums.txt")) return new Response(`${EVEN_HEX} kit.tar.gz\n`, { status: 200 }) + return jsonResponse({}) + }).pipe(Effect.exit) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const err = Cause.squash(exit.cause) + expect(err).toBeInstanceOf(ReleaseError) + expect((err as ReleaseError).kind).toBe("not-found") + } + }), + ) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/updater.test.ts b/packages/opencode/test/ockit/updater.test.ts new file mode 100644 index 000000000..b7faf3b52 --- /dev/null +++ b/packages/opencode/test/ockit/updater.test.ts @@ -0,0 +1,244 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { testEffect } from "../lib/effect" +import { Hash } from "@opencode-ai/core/util/hash" +import os from "os" +import path from "path" +import fs from "fs/promises" +import { update, rollback, previewUpdate, UpdateSummary, UpdateError } from "../../src/ockit/updater" +import { COLLECTED_ROOT_DIR, install } from "../../src/ockit/installer" +import { loadOwnership } from "../../src/ockit/ownership" +import { RemoteRegistrySource } from "../../src/ockit/registry-remote" + +const layer = LayerNode.compile(FSUtil.node) +const it = testEffect(layer) + +const SOURCE = new RemoteRegistrySource({ owner: "opencode-ai", repo: "kits" }) + +function jsonResponse(body: unknown) { + return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }) +} + +function releaseAsset(name: string, url = `https://example.com/${name}`) { + return { name, browser_download_url: url } +} + +function releasePayload(tag: string, assets: Array<{ name: string; browser_download_url: string }>) { + return { tag_name: tag, assets } +} + +function clientFor(handler: (url: string) => Response) { + const client = HttpClient.make((request: HttpClientRequest.HttpClientRequest) => + Effect.succeed(HttpClientResponse.fromWeb(request, handler(request.url))), + ) + return Layer.succeed(HttpClient.HttpClient, client) +} + +function withRoot(use: (root: string) => Effect.Effect) { + return Effect.acquireUseRelease( + Effect.gen(function* () { + const dir = path.join(os.tmpdir(), "ockit-upd-" + Math.random().toString(36).slice(2)) + yield* Effect.promise(() => fs.mkdir(path.join(dir, ".oc", "state"), { recursive: true })) + return dir + }), + use, + (dir) => Effect.promise(() => fs.rm(dir, { recursive: true, force: true })), + ) +} + +const KIT_V1_MANIFEST = { + id: "engineer", + name: "OC Engineer Kit", + version: "1.0.0", + runtime: "opencode", + skills: [{ id: "plan", description: "Plan" }], +} + +const KIT_V2_MANIFEST = { + id: "engineer", + name: "OC Engineer Kit", + version: "2.0.0", + runtime: "opencode", + skills: [{ id: "plan", description: "Plan v2" }], +} + +const KIT_V1_FILES: Record = { + "kit.json": JSON.stringify(KIT_V1_MANIFEST), + "skills/plan.md": "# Plan v1", +} + +const KIT_V2_FILES: Record = { + "kit.json": JSON.stringify(KIT_V2_MANIFEST), + "skills/plan.md": "# Plan v2", +} + +function fakeExtract(files: Record) { + return (archive: Uint8Array, dest: string) => + Effect.gen(function* () { + const fsutil = yield* FSUtil.Service + yield* fsutil.ensureDir(dest) + for (const [file, content] of Object.entries(files)) { + yield* fsutil.writeWithDirs(path.join(dest, file), content) + } + }) as unknown as Effect.Effect +} + +const V1_BYTES = "v1-archive" +const V2_BYTES = "v2-archive" + +function v1Handler(url: string) { + if (url.endsWith("/releases/tags/1.0.0")) { + return jsonResponse( + releasePayload("1.0.0", [ + releaseAsset("kit.tar.gz", "https://example.com/v1.tar.gz"), + releaseAsset("checksums.txt", "https://example.com/v1-checksums.txt"), + ]), + ) + } + if (url.endsWith("v1.tar.gz")) return new Response(V1_BYTES, { status: 200 }) + if (url.endsWith("checksums.txt")) return new Response(`${Hash.sha256(Buffer.from(V1_BYTES))} kit.tar.gz\n`, { status: 200 }) + if (url.includes("kit.json")) return jsonResponse(KIT_V1_MANIFEST) + return jsonResponse({}) +} + +function v2Handler(url: string) { + if (url.endsWith("/releases")) { + return jsonResponse([ + releasePayload("v2.0.0", [ + releaseAsset("kit.tar.gz", "https://example.com/v2.tar.gz"), + releaseAsset("checksums.txt", "https://example.com/v2-checksums.txt"), + ]), + ]) + } + if (url.endsWith("v2.tar.gz")) return new Response(V2_BYTES, { status: 200 }) + if (url.endsWith("checksums.txt")) return new Response(`${Hash.sha256(Buffer.from(V2_BYTES))} kit.tar.gz\n`, { status: 200 }) + if (url.includes("kit.json")) return jsonResponse(KIT_V2_MANIFEST) + return jsonResponse({}) +} + +/** Install v1 into root so an update can run against it. */ +function installedV1(root: string) { + return install("engineer", { + source: SOURCE, + root, + version: "1.0.0", + extract: fakeExtract(KIT_V1_FILES), + }).pipe(Effect.provide(clientFor(v1Handler))) +} + +describe("ockit updater", () => { + it.effect("update with --dry-run previews without mutating", () => + withRoot((root) => + installedV1(root).pipe( + Effect.flatMap(() => + update("engineer", { source: SOURCE, root, dryRun: true, extract: fakeExtract(KIT_V2_FILES) }).pipe(Effect.provide(clientFor(v2Handler))), + ), + Effect.flatMap((summary: UpdateSummary) => + Effect.gen(function* () { + expect(summary.dryRun).toBe(true) + expect(summary.toVersion).toBe("2.0.0") + expect(summary.replaced).toContain(`${COLLECTED_ROOT_DIR}/engineer/kit.json`) + + // --dry-run must NOT change the installed kit.json on disk. + const kitJson = yield* Effect.promise(() => + fs.readFile(path.join(root, COLLECTED_ROOT_DIR, "engineer", "kit.json"), "utf8"), + ) + expect(kitJson).toContain('"version": "1.0.0"') + }), + ), + ), + ), + ) + + it.effect("update replaces owned-unmodified files and preserves user edits", () => + withRoot((root) => + installedV1(root).pipe( + Effect.flatMap(() => + Effect.gen(function* () { + // User edits skills/plan.md after v1 install. + yield* Effect.promise(() => + fs.writeFile(path.join(root, COLLECTED_ROOT_DIR, "engineer", "skills", "plan.md"), "# user edit"), + ) + const summary = yield* update("engineer", { source: SOURCE, root, extract: fakeExtract(KIT_V2_FILES) }).pipe( + Effect.provide(clientFor(v2Handler)), + ) + expect(summary.toVersion).toBe("2.0.0") + expect(summary.replaced).toContain(`${COLLECTED_ROOT_DIR}/engineer/kit.json`) + // User-edited file is preserved, not overwritten. + expect(summary.preserved).toContain(`${COLLECTED_ROOT_DIR}/engineer/skills/plan.md`) + + const planMd = yield* Effect.promise(() => + fs.readFile(path.join(root, COLLECTED_ROOT_DIR, "engineer", "skills", "plan.md"), "utf8"), + ) + expect(planMd).toBe("# user edit") + + const kitJson = yield* Effect.promise(() => + fs.readFile(path.join(root, COLLECTED_ROOT_DIR, "engineer", "kit.json"), "utf8"), + ) + expect(kitJson).toContain('"version": "2.0.0"') + }), + ), + ), + ), + ) + + it.effect("rollback restores the previous bytes from the latest checkpoint", () => + withRoot((root) => + installedV1(root).pipe( + Effect.flatMap(() => + update("engineer", { source: SOURCE, root, extract: fakeExtract(KIT_V2_FILES) }).pipe(Effect.provide(clientFor(v2Handler))), + ), + Effect.flatMap(() => { + // After update, engine.json says 2.0.0. + return Effect.gen(function* () { + const after = yield* Effect.promise(() => + fs.readFile(path.join(root, COLLECTED_ROOT_DIR, "engineer", "kit.json"), "utf8"), + ) + expect(after).toContain('"version": "2.0.0"') + }) + }), + Effect.flatMap(() => rollback("engineer", { root }).pipe( + Effect.flatMap((summary: UpdateSummary) => + Effect.gen(function* () { + const restored = yield* Effect.promise(() => + fs.readFile(path.join(root, COLLECTED_ROOT_DIR, "engineer", "kit.json"), "utf8"), + ) + // The rollback restores the backup of the previous version. + expect(restored).toContain('"version": "1.0.0"') + }), + ), + )), + ), + ), + ) + + it.effect("rollback fails with a typed error when no checkpoint exists", () => + withRoot((root) => + rollback("engineer", { root }).pipe( + Effect.flip, + Effect.flatMap((err: UpdateError) => { + expect(err).toBeInstanceOf(UpdateError) + expect(err.kind).toBe("rollback") + return Effect.succeed(undefined) + }), + ), + ), + ) + + it.effect("update fails with not-found when the kit is not installed", () => + withRoot((root) => + previewUpdate("engineer", { source: SOURCE, root }).pipe( + Effect.provide(clientFor(v2Handler)), + Effect.flip, + Effect.flatMap((err: UpdateError) => { + expect(err).toBeInstanceOf(UpdateError) + expect(err.kind).toBe("not-found") + return Effect.succeed(undefined) + }), + ), + ), + ) +}) \ No newline at end of file diff --git a/scripts/install.ps1 b/scripts/install.ps1 new file mode 100644 index 000000000..8f927c1df --- /dev/null +++ b/scripts/install.ps1 @@ -0,0 +1,134 @@ +# OC Kit single-command installer (Windows PowerShell). +# +# Pipeline (plan §34-35): detect OS/arch -> fetch release metadata from the +# GitHub Releases registry -> verify sha256 -> install the archive -> update +# PATH -> verify the executable -> surface post-install checks. +# +# The release registry is 'opencode-ai/kits' by default; override with +# OCKIT_REGISTRY_OWNER / OCKIT_REGISTRY_REPO. +# +# NOTE: CI validates the syntax of this script only; no live network install +# ever runs in CI. + +[CmdletBinding()] +param( + [string]$KitId = "engineer", + [string]$Version = "", + [string]$InstallDir = "" +) + +$ErrorActionPreference = "Stop" +$ProgressPreference = "SilentlyContinue" + +$Owner = if ($env:OCKIT_REGISTRY_OWNER) { $env:OCKIT_REGISTRY_OWNER } else { "opencode-ai" } +$Repo = if ($env:OCKIT_REGISTRY_REPO) { $env:OCKIT_REGISTRY_REPO } else { "kits" } +if ($env:OCKIT_KIT_VERSION) { $Version = $env:OCKIT_KIT_VERSION } + +$ApiUrl = "https://api.github.com/repos/$Owner/$Repo/releases" +$RawUrl = "https://raw.githubusercontent.com/$Owner/$Repo" + +function Get-Os { + if ($IsLinux -or $IsMacOS) { + if ($IsMacOS) { return "darwin" } + return "linux" + } + return "windows" +} + +function Get-Arch { + switch ($env:PROCESSOR_ARCHITECTURE) { + "AMD64" { return "amd64" } + "ARM64" { return "arm64" } + "x86" { return "386" } + default { + $unameArch = (& uname -m 2>$null) + if ($unameArch -match "aarch64|arm64") { return "arm64" } + if ($unameArch -match "x86_64|amd64") { return "amd64" } + return "unknown" + } + } +} + +function Resolve-Release { + if ($Version -ne "") { return $Version } + $headers = @{ "User-Agent" = "ockit-installer" } + $releases = Invoke-RestMethod -Uri $ApiUrl -Headers $headers + if ($releases.Count -eq 0) { throw "No releases found for $Owner/$Repo" } + return $releases[0].tag_name +} + +function Get-JsonField { + param([string]$Json, [string]$Key) + $parsed = $Json | ConvertFrom-Json + return $parsed.$Key +} + +function Main { + $os = Get-Os + $arch = Get-Arch + if ($arch -eq "unknown") { throw "Unsupported architecture" } + Write-Host "OC Kit installer - os=$os arch=$arch kit=$KitId" + + $release = Resolve-Release + Write-Host "release: $release" + + if ($InstallDir -eq "") { + $InstallDir = Join-Path $HOME ".opencode-kits\$KitId" + } + New-Item -ItemType Directory -Force -Path $InstallDir | Out-Null + + $archive = "kit-$os-$arch.tar.gz" + $archiveUrl = "$RawUrl/$release/$archive" + $checksumsUrl = "$RawUrl/$release/checksums.txt" + + $tmpPath = Join-Path $env:TEMP "ockit-$KitId-$release.tar.gz" + $checksumsPath = Join-Path $env:TEMP "ockit-$KitId-$release-checksums.txt" + + Write-Host "fetching $archiveUrl" + Invoke-WebRequest -Uri $archiveUrl -OutFile $tmpPath + + # --- verify -------------------------------------------------------------- + $expected = "" + try { + Invoke-WebRequest -Uri $checksumsUrl -OutFile $checksumsPath + $lines = Get-Content $checksumsPath | Where-Object { $_ -match $archive } + if ($lines) { $expected = ($lines[0] -split "\s+")[0].Trim() } + } catch { + Write-Host "warning: no checksum entry found for $archive; skipping verification" + } + if ($expected -ne "") { + $actual = (Get-FileHash -Algorithm SHA256 $tmpPath).Hash.ToLower() + if ($actual -ne $expected.ToLower()) { + Remove-Item $tmpPath -ErrorAction SilentlyContinue + throw "Checksum mismatch for $archive (expected $expected, got $actual)" + } + Write-Host "checksum verified" + } + + # --- install ------------------------------------------------------------- + Expand-Archive -Path $tmpPath -DestinationPath $InstallDir -Force + Remove-Item $tmpPath -ErrorAction SilentlyContinue + Write-Host "installed kit to $InstallDir" + + # --- PATH ---------------------------------------------------------------- + if (Test-Path (Join-Path $InstallDir "bin")) { + $binDir = Join-Path $InstallDir "bin" + $userPath = [Environment]::GetEnvironmentVariable("Path", "User") + if ($userPath -notmatch [regex]::Escape($binDir)) { + [Environment]::SetEnvironmentVariable("Path", "$userPath;$binDir", "User") + Write-Host "added $binDir to user PATH" + } + } + + # --- verify + post-checks ------------------------------------------------ + $opencode = Get-Command opencode -ErrorAction SilentlyContinue + if ($opencode) { + Write-Host "opencode: $(& opencode --version)" + & opencode doctor --install 2>$null + } else { + Write-Host "warning: opencode not found on PATH after install" + } + Write-Host "done" +} + +Main \ No newline at end of file diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100644 index 000000000..f14eecee4 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env sh +# OC Kit single-command installer (macOS / Linux / WSL). +# +# Pipeline (plan §34-35): detect OS/arch → fetch release metadata from the +# GitHub Releases registry → verify sha256 → install the archive → update PATH → +# verify the executable → surface post-install checks. +# +# The release registry is `opencode-ai/kits` by default; override with +# OCKIT_REGISTRY_OWNER / OCKIT_REGISTRY_REPO. +# +# NOTE: CI validates the syntax of this script only (`sh -n`); no live network +# install ever runs in CI. + +set -eu + +KIT_ID="${1:-engineer}" +VERSION="${OCKIT_KIT_VERSION:-}" +OWNER="${OCKIT_REGISTRY_OWNER:-opencode-ai}" +REPO="${OCKIT_REGISTRY_REPO:-kits}" +INSTALL_DIR="${OCKIT_INSTALL_DIR:-}" +API_URL="https://api.github.com/repos/${OWNER}/${REPO}/releases" +RAW_URL="https://raw.githubusercontent.com/${OWNER}/${REPO}" + +# --- detect ---------------------------------------------------------------- +detect_os() { + case "$(uname -s)" in + Linux*) echo "linux" ;; + Darwin*) echo "darwin" ;; + *MINGW*|*MSYS*|*CYGWIN*) echo "windows" ;; + *) echo "unknown" ;; + esac +} + +detect_arch() { + case "$(uname -m)" in + x86_64|amd64) echo "amd64" ;; + arm64|aarch64) echo "arm64" ;; + i386|i686) echo "386" ;; + *) echo "unknown" ;; + esac +} + +have() { + command -v "$1" >/dev/null 2>&1 +} + +# --- fetch ----------------------------------------------------------------- +# Resolve the latest release tag whose kit manifest is compatible with the +# running opencode runtime (min_opencode guard lives in the manifest). +resolve_release() { + if [ -n "$VERSION" ]; then + echo "$VERSION" + return + fi + if ! have curl; then + echo "error: curl is required to install OC Kit" >&2 + exit 1 + fi + curl -fsSL "${API_URL}" | + sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | + head -n 1 +} + +from_json() { + # Minimal JSON field extractor (no jq dependency): prints the value of a + # string field whose key exactly matches "$1". + sed -n "s/.*\"$1\" *: *\"\([^\"]*\)\".*/\1/p" | head -n 1 +} + +main() { + OS="$(detect_os)" + ARCH="$(detect_arch)" + if [ "${OS}" = "unknown" ] || [ "${ARCH}" = "unknown" ]; then + echo "error: unsupported platform (os=${OS}, arch=${ARCH})" >&2 + exit 1 + fi + + echo "OC Kit installer — os=${OS} arch=${ARCH} kit=${KIT_ID}" + + RELEASE="$(resolve_release)" + if [ -z "$RELEASE" ]; then + echo "error: no release found for ${OWNER}/${REPO}" >&2 + exit 1 + fi + echo "release: $RELEASE" + + if [ -z "$INSTALL_DIR" ]; then + INSTALL_DIR="${HOME}/.opencode-kits/${KIT_ID}" + fi + mkdir -p "$INSTALL_DIR" + + ARCHIVE="kit-${OS}-${ARCH}.tar.gz" + ARCHIVE_URL="${RAW_URL}/${RELEASE}/${ARCHIVE}" + CHECKSUMS_URL="${RAW_URL}/${RELEASE}/checksums.txt" + + # --- verify -------------------------------------------------------------- + if [ -n "$VERSION" ] || [ -z "${VERSION}" ]; then :; fi + if have shasum; then + SHA_BIN="shasum" + elif have sha256sum; then + SHA_BIN="sha256sum" + else + echo "error: no sha256 tool found (shasum/sha256sum)" >&2 + exit 1 + fi + + TMPDIR_SAFE="${TMPDIR:-/tmp}" + ARCHIVE_PATH="${TMPDIR_SAFE}/ockit-${KIT_ID}-${RELEASE}.tar.gz" + + echo "fetching ${ARCHIVE_URL}" + curl -fsSL "$ARCHIVE_URL" -o "$ARCHIVE_PATH" + + EXPECTED="" + if curl -fsSL "$CHECKSUMS_URL" 2>/dev/null | grep -q "${ARCHIVE}"; then + EXPECTED="$(curl -fsSL "$CHECKSUMS_URL" 2>/dev/null | grep "${ARCHIVE}" | awk '{print $1}' | head -n 1)" + fi + if [ -n "$EXPECTED" ]; then + ACTUAL="$($SHA_BIN -a 256 "$ARCHIVE_PATH" | awk '{print $1}')" + if [ "$ACTUAL" != "$EXPECTED" ]; then + echo "error: checksum mismatch for ${ARCHIVE} (expected ${EXPECTED}, got ${ACTUAL})" >&2 + rm -f "$ARCHIVE_PATH" + exit 1 + fi + echo "checksum verified" + else + echo "warning: no checksum entry found for ${ARCHIVE}; skipping verification" + fi + + # --- install ------------------------------------------------------------- + tar -xzf "$ARCHIVE_PATH" -C "$INSTALL_DIR" + rm -f "$ARCHIVE_PATH" + echo "installed kit to ${INSTALL_DIR}" + + # --- PATH ---------------------------------------------------------------- + if [ -d "${INSTALL_DIR}/bin" ]; then + case ":$PATH:" in + *":${INSTALL_DIR}/bin:"*) : ;; + *) + echo "export PATH=\"${INSTALL_DIR}/bin:\$PATH\"" >>"${HOME}/.profile" + echo "added ${INSTALL_DIR}/bin to PATH (${HOME}/.profile)" + ;; + esac + fi + + # --- verify + post-checks ------------------------------------------------ + if have opencode; then + echo "opencode: $(opencode --version 2>/dev/null || echo 'unknown')" + if have "opencode" && [ "${OS}" != "windows" ]; then + opencode doctor --install 2>/dev/null || echo "opencode doctor unavailable (non-fatal)" + fi + else + echo "warning: opencode not found on PATH after install" + fi + echo "done" +} + +main "$@" \ No newline at end of file