From 7f2f3bff360ac6801c48ed6b7108d13179079869 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Fri, 14 Aug 2026 19:53:39 +0700 Subject: [PATCH 01/12] docs: add OC Kit phase 0/1 plan and upstream tracking Record the fork's relationship to upstream anomalyco/opencode (1.18.18 line, no re-pin) and the phase 0+1 plan covering the OC Kit domain model, branch strategy, and CI-first verification. Upstream: https://github.com/anomalyco/opencode --- UPSTREAM.md | 32 ++++++++++ plans/260814-1636-oc-kit-phase0-1/plan.md | 78 +++++++++++++++++++++++ 2 files changed, 110 insertions(+) create mode 100644 UPSTREAM.md create mode 100644 plans/260814-1636-oc-kit-phase0-1/plan.md diff --git a/UPSTREAM.md b/UPSTREAM.md new file mode 100644 index 000000000..7cbf31c57 --- /dev/null +++ b/UPSTREAM.md @@ -0,0 +1,32 @@ +# Upstream Tracking + +This file records the relationship between this fork and the upstream OpenCode +repository, per the OC Kit integration plan (Phase 0: upstream freeze & audit). + +## Upstream + +- Repository: `https://github.com/anomalyco/opencode` +- License: MIT + +## Fork status + +- Local fork: `vibecoder880/opencode` +- Local `packages/opencode/package.json` version: `1.18.18` +- Upstream main has moved beyond this line (upstream exposes a `2.0` branch); + this fork is a snapshot of the `1.18.x` line and does NOT track upstream main. + +## Divergence policy + +- OC Kit is designed to extend OpenCode through existing extension points + (skills, agents, commands, plugins, config, tools) rather than invasive core + patches. +- We do not re-pin to upstream in Phase 0/1. Re-evaluate upstream sync when a + concrete merge target is agreed. +- Custom patches to core OpenCode files are documented inline at each patch + site and summarized in this file. + +## Commit conventions + +- Conventional commit style: `type(scope): summary`. +- Commit author email: `cavangcute478@gmail.com`. +- Verified via GitHub Actions CI (`test.yml`, `typecheck.yml`) on PRs into `dev`. diff --git a/plans/260814-1636-oc-kit-phase0-1/plan.md b/plans/260814-1636-oc-kit-phase0-1/plan.md new file mode 100644 index 000000000..4edb1bd95 --- /dev/null +++ b/plans/260814-1636-oc-kit-phase0-1/plan.md @@ -0,0 +1,78 @@ +# OC Kit — Phase 0 + Phase 1 + +## Context + +This fork (`vibecoder880/opencode`, based on `anomalyco/opencode`) aims to build **OC Kit**: a workflow/agent engineering layer native to OpenCode, turning it into an Agent Runtime + Workflow OS. The full vision is in `OC-Kit_OpenCode_Integration_Plan.md` (Kit → Skill → Agent → Workflow → Hook → Artifact → Checkpoint, plus CLI, registry, installer). + +This plan covers the first two phases only (per user decision): + +- **Phase 0** — Upstream freeze & codebase audit: verify the vanilla fork builds/tests on CI, pin upstream context, create `UPSTREAM.md`. +- **Phase 1** — OC Kit domain model: `Kit` / `Skill` / `Agent` / `Workflow` / `Hook` / `Artifact` / `Checkpoint` / `Ownership` types + schemas + validators + storage. Exit criteria: load & validate a complete local kit. + +## Workflow contract (user-set, persisted in memory) + +- No local build / `npm i` / project run. Test + build happen on **GitHub Actions CI**. +- Light tests only locally (and locally we lack `bun`, so verification is CI-first). +- Commit each finished unit with **detailed English** messages; one language (English). +- Commit email: `cavangcute478@gmail.com` (already set for this repo). +- Push only when tests pass. + +## Branch strategy (user decision) + +- Work on a **feature branch** (per AGENTS.md: ≤3 words, no `feat/` prefix) and open a **PR into `dev`**. +- CI (`test.yml`, `typecheck.yml`) triggers on pushes to `dev` and on PRs — so the PR itself is the CI gate. +- `dev` branch does not exist yet on origin (only `main`). It must be created from `main` before PRs can target it. + +## Findings from audit (Phase 0) + +- Repo is a monorepo; OpenCode runtime lives in `packages/opencode` (version 1.18.18). +- `AGENTS.md` governs style: no aliased imports, no star imports, `@/*` → `./src/*`, `@test/*` → `./test/*`, Effect Schema everywhere, kebab-case names, self-export pattern in `src/config/*`. +- CLI commands: yargs `CommandModule` via `effectCmd` (packages/opencode/src/cli/effect-cmd.ts), registered in `src/index.ts` via `.command(X)`. +- Skill system: `packages/opencode/src/skill/index.ts` — loads `SKILL.md` via `ConfigMarkdown.parse`, exposes `Skill.Service` with `get/require/all/available`. Built-in skill `customize-opencode`. Skills also surface as slash commands in `command/index.ts`. +- Agent system: `src/agent/agent.ts` + `src/config/agent.ts`; agents are `.md` files with frontmatter in `.opencode/agent`. +- Config: `ConfigV1.Info` (packages/core/src/v1/config/config.ts) is an `Effect.Schema.Struct`; new sections are added there + a self-export module in `src/config/`. +- Tool registry: `src/tool/registry.ts` — builtins registered via `Tool.init(...)`, custom from plugins/`.opencode/tool`. +- Tests: `bun:test` in `packages/opencode/test/`, `testEffect(layer)` helper (test/lib/effect.ts), fixtures in `test/fixture/fixture.ts`. CI runs `bun turbo test`. +- Upstream reachable (`anomalyco/opencode`); local fork tracks a different line (1.18.18) than upstream main (has `2.0` branch). We do NOT re-pin to upstream in this phase — document the divergence in `UPSTREAM.md`. + +## Deliverables + +### Phase 0 +- [ ] `UPSTREAM.md` at repo root — upstream repo URL, fork divergence notes, custom-patch policy. +- [ ] `dev` branch created from `main` and pushed to origin (so PRs can target it). +- [ ] First feature branch pushed + a trivial PR into `dev` runs CI green (baseline). + +### Phase 1 — `packages/opencode/src/ockit/` +- [ ] `types.ts` — Effect Schema for Kit/Skill/Agent/Workflow/Hook/Artifact/Checkpoint/Ownership. +- [ ] `manifest.ts` — kit manifest parse/validate (`kit.yaml` → typed Kit). +- [ ] `registry.ts` — registry of installed kits + kit metadata index. +- [ ] `resolver.ts` — resolve a skill/agent/workflow by name from an installed kit. +- [ ] `ownership.ts` — ownership manifest (`files → {owner, kit, version, sha256}`), conflict detection. +- [ ] `checkpoint.ts` — checkpoint records (before/after hashes, operation, session). +- [ ] `config.ts` — `oc_kit` config schema (enabled, default_kit, default_mode, auto_workflow, checkpoint, telemetry). +- [ ] `index.ts` — export surface + `ockit` namespace. +- [ ] Unit tests in `packages/opencode/test/ockit/` (manifest, registry, resolver, ownership, checkpoint, config). + +Note: workflow engine, hook dispatcher, artifact manager, CLI, installer, registry backend are later phases — NOT in scope here (YAGNI). + +## Files to create + +``` +packages/opencode/src/ockit/{index,types,manifest,registry,resolver,ownership,checkpoint,config}.ts +packages/opencode/test/ockit/*.test.ts +UPSTREAM.md +``` + +## Verification (CI-first) + +1. Feature branch → push → open PR into `dev`. +2. GitHub Actions `test.yml` runs `bun turbo test` (unit tests incl. new `ockit` tests) on the PR. +3. `typecheck.yml` runs `bun typecheck`. +4. Only merge PR (to `dev`) when both are green. +5. Commit messages: English, conventional format, email `cavangcute478@gmail.com`. + +## Risks / rollback + +- `dev` branch creation is a one-time repo setup; safe (branches off current `main`). +- Adding `oc_kit` to `ConfigV1.Info` touches the shared config schema — keep it strictly optional so existing projects are unaffected (plan §40 compatibility). +- No runtime wiring yet (no workflow engine / hooks) — no risk to existing OpenCode behavior in this phase. From e035562857632bc5b3e5c14b5e2ea5b948783802 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Fri, 14 Aug 2026 19:53:47 +0700 Subject: [PATCH 02/12] feat(opencode): add OC Kit domain model (Phase 1) Introduce the OC Kit workflow/agent engineering layer in packages/opencode/src/ockit. Phase 1 delivers the typed domain model only; the workflow engine, hook dispatcher, artifact manager, CLI, and installer land in later phases. Schemas (types.ts): Kit, KitSkill, KitAgent, Workflow/WorkflowStep, KitHook, Mode, WorkflowState, WorkflowRun, Artifact, Checkpoint, OwnershipEntry/Manifest, OCKitConfig as Effect Schemas. Manifest (manifest.ts): loadManifest reads kit.json (prefers) or kit.yaml via Bun.YAML, validates against the Kit schema, and reports ManifestError. Parse/schema failures are effectful errors, never synchronous throws. Registry (registry.ts): OCKitRegistry service scans global /kits and per-project config-dir kits/ lazily via InstanceState; all/get/require/dirs with NotFoundError and invalid-manifest skips. Resolver (resolver.ts): indexKit builds name-indexed maps; resolveFromKit throws ResolveError; resolveAcross searches kits in order. Ownership (ownership.ts): load/save/claim/detectUserEdits/planUpdate implement the ownership manifest with sha256 conflict detection and replace/preserve planning. Checkpoint (checkpoint.ts): create/list/read checkpoint snapshots under .oc/state/checkpoints recording per-file sha256. Config (config.ts): defaults, read, enabled, validate for the oc_kit section. Config schema (core): add optional oc_kit section to ConfigV1.Info. Tests: unit suites under packages/opencode/test/ockit for manifest, registry, resolver, ownership, checkpoint, config. --- UPSTREAM.md | 2 +- packages/core/src/v1/config/config.ts | 20 +++ packages/opencode/src/ockit/checkpoint.ts | 72 ++++++++ packages/opencode/src/ockit/config.ts | 37 ++++ packages/opencode/src/ockit/index.ts | 31 ++++ packages/opencode/src/ockit/manifest.ts | 84 +++++++++ packages/opencode/src/ockit/ownership.ts | 116 +++++++++++++ packages/opencode/src/ockit/registry.ts | 124 ++++++++++++++ packages/opencode/src/ockit/resolver.ts | 65 +++++++ packages/opencode/src/ockit/types.ts | 159 ++++++++++++++++++ .../opencode/test/ockit/checkpoint.test.ts | 67 ++++++++ packages/opencode/test/ockit/config.test.ts | 40 +++++ packages/opencode/test/ockit/manifest.test.ts | 100 +++++++++++ .../opencode/test/ockit/ownership.test.ts | 108 ++++++++++++ packages/opencode/test/ockit/registry.test.ts | 90 ++++++++++ packages/opencode/test/ockit/resolver.test.ts | 52 ++++++ plans/260814-1636-oc-kit-phase0-1/plan.md | 19 ++- 17 files changed, 1176 insertions(+), 10 deletions(-) create mode 100644 packages/opencode/src/ockit/checkpoint.ts create mode 100644 packages/opencode/src/ockit/config.ts create mode 100644 packages/opencode/src/ockit/index.ts create mode 100644 packages/opencode/src/ockit/manifest.ts create mode 100644 packages/opencode/src/ockit/ownership.ts create mode 100644 packages/opencode/src/ockit/registry.ts create mode 100644 packages/opencode/src/ockit/resolver.ts create mode 100644 packages/opencode/src/ockit/types.ts create mode 100644 packages/opencode/test/ockit/checkpoint.test.ts create mode 100644 packages/opencode/test/ockit/config.test.ts create mode 100644 packages/opencode/test/ockit/manifest.test.ts create mode 100644 packages/opencode/test/ockit/ownership.test.ts create mode 100644 packages/opencode/test/ockit/registry.test.ts create mode 100644 packages/opencode/test/ockit/resolver.test.ts diff --git a/UPSTREAM.md b/UPSTREAM.md index 7cbf31c57..225c1d653 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -29,4 +29,4 @@ repository, per the OC Kit integration plan (Phase 0: upstream freeze & audit). - Conventional commit style: `type(scope): summary`. - Commit author email: `cavangcute478@gmail.com`. -- Verified via GitHub Actions CI (`test.yml`, `typecheck.yml`) on PRs into `dev`. +- Verified via GitHub Actions CI (`test.yml`, `typecheck.yml`) on PRs into `main`. diff --git a/packages/core/src/v1/config/config.ts b/packages/core/src/v1/config/config.ts index 7ebb4b69b..2c2a9490e 100644 --- a/packages/core/src/v1/config/config.ts +++ b/packages/core/src/v1/config/config.ts @@ -187,6 +187,26 @@ export const Info = Schema.Struct({ }), }), ), + oc_kit: Schema.optional( + Schema.Struct({ + enabled: Schema.optional(Schema.Boolean).annotate({ description: "Enable OC Kit" }), + default_kit: Schema.optional(Schema.String).annotate({ description: "Kit used by default" }), + default_mode: Schema.optional(Schema.Literals(["fast", "normal", "deep", "autonomous"])).annotate({ + description: "Default OC Kit workflow mode", + }), + auto_workflow: Schema.optional(Schema.Boolean).annotate({ + description: "Auto-select a workflow from a task description", + }), + auto_review: Schema.optional(Schema.Boolean).annotate({ description: "Review after implementation" }), + auto_test: Schema.optional(Schema.Boolean).annotate({ description: "Test after implementation" }), + checkpoint: Schema.optional(Schema.Boolean).annotate({ + description: "Snapshot managed files before risky kit updates", + }), + telemetry: Schema.optional(Schema.Boolean).annotate({ + description: "Send anonymous operational metrics (default: off)", + }), + }), + ).annotate({ description: "OC Kit workflow/agent engineering layer configuration" }), }).annotate({ identifier: "Config" }) export type Info = DeepMutable> diff --git a/packages/opencode/src/ockit/checkpoint.ts b/packages/opencode/src/ockit/checkpoint.ts new file mode 100644 index 000000000..3dc0b5ec2 --- /dev/null +++ b/packages/opencode/src/ockit/checkpoint.ts @@ -0,0 +1,72 @@ +// OC Kit checkpoints: a snapshot of managed files taken before a +// risky operation (kit install/update/rollback). Each checkpoint records the +// kit version, operation, timestamp, and per-file sha256 so the operation can +// be rolled back to a known-good state. + +import { Effect, Schema } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Hash } from "@opencode-ai/core/util/hash" +import { Checkpoint } from "./types" + +/** Default directory where checkpoint snapshots are stored. */ +export const CHECKPOINT_DIR = ".oc/state/checkpoints" + +export class CheckpointError extends Schema.TaggedErrorClass()("OCKitCheckpointError", { + path: Schema.String, + message: Schema.optional(Schema.String), +}) { + override get message() { + return `OC Kit checkpoint: ${this.path}${this.message ? ` — ${this.message}` : ""}` + } +} + +/** Write a checkpoint file for the given operation + managed files. */ +export const create = Effect.fn("OCKit.checkpoint.create")(function* (input: { + root: string + kit: string + kitVersion: string + operation: string + session?: string + workflow?: string + files: Record +}) { + const fs = yield* FSUtil.Service + const id = `${Date.now()}-${input.kit}-${input.operation}` + const checkpoint: Checkpoint = { + kit: input.kit, + kit_version: input.kitVersion, + operation: input.operation, + timestamp: new Date().toISOString(), + session: input.session, + workflow: input.workflow, + files: Object.fromEntries(Object.entries(input.files).map(([file, content]) => [file, Hash.sha256(content)])), + } + const path = `${input.root}/${CHECKPOINT_DIR}/${id}.json` + yield* fs.writeWithDirs(path, JSON.stringify(checkpoint, null, 2)) + return path +}) + +/** List checkpoint ids for a kit/operation, newest first. */ +export const list = Effect.fn("OCKit.checkpoint.list")(function* (root: string, kit?: string) { + const fs = yield* FSUtil.Service + const dir = `${root}/${CHECKPOINT_DIR}` + if (!(yield* fs.isDir(dir))) return [] as string[] + const entries = yield* fs.readDirectoryEntries(dir) + const files = entries.filter((entry) => entry.type === "file" && entry.name.endsWith(".json")) + const ids = files.map((entry) => entry.name.replace(/\.json$/, "")) + return kit ? ids.filter((id) => id.includes(`-${kit}-`)).toReversed() : ids.toReversed() +}) + +/** Read a single checkpoint by id. */ +export const read = Effect.fn("OCKit.checkpoint.read")(function* (root: string, id: string) { + const fs = yield* FSUtil.Service + const path = `${root}/${CHECKPOINT_DIR}/${id}.json` + const raw = yield* fs.readFileStringSafe(path) + if (raw === undefined) return yield* new CheckpointError({ path, message: `No checkpoint "${id}"` }) + const decoded = yield* Schema.decodeUnknown(Checkpoint)(JSON.parse(raw)).pipe( + Effect.mapError((err) => new CheckpointError({ path, message: Schema.TreeFormatter.formatIssueSync(err.issue) })), + ) + return decoded +}) + +export * as Checkpoint from "./checkpoint" \ No newline at end of file diff --git a/packages/opencode/src/ockit/config.ts b/packages/opencode/src/ockit/config.ts new file mode 100644 index 000000000..caf2f05be --- /dev/null +++ b/packages/opencode/src/ockit/config.ts @@ -0,0 +1,37 @@ +// OC Kit config access. The `oc_kit` section lives in opencode.json under +// ConfigV1.Info (schema in packages/core/src/v1/config/config.ts). This module +// exposes typed accessors so OC Kit runtime code reads its settings through the +// existing Config service instead of a parallel config system. + +import { Effect } from "effect" +import { Config } from "@/config/config" +import { OCKitConfig, type OCKitConfig as OCKitConfigType } from "./types" + +export const defaults: OCKitConfigType = { + enabled: true, + default_kit: "engineer", + default_mode: "normal", + auto_workflow: true, + auto_review: true, + auto_test: true, + checkpoint: true, + telemetry: false, +} + +/** Read the effective OC Kit config, applying defaults over the user's values. */ +export const read = Effect.fn("OCKit.config")(function* () { + const config = yield* Config.Service + const cfg = yield* config.get() + const user = cfg.oc_kit ?? {} + return { ...defaults, ...user } +}) + +/** True when OC Kit is enabled in the current project config. */ +export const enabled = Effect.fn("OCKit.config.enabled")(function* () { + return (yield* read()).enabled === true +}) + +/** Validate a raw `oc_kit` value structurally (used when parsing config). */ +export function validate(input: unknown): OCKitConfigType | undefined { + return OCKitConfig.decodeUnknownOption(input) +} diff --git a/packages/opencode/src/ockit/index.ts b/packages/opencode/src/ockit/index.ts new file mode 100644 index 000000000..4e9d25290 --- /dev/null +++ b/packages/opencode/src/ockit/index.ts @@ -0,0 +1,31 @@ +// OC Kit — workflow/agent engineering layer for OpenCode. +// Phase 1 scope: domain types + manifest/registry/resolver/ownership/checkpoint +// + config access. Workflow engine, hooks, artifact manager, CLI, registry +// backend, and installer arrive in later phases. + +export * as OCKitTypes from "./types" +export * as OCKitManifest from "./manifest" +export * as OCKitRegistry from "./registry" +export * as OCKitResolver from "./resolver" +export * as OCKitOwnership from "./ownership" +export * as OCKitCheckpoint from "./checkpoint" +export * as OCKitConfigModule from "./config" + +export { + Kit, + KitSkill, + KitAgent, + Workflow, + WorkflowStep, + KitHook, + WorkflowRun, + WorkflowState, + Mode, + Artifact, + Checkpoint, + OwnershipManifest, + OwnershipEntry, + OCKitConfig, +} from "./types" + +export { Service as Registry, node as registryNode } from "./registry" diff --git a/packages/opencode/src/ockit/manifest.ts b/packages/opencode/src/ockit/manifest.ts new file mode 100644 index 000000000..428b76227 --- /dev/null +++ b/packages/opencode/src/ockit/manifest.ts @@ -0,0 +1,84 @@ +// Kit manifest loading and validation. A kit is a directory containing a +// manifest file (`kit.json` or `kit.yaml`) plus optional skills/agents/ +// workflows/hooks/rules directories. Manifest data is validated structurally +// against the OC Kit schema so a malformed kit fails with a typed error. + +import { Effect, Schema } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Kit, KitSkill, KitAgent, Workflow, KitHook } from "./types" + +export const KIT_MANIFEST_JSON = "kit.json" +export const KIT_MANIFEST_YAML = "kit.yaml" + +export class ManifestError extends Schema.TaggedErrorClass()("OCKitManifestError", { + path: Schema.String, + message: Schema.optional(Schema.String), +}) {} + +/** + * Read and validate the manifest of a kit directory. Prefers `kit.json`; + * falls back to `kit.yaml` (parsed via Bun's built-in YAML support, so no + * extra dependency). Returns the typed kit manifest, or a ManifestError when + * neither manifest exists or the content does not validate. + */ +export const loadManifest = Effect.fn("OCKit.manifest")(function* (kitDir: string) { + const fs = yield* FSUtil.Service + + const jsonPath = `${kitDir}/${KIT_MANIFEST_JSON}` + const yamlPath = `${kitDir}/${KIT_MANIFEST_YAML}` + + const hasJson = yield* fs.exists(jsonPath) + const hasYaml = yield* fs.exists(yamlPath) + if (!hasJson && !hasYaml) { + return yield* new ManifestError({ + path: kitDir, + message: `No kit manifest found (expected ${KIT_MANIFEST_JSON} or ${KIT_MANIFEST_YAML})`, + }) + } + + const path = hasJson ? jsonPath : yamlPath + const source = yield* fs.readFileStringSafe(path) + if (source === undefined) { + return yield* new ManifestError({ path, message: `Unable to read ${path}` }) + } + const raw = yield* Effect.try({ + try: () => (hasJson ? JSON.parse(source) : Bun.YAML.parse(source)), + catch: (cause) => new ManifestError({ path, message: `Invalid ${KIT_MANIFEST_JSON} syntax: ${String(cause)}` }), + }) + + const decoded = yield* Schema.decodeUnknown(Kit)(raw).pipe( + Effect.mapError( + (err) => new ManifestError({ path, message: Schema.TreeFormatter.formatIssueSync(err.issue) }), + ), + ) + + return decoded +}) + +/** + * Load the skill/agent/workflow/hook definitions embedded in a kit's + * directory tree (`.opencode`-style SKILL.md/agent files are NOT loaded here — + * they surface through the existing OpenCode Skill/Agent services). This + * resolves the declarative skill/agent definitions from `kit.yaml`/`kit.json` + * manifests into runnable metadata. + */ +export function resolveKitDeclarations(kit: Kit) { + const skills = (kit.skills ?? []).map((skill) => SkillDeclaration(skill)) + const agents = (kit.agents ?? []).map((agent) => AgentDeclaration(agent)) + const workflows = (kit.workflows ?? []).map((workflow) => WorkflowDeclaration(workflow)) + const hooks = (kit.hooks ?? []).map((hook) => HookDeclaration(hook)) + return { skills, agents, workflows, hooks } +} + +function SkillDeclaration(skill: KitSkill) { + return { type: "skill" as const, ...skill } +} +function AgentDeclaration(agent: KitAgent) { + return { type: "agent" as const, ...agent } +} +function WorkflowDeclaration(workflow: Workflow) { + return { type: "workflow" as const, ...workflow } +} +function HookDeclaration(hook: KitHook) { + return { type: "hook" as const, ...hook } +} diff --git a/packages/opencode/src/ockit/ownership.ts b/packages/opencode/src/ockit/ownership.ts new file mode 100644 index 000000000..187006556 --- /dev/null +++ b/packages/opencode/src/ockit/ownership.ts @@ -0,0 +1,116 @@ +// OC Kit ownership model: tracks which kit owns a managed file, +// at which version, and the sha256 it shipped. Used to make kit update/rollback +// safe — files the user has modified since install are preserved, never +// overwritten, and conflicts between kits are detected. + +import { Effect, Schema } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Hash } from "@opencode-ai/core/util/hash" +import { OwnershipManifest, type OwnershipEntry } from "./types" + +/** Default location of the ownership manifest inside `.oc/state`. */ +export const OWNERSHIP_MANIFEST_PATH = ".oc/state/ownership.json" + +export class OwnershipError extends Schema.TaggedErrorClass()("OCKitOwnershipError", { + path: Schema.String, + message: Schema.optional(Schema.String), +}) { + override get message() { + return `OC Kit ownership: ${this.path}${this.message ? ` — ${this.message}` : ""}` + } +} + +/** Load the ownership manifest, returning an empty manifest when absent. */ +export const loadOwnership = Effect.fn("OCKit.ownership.load")(function* (root: string) { + const fs = yield* FSUtil.Service + const path = `${root}/${OWNERSHIP_MANIFEST_PATH}` + const raw = yield* fs.readFileStringSafe(path) + if (raw === undefined) return { files: {} } + const decoded = yield* Schema.decodeUnknown(OwnershipManifest)(JSON.parse(raw)).pipe( + Effect.mapError((err) => new OwnershipError({ path, message: Schema.TreeFormatter.formatIssueSync(err.issue) })), + ) + return decoded +}) + +/** Persist an ownership manifest (creating parent directories as needed). */ +export const saveOwnership = Effect.fn("OCKit.ownership.save")(function* (root: string, manifest: OwnershipManifest) { + const fs = yield* FSUtil.Service + const path = `${root}/${OWNERSHIP_MANIFEST_PATH}` + yield* fs.writeWithDirs(path, JSON.stringify(manifest, null, 2)) +}) + +/** + * Claim ownership of files shipped by a kit: records each file's owner, kit, + * version, and the sha256 of the content being installed. Existing entries are + * checked for conflicting owners (a file may only be owned by one kit). + */ +export const claim = Effect.fn("OCKit.ownership.claim")(function* ( + manifest: OwnershipManifest, + kit: string, + version: string, + files: Record, +) { + const conflicts: string[] = [] + for (const file of Object.keys(files)) { + const existing = manifest.files[file] + if (existing && existing.kit !== kit) conflicts.push(file) + } + if (conflicts.length > 0) { + return yield* new OwnershipError({ + path: conflicts.join(", "), + message: `These files are already owned by another kit`, + }) + } + for (const [file, content] of Object.entries(files)) { + const entry: OwnershipEntry = { owner: "oc-kit", kit, version, sha256: Hash.sha256(content) } + manifest.files[file] = entry + } + return manifest +}) + +/** + * Detect user edits: compares the current sha256 of a managed file against the + * sha256 recorded at install time. Returns the list of modified files. + */ +export const detectUserEdits = Effect.fn("OCKit.ownership.detectEdits")(function* ( + fs: FSUtil.Interface, + root: string, + manifest: OwnershipManifest, +) { + const modified: string[] = [] + for (const [file, entry] of Object.entries(manifest.files)) { + const content = yield* fs.readFileStringSafe(`${root}/${file}`) + if (content !== undefined && Hash.sha256(content) !== entry.sha256) modified.push(file) + } + return modified +}) + +/** + * Decide per-file update action: + * - owned by us and unmodified → "replace" + * - owned by us but user-modified → "preserve" (warn) + * - not owned (user file) → "preserve" + */ +export const planUpdate = Effect.fn("OCKit.ownership.planUpdate")(function* ( + fs: FSUtil.Interface, + root: string, + manifest: OwnershipManifest, + kit: string, + files: Record, +) { + const plan: { replace: string[]; preserve: string[]; warn: string[] } = { replace: [], preserve: [], warn: [] } + for (const file of Object.keys(files)) { + const entry = manifest.files[file] + if (!entry || entry.kit !== kit) { + plan.preserve.push(file) + continue + } + const content = yield* fs.readFileStringSafe(`${root}/${file}`) + if (content === undefined || Hash.sha256(content) === entry.sha256) plan.replace.push(file) + else plan.warn.push(file) + } + plan.warn.forEach((file) => plan.preserve.push(file)) + return plan +}) + +export * as Ownership from "./ownership" \ No newline at end of file diff --git a/packages/opencode/src/ockit/registry.ts b/packages/opencode/src/ockit/registry.ts new file mode 100644 index 000000000..e79a097e1 --- /dev/null +++ b/packages/opencode/src/ockit/registry.ts @@ -0,0 +1,124 @@ +// OC Kit registry: discovers installed kits across the global config dir and +// project `.opencode/kits` dirs, indexes their manifests, and resolves a kit +// by id. Loads lazily through the instance state so startup cost stays ~0 when +// OC Kit is disabled. + +import { Effect, Layer, Context, Schema } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Global } from "@opencode-ai/core/global" +import { InstanceState } from "@/effect/instance-state" +import { Config } from "@/config/config" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import path from "path" +import { loadManifest } from "./manifest" +import { Kit } from "./types" + +/** Directory name that holds installed kits (global and per-project). */ +export const KITS_DIR = "kits" + +export class NotFoundError extends Schema.TaggedErrorClass()("OCKit.NotFoundError", { + id: Schema.String, + available: Schema.Array(Schema.String), +}) {} + +type State = { + kits: Record + dirs: string[] +} + +export interface Interface { + readonly all: () => Effect.Effect + readonly get: (id: string) => Effect.Effect + readonly require: (id: string) => Effect.Effect + readonly dirs: () => Effect.Effect +} + +export class Service extends Context.Service()("@opencode/OCKitRegistry") {} + +const layer = Layer.effect( + Service, + Effect.gen(function* () { + const config = yield* Config.Service + const fs = yield* FSUtil.Service + + const indexKit = Effect.fn("OCKitRegistry.indexKit")(function* ( + kitDir: string, + kits: State["kits"], + dirs: string[], + ) { + const manifest = yield* loadManifest(kitDir).pipe( + Effect.catchTag("OCKitManifestError", (err) => + Effect.logWarning("skipping invalid kit manifest", { dir: kitDir, error: err.message }).pipe(Effect.as(undefined)), + ), + ) + if (!manifest) return + if (kits[manifest.id]) { + yield* Effect.logWarning("duplicate kit id, keeping first", { id: manifest.id, dir: kitDir }) + return + } + kits[manifest.id] = manifest + dirs.push(kitDir) + }) + + const state = yield* InstanceState.make( + Effect.fn("OCKitRegistry.state")(function* (ctx) { + const kits: Record = {} + const dirs: string[] = [] + + // Global: /kits// + const globalKits = path.join(Global.Path.config, KITS_DIR) + if (yield* fs.isDir(globalKits)) { + for (const entry of yield* fs.readDirectoryEntries(globalKits)) { + if (entry.type !== "directory") continue + yield* indexKit(path.join(globalKits, entry.name), kits, dirs) + } + } + + // Project: /kits/ from each config directory (up-find of .opencode). + const configDirs = yield* config.directories() + for (const dir of configDirs) { + const projectKits = path.join(dir, KITS_DIR) + if (!(yield* fs.isDir(projectKits))) continue + for (const entry of yield* fs.readDirectoryEntries(projectKits)) { + if (entry.type !== "directory") continue + yield* indexKit(path.join(projectKits, entry.name), kits, dirs) + } + } + + return { kits, dirs } + }), + ) + + const all = Effect.fn("OCKitRegistry.all")(function* () { + const s = yield* InstanceState.get(state) + return Object.values(s.kits) + }) + + const get = Effect.fn("OCKitRegistry.get")(function* (id: string) { + const s = yield* InstanceState.get(state) + return s.kits[id] + }) + + const require = Effect.fn("OCKitRegistry.require")(function* (id: string) { + const s = yield* InstanceState.get(state) + const kit = s.kits[id] + if (kit) return kit + return yield* new NotFoundError({ id, available: Object.keys(s.kits).toSorted() }) + }) + + const dirs = Effect.fn("OCKitRegistry.dirs")(function* () { + const s = yield* InstanceState.get(state) + return s.dirs + }) + + return Service.of({ all, get, require, dirs }) + }), +) + +export const node = LayerNode.make({ + service: Service, + layer, + deps: [Config.node, FSUtil.node], +}) + +export * as Registry from "./registry" diff --git a/packages/opencode/src/ockit/resolver.ts b/packages/opencode/src/ockit/resolver.ts new file mode 100644 index 000000000..6c9585f8f --- /dev/null +++ b/packages/opencode/src/ockit/resolver.ts @@ -0,0 +1,65 @@ +// OC Kit resolver: resolve a skill/agent/workflow declared by a kit by name. +// Works purely against the typed kit manifest (no disk I/O), so it is cheap to +// call and trivially testable. + +import { Schema } from "effect" +import { Kit, KitSkill, KitAgent, Workflow, KitHook } from "./types" + +export class ResolveError extends Schema.TaggedErrorClass()("OCKit.ResolveError", { + kind: Schema.Literals(["skill", "agent", "workflow", "hook"]), + id: Schema.String, + kit: Schema.String, +}) { + override get message() { + return `OC Kit: no ${this.kind} "${this.id}" declared in kit "${this.kit}"` + } +} + +/** Everything a kit declares, indexed by name for lookup. */ +export interface KitIndex { + readonly kit: Kit + readonly skills: Map + readonly agents: Map + readonly workflows: Map + readonly hooks: Map +} + +/** Build a name-indexed view of a kit's declarations. */ +export function indexKit(kit: Kit): KitIndex { + return { + kit, + skills: new Map((kit.skills ?? []).map((skill) => [skill.id, skill])), + agents: new Map((kit.agents ?? []).map((agent) => [agent.id, agent])), + workflows: new Map((kit.workflows ?? []).map((workflow) => [workflow.id, workflow])), + hooks: new Map((kit.hooks ?? []).map((hook) => [hook.event, hook])), + } +} + +/** Resolve a kit's own declarations by name; throws ResolveError when absent. */ +export function resolveFromKit(index: KitIndex, kind: KitIndexKeys, id: string) { + const found = index[kind].get(id) + if (found) return found + throw new ResolveError({ kind, id, kit: index.kit.id }) +} + +type KitIndexKeys = "skills" | "agents" | "workflows" | "hooks" + +/** + * Resolve a declaration across all installed kits. `registry` is an injected + * async iterator of kits (an Effect), so this stays framework-agnostic and can + * be driven by the Registry.Service in production and by a plain array in tests. + */ +export async function resolveAcross( + kits: Iterable, + kind: KitIndexKeys, + id: string, +): Promise<{ kit: Kit; value: unknown } | undefined> { + for (const kit of kits) { + const index = indexKit(kit) + const value = index[kind].get(id) + if (value) return { kit, value } + } + return undefined +} + +export * as Resolver from "./resolver" diff --git a/packages/opencode/src/ockit/types.ts b/packages/opencode/src/ockit/types.ts new file mode 100644 index 000000000..8b492e7e8 --- /dev/null +++ b/packages/opencode/src/ockit/types.ts @@ -0,0 +1,159 @@ +// OC Kit core domain types. Every OC Kit primitive (Kit, Skill, Agent, +// Workflow, Hook, Artifact, Checkpoint, Ownership) is an Effect Schema so +// loaded kit manifests validate structurally and errors are typed. + +import { Schema } from "effect" + +/** + * A workflow step references one capability (a skill) plus optional per-step + * overrides. `run` names the skill; `as` is an optional local alias used when + * the same skill is referenced more than once in a workflow. + */ +export const WorkflowStep = Schema.Struct({ + skill: Schema.String, + as: Schema.optional(Schema.String), +}) +export type WorkflowStep = Schema.Schema.Type + +/** A workflow is an ordered sequence of skills with an optional failure handler. */ +export const Workflow = Schema.Struct({ + id: Schema.String, + description: Schema.optional(Schema.String), + steps: Schema.Array(WorkflowStep), + onFailure: Schema.optional(Schema.Array(Schema.String)), +}) +export type Workflow = Schema.Schema.Type + +/** Skill capability declared by a kit. Maps onto OpenCode's SKILL.md format. */ +export const KitSkill = Schema.Struct({ + id: Schema.String, + description: Schema.optional(Schema.String), + agent: Schema.optional(Schema.String), + tools: Schema.optional(Schema.Array(Schema.String)), + permissions: Schema.optional(Schema.Record(Schema.String, Schema.Literals(["allow", "deny"]))), + artifacts: Schema.optional(Schema.Array(Schema.String)), +}) +export type KitSkill = Schema.Schema.Type + +/** Agent profile declared by a kit. Maps onto OpenCode's agent md format. */ +export const KitAgent = Schema.Struct({ + id: Schema.String, + role: Schema.optional(Schema.String), + description: Schema.optional(Schema.String), + tools: Schema.optional(Schema.Record(Schema.String, Schema.Boolean)), + skills: Schema.optional(Schema.Array(Schema.String)), + model: Schema.optional( + Schema.Struct({ + preferred: Schema.String, + fallback: Schema.optional(Schema.Array(Schema.String)), + }), + ), +}) +export type KitAgent = Schema.Schema.Type + +/** A lifecycle hook declared by a kit. `event` names the OC Kit event. */ +export const KitHook = Schema.Struct({ + event: Schema.String, + command: Schema.String, +}) +export type KitHook = Schema.Schema.Type + +/** A kit manifest (`kit.yaml`) describing one workflow package. */ +export const Kit = Schema.Struct({ + id: Schema.String, + name: Schema.String, + version: Schema.String, + runtime: Schema.optional(Schema.Literal("opencode")), + min_opencode: Schema.optional(Schema.String), + description: Schema.optional(Schema.String), + skills: Schema.optional(Schema.Array(KitSkill)), + agents: Schema.optional(Schema.Array(KitAgent)), + workflows: Schema.optional(Schema.Array(Workflow)), + hooks: Schema.optional(Schema.Array(KitHook)), +}) +export type Kit = Schema.Schema.Type + +/** OC Kit runtime modes (fast/normal/deep/autonomous). */ +export const Mode = Schema.Literals(["fast", "normal", "deep", "autonomous"]) +export type Mode = Schema.Schema.Type + +/** Workflow lifecycle states. */ +export const WorkflowState = Schema.Literals([ + "CREATED", + "PLANNING", + "IMPLEMENTING", + "TESTING", + "REVIEWING", + "VERIFYING", + "BLOCKED", + "FAILED", + "COMPLETED", + "CANCELLED", +]) +export type WorkflowState = Schema.Schema.Type + +/** Session-scoped workflow run state. */ +export const WorkflowRun = Schema.Struct({ + session_id: Schema.String, + workflow_id: Schema.String, + run_id: Schema.String, + agent: Schema.optional(Schema.String), + step: Schema.optional(Schema.Number), + state: WorkflowState, +}) +export type WorkflowRun = Schema.Schema.Type + +/** Artifact produced by a workflow. */ +export const Artifact = Schema.Struct({ + id: Schema.String, + type: Schema.String, + workflow_id: Schema.optional(Schema.String), + session_id: Schema.optional(Schema.String), + path: Schema.String, + status: Schema.Literals(["created", "verified", "failed"]), + checksum: Schema.optional(Schema.String), +}) +export type Artifact = Schema.Schema.Type + +/** Checkpoint snapshot before a risky OC Kit operation. */ +export const Checkpoint = Schema.Struct({ + kit: Schema.String, + kit_version: Schema.String, + operation: Schema.String, + timestamp: Schema.String, + session: Schema.optional(Schema.String), + workflow: Schema.optional(Schema.String), + files: Schema.Record(Schema.String, Schema.String), // path -> sha256 +}) +export type Checkpoint = Schema.Schema.Type + +/** + * Ownership manifest entry: tracks which kit owns a managed file, + * at which version, with the sha256 it shipped — so updates/rollbacks can + * detect user edits and conflicting kits. + */ +export const OwnershipEntry = Schema.Struct({ + owner: Schema.Literal("oc-kit"), + kit: Schema.String, + version: Schema.String, + sha256: Schema.String, +}) +export type OwnershipEntry = Schema.Schema.Type + +export const OwnershipManifest = Schema.Struct({ + files: Schema.Record(Schema.String, OwnershipEntry), +}) +export type OwnershipManifest = Schema.Schema.Type + +/** OC Kit config section (`oc_kit` in opencode.json). */ +export const OCKitConfig = Schema.Struct({ + enabled: Schema.optional(Schema.Boolean).annotate({ description: "Enable OC Kit" }), + default_kit: Schema.optional(Schema.String).annotate({ description: "Kit used by default" }), + default_mode: Schema.optional(Mode).annotate({ description: "Default workflow mode" }), + auto_workflow: Schema.optional(Schema.Boolean).annotate({ description: "Auto-select a workflow from a task" }), + auto_review: Schema.optional(Schema.Boolean).annotate({ description: "Review after implementation" }), + auto_test: Schema.optional(Schema.Boolean).annotate({ description: "Test after implementation" }), + checkpoint: Schema.optional(Schema.Boolean).annotate({ description: "Snapshot before risky updates" }), + telemetry: Schema.optional(Schema.Boolean).annotate({ description: "Send anonymous operational metrics" }), +}) +export type OCKitConfig = Schema.Schema.Type diff --git a/packages/opencode/test/ockit/checkpoint.test.ts b/packages/opencode/test/ockit/checkpoint.test.ts new file mode 100644 index 000000000..6ab3e5e27 --- /dev/null +++ b/packages/opencode/test/ockit/checkpoint.test.ts @@ -0,0 +1,67 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { testEffect } from "../lib/effect" +import { create, list, read } from "../../src/ockit/checkpoint" +import { Hash } from "@opencode-ai/core/util/hash" +import os from "os" +import path from "path" +import fs from "fs/promises" + +const layer = LayerNode.compile(FSUtil.node) +const it = testEffect(layer) + +async function makeRoot() { + const dir = path.join(os.tmpdir(), "ockit-cp-" + Math.random().toString(36).slice(2)) + await fs.mkdir(dir, { recursive: true }) + return dir +} + +describe("ockit checkpoint", () => { + it.effect("creates a checkpoint recording file hashes", async () => { + const root = await makeRoot() + try { + const path_ = await Effect.runPromise( + create({ root, kit: "engineer", kitVersion: "1.0.0", operation: "update", files: { "a.md": "content" } }), + ) + expect(path_).toContain(".oc/state/checkpoints") + const cp = await Effect.runPromise(read(root, path_.split("/").pop()!.replace(".json", ""))) + expect(cp.kit).toBe("engineer") + expect(cp.files["a.md"]).toBe(Hash.sha256("content")) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }) + + it.effect("lists checkpoints newest first and filters by kit", async () => { + const root = await makeRoot() + try { + const one = await Effect.runPromise( + create({ root, kit: "engineer", kitVersion: "1.0.0", operation: "update", files: {} }), + ) + await new Promise((r) => setTimeout(r, 5)) + const two = await Effect.runPromise( + create({ root, kit: "security", kitVersion: "1.0.0", operation: "update", files: {} }), + ) + const idOne = one.split("/").pop()!.replace(".json", "") + const idTwo = two.split("/").pop()!.replace(".json", "") + const engineerIds = await Effect.runPromise(list(root, "engineer")) + expect(engineerIds).toEqual([idOne]) + const all = await Effect.runPromise(list(root)) + expect(all.sort()).toEqual([idOne, idTwo].sort()) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }) + + it.effect("fails with CheckpointError reading a missing checkpoint", async () => { + const root = await makeRoot() + try { + const result = await Effect.runPromise(read(root, "nope").pipe(Effect.exit)) + expect(result._tag).toBe("Failure") + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/opencode/test/ockit/config.test.ts b/packages/opencode/test/ockit/config.test.ts new file mode 100644 index 000000000..7537374e3 --- /dev/null +++ b/packages/opencode/test/ockit/config.test.ts @@ -0,0 +1,40 @@ +import { describe, expect } from "bun:test" +import { it } from "../lib/effect" +import { defaults, validate } from "../../src/ockit/config" +import { OCKitConfig } from "../../src/ockit/types" + +describe("ockit config", () => { + it.effect("applies defaults over user config", () => { + expect(defaults.enabled).toBe(true) + expect(defaults.default_kit).toBe("engineer") + expect(defaults.default_mode).toBe("normal") + expect(defaults.telemetry).toBe(false) + }) + + it.effect("validates a well-formed oc_kit value", () => { + const parsed = validate({ enabled: false, default_kit: "security", default_mode: "deep" }) + expect(parsed?.enabled).toBe(false) + expect(parsed?.default_kit).toBe("security") + expect(parsed?.default_mode).toBe("deep") + }) + + it.effect("returns undefined for an invalid oc_kit value", () => { + expect(validate({ default_mode: "turbo" })).toBeUndefined() + expect(validate("nope")).toBeUndefined() + }) + + it.effect("OCKitConfig schema decodes a full config", () => { + const decoded = OCKitConfig.decodeUnknownSync({ + enabled: true, + default_kit: "engineer", + default_mode: "autonomous", + auto_workflow: true, + auto_review: false, + auto_test: true, + checkpoint: true, + telemetry: true, + }) + expect(decoded.default_mode).toBe("autonomous") + expect(decoded.telemetry).toBe(true) + }) +}) diff --git a/packages/opencode/test/ockit/manifest.test.ts b/packages/opencode/test/ockit/manifest.test.ts new file mode 100644 index 000000000..6f103426c --- /dev/null +++ b/packages/opencode/test/ockit/manifest.test.ts @@ -0,0 +1,100 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { testEffect } from "../lib/effect" +import { loadManifest } from "../../src/ockit/manifest" +import os from "os" +import path from "path" +import fs from "fs/promises" + +const layer = LayerNode.compile(FSUtil.node) +const it = testEffect(layer) + +const VALID_KIT = { + id: "engineer", + name: "OC Engineer Kit", + version: "1.0.0", + runtime: "opencode", + skills: [{ id: "plan", description: "Create an implementation plan" }], +} + +async function makeKitDir(files: Record) { + const dir = path.join(os.tmpdir(), "ockit-test-" + Math.random().toString(36).slice(2)) + for (const [rel, content] of Object.entries(files)) { + const full = path.join(dir, rel) + await fs.mkdir(path.dirname(full), { recursive: true }) + await Bun.write(full, content) + } + return dir +} + +describe("ockit manifest", () => { + it.effect("loads a valid kit.json manifest", async () => { + const dir = await makeKitDir({ "kit.json": JSON.stringify(VALID_KIT) }) + try { + const kit = await Effect.runPromise(loadManifest(dir)) + expect(kit.id).toBe("engineer") + expect(kit.skills?.[0]?.id).toBe("plan") + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + it.effect("loads a kit.yaml manifest via Bun.YAML", async () => { + const dir = await makeKitDir({ + "kit.yaml": `id: engineer +name: OC Engineer Kit +version: 1.0.0 +runtime: opencode +skills: + - id: plan + description: Create an implementation plan +`, + }) + try { + const kit = await Effect.runPromise(loadManifest(dir)) + expect(kit.id).toBe("engineer") + expect(kit.skills?.[0]?.id).toBe("plan") + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + it.effect("prefers kit.json over kit.yaml", async () => { + const dir = await makeKitDir({ + "kit.json": JSON.stringify({ ...VALID_KIT, name: "JSON KIT" }), + "kit.yaml": "id: engineer\nname: YAML KIT\nversion: 1.0.0\n", + }) + try { + const kit = await Effect.runPromise(loadManifest(dir)) + expect(kit.name).toBe("JSON KIT") + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + it.effect("fails with ManifestError when no manifest exists", async () => { + const dir = await makeKitDir({ "README.md": "no manifest here" }) + try { + const result = await Effect.runPromise(loadManifest(dir).pipe(Effect.exit)) + expect(result._tag).toBe("Failure") + if (result._tag === "Failure") { + const error = result.cause.defects[0] ?? result.cause.failures[0] + expect(String(error)).toContain("No kit manifest found") + } + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + it.effect("fails with ManifestError on invalid schema", async () => { + const dir = await makeKitDir({ "kit.json": JSON.stringify({ id: "engineer" }) }) + try { + const result = await Effect.runPromise(loadManifest(dir).pipe(Effect.exit)) + expect(result._tag).toBe("Failure") + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/opencode/test/ockit/ownership.test.ts b/packages/opencode/test/ockit/ownership.test.ts new file mode 100644 index 000000000..ebdd1e8ae --- /dev/null +++ b/packages/opencode/test/ockit/ownership.test.ts @@ -0,0 +1,108 @@ +import { describe, expect } from "bun:test" +import { Effect, Layer } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { testEffect } from "../lib/effect" +import { claim, detectUserEdits, planUpdate, loadOwnership, saveOwnership } from "../../src/ockit/ownership" +import { Hash } from "@opencode-ai/core/util/hash" +import type { OwnershipManifest } from "../../src/ockit/types" +import os from "os" +import path from "path" +import fs from "fs/promises" + +const layer = LayerNode.compile(FSUtil.node) +const it = testEffect(layer) + +async function makeRoot() { + const dir = path.join(os.tmpdir(), "ockit-own-" + Math.random().toString(36).slice(2)) + await fs.mkdir(path.join(dir, ".oc", "state"), { recursive: true }) + return dir +} + +describe("ockit ownership", () => { + it.effect("claims ownership of shipped files with sha256", async () => { + const manifest: OwnershipManifest = { files: {} } + const result = await Effect.runPromise(claim(manifest, "engineer", "1.0.0", { "a.md": "hello" })) + const entry = result.files["a.md"] + expect(entry?.owner).toBe("oc-kit") + expect(entry?.kit).toBe("engineer") + expect(entry?.sha256).toBe(Hash.sha256("hello")) + }) + + it.effect("rejects a file already owned by another kit", async () => { + const manifest: OwnershipManifest = { + files: { "a.md": { owner: "oc-kit", kit: "security", version: "1.0.0", sha256: Hash.sha256("x") } }, + } + const result = await Effect.runPromise(claim(manifest, "engineer", "1.0.0", { "a.md": "hello" }).pipe(Effect.exit)) + expect(result._tag).toBe("Failure") + }) + + it.effect("detects user edits by hash mismatch", async () => { + const root = await makeRoot() + try { + await Bun.write(path.join(root, "a.md"), "original") + const manifest: OwnershipManifest = { + files: { "a.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("original") } }, + } + const runEdits = (m: OwnershipManifest) => Effect.gen(function* () { + const fs = yield* FSUtil.Service + return yield* detectUserEdits(fs, root, m) + }) + expect((await Effect.runPromise(runEdits(manifest))).length).toBe(0) + + await Bun.write(path.join(root, "a.md"), "edited") + expect(await Effect.runPromise(runEdits(manifest))).toEqual(["a.md"]) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }) + + it.effect("planUpdate replaces owned/unmodified, preserves modified and foreign files", async () => { + const root = await makeRoot() + try { + await Bun.write(path.join(root, "owned.md"), "owned content") + await Bun.write(path.join(root, "foreign.md"), "user file") + const manifest: OwnershipManifest = { + files: { + "owned.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("owned content") }, + "foreign.md": { owner: "oc-kit", kit: "security", version: "1.0.0", sha256: Hash.sha256("other") }, + }, + } + const plan = await Effect.runPromise( + Effect.gen(function* () { + const fs = yield* FSUtil.Service + return yield* planUpdate(fs, root, manifest, "engineer", { "owned.md": "new content", "new.md": "x" }) + }), + ) + expect(plan.replace).toEqual(["owned.md"]) + expect(plan.preserve).toContain("foreign.md") + expect(plan.preserve).toContain("new.md") + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }) + + it.effect("round-trips an ownership manifest through disk", async () => { + const root = await makeRoot() + try { + const manifest: OwnershipManifest = { + files: { "a.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("a") } }, + } + await Effect.runPromise(saveOwnership(root, manifest)) + const loaded = await Effect.runPromise(loadOwnership(root)) + expect(loaded.files["a.md"]?.kit).toBe("engineer") + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }) + + it.effect("loadOwnership returns empty manifest when absent", async () => { + const root = await makeRoot() + try { + const loaded = await Effect.runPromise(loadOwnership(root)) + expect(loaded.files).toEqual({}) + } finally { + await fs.rm(root, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/opencode/test/ockit/registry.test.ts b/packages/opencode/test/ockit/registry.test.ts new file mode 100644 index 000000000..05f35d967 --- /dev/null +++ b/packages/opencode/test/ockit/registry.test.ts @@ -0,0 +1,90 @@ +import { describe, expect } from "bun:test" +import { Effect } from "effect" +import { LayerNode } from "@opencode-ai/core/effect/layer-node" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { testEffect } from "../lib/effect" +import { Service as Registry, node as registryNode } from "../../src/ockit/registry" +import { testInstanceStoreLayer } from "../fixture/fixture" +import path from "path" +import fs from "fs/promises" + +const it = testEffect(LayerNode.compile(registryNode, testInstanceStoreLayer)) + +const VALID_KIT = { + id: "engineer", + name: "OC Engineer Kit", + version: "1.0.0", + runtime: "opencode", + skills: [{ id: "plan", description: "Create an implementation plan" }], +} + +async function writeGlobalKit(home: string, kitId: string, manifest: unknown) { + const dir = path.join(home, ".config", "opencode", "kits", kitId) + await fs.mkdir(dir, { recursive: true }) + await Bun.write(path.join(dir, "kit.json"), JSON.stringify(manifest)) +} + +const withHome = (home: string, self: Effect.Effect) => + Effect.acquireUseRelease( + Effect.sync(() => { + const prev = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = home + return prev + }), + () => self, + (prev) => + Effect.sync(() => { + process.env.OPENCODE_TEST_HOME = prev + }), + ) + +describe("ockit registry", () => { + it.effect("indexes a global kit and resolves it by id", async () => { + const home = path.join(process.cwd(), "tmp-ockit-home-" + Math.random().toString(36).slice(2)) + await writeGlobalKit(home, "engineer", VALID_KIT) + try { + const result = await Effect.runPromise( + withHome(home, Effect.gen(function* () { + const registry = yield* Registry + return yield* registry.get("engineer") + })), + ) + expect(result?.name).toBe("OC Engineer Kit") + } finally { + await fs.rm(home, { recursive: true, force: true }) + } + }) + + it.effect("require throws NotFoundError for an unknown kit", async () => { + const home = path.join(process.cwd(), "tmp-ockit-home-" + Math.random().toString(36).slice(2)) + await writeGlobalKit(home, "engineer", VALID_KIT) + try { + const result = await Effect.runPromise( + withHome(home, Effect.gen(function* () { + const registry = yield* Registry + return yield* registry.require("missing").pipe(Effect.exit) + })), + ) + expect(result._tag).toBe("Failure") + } finally { + await fs.rm(home, { recursive: true, force: true }) + } + }) + + it.effect("skips a kit with an invalid manifest", async () => { + const home = path.join(process.cwd(), "tmp-ockit-home-" + Math.random().toString(36).slice(2)) + await writeGlobalKit(home, "broken", { id: "broken" }) + await writeGlobalKit(home, "engineer", VALID_KIT) + try { + const result = await Effect.runPromise( + withHome(home, Effect.gen(function* () { + const registry = yield* Registry + return yield* registry.all() + })), + ) + expect(result.map((kit) => kit.id)).toEqual(["engineer"]) + } finally { + await fs.rm(home, { recursive: true, force: true }) + } + }) +}) diff --git a/packages/opencode/test/ockit/resolver.test.ts b/packages/opencode/test/ockit/resolver.test.ts new file mode 100644 index 000000000..33170d7b5 --- /dev/null +++ b/packages/opencode/test/ockit/resolver.test.ts @@ -0,0 +1,52 @@ +import { describe, expect } from "bun:test" +import { it } from "../lib/effect" +import { Kit } from "../../src/ockit/types" +import { indexKit, resolveFromKit, resolveAcross } from "../../src/ockit/resolver" + +const kit: Kit = { + id: "engineer", + name: "OC Engineer Kit", + version: "1.0.0", + runtime: "opencode", + skills: [{ id: "plan", description: "Create an implementation plan" }], + agents: [{ id: "reviewer", role: "reviewer", tools: { write: false } }], + workflows: [{ id: "feature-development", steps: [{ skill: "plan" }] }], + hooks: [{ event: "workflow:start", command: "echo start" }], +} + +describe("ockit resolver", () => { + it.effect("indexes kit declarations by name", () => { + const index = indexKit(kit) + expect(index.skills.get("plan")?.description).toBe("Create an implementation plan") + expect(index.agents.get("reviewer")?.role).toBe("reviewer") + expect(index.workflows.get("feature-development")?.steps[0]?.skill).toBe("plan") + expect(index.hooks.get("workflow:start")?.command).toBe("echo start") + }) + + it.effect("resolves an existing declaration", () => { + const index = indexKit(kit) + expect(resolveFromKit(index, "skills", "plan")?.id).toBe("plan") + }) + + it.effect("throws ResolveError for a missing declaration", () => { + const index = indexKit(kit) + expect(() => resolveFromKit(index, "skills", "missing")).toThrow("no skill \"missing\"") + }) + + it.effect("resolves across multiple kits, first match wins", async () => { + const other: Kit = { + id: "security", + name: "OC Security Kit", + version: "1.0.0", + skills: [{ id: "security", description: "Audit" }], + } + const found = await resolveAcross([other, kit], "skills", "security") + expect(found?.kit.id).toBe("security") + const plan = await resolveAcross([other, kit], "workflows", "feature-development") + expect(plan?.kit.id).toBe("engineer") + }) + + it.effect("returns undefined when no kit declares the id", async () => { + expect(await resolveAcross([kit], "skills", "nope")).toBeUndefined() + }) +}) diff --git a/plans/260814-1636-oc-kit-phase0-1/plan.md b/plans/260814-1636-oc-kit-phase0-1/plan.md index 4edb1bd95..c440ad4a2 100644 --- a/plans/260814-1636-oc-kit-phase0-1/plan.md +++ b/plans/260814-1636-oc-kit-phase0-1/plan.md @@ -19,9 +19,9 @@ This plan covers the first two phases only (per user decision): ## Branch strategy (user decision) -- Work on a **feature branch** (per AGENTS.md: ≤3 words, no `feat/` prefix) and open a **PR into `dev`**. -- CI (`test.yml`, `typecheck.yml`) triggers on pushes to `dev` and on PRs — so the PR itself is the CI gate. -- `dev` branch does not exist yet on origin (only `main`). It must be created from `main` before PRs can target it. +- Work on a **feature branch** (per AGENTS.md: ≤3 words, no `feat/` prefix) and open a **PR into `main`** (updated 2026-08-14: user asked to target `main` directly). +- CI (`test.yml`, `typecheck.yml`) triggers on pushes to the base branch and on PRs — so the PR itself is the CI gate. +- NOTE: `origin/main` is an orphan root (`2b5f70e`) unrelated to local history (`1862432`, which `dev` uses). Feature branches must be rebased onto `origin/main` for GitHub to accept PRs. ## Findings from audit (Phase 0) @@ -38,9 +38,9 @@ This plan covers the first two phases only (per user decision): ## Deliverables ### Phase 0 -- [ ] `UPSTREAM.md` at repo root — upstream repo URL, fork divergence notes, custom-patch policy. -- [ ] `dev` branch created from `main` and pushed to origin (so PRs can target it). -- [ ] First feature branch pushed + a trivial PR into `dev` runs CI green (baseline). +- [x] `UPSTREAM.md` at repo root — upstream repo URL, fork divergence notes, custom-patch policy. +- [ ] `dev` branch created from `main` and pushed to origin (so PRs can target it). — note: superseded; PRs now target `main` directly. +- [ ] First feature branch pushed + a trivial PR into `main` runs CI green (baseline). ### Phase 1 — `packages/opencode/src/ockit/` - [ ] `types.ts` — Effect Schema for Kit/Skill/Agent/Workflow/Hook/Artifact/Checkpoint/Ownership. @@ -65,14 +65,15 @@ UPSTREAM.md ## Verification (CI-first) -1. Feature branch → push → open PR into `dev`. +1. Feature branch → push → open PR into `main`. 2. GitHub Actions `test.yml` runs `bun turbo test` (unit tests incl. new `ockit` tests) on the PR. 3. `typecheck.yml` runs `bun typecheck`. -4. Only merge PR (to `dev`) when both are green. +4. Only merge PR (to `main`) when both are green. 5. Commit messages: English, conventional format, email `cavangcute478@gmail.com`. ## Risks / rollback -- `dev` branch creation is a one-time repo setup; safe (branches off current `main`). +- `origin/main` is an orphan root unrelated to local history; rebasing feature branches onto `origin/main` is required for GitHub to accept PRs. +- CI is currently blocked: every test/typecheck workflow uses `blacksmith-*` self-hosted runner labels that are not registered on this standalone repo. Unblock requires registering runners (or switching CI to GitHub-hosted runners). - Adding `oc_kit` to `ConfigV1.Info` touches the shared config schema — keep it strictly optional so existing projects are unaffected (plan §40 compatibility). - No runtime wiring yet (no workflow engine / hooks) — no risk to existing OpenCode behavior in this phase. From 5f8a8fce298842f33abeafe7d078f828d9e46d77 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 02:20:23 +0700 Subject: [PATCH 03/12] ci: use GitHub-hosted runners for PR verification OpenCode's test/typecheck/nix-eval/pr-management workflows rely on blacksmith self-hosted runners that are not registered on this repo. Swap all blacksmith labels to GitHub-hosted runners (ubuntu-latest, windows-latest) so PR checks can run, and widen the typecheck/nix-eval branch filters from dev to [main, dev] since this fork's default branch is main. --- .github/workflows/nix-eval.yml | 6 +++--- .github/workflows/pr-management.yml | 2 +- .github/workflows/typecheck.yml | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/nix-eval.yml b/.github/workflows/nix-eval.yml index 75332695a..38b604371 100644 --- a/.github/workflows/nix-eval.yml +++ b/.github/workflows/nix-eval.yml @@ -2,9 +2,9 @@ name: nix-eval on: push: - branches: [dev] + branches: [main, dev] pull_request: - branches: [dev] + branches: [main, dev] workflow_dispatch: concurrency: @@ -16,7 +16,7 @@ permissions: jobs: nix-eval: - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ubuntu-latest timeout-minutes: 15 steps: - name: Checkout repository diff --git a/.github/workflows/pr-management.yml b/.github/workflows/pr-management.yml index b6aa4e589..1b3c60a36 100644 --- a/.github/workflows/pr-management.yml +++ b/.github/workflows/pr-management.yml @@ -6,7 +6,7 @@ on: jobs: check-duplicates: - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ubuntu-latest permissions: contents: read pull-requests: write diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml index fc9a52797..c79034f47 100644 --- a/.github/workflows/typecheck.yml +++ b/.github/workflows/typecheck.yml @@ -2,14 +2,14 @@ name: typecheck on: push: - branches: [dev] + branches: [main, dev] pull_request: - branches: [dev] + branches: [main, dev] workflow_dispatch: jobs: typecheck: - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 From f22ca13fbef8be6ff078b72488e417557ed1d2e5 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 02:56:23 +0700 Subject: [PATCH 04/12] fix(ockit): make tests return Effects and use correct Schema decoder The ockit tests were written as async callbacks that called Effect.runPromise inside the test body, but the repo's testEffect(it.effect/it.instance) runners require the body to return an Effect. That made every ockit unit test throw 'Fiber.runLoop: Not a valid effect' at runtime and fail typecheck. - config.test/manifest.test/checkpoint.test/ownership.test/resolver.test: convert async bodies to pure Effect (Effect.sync / Effect.gen / Effect.promise), move temp-file setup into Effects, and use Effect.sleep for the checkpoint ordering assertion. - registry.test: replace the hand-rolled OPENCODE_TEST_HOME/compile misuse with it.instance (real InstanceRef) + OPENCODE_CONFIG_DIR pointing at the tmpdir instance dir so the global kit scan finds /kits//kit.json. - config.ts: OCKitConfig.decodeUnknownOption -> Schema.decodeUnknownOption(OCKitConfig), matching the repo's free-standing decoder convention. - resolver.ts: make resolveFromKit generic over kind so the return type narrows to the requested declaration (fixes TS2339 on the hooks member). --- packages/opencode/src/ockit/config.ts | 4 +- packages/opencode/src/ockit/resolver.ts | 8 +- .../opencode/test/ockit/checkpoint.test.ts | 99 +++++------ packages/opencode/test/ockit/config.test.ts | 65 +++---- packages/opencode/test/ockit/manifest.test.ts | 133 ++++++++------- .../opencode/test/ockit/ownership.test.ts | 159 +++++++++--------- packages/opencode/test/ockit/registry.test.ts | 130 +++++++------- packages/opencode/test/ockit/resolver.test.ts | 69 ++++---- 8 files changed, 352 insertions(+), 315 deletions(-) diff --git a/packages/opencode/src/ockit/config.ts b/packages/opencode/src/ockit/config.ts index caf2f05be..f6d6d7914 100644 --- a/packages/opencode/src/ockit/config.ts +++ b/packages/opencode/src/ockit/config.ts @@ -3,7 +3,7 @@ // exposes typed accessors so OC Kit runtime code reads its settings through the // existing Config service instead of a parallel config system. -import { Effect } from "effect" +import { Effect, Schema } from "effect" import { Config } from "@/config/config" import { OCKitConfig, type OCKitConfig as OCKitConfigType } from "./types" @@ -33,5 +33,5 @@ export const enabled = Effect.fn("OCKit.config.enabled")(function* () { /** Validate a raw `oc_kit` value structurally (used when parsing config). */ export function validate(input: unknown): OCKitConfigType | undefined { - return OCKitConfig.decodeUnknownOption(input) + return Schema.decodeUnknownOption(OCKitConfig)(input) } diff --git a/packages/opencode/src/ockit/resolver.ts b/packages/opencode/src/ockit/resolver.ts index 6c9585f8f..10bcc2fc5 100644 --- a/packages/opencode/src/ockit/resolver.ts +++ b/packages/opencode/src/ockit/resolver.ts @@ -36,9 +36,13 @@ export function indexKit(kit: Kit): KitIndex { } /** Resolve a kit's own declarations by name; throws ResolveError when absent. */ -export function resolveFromKit(index: KitIndex, kind: KitIndexKeys, id: string) { +export function resolveFromKit( + index: KitIndex, + kind: K, + id: string, +): KitIndex[K] extends Map ? V : never { const found = index[kind].get(id) - if (found) return found + if (found) return found as KitIndex[K] extends Map ? V : never throw new ResolveError({ kind, id, kit: index.kit.id }) } diff --git a/packages/opencode/test/ockit/checkpoint.test.ts b/packages/opencode/test/ockit/checkpoint.test.ts index 6ab3e5e27..91b3a243d 100644 --- a/packages/opencode/test/ockit/checkpoint.test.ts +++ b/packages/opencode/test/ockit/checkpoint.test.ts @@ -12,56 +12,61 @@ import fs from "fs/promises" const layer = LayerNode.compile(FSUtil.node) const it = testEffect(layer) -async function makeRoot() { - const dir = path.join(os.tmpdir(), "ockit-cp-" + Math.random().toString(36).slice(2)) - await fs.mkdir(dir, { recursive: true }) - return dir +function makeRoot() { + return Effect.gen(function* () { + const dir = path.join(os.tmpdir(), "ockit-cp-" + Math.random().toString(36).slice(2)) + yield* Effect.promise(() => fs.mkdir(dir, { recursive: true })) + return dir + }) } describe("ockit checkpoint", () => { - it.effect("creates a checkpoint recording file hashes", async () => { - const root = await makeRoot() - try { - const path_ = await Effect.runPromise( - create({ root, kit: "engineer", kitVersion: "1.0.0", operation: "update", files: { "a.md": "content" } }), - ) - expect(path_).toContain(".oc/state/checkpoints") - const cp = await Effect.runPromise(read(root, path_.split("/").pop()!.replace(".json", ""))) - expect(cp.kit).toBe("engineer") - expect(cp.files["a.md"]).toBe(Hash.sha256("content")) - } finally { - await fs.rm(root, { recursive: true, force: true }) - } - }) + it.effect("creates a checkpoint recording file hashes", () => + Effect.gen(function* () { + const root = yield* makeRoot() + try { + const path_ = yield* create({ + root, + kit: "engineer", + kitVersion: "1.0.0", + operation: "update", + files: { "a.md": "content" }, + }) + expect(path_).toContain(".oc/state/checkpoints") + const cp = yield* read(root, path_.split("/").pop()!.replace(".json", "")) + expect(cp.kit).toBe("engineer") + expect(cp.files["a.md"]).toBe(Hash.sha256("content")) + } finally { + yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) + } + })) - it.effect("lists checkpoints newest first and filters by kit", async () => { - const root = await makeRoot() - try { - const one = await Effect.runPromise( - create({ root, kit: "engineer", kitVersion: "1.0.0", operation: "update", files: {} }), - ) - await new Promise((r) => setTimeout(r, 5)) - const two = await Effect.runPromise( - create({ root, kit: "security", kitVersion: "1.0.0", operation: "update", files: {} }), - ) - const idOne = one.split("/").pop()!.replace(".json", "") - const idTwo = two.split("/").pop()!.replace(".json", "") - const engineerIds = await Effect.runPromise(list(root, "engineer")) - expect(engineerIds).toEqual([idOne]) - const all = await Effect.runPromise(list(root)) - expect(all.sort()).toEqual([idOne, idTwo].sort()) - } finally { - await fs.rm(root, { recursive: true, force: true }) - } - }) + it.effect("lists checkpoints newest first and filters by kit", () => + Effect.gen(function* () { + const root = yield* makeRoot() + try { + const one = yield* create({ root, kit: "engineer", kitVersion: "1.0.0", operation: "update", files: {} }) + yield* Effect.sleep("5 millis") + const two = yield* create({ root, kit: "security", kitVersion: "1.0.0", operation: "update", files: {} }) + const idOne = one.split("/").pop()!.replace(".json", "") + const idTwo = two.split("/").pop()!.replace(".json", "") + const engineerIds = yield* list(root, "engineer") + expect(engineerIds).toEqual([idOne]) + const all = yield* list(root) + expect(all.sort()).toEqual([idOne, idTwo].sort()) + } finally { + yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) + } + })) - it.effect("fails with CheckpointError reading a missing checkpoint", async () => { - const root = await makeRoot() - try { - const result = await Effect.runPromise(read(root, "nope").pipe(Effect.exit)) - expect(result._tag).toBe("Failure") - } finally { - await fs.rm(root, { recursive: true, force: true }) - } - }) + it.effect("fails with CheckpointError reading a missing checkpoint", () => + Effect.gen(function* () { + const root = yield* makeRoot() + try { + const result = yield* read(root, "nope").pipe(Effect.exit) + expect(result._tag).toBe("Failure") + } finally { + yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) + } + })) }) diff --git a/packages/opencode/test/ockit/config.test.ts b/packages/opencode/test/ockit/config.test.ts index 7537374e3..a9ee12df9 100644 --- a/packages/opencode/test/ockit/config.test.ts +++ b/packages/opencode/test/ockit/config.test.ts @@ -1,40 +1,45 @@ import { describe, expect } from "bun:test" +import { Effect, Schema } from "effect" import { it } from "../lib/effect" import { defaults, validate } from "../../src/ockit/config" import { OCKitConfig } from "../../src/ockit/types" describe("ockit config", () => { - it.effect("applies defaults over user config", () => { - expect(defaults.enabled).toBe(true) - expect(defaults.default_kit).toBe("engineer") - expect(defaults.default_mode).toBe("normal") - expect(defaults.telemetry).toBe(false) - }) + it.effect("applies defaults over user config", () => + Effect.sync(() => { + expect(defaults.enabled).toBe(true) + expect(defaults.default_kit).toBe("engineer") + expect(defaults.default_mode).toBe("normal") + expect(defaults.telemetry).toBe(false) + })) - it.effect("validates a well-formed oc_kit value", () => { - const parsed = validate({ enabled: false, default_kit: "security", default_mode: "deep" }) - expect(parsed?.enabled).toBe(false) - expect(parsed?.default_kit).toBe("security") - expect(parsed?.default_mode).toBe("deep") - }) + it.effect("validates a well-formed oc_kit value", () => + Effect.sync(() => { + const parsed = validate({ enabled: false, default_kit: "security", default_mode: "deep" }) + expect(parsed?.enabled).toBe(false) + expect(parsed?.default_kit).toBe("security") + expect(parsed?.default_mode).toBe("deep") + })) - it.effect("returns undefined for an invalid oc_kit value", () => { - expect(validate({ default_mode: "turbo" })).toBeUndefined() - expect(validate("nope")).toBeUndefined() - }) + it.effect("returns undefined for an invalid oc_kit value", () => + Effect.sync(() => { + expect(validate({ default_mode: "turbo" })).toBeUndefined() + expect(validate("nope")).toBeUndefined() + })) - it.effect("OCKitConfig schema decodes a full config", () => { - const decoded = OCKitConfig.decodeUnknownSync({ - enabled: true, - default_kit: "engineer", - default_mode: "autonomous", - auto_workflow: true, - auto_review: false, - auto_test: true, - checkpoint: true, - telemetry: true, - }) - expect(decoded.default_mode).toBe("autonomous") - expect(decoded.telemetry).toBe(true) - }) + it.effect("OCKitConfig schema decodes a full config", () => + Effect.sync(() => { + const decoded = Schema.decodeUnknownSync(OCKitConfig)({ + enabled: true, + default_kit: "engineer", + default_mode: "autonomous", + auto_workflow: true, + auto_review: false, + auto_test: true, + checkpoint: true, + telemetry: true, + }) + expect(decoded.default_mode).toBe("autonomous") + expect(decoded.telemetry).toBe(true) + })) }) diff --git a/packages/opencode/test/ockit/manifest.test.ts b/packages/opencode/test/ockit/manifest.test.ts index 6f103426c..709089019 100644 --- a/packages/opencode/test/ockit/manifest.test.ts +++ b/packages/opencode/test/ockit/manifest.test.ts @@ -19,31 +19,35 @@ const VALID_KIT = { skills: [{ id: "plan", description: "Create an implementation plan" }], } -async function makeKitDir(files: Record) { - const dir = path.join(os.tmpdir(), "ockit-test-" + Math.random().toString(36).slice(2)) - for (const [rel, content] of Object.entries(files)) { - const full = path.join(dir, rel) - await fs.mkdir(path.dirname(full), { recursive: true }) - await Bun.write(full, content) - } - return dir +function makeKitDir(files: Record) { + return Effect.gen(function* () { + const dir = path.join(os.tmpdir(), "ockit-test-" + Math.random().toString(36).slice(2)) + for (const [rel, content] of Object.entries(files)) { + const full = path.join(dir, rel) + yield* Effect.promise(() => fs.mkdir(path.dirname(full), { recursive: true })) + yield* Effect.promise(() => Bun.write(full, content)) + } + return dir + }) } describe("ockit manifest", () => { - it.effect("loads a valid kit.json manifest", async () => { - const dir = await makeKitDir({ "kit.json": JSON.stringify(VALID_KIT) }) - try { - const kit = await Effect.runPromise(loadManifest(dir)) - expect(kit.id).toBe("engineer") - expect(kit.skills?.[0]?.id).toBe("plan") - } finally { - await fs.rm(dir, { recursive: true, force: true }) - } - }) + it.effect("loads a valid kit.json manifest", () => + Effect.gen(function* () { + const dir = yield* makeKitDir({ "kit.json": JSON.stringify(VALID_KIT) }) + try { + const kit = yield* loadManifest(dir) + expect(kit.id).toBe("engineer") + expect(kit.skills?.[0]?.id).toBe("plan") + } finally { + yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) + } + })) - it.effect("loads a kit.yaml manifest via Bun.YAML", async () => { - const dir = await makeKitDir({ - "kit.yaml": `id: engineer + it.effect("loads a kit.yaml manifest via Bun.YAML", () => + Effect.gen(function* () { + const dir = yield* makeKitDir({ + "kit.yaml": `id: engineer name: OC Engineer Kit version: 1.0.0 runtime: opencode @@ -51,50 +55,53 @@ skills: - id: plan description: Create an implementation plan `, - }) - try { - const kit = await Effect.runPromise(loadManifest(dir)) - expect(kit.id).toBe("engineer") - expect(kit.skills?.[0]?.id).toBe("plan") - } finally { - await fs.rm(dir, { recursive: true, force: true }) - } - }) + }) + try { + const kit = yield* loadManifest(dir) + expect(kit.id).toBe("engineer") + expect(kit.skills?.[0]?.id).toBe("plan") + } finally { + yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) + } + })) - it.effect("prefers kit.json over kit.yaml", async () => { - const dir = await makeKitDir({ - "kit.json": JSON.stringify({ ...VALID_KIT, name: "JSON KIT" }), - "kit.yaml": "id: engineer\nname: YAML KIT\nversion: 1.0.0\n", - }) - try { - const kit = await Effect.runPromise(loadManifest(dir)) - expect(kit.name).toBe("JSON KIT") - } finally { - await fs.rm(dir, { recursive: true, force: true }) - } - }) + it.effect("prefers kit.json over kit.yaml", () => + Effect.gen(function* () { + const dir = yield* makeKitDir({ + "kit.json": JSON.stringify({ ...VALID_KIT, name: "JSON KIT" }), + "kit.yaml": "id: engineer\nname: YAML KIT\nversion: 1.0.0\n", + }) + try { + const kit = yield* loadManifest(dir) + expect(kit.name).toBe("JSON KIT") + } finally { + yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) + } + })) - it.effect("fails with ManifestError when no manifest exists", async () => { - const dir = await makeKitDir({ "README.md": "no manifest here" }) - try { - const result = await Effect.runPromise(loadManifest(dir).pipe(Effect.exit)) - expect(result._tag).toBe("Failure") - if (result._tag === "Failure") { - const error = result.cause.defects[0] ?? result.cause.failures[0] - expect(String(error)).toContain("No kit manifest found") + it.effect("fails with ManifestError when no manifest exists", () => + Effect.gen(function* () { + const dir = yield* makeKitDir({ "README.md": "no manifest here" }) + try { + const result = yield* loadManifest(dir).pipe(Effect.exit) + expect(result._tag).toBe("Failure") + if (result._tag === "Failure") { + const error = result.cause.defects[0] ?? result.cause.failures[0] + expect(String(error)).toContain("No kit manifest found") + } + } finally { + yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) } - } finally { - await fs.rm(dir, { recursive: true, force: true }) - } - }) + })) - it.effect("fails with ManifestError on invalid schema", async () => { - const dir = await makeKitDir({ "kit.json": JSON.stringify({ id: "engineer" }) }) - try { - const result = await Effect.runPromise(loadManifest(dir).pipe(Effect.exit)) - expect(result._tag).toBe("Failure") - } finally { - await fs.rm(dir, { recursive: true, force: true }) - } - }) + it.effect("fails with ManifestError on invalid schema", () => + Effect.gen(function* () { + const dir = yield* makeKitDir({ "kit.json": JSON.stringify({ id: "engineer" }) }) + try { + const result = yield* loadManifest(dir).pipe(Effect.exit) + expect(result._tag).toBe("Failure") + } finally { + yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) + } + })) }) diff --git a/packages/opencode/test/ockit/ownership.test.ts b/packages/opencode/test/ockit/ownership.test.ts index ebdd1e8ae..ff12ad17c 100644 --- a/packages/opencode/test/ockit/ownership.test.ts +++ b/packages/opencode/test/ockit/ownership.test.ts @@ -13,96 +13,97 @@ import fs from "fs/promises" const layer = LayerNode.compile(FSUtil.node) const it = testEffect(layer) -async function makeRoot() { - const dir = path.join(os.tmpdir(), "ockit-own-" + Math.random().toString(36).slice(2)) - await fs.mkdir(path.join(dir, ".oc", "state"), { recursive: true }) - return dir +function makeRoot() { + return Effect.gen(function* () { + const dir = path.join(os.tmpdir(), "ockit-own-" + Math.random().toString(36).slice(2)) + yield* Effect.promise(() => fs.mkdir(path.join(dir, ".oc", "state"), { recursive: true })) + return dir + }) } describe("ockit ownership", () => { - it.effect("claims ownership of shipped files with sha256", async () => { - const manifest: OwnershipManifest = { files: {} } - const result = await Effect.runPromise(claim(manifest, "engineer", "1.0.0", { "a.md": "hello" })) - const entry = result.files["a.md"] - expect(entry?.owner).toBe("oc-kit") - expect(entry?.kit).toBe("engineer") - expect(entry?.sha256).toBe(Hash.sha256("hello")) - }) - - it.effect("rejects a file already owned by another kit", async () => { - const manifest: OwnershipManifest = { - files: { "a.md": { owner: "oc-kit", kit: "security", version: "1.0.0", sha256: Hash.sha256("x") } }, - } - const result = await Effect.runPromise(claim(manifest, "engineer", "1.0.0", { "a.md": "hello" }).pipe(Effect.exit)) - expect(result._tag).toBe("Failure") - }) + it.effect("claims ownership of shipped files with sha256", () => + Effect.gen(function* () { + const manifest: OwnershipManifest = { files: {} } + const result = yield* claim(manifest, "engineer", "1.0.0", { "a.md": "hello" }) + const entry = result.files["a.md"] + expect(entry?.owner).toBe("oc-kit") + expect(entry?.kit).toBe("engineer") + expect(entry?.sha256).toBe(Hash.sha256("hello")) + })) - it.effect("detects user edits by hash mismatch", async () => { - const root = await makeRoot() - try { - await Bun.write(path.join(root, "a.md"), "original") + it.effect("rejects a file already owned by another kit", () => + Effect.gen(function* () { const manifest: OwnershipManifest = { - files: { "a.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("original") } }, + files: { "a.md": { owner: "oc-kit", kit: "security", version: "1.0.0", sha256: Hash.sha256("x") } }, } - const runEdits = (m: OwnershipManifest) => Effect.gen(function* () { + const result = yield* claim(manifest, "engineer", "1.0.0", { "a.md": "hello" }).pipe(Effect.exit) + expect(result._tag).toBe("Failure") + })) + + it.effect("detects user edits by hash mismatch", () => + Effect.gen(function* () { + const root = yield* makeRoot() + try { + yield* Effect.promise(() => Bun.write(path.join(root, "a.md"), "original")) + const manifest: OwnershipManifest = { + files: { "a.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("original") } }, + } const fs = yield* FSUtil.Service - return yield* detectUserEdits(fs, root, m) - }) - expect((await Effect.runPromise(runEdits(manifest))).length).toBe(0) + expect((yield* detectUserEdits(fs, root, manifest)).length).toBe(0) - await Bun.write(path.join(root, "a.md"), "edited") - expect(await Effect.runPromise(runEdits(manifest))).toEqual(["a.md"]) - } finally { - await fs.rm(root, { recursive: true, force: true }) - } - }) + yield* Effect.promise(() => Bun.write(path.join(root, "a.md"), "edited")) + expect(yield* detectUserEdits(fs, root, manifest)).toEqual(["a.md"]) + } finally { + yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) + } + })) - it.effect("planUpdate replaces owned/unmodified, preserves modified and foreign files", async () => { - const root = await makeRoot() - try { - await Bun.write(path.join(root, "owned.md"), "owned content") - await Bun.write(path.join(root, "foreign.md"), "user file") - const manifest: OwnershipManifest = { - files: { - "owned.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("owned content") }, - "foreign.md": { owner: "oc-kit", kit: "security", version: "1.0.0", sha256: Hash.sha256("other") }, - }, + it.effect("planUpdate replaces owned/unmodified, preserves modified and foreign files", () => + Effect.gen(function* () { + const root = yield* makeRoot() + try { + yield* Effect.promise(() => Bun.write(path.join(root, "owned.md"), "owned content")) + yield* Effect.promise(() => Bun.write(path.join(root, "foreign.md"), "user file")) + const manifest: OwnershipManifest = { + files: { + "owned.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("owned content") }, + "foreign.md": { owner: "oc-kit", kit: "security", version: "1.0.0", sha256: Hash.sha256("other") }, + }, + } + const fs = yield* FSUtil.Service + const plan = yield* planUpdate(fs, root, manifest, "engineer", { "owned.md": "new content", "new.md": "x" }) + expect(plan.replace).toEqual(["owned.md"]) + expect(plan.preserve).toContain("foreign.md") + expect(plan.preserve).toContain("new.md") + } finally { + yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) } - const plan = await Effect.runPromise( - Effect.gen(function* () { - const fs = yield* FSUtil.Service - return yield* planUpdate(fs, root, manifest, "engineer", { "owned.md": "new content", "new.md": "x" }) - }), - ) - expect(plan.replace).toEqual(["owned.md"]) - expect(plan.preserve).toContain("foreign.md") - expect(plan.preserve).toContain("new.md") - } finally { - await fs.rm(root, { recursive: true, force: true }) - } - }) + })) - it.effect("round-trips an ownership manifest through disk", async () => { - const root = await makeRoot() - try { - const manifest: OwnershipManifest = { - files: { "a.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("a") } }, + it.effect("round-trips an ownership manifest through disk", () => + Effect.gen(function* () { + const root = yield* makeRoot() + try { + const manifest: OwnershipManifest = { + files: { "a.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("a") } }, + } + yield* saveOwnership(root, manifest) + const loaded = yield* loadOwnership(root) + expect(loaded.files["a.md"]?.kit).toBe("engineer") + } finally { + yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) } - await Effect.runPromise(saveOwnership(root, manifest)) - const loaded = await Effect.runPromise(loadOwnership(root)) - expect(loaded.files["a.md"]?.kit).toBe("engineer") - } finally { - await fs.rm(root, { recursive: true, force: true }) - } - }) + })) - it.effect("loadOwnership returns empty manifest when absent", async () => { - const root = await makeRoot() - try { - const loaded = await Effect.runPromise(loadOwnership(root)) - expect(loaded.files).toEqual({}) - } finally { - await fs.rm(root, { recursive: true, force: true }) - } - }) + it.effect("loadOwnership returns empty manifest when absent", () => + Effect.gen(function* () { + const root = yield* makeRoot() + try { + const loaded = yield* loadOwnership(root) + expect(loaded.files).toEqual({}) + } finally { + yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) + } + })) }) diff --git a/packages/opencode/test/ockit/registry.test.ts b/packages/opencode/test/ockit/registry.test.ts index 05f35d967..3a5f018b7 100644 --- a/packages/opencode/test/ockit/registry.test.ts +++ b/packages/opencode/test/ockit/registry.test.ts @@ -1,14 +1,16 @@ import { describe, expect } from "bun:test" import { Effect } from "effect" import { LayerNode } from "@opencode-ai/core/effect/layer-node" -import { FSUtil } from "@opencode-ai/core/fs-util" import { testEffect } from "../lib/effect" import { Service as Registry, node as registryNode } from "../../src/ockit/registry" -import { testInstanceStoreLayer } from "../fixture/fixture" -import path from "path" +import { TestInstance } from "../fixture/fixture" import fs from "fs/promises" -const it = testEffect(LayerNode.compile(registryNode, testInstanceStoreLayer)) +// The registry scans Global.Path.config (== Flag.OPENCODE_CONFIG_DIR when set) +// for /kits//kit.json, and needs a live InstanceRef. Each test +// points OPENCODE_CONFIG_DIR at the tmpdir instance dir, writes kits under it, +// and runs inside that instance (via it.instance) so InstanceState resolves. +const it = testEffect(LayerNode.compile(registryNode)) const VALID_KIT = { id: "engineer", @@ -18,73 +20,79 @@ const VALID_KIT = { skills: [{ id: "plan", description: "Create an implementation plan" }], } -async function writeGlobalKit(home: string, kitId: string, manifest: unknown) { - const dir = path.join(home, ".config", "opencode", "kits", kitId) - await fs.mkdir(dir, { recursive: true }) - await Bun.write(path.join(dir, "kit.json"), JSON.stringify(manifest)) -} - -const withHome = (home: string, self: Effect.Effect) => - Effect.acquireUseRelease( +function withConfigDir(configDir: string, self: Effect.Effect) { + return Effect.acquireUseRelease( Effect.sync(() => { - const prev = process.env.OPENCODE_TEST_HOME - process.env.OPENCODE_TEST_HOME = home + const prev = process.env.OPENCODE_CONFIG_DIR + process.env.OPENCODE_CONFIG_DIR = configDir return prev }), () => self, (prev) => Effect.sync(() => { - process.env.OPENCODE_TEST_HOME = prev + if (prev === undefined) delete process.env.OPENCODE_CONFIG_DIR + else process.env.OPENCODE_CONFIG_DIR = prev }), ) +} -describe("ockit registry", () => { - it.effect("indexes a global kit and resolves it by id", async () => { - const home = path.join(process.cwd(), "tmp-ockit-home-" + Math.random().toString(36).slice(2)) - await writeGlobalKit(home, "engineer", VALID_KIT) - try { - const result = await Effect.runPromise( - withHome(home, Effect.gen(function* () { - const registry = yield* Registry - return yield* registry.get("engineer") - })), - ) - expect(result?.name).toBe("OC Engineer Kit") - } finally { - await fs.rm(home, { recursive: true, force: true }) - } +function writeKit(configDir: string, kitId: string, manifest: unknown = VALID_KIT) { + return Effect.gen(function* () { + yield* Effect.promise(() => fs.mkdir(`${configDir}/kits/${kitId}`, { recursive: true })) + yield* Effect.promise(() => Bun.write(`${configDir}/kits/${kitId}/kit.json`, JSON.stringify(manifest))) }) +} - it.effect("require throws NotFoundError for an unknown kit", async () => { - const home = path.join(process.cwd(), "tmp-ockit-home-" + Math.random().toString(36).slice(2)) - await writeGlobalKit(home, "engineer", VALID_KIT) - try { - const result = await Effect.runPromise( - withHome(home, Effect.gen(function* () { - const registry = yield* Registry - return yield* registry.require("missing").pipe(Effect.exit) - })), - ) - expect(result._tag).toBe("Failure") - } finally { - await fs.rm(home, { recursive: true, force: true }) - } - }) +describe("ockit registry", () => { + it.instance( + "indexes a global kit and resolves it by id", + () => + Effect.gen(function* () { + const { directory } = yield* TestInstance + yield* withConfigDir( + directory, + Effect.gen(function* () { + yield* writeKit(directory, "engineer") + const registry = yield* Registry + const result = yield* registry.get("engineer") + expect(result?.name).toBe("OC Engineer Kit") + }), + ) + }), + ) - it.effect("skips a kit with an invalid manifest", async () => { - const home = path.join(process.cwd(), "tmp-ockit-home-" + Math.random().toString(36).slice(2)) - await writeGlobalKit(home, "broken", { id: "broken" }) - await writeGlobalKit(home, "engineer", VALID_KIT) - try { - const result = await Effect.runPromise( - withHome(home, Effect.gen(function* () { - const registry = yield* Registry - return yield* registry.all() - })), - ) - expect(result.map((kit) => kit.id)).toEqual(["engineer"]) - } finally { - await fs.rm(home, { recursive: true, force: true }) - } - }) + it.instance( + "require throws NotFoundError for an unknown kit", + () => + Effect.gen(function* () { + const { directory } = yield* TestInstance + yield* withConfigDir( + directory, + Effect.gen(function* () { + yield* writeKit(directory, "engineer") + const registry = yield* Registry + const result = yield* registry.require("missing").pipe(Effect.exit) + expect(result._tag).toBe("Failure") + }), + ) + }), + ) + + it.instance( + "skips a kit with an invalid manifest", + () => + Effect.gen(function* () { + const { directory } = yield* TestInstance + yield* withConfigDir( + directory, + Effect.gen(function* () { + yield* writeKit(directory, "engineer") + yield* writeKit(directory, "broken", { id: "broken" }) + const registry = yield* Registry + const result = yield* registry.all() + expect(result.map((kit) => kit.id)).toEqual(["engineer"]) + }), + ) + }), + ) }) diff --git a/packages/opencode/test/ockit/resolver.test.ts b/packages/opencode/test/ockit/resolver.test.ts index 33170d7b5..eafb4aba4 100644 --- a/packages/opencode/test/ockit/resolver.test.ts +++ b/packages/opencode/test/ockit/resolver.test.ts @@ -1,6 +1,7 @@ import { describe, expect } from "bun:test" +import { Effect } from "effect" import { it } from "../lib/effect" -import { Kit } from "../../src/ockit/types" +import type { Kit } from "../../src/ockit/types" import { indexKit, resolveFromKit, resolveAcross } from "../../src/ockit/resolver" const kit: Kit = { @@ -15,38 +16,44 @@ const kit: Kit = { } describe("ockit resolver", () => { - it.effect("indexes kit declarations by name", () => { - const index = indexKit(kit) - expect(index.skills.get("plan")?.description).toBe("Create an implementation plan") - expect(index.agents.get("reviewer")?.role).toBe("reviewer") - expect(index.workflows.get("feature-development")?.steps[0]?.skill).toBe("plan") - expect(index.hooks.get("workflow:start")?.command).toBe("echo start") - }) + it.effect("indexes kit declarations by name", () => + Effect.sync(() => { + const index = indexKit(kit) + expect(index.skills.get("plan")?.description).toBe("Create an implementation plan") + expect(index.agents.get("reviewer")?.role).toBe("reviewer") + expect(index.workflows.get("feature-development")?.steps[0]?.skill).toBe("plan") + expect(index.hooks.get("workflow:start")?.command).toBe("echo start") + })) - it.effect("resolves an existing declaration", () => { - const index = indexKit(kit) - expect(resolveFromKit(index, "skills", "plan")?.id).toBe("plan") - }) + it.effect("resolves an existing declaration", () => + Effect.sync(() => { + const index = indexKit(kit) + expect(resolveFromKit(index, "skills", "plan")?.id).toBe("plan") + })) - it.effect("throws ResolveError for a missing declaration", () => { - const index = indexKit(kit) - expect(() => resolveFromKit(index, "skills", "missing")).toThrow("no skill \"missing\"") - }) + it.effect("throws ResolveError for a missing declaration", () => + Effect.sync(() => { + const index = indexKit(kit) + expect(() => resolveFromKit(index, "skills", "missing")).toThrow("no skill \"missing\"") + })) - it.effect("resolves across multiple kits, first match wins", async () => { - const other: Kit = { - id: "security", - name: "OC Security Kit", - version: "1.0.0", - skills: [{ id: "security", description: "Audit" }], - } - const found = await resolveAcross([other, kit], "skills", "security") - expect(found?.kit.id).toBe("security") - const plan = await resolveAcross([other, kit], "workflows", "feature-development") - expect(plan?.kit.id).toBe("engineer") - }) + it.effect("resolves across multiple kits, first match wins", () => + Effect.gen(function* () { + const other: Kit = { + id: "security", + name: "OC Security Kit", + version: "1.0.0", + skills: [{ id: "security", description: "Audit" }], + } + const found = yield* Effect.promise(() => resolveAcross([other, kit], "skills", "security")) + expect(found?.kit.id).toBe("security") + const plan = yield* Effect.promise(() => resolveAcross([other, kit], "workflows", "feature-development")) + expect(plan?.kit.id).toBe("engineer") + })) - it.effect("returns undefined when no kit declares the id", async () => { - expect(await resolveAcross([kit], "skills", "nope")).toBeUndefined() - }) + it.effect("returns undefined when no kit declares the id", () => + Effect.gen(function* () { + const result = yield* Effect.promise(() => resolveAcross([kit], "skills", "nope")) + expect(result).toBeUndefined() + })) }) From d7cdea7ff87d875bc07dd409563349eb1ad24a47 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 03:33:57 +0700 Subject: [PATCH 05/12] fix(ockit): use decodeUnknownEffect and repair ownership plan logic - Replace the non-existent Schema.decodeUnknown / Schema.TreeFormatter calls with decodeUnknownEffect + String(err) (effect 4.0.0-beta.83) - Unwrap validate() Option result so it returns the value or undefined - Make claim() operate on a mutable copy (schema type is read-only) - Have planUpdate() preserve manifest-owned files outside the update set - Annotate tagged error message getters to fix TS7023 - Fix resolver plural->singular kind label in ResolveError - Allow registry state factory to fail with Error - Rewrite ockit unit tests to Effect.acquireUseRelease scoping (the try/finally-in-gen shape widened to unknown requirements) --- packages/opencode/src/ockit/checkpoint.ts | 6 +- packages/opencode/src/ockit/config.ts | 4 +- packages/opencode/src/ockit/manifest.ts | 6 +- packages/opencode/src/ockit/ownership.ts | 22 +++- packages/opencode/src/ockit/registry.ts | 2 +- packages/opencode/src/ockit/resolver.ts | 12 +- .../opencode/test/ockit/checkpoint.test.ts | 55 +++++---- packages/opencode/test/ockit/manifest.test.ts | 109 +++++++++--------- .../opencode/test/ockit/ownership.test.ts | 83 +++++++------ packages/opencode/test/ockit/registry.test.ts | 2 +- 10 files changed, 157 insertions(+), 144 deletions(-) diff --git a/packages/opencode/src/ockit/checkpoint.ts b/packages/opencode/src/ockit/checkpoint.ts index 3dc0b5ec2..a8dc7fbbb 100644 --- a/packages/opencode/src/ockit/checkpoint.ts +++ b/packages/opencode/src/ockit/checkpoint.ts @@ -15,7 +15,7 @@ export class CheckpointError extends Schema.TaggedErrorClass()( path: Schema.String, message: Schema.optional(Schema.String), }) { - override get message() { + override get message(): string { return `OC Kit checkpoint: ${this.path}${this.message ? ` — ${this.message}` : ""}` } } @@ -63,8 +63,8 @@ export const read = Effect.fn("OCKit.checkpoint.read")(function* (root: string, const path = `${root}/${CHECKPOINT_DIR}/${id}.json` const raw = yield* fs.readFileStringSafe(path) if (raw === undefined) return yield* new CheckpointError({ path, message: `No checkpoint "${id}"` }) - const decoded = yield* Schema.decodeUnknown(Checkpoint)(JSON.parse(raw)).pipe( - Effect.mapError((err) => new CheckpointError({ path, message: Schema.TreeFormatter.formatIssueSync(err.issue) })), + const decoded = yield* Schema.decodeUnknownEffect(Checkpoint)(JSON.parse(raw)).pipe( + Effect.mapError((err) => new CheckpointError({ path, message: String(err) })), ) return decoded }) diff --git a/packages/opencode/src/ockit/config.ts b/packages/opencode/src/ockit/config.ts index f6d6d7914..8a515d3a5 100644 --- a/packages/opencode/src/ockit/config.ts +++ b/packages/opencode/src/ockit/config.ts @@ -3,7 +3,7 @@ // exposes typed accessors so OC Kit runtime code reads its settings through the // existing Config service instead of a parallel config system. -import { Effect, Schema } from "effect" +import { Effect, Option, Schema } from "effect" import { Config } from "@/config/config" import { OCKitConfig, type OCKitConfig as OCKitConfigType } from "./types" @@ -33,5 +33,5 @@ export const enabled = Effect.fn("OCKit.config.enabled")(function* () { /** Validate a raw `oc_kit` value structurally (used when parsing config). */ export function validate(input: unknown): OCKitConfigType | undefined { - return Schema.decodeUnknownOption(OCKitConfig)(input) + return Option.getOrUndefined(Schema.decodeUnknownOption(OCKitConfig)(input)) } diff --git a/packages/opencode/src/ockit/manifest.ts b/packages/opencode/src/ockit/manifest.ts index 428b76227..322a8a5f1 100644 --- a/packages/opencode/src/ockit/manifest.ts +++ b/packages/opencode/src/ockit/manifest.ts @@ -46,10 +46,8 @@ export const loadManifest = Effect.fn("OCKit.manifest")(function* (kitDir: strin catch: (cause) => new ManifestError({ path, message: `Invalid ${KIT_MANIFEST_JSON} syntax: ${String(cause)}` }), }) - const decoded = yield* Schema.decodeUnknown(Kit)(raw).pipe( - Effect.mapError( - (err) => new ManifestError({ path, message: Schema.TreeFormatter.formatIssueSync(err.issue) }), - ), + const decoded = yield* Schema.decodeUnknownEffect(Kit)(raw).pipe( + Effect.mapError((err) => new ManifestError({ path, message: String(err) })), ) return decoded diff --git a/packages/opencode/src/ockit/ownership.ts b/packages/opencode/src/ockit/ownership.ts index 187006556..b905337e3 100644 --- a/packages/opencode/src/ockit/ownership.ts +++ b/packages/opencode/src/ockit/ownership.ts @@ -15,7 +15,7 @@ export class OwnershipError extends Schema.TaggedErrorClass()("O path: Schema.String, message: Schema.optional(Schema.String), }) { - override get message() { + override get message(): string { return `OC Kit ownership: ${this.path}${this.message ? ` — ${this.message}` : ""}` } } @@ -26,8 +26,8 @@ export const loadOwnership = Effect.fn("OCKit.ownership.load")(function* (root: const path = `${root}/${OWNERSHIP_MANIFEST_PATH}` const raw = yield* fs.readFileStringSafe(path) if (raw === undefined) return { files: {} } - const decoded = yield* Schema.decodeUnknown(OwnershipManifest)(JSON.parse(raw)).pipe( - Effect.mapError((err) => new OwnershipError({ path, message: Schema.TreeFormatter.formatIssueSync(err.issue) })), + const decoded = yield* Schema.decodeUnknownEffect(OwnershipManifest)(JSON.parse(raw)).pipe( + Effect.mapError((err) => new OwnershipError({ path, message: String(err) })), ) return decoded }) @@ -50,9 +50,11 @@ export const claim = Effect.fn("OCKit.ownership.claim")(function* ( version: string, files: Record, ) { + // Work on a mutable copy — the manifest schema type is read-only. + const next: Record = { ...manifest.files } const conflicts: string[] = [] for (const file of Object.keys(files)) { - const existing = manifest.files[file] + const existing = next[file] if (existing && existing.kit !== kit) conflicts.push(file) } if (conflicts.length > 0) { @@ -63,9 +65,9 @@ export const claim = Effect.fn("OCKit.ownership.claim")(function* ( } for (const [file, content] of Object.entries(files)) { const entry: OwnershipEntry = { owner: "oc-kit", kit, version, sha256: Hash.sha256(content) } - manifest.files[file] = entry + next[file] = entry } - return manifest + return { files: next } }) /** @@ -99,7 +101,9 @@ export const planUpdate = Effect.fn("OCKit.ownership.planUpdate")(function* ( files: Record, ) { const plan: { replace: string[]; preserve: string[]; warn: string[] } = { replace: [], preserve: [], warn: [] } + const handled = new Set() for (const file of Object.keys(files)) { + handled.add(file) const entry = manifest.files[file] if (!entry || entry.kit !== kit) { plan.preserve.push(file) @@ -109,6 +113,12 @@ export const planUpdate = Effect.fn("OCKit.ownership.planUpdate")(function* ( if (content === undefined || Hash.sha256(content) === entry.sha256) plan.replace.push(file) else plan.warn.push(file) } + // Files the manifest tracks but this update does not touch are never + // replaced — preserve anything we do not own so another kit's or the + // user's work is not overwritten. + for (const [file, entry] of Object.entries(manifest.files)) { + if (!handled.has(file) && entry.kit !== kit) plan.preserve.push(file) + } plan.warn.forEach((file) => plan.preserve.push(file)) return plan }) diff --git a/packages/opencode/src/ockit/registry.ts b/packages/opencode/src/ockit/registry.ts index e79a097e1..97e7b652f 100644 --- a/packages/opencode/src/ockit/registry.ts +++ b/packages/opencode/src/ockit/registry.ts @@ -60,7 +60,7 @@ const layer = Layer.effect( dirs.push(kitDir) }) - const state = yield* InstanceState.make( + const state = yield* InstanceState.make( Effect.fn("OCKitRegistry.state")(function* (ctx) { const kits: Record = {} const dirs: string[] = [] diff --git a/packages/opencode/src/ockit/resolver.ts b/packages/opencode/src/ockit/resolver.ts index 10bcc2fc5..744bfc94a 100644 --- a/packages/opencode/src/ockit/resolver.ts +++ b/packages/opencode/src/ockit/resolver.ts @@ -10,7 +10,7 @@ export class ResolveError extends Schema.TaggedErrorClass()("OCKit id: Schema.String, kit: Schema.String, }) { - override get message() { + override get message(): string { return `OC Kit: no ${this.kind} "${this.id}" declared in kit "${this.kit}"` } } @@ -43,11 +43,19 @@ export function resolveFromKit( ): KitIndex[K] extends Map ? V : never { const found = index[kind].get(id) if (found) return found as KitIndex[K] extends Map ? V : never - throw new ResolveError({ kind, id, kit: index.kit.id }) + throw new ResolveError({ kind: KIND_LABEL[kind], id, kit: index.kit.id }) } type KitIndexKeys = "skills" | "agents" | "workflows" | "hooks" +/** Singular label used in error messages, keyed by the plural index key. */ +const KIND_LABEL: Record = { + skills: "skill", + agents: "agent", + workflows: "workflow", + hooks: "hook", +} + /** * Resolve a declaration across all installed kits. `registry` is an injected * async iterator of kits (an Effect), so this stays framework-agnostic and can diff --git a/packages/opencode/test/ockit/checkpoint.test.ts b/packages/opencode/test/ockit/checkpoint.test.ts index 91b3a243d..e33e28540 100644 --- a/packages/opencode/test/ockit/checkpoint.test.ts +++ b/packages/opencode/test/ockit/checkpoint.test.ts @@ -12,19 +12,23 @@ import fs from "fs/promises" const layer = LayerNode.compile(FSUtil.node) const it = testEffect(layer) -function makeRoot() { - return Effect.gen(function* () { - const dir = path.join(os.tmpdir(), "ockit-cp-" + Math.random().toString(36).slice(2)) - yield* Effect.promise(() => fs.mkdir(dir, { recursive: true })) - return dir - }) +/** Create a clean root dir, then remove it when the effect scope closes. */ +function withRoot(use: (root: string) => Effect.Effect) { + return Effect.acquireUseRelease( + Effect.gen(function* () { + const dir = path.join(os.tmpdir(), "ockit-cp-" + Math.random().toString(36).slice(2)) + yield* Effect.promise(() => fs.mkdir(dir, { recursive: true })) + return dir + }), + use, + (dir) => Effect.promise(() => fs.rm(dir, { recursive: true, force: true })), + ) } describe("ockit checkpoint", () => { it.effect("creates a checkpoint recording file hashes", () => - Effect.gen(function* () { - const root = yield* makeRoot() - try { + withRoot((root) => + Effect.gen(function* () { const path_ = yield* create({ root, kit: "engineer", @@ -36,15 +40,13 @@ describe("ockit checkpoint", () => { const cp = yield* read(root, path_.split("/").pop()!.replace(".json", "")) expect(cp.kit).toBe("engineer") expect(cp.files["a.md"]).toBe(Hash.sha256("content")) - } finally { - yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) - } - })) + }), + ), + ) it.effect("lists checkpoints newest first and filters by kit", () => - Effect.gen(function* () { - const root = yield* makeRoot() - try { + withRoot((root) => + Effect.gen(function* () { const one = yield* create({ root, kit: "engineer", kitVersion: "1.0.0", operation: "update", files: {} }) yield* Effect.sleep("5 millis") const two = yield* create({ root, kit: "security", kitVersion: "1.0.0", operation: "update", files: {} }) @@ -54,19 +56,16 @@ describe("ockit checkpoint", () => { expect(engineerIds).toEqual([idOne]) const all = yield* list(root) expect(all.sort()).toEqual([idOne, idTwo].sort()) - } finally { - yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) - } - })) + }), + ), + ) it.effect("fails with CheckpointError reading a missing checkpoint", () => - Effect.gen(function* () { - const root = yield* makeRoot() - try { + withRoot((root) => + Effect.gen(function* () { const result = yield* read(root, "nope").pipe(Effect.exit) expect(result._tag).toBe("Failure") - } finally { - yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) - } - })) -}) + }), + ), + ) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/manifest.test.ts b/packages/opencode/test/ockit/manifest.test.ts index 709089019..55eba355c 100644 --- a/packages/opencode/test/ockit/manifest.test.ts +++ b/packages/opencode/test/ockit/manifest.test.ts @@ -1,5 +1,5 @@ import { describe, expect } from "bun:test" -import { Effect, Layer } from "effect" +import { Cause, Effect, Layer } from "effect" import { FSUtil } from "@opencode-ai/core/fs-util" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { testEffect } from "../lib/effect" @@ -19,34 +19,37 @@ const VALID_KIT = { skills: [{ id: "plan", description: "Create an implementation plan" }], } -function makeKitDir(files: Record) { - return Effect.gen(function* () { - const dir = path.join(os.tmpdir(), "ockit-test-" + Math.random().toString(36).slice(2)) - for (const [rel, content] of Object.entries(files)) { - const full = path.join(dir, rel) - yield* Effect.promise(() => fs.mkdir(path.dirname(full), { recursive: true })) - yield* Effect.promise(() => Bun.write(full, content)) - } - return dir - }) +/** Create a kit dir with the given files, then clean it up when the effect scope closes. */ +function withKitDir(files: Record, use: (dir: string) => Effect.Effect) { + return Effect.acquireUseRelease( + Effect.gen(function* () { + const dir = path.join(os.tmpdir(), "ockit-test-" + Math.random().toString(36).slice(2)) + for (const [rel, content] of Object.entries(files)) { + const full = path.join(dir, rel) + yield* Effect.promise(() => fs.mkdir(path.dirname(full), { recursive: true })) + yield* Effect.promise(() => Bun.write(full, content)) + } + return dir + }), + use, + (dir) => Effect.promise(() => fs.rm(dir, { recursive: true, force: true })), + ) } describe("ockit manifest", () => { it.effect("loads a valid kit.json manifest", () => - Effect.gen(function* () { - const dir = yield* makeKitDir({ "kit.json": JSON.stringify(VALID_KIT) }) - try { + withKitDir({ "kit.json": JSON.stringify(VALID_KIT) }, (dir) => + Effect.gen(function* () { const kit = yield* loadManifest(dir) expect(kit.id).toBe("engineer") expect(kit.skills?.[0]?.id).toBe("plan") - } finally { - yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) - } - })) + }), + ), + ) it.effect("loads a kit.yaml manifest via Bun.YAML", () => - Effect.gen(function* () { - const dir = yield* makeKitDir({ + withKitDir( + { "kit.yaml": `id: engineer name: OC Engineer Kit version: 1.0.0 @@ -55,53 +58,49 @@ skills: - id: plan description: Create an implementation plan `, - }) - try { - const kit = yield* loadManifest(dir) - expect(kit.id).toBe("engineer") - expect(kit.skills?.[0]?.id).toBe("plan") - } finally { - yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) - } - })) + }, + (dir) => + Effect.gen(function* () { + const kit = yield* loadManifest(dir) + expect(kit.id).toBe("engineer") + expect(kit.skills?.[0]?.id).toBe("plan") + }), + ), + ) it.effect("prefers kit.json over kit.yaml", () => - Effect.gen(function* () { - const dir = yield* makeKitDir({ + withKitDir( + { "kit.json": JSON.stringify({ ...VALID_KIT, name: "JSON KIT" }), "kit.yaml": "id: engineer\nname: YAML KIT\nversion: 1.0.0\n", - }) - try { - const kit = yield* loadManifest(dir) - expect(kit.name).toBe("JSON KIT") - } finally { - yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) - } - })) + }, + (dir) => + Effect.gen(function* () { + const kit = yield* loadManifest(dir) + expect(kit.name).toBe("JSON KIT") + }), + ), + ) it.effect("fails with ManifestError when no manifest exists", () => - Effect.gen(function* () { - const dir = yield* makeKitDir({ "README.md": "no manifest here" }) - try { + withKitDir({ "README.md": "no manifest here" }, (dir) => + Effect.gen(function* () { const result = yield* loadManifest(dir).pipe(Effect.exit) expect(result._tag).toBe("Failure") if (result._tag === "Failure") { - const error = result.cause.defects[0] ?? result.cause.failures[0] + const error = Cause.squash(result.cause) expect(String(error)).toContain("No kit manifest found") } - } finally { - yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) - } - })) + }), + ), + ) it.effect("fails with ManifestError on invalid schema", () => - Effect.gen(function* () { - const dir = yield* makeKitDir({ "kit.json": JSON.stringify({ id: "engineer" }) }) - try { + withKitDir({ "kit.json": JSON.stringify({ id: "engineer" }) }, (dir) => + Effect.gen(function* () { const result = yield* loadManifest(dir).pipe(Effect.exit) expect(result._tag).toBe("Failure") - } finally { - yield* Effect.promise(() => fs.rm(dir, { recursive: true, force: true })) - } - })) -}) + }), + ), + ) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/ownership.test.ts b/packages/opencode/test/ockit/ownership.test.ts index ff12ad17c..005978488 100644 --- a/packages/opencode/test/ockit/ownership.test.ts +++ b/packages/opencode/test/ockit/ownership.test.ts @@ -13,12 +13,17 @@ import fs from "fs/promises" const layer = LayerNode.compile(FSUtil.node) const it = testEffect(layer) -function makeRoot() { - return Effect.gen(function* () { - const dir = path.join(os.tmpdir(), "ockit-own-" + Math.random().toString(36).slice(2)) - yield* Effect.promise(() => fs.mkdir(path.join(dir, ".oc", "state"), { recursive: true })) - return dir - }) +/** Create a root with `.oc/state`, then remove it when the effect scope closes. */ +function withRoot(use: (root: string) => Effect.Effect) { + return Effect.acquireUseRelease( + Effect.gen(function* () { + const dir = path.join(os.tmpdir(), "ockit-own-" + 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 ownership", () => { @@ -30,7 +35,8 @@ describe("ockit ownership", () => { expect(entry?.owner).toBe("oc-kit") expect(entry?.kit).toBe("engineer") expect(entry?.sha256).toBe(Hash.sha256("hello")) - })) + }), + ) it.effect("rejects a file already owned by another kit", () => Effect.gen(function* () { @@ -39,30 +45,28 @@ describe("ockit ownership", () => { } const result = yield* claim(manifest, "engineer", "1.0.0", { "a.md": "hello" }).pipe(Effect.exit) expect(result._tag).toBe("Failure") - })) + }), + ) it.effect("detects user edits by hash mismatch", () => - Effect.gen(function* () { - const root = yield* makeRoot() - try { + withRoot((root) => + Effect.gen(function* () { yield* Effect.promise(() => Bun.write(path.join(root, "a.md"), "original")) const manifest: OwnershipManifest = { files: { "a.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("original") } }, } - const fs = yield* FSUtil.Service - expect((yield* detectUserEdits(fs, root, manifest)).length).toBe(0) + const fsutil = yield* FSUtil.Service + expect((yield* detectUserEdits(fsutil, root, manifest)).length).toBe(0) yield* Effect.promise(() => Bun.write(path.join(root, "a.md"), "edited")) - expect(yield* detectUserEdits(fs, root, manifest)).toEqual(["a.md"]) - } finally { - yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) - } - })) + expect(yield* detectUserEdits(fsutil, root, manifest)).toEqual(["a.md"]) + }), + ), + ) it.effect("planUpdate replaces owned/unmodified, preserves modified and foreign files", () => - Effect.gen(function* () { - const root = yield* makeRoot() - try { + withRoot((root) => + Effect.gen(function* () { yield* Effect.promise(() => Bun.write(path.join(root, "owned.md"), "owned content")) yield* Effect.promise(() => Bun.write(path.join(root, "foreign.md"), "user file")) const manifest: OwnershipManifest = { @@ -71,39 +75,34 @@ describe("ockit ownership", () => { "foreign.md": { owner: "oc-kit", kit: "security", version: "1.0.0", sha256: Hash.sha256("other") }, }, } - const fs = yield* FSUtil.Service - const plan = yield* planUpdate(fs, root, manifest, "engineer", { "owned.md": "new content", "new.md": "x" }) + const fsutil = yield* FSUtil.Service + const plan = yield* planUpdate(fsutil, root, manifest, "engineer", { "owned.md": "new content", "new.md": "x" }) expect(plan.replace).toEqual(["owned.md"]) expect(plan.preserve).toContain("foreign.md") expect(plan.preserve).toContain("new.md") - } finally { - yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) - } - })) + }), + ), + ) it.effect("round-trips an ownership manifest through disk", () => - Effect.gen(function* () { - const root = yield* makeRoot() - try { + withRoot((root) => + Effect.gen(function* () { const manifest: OwnershipManifest = { files: { "a.md": { owner: "oc-kit", kit: "engineer", version: "1.0.0", sha256: Hash.sha256("a") } }, } yield* saveOwnership(root, manifest) const loaded = yield* loadOwnership(root) expect(loaded.files["a.md"]?.kit).toBe("engineer") - } finally { - yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) - } - })) + }), + ), + ) it.effect("loadOwnership returns empty manifest when absent", () => - Effect.gen(function* () { - const root = yield* makeRoot() - try { + withRoot((root) => + Effect.gen(function* () { const loaded = yield* loadOwnership(root) expect(loaded.files).toEqual({}) - } finally { - yield* Effect.promise(() => fs.rm(root, { recursive: true, force: true })) - } - })) -}) + }), + ), + ) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/registry.test.ts b/packages/opencode/test/ockit/registry.test.ts index 3a5f018b7..4aea0d017 100644 --- a/packages/opencode/test/ockit/registry.test.ts +++ b/packages/opencode/test/ockit/registry.test.ts @@ -20,7 +20,7 @@ const VALID_KIT = { skills: [{ id: "plan", description: "Create an implementation plan" }], } -function withConfigDir(configDir: string, self: Effect.Effect) { +function withConfigDir(configDir: string, self: Effect.Effect) { return Effect.acquireUseRelease( Effect.sync(() => { const prev = process.env.OPENCODE_CONFIG_DIR From 0da1a911e7b6dbd420b621a8a47cb01af082c520 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 03:38:15 +0700 Subject: [PATCH 06/12] fix(ockit): keep registry state factory service-free within scope The InstanceState factory cannot re-require Config/FSUtil services from inside the scoped cache lookup. Capture fs and config as closure values, provide the captured fs to loadManifest, and orDie filesystem scan errors so the state factory's error/requirement channels resolve to never. --- packages/opencode/src/ockit/registry.ts | 89 +++++++++++++------------ 1 file changed, 47 insertions(+), 42 deletions(-) diff --git a/packages/opencode/src/ockit/registry.ts b/packages/opencode/src/ockit/registry.ts index 97e7b652f..bdb39af05 100644 --- a/packages/opencode/src/ockit/registry.ts +++ b/packages/opencode/src/ockit/registry.ts @@ -42,52 +42,57 @@ const layer = Layer.effect( const fs = yield* FSUtil.Service const indexKit = Effect.fn("OCKitRegistry.indexKit")(function* ( - kitDir: string, - kits: State["kits"], - dirs: string[], - ) { - const manifest = yield* loadManifest(kitDir).pipe( - Effect.catchTag("OCKitManifestError", (err) => - Effect.logWarning("skipping invalid kit manifest", { dir: kitDir, error: err.message }).pipe(Effect.as(undefined)), - ), - ) - if (!manifest) return - if (kits[manifest.id]) { - yield* Effect.logWarning("duplicate kit id, keeping first", { id: manifest.id, dir: kitDir }) - return - } - kits[manifest.id] = manifest - dirs.push(kitDir) - }) - - const state = yield* InstanceState.make( - Effect.fn("OCKitRegistry.state")(function* (ctx) { - const kits: Record = {} - const dirs: string[] = [] - - // Global: /kits// - const globalKits = path.join(Global.Path.config, KITS_DIR) - if (yield* fs.isDir(globalKits)) { - for (const entry of yield* fs.readDirectoryEntries(globalKits)) { - if (entry.type !== "directory") continue - yield* indexKit(path.join(globalKits, entry.name), kits, dirs) - } + fs: FSUtil.Interface, + kitDir: string, + kits: State["kits"], + dirs: string[], + ) { + const manifest = yield* loadManifest(kitDir).pipe( + Effect.provideService(FSUtil.Service, fs), + Effect.catchTag("OCKitManifestError", (err) => + Effect.logWarning("skipping invalid kit manifest", { dir: kitDir, error: err.message }).pipe( + Effect.as(undefined), + ), + ), + Effect.orDie, + ) + if (!manifest) return + if (kits[manifest.id]) { + yield* Effect.logWarning("duplicate kit id, keeping first", { id: manifest.id, dir: kitDir }) + return } + kits[manifest.id] = manifest + dirs.push(kitDir) + }) - // Project: /kits/ from each config directory (up-find of .opencode). - const configDirs = yield* config.directories() - for (const dir of configDirs) { - const projectKits = path.join(dir, KITS_DIR) - if (!(yield* fs.isDir(projectKits))) continue - for (const entry of yield* fs.readDirectoryEntries(projectKits)) { - if (entry.type !== "directory") continue - yield* indexKit(path.join(projectKits, entry.name), kits, dirs) + const state = yield* InstanceState.make( + Effect.fn("OCKitRegistry.state")(function* (ctx) { + const kits: Record = {} + const dirs: string[] = [] + + // Global: /kits// + const globalKits = path.join(Global.Path.config, KITS_DIR) + if (yield* fs.isDir(globalKits)) { + for (const entry of yield* fs.readDirectoryEntries(globalKits).pipe(Effect.orDie)) { + if (entry.type !== "directory") continue + yield* indexKit(fs, path.join(globalKits, entry.name), kits, dirs) + } } - } - return { kits, dirs } - }), - ) + // Project: /kits/ from each config directory (up-find of .opencode). + const configDirs = yield* config.directories() + for (const dir of configDirs) { + const projectKits = path.join(dir, KITS_DIR) + if (!(yield* fs.isDir(projectKits))) continue + for (const entry of yield* fs.readDirectoryEntries(projectKits).pipe(Effect.orDie)) { + if (entry.type !== "directory") continue + yield* indexKit(fs, path.join(projectKits, entry.name), kits, dirs) + } + } + + return { kits, dirs } + }), + ) const all = Effect.fn("OCKitRegistry.all")(function* () { const s = yield* InstanceState.get(state) From 4e8c491fd6036bbf92b8d2b7d5a01136be34edf7 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 03:50:00 +0700 Subject: [PATCH 07/12] fix(test): run checkpoint list test under the real clock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 'lists checkpoints newest first and filters by kit' test used Effect.sleep inside it.effect, which layers in TestClock. Under TestClock + runPromise the virtual clock never advances, so the sleep never completes and the test hangs until bun's 30s timeout kills it — deterministically failing unit (linux) and unit (windows). Switch the test to it.live so it uses the live clock. --- packages/opencode/test/ockit/checkpoint.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/opencode/test/ockit/checkpoint.test.ts b/packages/opencode/test/ockit/checkpoint.test.ts index e33e28540..9d1be0904 100644 --- a/packages/opencode/test/ockit/checkpoint.test.ts +++ b/packages/opencode/test/ockit/checkpoint.test.ts @@ -44,7 +44,9 @@ describe("ockit checkpoint", () => { ), ) - it.effect("lists checkpoints newest first and filters by kit", () => + // Needs the real clock: `Effect.sleep` below would otherwise suspend forever + // under the TestClock that `it.effect` layers in (see test/lib/effect.ts). + it.live("lists checkpoints newest first and filters by kit", () => withRoot((root) => Effect.gen(function* () { const one = yield* create({ root, kit: "engineer", kitVersion: "1.0.0", operation: "update", files: {} }) From 933dc495f34acfcbe30a6ef35ab65904951f69a9 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 04:03:30 +0700 Subject: [PATCH 08/12] test(opencode): give the unknown-model promptness test headroom for shared runners The 27371 regression test asserted the subprocess exits nonzero within 15s of wall-clock while also letting appProc kill the child at 15s. On loaded GitHub-hosted runners the bun subprocess startup (transpile, plugin init, server boot, SDK call) pushes the prompt error path past 15s, so the child was killed by the 15s timeout before it could self-exit and the test failed with durationMs ~15.5s -- on every run, including the pre-ockit baseline. Raise both the subprocess kill timeout and the wall-clock bound to 25s. A prompt nonzero exit lands well under 25s once allowed; a genuine hang is killed by the 25s subprocess timeout and still fails toBeLessThan(25_000). The 30s harness timeout remains the backstop, so hang detection is preserved. --- packages/opencode/test/cli/run/run-process.test.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/opencode/test/cli/run/run-process.test.ts b/packages/opencode/test/cli/run/run-process.test.ts index c98f0cd3c..f2a35a681 100644 --- a/packages/opencode/test/cli/run/run-process.test.ts +++ b/packages/opencode/test/cli/run/run-process.test.ts @@ -67,13 +67,22 @@ describe("opencode run (non-interactive subprocess)", () => { // makes the SDK call surface an error promptly so the process exits nonzero. // We assert nonzero exit AND wall-clock under the harness timeout — a hang // would expire the timeout and produce a different (signal-killed) failure. + // + // The 15s figure used to sit at both the subprocess kill timeout and the + // wall-clock bound, but loaded shared runners push `bun` subprocess startup + // (transpile of the CLI entry, plugin init, server boot, SDK call) past 15s, + // so appProc killed the child before a prompt (non-hanging) error could + // self-exit and the test failed on ~15.5s wall-clock. Raise the bound and the + // kill timeout together to 25s: a prompt error self-exits nonzero well under + // 25s; a true hang is killed by the 25s subprocess timeout and still fails + // `toBeLessThan(25_000)`. The 30s harness timeout remains the backstop. cliIt.concurrent( "exits nonzero promptly when the model is unknown (regression for #27371)", ({ opencode }) => Effect.gen(function* () { const result = yield* opencode.run("say hi", { model: "test/nonexistent-model", - timeoutMs: 15_000, + timeoutMs: 25_000, }) expect(result.exitCode).not.toBe(0) // Allow headroom for cold-start jitter on the CI container (the process From 136eac98ab34d4cfa9e2339844a26df5299f6e8b Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 05:10:47 +0700 Subject: [PATCH 09/12] test(core): raise slow core test timeouts to 30s for Windows CI RepositoryCache and Ripgrep tests do real subprocess work (git clone/commit, ripgrep binary install via Expand-Archive) that exceeds bun's default 5000ms per-test timeout on slow shared Windows runners. The PR diff touches zero core/ripgrep/repository code and the pre-PR baseline passed, so this is a test-infra fix, not a code regression: the 11 slow it.live tests now carry a 30_000ms bun test timeout (matching the existing run-process subprocess tests, which already pass 60s/30s timeouts). --- packages/core/test/repository-cache.test.ts | 6 ++++++ packages/core/test/ripgrep.test.ts | 3 +++ 2 files changed, 9 insertions(+) diff --git a/packages/core/test/repository-cache.test.ts b/packages/core/test/repository-cache.test.ts index 4433583bf..b68e4c742 100644 --- a/packages/core/test/repository-cache.test.ts +++ b/packages/core/test/repository-cache.test.ts @@ -31,6 +31,7 @@ describe("RepositoryCache", () => { expect(yield* read(path.join(localPath, "README.md"))).toBe("one\n") }).pipe(Effect.provide(cacheLayer(fixture.root))), ), + 30_000, // bun per-test timeout (defaults to 5000); real git subprocesses need headroom on CI ) it.live("serializes concurrent materialization for the same checkout", () => @@ -46,6 +47,7 @@ describe("RepositoryCache", () => { expect(results[0].localPath).toBe(results[1].localPath) }).pipe(Effect.provide(cacheLayer(fixture.root))), ), + 30_000, // bun per-test timeout (defaults to 5000); real git subprocesses need headroom on CI ) it.live("replaces an existing checkout whose origin does not match", () => @@ -64,6 +66,7 @@ describe("RepositoryCache", () => { expect(yield* exists(path.join(replaced.localPath, "stale.txt"))).toBe(false) }).pipe(Effect.provide(cacheLayer(fixture.root))), ), + 30_000, // bun per-test timeout (defaults to 5000); real git subprocesses need headroom on CI ) it.live("keeps branch checkouts isolated from branchless refreshes", () => @@ -86,6 +89,7 @@ describe("RepositoryCache", () => { expect(yield* read(path.join(cached.localPath, "README.md"))).toBe("two\n") }).pipe(Effect.provide(cacheLayer(fixture.root))), ), + 30_000, // bun per-test timeout (defaults to 5000); real git subprocesses need headroom on CI ) it.live("does not mistake an enclosing repository for the cache checkout", () => @@ -99,6 +103,7 @@ describe("RepositoryCache", () => { expect(yield* read(path.join(result.localPath, "README.md"))).toBe("one\n") }).pipe(Effect.provide(cacheLayer(fixture.root))), ), + 30_000, // bun per-test timeout (defaults to 5000); real git subprocesses need headroom on CI ) it.live("returns typed validation and clone failures", () => @@ -119,6 +124,7 @@ describe("RepositoryCache", () => { expect(cloneFailure).toBeInstanceOf(RepositoryCache.CloneFailedError) }).pipe(Effect.provide(cacheLayer(fixture.root))), ), + 30_000, // bun per-test timeout (defaults to 5000); real git subprocesses need headroom on CI ) }) diff --git a/packages/core/test/ripgrep.test.ts b/packages/core/test/ripgrep.test.ts index 5695af000..aae302175 100644 --- a/packages/core/test/ripgrep.test.ts +++ b/packages/core/test/ripgrep.test.ts @@ -29,6 +29,7 @@ describe("Ripgrep", () => { }), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ), + 30_000, // bun per-test timeout (defaults to 5000); the ripgrep binary download on Windows is slow ) it.live("never includes git metadata", () => @@ -61,6 +62,7 @@ describe("Ripgrep", () => { }), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ), + 30_000, // bun per-test timeout (defaults to 5000); the ripgrep binary download on Windows is slow ) it.live("does not split surrogate pairs in oversized line previews", () => Effect.acquireUseRelease( @@ -81,5 +83,6 @@ describe("Ripgrep", () => { }), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ), + 30_000, // bun per-test timeout (defaults to 5000); the ripgrep binary download on Windows is slow ) }) From 0ad0ad4c350078273315bde5e8f550b0dbbbf0ca Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 12:14:23 +0700 Subject: [PATCH 10/12] test(core): cover the remaining slow core tests missed by the 30s bump The Windows unit run at 6d62f21 still had 6 failures: the 30s bump landed on repository-cache.test.ts and ripgrep.test.ts, but missed filesystem/search.test.ts (2 Ripgrep tests at the 5s default) and raised ripgrep.test.ts to 30s, which the cold ripgrep binary download + Expand-Archive on a shared Windows runner can still exceed. - filesystem/search.test.ts: 2 it.live tests now pass 30_000ms. - ripgrep.test.ts: 3 tests raised 30s -> 60s, matching the 60s precedent in the opencode run-process subprocess tests. - util/effect-flock.test.ts: raised the internal worker-readiness wait (waitForFile ready) 5s -> 15s for the "recovers after a crashed lock owner" test, a pre-existing Windows spawn-latency flake independent of bun's per-test timeout. Test-infra only; the PR diff still touches zero core/ripgrep/repository source code. --- packages/core/test/filesystem/search.test.ts | 2 ++ packages/core/test/ripgrep.test.ts | 6 +++--- packages/core/test/util/effect-flock.test.ts | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/core/test/filesystem/search.test.ts b/packages/core/test/filesystem/search.test.ts index 6c47c85e9..fe7ba180a 100644 --- a/packages/core/test/filesystem/search.test.ts +++ b/packages/core/test/filesystem/search.test.ts @@ -26,6 +26,7 @@ describe("Ripgrep", () => { expect(result.map((item) => item.path)).toEqual([RelativePath.make("src/match.ts")]) }), ), + 30_000, // bun per-test timeout (defaults to 5000); cold ripgrep binary install on Windows CI is slow ) it.live("greps files with include filtering", () => @@ -40,5 +41,6 @@ describe("Ripgrep", () => { expect(result[0]?.submatches[0]?.text).toBe("needle") }), ), + 30_000, // bun per-test timeout (defaults to 5000); cold ripgrep binary install on Windows CI is slow ) }) diff --git a/packages/core/test/ripgrep.test.ts b/packages/core/test/ripgrep.test.ts index aae302175..d9b24bac1 100644 --- a/packages/core/test/ripgrep.test.ts +++ b/packages/core/test/ripgrep.test.ts @@ -29,7 +29,7 @@ describe("Ripgrep", () => { }), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ), - 30_000, // bun per-test timeout (defaults to 5000); the ripgrep binary download on Windows is slow + 60_000, // bun per-test timeout (defaults to 5000); cold ripgrep binary download + Expand-Archive on Windows CI can exceed 30s ) it.live("never includes git metadata", () => @@ -62,7 +62,7 @@ describe("Ripgrep", () => { }), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ), - 30_000, // bun per-test timeout (defaults to 5000); the ripgrep binary download on Windows is slow + 60_000, // bun per-test timeout (defaults to 5000); cold ripgrep binary download + Expand-Archive on Windows CI can exceed 30s ) it.live("does not split surrogate pairs in oversized line previews", () => Effect.acquireUseRelease( @@ -83,6 +83,6 @@ describe("Ripgrep", () => { }), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ), - 30_000, // bun per-test timeout (defaults to 5000); the ripgrep binary download on Windows is slow + 60_000, // bun per-test timeout (defaults to 5000); cold ripgrep binary download + Expand-Archive on Windows CI can exceed 30s ) }) diff --git a/packages/core/test/util/effect-flock.test.ts b/packages/core/test/util/effect-flock.test.ts index d7c412851..5c35bcb9d 100644 --- a/packages/core/test/util/effect-flock.test.ts +++ b/packages/core/test/util/effect-flock.test.ts @@ -372,7 +372,7 @@ describe("util.effect-flock", () => { const proc = spawnWorker({ key: "eflock:crash", dir, ready, holdMs: 120_000 }) try { - await waitForFile(ready, 5_000) + await waitForFile(ready, 15_000) await stopWorker(proc) // Backdate lock files so they're past STALE_MS (60s) From 2d5f339594a6450f2ecfae8e61c812fe1d14a1bd Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 14:38:41 +0700 Subject: [PATCH 11/12] ci(setup-bun): retry bun install with cache clear on Windows ENOTEMPTY bun install --linker hoisted on Windows occasionally fails to apply a patchfile (e.g. @ai-sdk/openai-compatible) with "ENOTEMPTY: ... Directory not empty" while renaming the patched package into the dependency cache. This is a bun-Windows race with a leftover half-written cache dir, not a code defect, and it recurred on every recent Windows unit run, blocking the test step before it could start. Retry the install up to 3 times, clearing the bun package cache between attempts so the reinstall starts from a clean dir. Non-Windows behavior is unchanged. --- .github/actions/setup-bun/action.yml | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/.github/actions/setup-bun/action.yml b/.github/actions/setup-bun/action.yml index 9d29724d8..acdf2e50d 100644 --- a/.github/actions/setup-bun/action.yml +++ b/.github/actions/setup-bun/action.yml @@ -54,16 +54,33 @@ runs: shell: bash - name: Install dependencies + shell: bash run: | # Workaround for patched peer variants # e.g. ./patches/ for standard-openapi # https://github.com/oven-sh/bun/issues/28147 - if [ "$RUNNER_OS" = "Windows" ]; then - bun install --linker hoisted ${{ inputs.install-flags }} - else + if [ "$RUNNER_OS" != "Windows" ]; then bun install ${{ inputs.install-flags }} + exit $? fi - shell: bash + + # On Windows, `bun install --linker hoisted` occasionally fails to apply + # a patchfile with "ENOTEMPTY: ... Directory not empty" while renaming the + # patched package into a cache dir (e.g. @ai-sdk/openai-compatible). This is + # a bun-Windows race with the dependency cache, not a code defect: the leftover + # half-written dir makes the rename collide on the next attempt. Retry by + # clearing the bun package cache first so the reinstall starts from a clean dir. + for attempt in 1 2 3; do + echo "bun install attempt $attempt (--linker hoisted)" + if bun install --linker hoisted ${{ inputs.install-flags }}; then + exit 0 + fi + echo "bun install failed on attempt $attempt; clearing bun cache and retrying" + bun pm cache rm 2>/dev/null || rm -rf "$(bun pm cache)" + echo "cleared bun package cache" + done + echo "bun install failed after 3 attempts" + exit 1 - name: Save Bun dependencies if: steps.bun-cache.outputs.cache-hit != 'true' && github.event_name != 'pull_request' && github.event_name != 'pull_request_target' From bdcc0222b15779d86006ad357827a75f562f7392 Mon Sep 17 00:00:00 2001 From: qkhalk Date: Sat, 15 Aug 2026 15:12:16 +0700 Subject: [PATCH 12/12] @ fix(core): use ZipFile for ripgrep extraction, bump snapshot test timeout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Expand-Archive (PowerShell 5.1) hangs indefinitely on shared Windows CI runners while staging files—observed SIGTERM at the 5s, 30s, and 60s test timeouts across three consecutive runs. The setup-bun action extracts a comparable zip in under 1s on the same runner via [IO.Compression.ZipFile]::ExtractToDirectory, so use the same .NET BCL method for the ripgrep binary install on Windows. Also give the Location-scoped snapshot test the same 30s bun per-test timeout already used by repository-cache tests: real git subprocesses (init/add/commit/ls-tree) need headroom on loaded Windows runners. @ --- packages/core/src/ripgrep/binary.ts | 9 ++++++++- packages/core/test/snapshot.test.ts | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/core/src/ripgrep/binary.ts b/packages/core/src/ripgrep/binary.ts index 762a8e613..af9f41825 100644 --- a/packages/core/src/ripgrep/binary.ts +++ b/packages/core/src/ripgrep/binary.ts @@ -57,11 +57,18 @@ export namespace RipgrepBinary { if (config.extension === "zip") { const shell = (yield* Effect.sync(() => which("powershell.exe") ?? which("pwsh.exe"))) ?? "powershell.exe" + // `Expand-Archive` (PowerShell 5.1) hangs indefinitely on shared Windows + // CI runners while staging files (observed SIGTERM at 5/30/60s test + // timeouts). `[IO.Compression.ZipFile]::ExtractToDirectory` is the same + // .NET BCL the setup-bun action uses to extract a comparable zip in + // under 1s on the same runner. Key differences: Add-Type is unconditional + // (progress bars are off by default in -NonInteractive), and the + // destination is a scoped temp dir so no :Delete\:\*:\* flags are needed. const result = yield* run(shell, [ "-NoProfile", "-NonInteractive", "-Command", - `$global:ProgressPreference = 'SilentlyContinue'; Expand-Archive -LiteralPath '${archive.replaceAll("'", "''")}' -DestinationPath '${dir.replaceAll("'", "''")}' -Force`, + `Add-Type -AssemblyName System.IO.Compression.FileSystem; [System.IO.Compression.ZipFile]::ExtractToDirectory('${archive.replaceAll("'", "''")}', '${dir.replaceAll("'", "''")}')`, ]) if (result.code !== 0) throw new Error( diff --git a/packages/core/test/snapshot.test.ts b/packages/core/test/snapshot.test.ts index 5e01fefc1..6c416d21a 100644 --- a/packages/core/test/snapshot.test.ts +++ b/packages/core/test/snapshot.test.ts @@ -65,6 +65,7 @@ describe("Snapshot", () => { }), (tmp) => Effect.promise(() => tmp[Symbol.asyncDispose]()), ), + 30_000, // bun per-test timeout (defaults to 5000); real git subprocesses need headroom on Windows CI ) testEffect(Layer.empty).live("treats capture outside Git as unavailable", () =>