Repository navigation
feat(opencode): OC Kit domain model (Phase 1) - #2
Conversation
|
Thanks for updating your PR! It now meets our contributing guidelines. 👍 |
There was a problem hiding this comment.
Pull request overview
Adds the Phase 1 OC Kit domain model to the OpenCode runtime: Effect Schema-based types plus manifest loading/validation, kit discovery via a registry, declaration resolution, ownership tracking, checkpoints, and config access. This is integrated with the shared config schema by introducing an optional oc_kit section in Core, with new unit tests covering the new functionality.
Changes:
- Introduces
packages/opencode/src/ockit/*domain modules (types, manifest loading, registry, resolver, ownership, checkpoints, config, exports). - Extends
packages/coreconfig schema with an optionaloc_kitsection (backward-compatible). - Adds a new
packages/opencode/test/ockit/*test suite for OC Kit Phase 1 primitives.
Reviewed changes
Copilot reviewed 17 out of 17 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
| UPSTREAM.md | Documents fork/upstream relationship and divergence policy. |
| plans/260814-1636-oc-kit-phase0-1/plan.md | Captures Phase 0/1 plan and deliverables for this fork. |
| packages/opencode/src/ockit/types.ts | Defines OC Kit domain schemas/types (Kit, Workflow, Ownership, Checkpoint, config). |
| packages/opencode/src/ockit/manifest.ts | Loads/parses kit manifests (JSON/YAML) and validates against schemas. |
| packages/opencode/src/ockit/registry.ts | Discovers kits from global + project config locations and indexes manifests. |
| packages/opencode/src/ockit/resolver.ts | Resolves declarations (skills/agents/workflows/hooks) from typed manifests. |
| packages/opencode/src/ockit/ownership.ts | Implements ownership manifest load/save + conflict/edit detection + update planning. |
| packages/opencode/src/ockit/checkpoint.ts | Implements checkpoint snapshot create/list/read under .oc/state/checkpoints. |
| packages/opencode/src/ockit/config.ts | Provides typed accessors/defaults/validation for oc_kit config section. |
| packages/opencode/src/ockit/index.ts | Exports the OC Kit public module surface. |
| packages/core/src/v1/config/config.ts | Adds optional oc_kit section to the shared Core config schema. |
| packages/opencode/test/ockit/manifest.test.ts | Tests manifest loading preference + schema validation failures. |
| packages/opencode/test/ockit/registry.test.ts | Tests registry discovery/lookup, not-found, and invalid-manifest skipping. |
| packages/opencode/test/ockit/resolver.test.ts | Tests kit indexing + resolution and missing-id error behavior. |
| packages/opencode/test/ockit/ownership.test.ts | Tests ownership claim/edit detection/update planning and disk roundtrip. |
| packages/opencode/test/ockit/checkpoint.test.ts | Tests checkpoint create/list/read behaviors and error cases. |
| packages/opencode/test/ockit/config.test.ts | Tests defaults, validation behavior, and schema decoding for oc_kit. |
Suppressed comments (2)
packages/opencode/src/ockit/checkpoint.ts:68
- checkpoint.read uses JSON.parse(raw) directly inside the Effect generator. If the checkpoint file is corrupted/partial, JSON.parse will throw synchronously and become an untyped defect instead of a CheckpointError.
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) })),
)
packages/opencode/test/ockit/config.test.ts:28
- Use Schema.decodeUnknownSync(OCKitConfig)(...) for schema decoding to match the established pattern in this repo (e.g. packages/core/test/shared-schema.test.ts:195).
it.effect("OCKitConfig schema decodes a full config", () => {
const decoded = OCKitConfig.decodeUnknownSync({
enabled: true,
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| * 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 class ResolveError extends Schema.TaggedErrorClass<ResolveError>()("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}"` | ||
| } | ||
| } |
| 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 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() |
| 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) })), | ||
| ) |
| export function validate(input: unknown): OCKitConfigType | undefined { | ||
| return OCKitConfig.decodeUnknownOption(input) | ||
| } |
| import { Effect } from "effect" | ||
| import { Config } from "@/config/config" | ||
| import { OCKitConfig, type OCKitConfig as OCKitConfigType } from "./types" |
| import { describe, expect } from "bun:test" | ||
| import { it } from "../lib/effect" | ||
| import { defaults, validate } from "../../src/ockit/config" | ||
| import { OCKitConfig } from "../../src/ockit/types" |
| Effect.gen(function* () { | ||
| const fs = yield* FSUtil.Service | ||
| return yield* planUpdate(fs, root, manifest, "engineer", { "owned.md": "new content", "new.md": "x" }) | ||
| }), |
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
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 <config>/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.
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.
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 <config>/kits/<id>/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).
- 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)
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.
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.
…hared 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.
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).
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.
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.
fix(core): use ZipFile for ripgrep extraction, bump snapshot test timeout 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. @
Issue for this PR
No issue — this is the first PR in the OC Kit integration plan for this fork. The roadmap is documented in
plans/260814-1636-oc-kit-phase0-1/plan.md.Type of change
What does this PR do?
Implements Phase 1 of the OC Kit integration plan: the OC Kit domain model — typed schemas, manifest loading/validation, kit discovery, resolution, ownership tracking, checkpoints, and config access. The workflow engine, hook dispatcher, artifact manager, CLI, and installer are explicitly out of scope (later phases).
New module
packages/opencode/src/ockit/:types.ts— Effect Schemas forKit,KitSkill,KitAgent,Workflow/WorkflowStep,KitHook,Mode,WorkflowState,WorkflowRun,Artifact,Checkpoint,OwnershipEntry/OwnershipManifest,OCKitConfig.manifest.ts—loadManifestreadskit.json(preferred) orkit.yaml(viaBun.YAML), validates against theKitschema, and reportsManifestError; parse/schema failures are effectful errors, never synchronous throws.registry.ts—OCKitRegistryservice discovers installed kits across global<config>/kitsand per-project config-dirkits/, lazily viaInstanceState;all/get/require/dirswithNotFoundErrorand invalid-manifest skips.resolver.ts—indexKitbuilds name-indexed maps;resolveFromKitthrowsResolveError;resolveAcrosssearches kits in order.ownership.ts—loadOwnership/saveOwnership/claim/detectUserEdits/planUpdateimplement the ownership manifest with sha256 conflict detection and replace/preserve planning.checkpoint.ts—create/list/readcheckpoint snapshots under.oc/state/checkpoints, recording per-file sha256.config.ts—defaults/read/enabled/validatefor theoc_kitsection.index.ts— export surface.Also adds an optional
oc_kitsection toConfigV1.Info(strictly backward-compatible — existing configs are unaffected) and unit suites underpackages/opencode/test/ockit/following the repo'stestEffect(layer)pattern.How did you verify your code works?
bun turbo test/bun typecheck) per the project workflow contract.Screenshots / recordings
Not a UI change.
Checklist