diff --git a/packages/opencode/src/ockit/artifact/index.ts b/packages/opencode/src/ockit/artifact/index.ts new file mode 100644 index 000000000..7ce5da96f --- /dev/null +++ b/packages/opencode/src/ockit/artifact/index.ts @@ -0,0 +1,9 @@ +// OC Kit artifact subsystem: typed artifact manager + persistent manifest index. +// This index aggregates the leaf modules AND self-exports the subsystem as the +// `Artifact` namespace, so integrators can `import { Artifact } from +// "./artifact"`. + +export * from "./manager" +export * from "./manifest" + +export * as Artifact from "./index" \ No newline at end of file diff --git a/packages/opencode/src/ockit/artifact/manager.ts b/packages/opencode/src/ockit/artifact/manager.ts new file mode 100644 index 000000000..7a920c87d --- /dev/null +++ b/packages/opencode/src/ockit/artifact/manager.ts @@ -0,0 +1,150 @@ +// OC Kit artifact manager. Artifacts persist as typed records under +// `.oc/artifacts//.json` and are indexed in the artifact manifest. +// Every record carries the sha256 of the artifact's content file so integrity +// can be re-verified later. The manager honors the `oc_kit.checkpoint` config +// flag: when enabled, creating an artifact also snapshots a checkpoint marker +// (through the shared checkpoint module); when disabled, no checkpoint is +// written. + +import { Effect, Schema } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Hash } from "@opencode-ai/core/util/hash" +import { Artifact } from "../types" +import { read as readOCKitConfig } from "../config" +import { create as createCheckpoint } from "../checkpoint" +import { loadArtifactManifest, saveArtifactManifest, artifactsRoot } from "./manifest" + +/** Directory holding artifact records, relative to a project root. */ +export const ARTIFACT_DIR = ".oc/artifacts" + +export class ArtifactError extends Schema.TaggedErrorClass()("OCKitArtifactError", { + path: Schema.String, + message: Schema.optional(Schema.String), +}) { + override get message(): string { + return `OC Kit artifact: ${this.path}${this.message ? ` — ${this.message}` : ""}` + } +} + +/** Path of a single artifact record. */ +export const artifactPath = (root: string, type: string, id: string) => + `${artifactsRoot(root)}/${type}/${id}.json` + +/** Write an artifact record to disk, creating parent directories as needed. */ +const writeRecord = Effect.fn("OCKit.artifact.writeRecord")(function* (root: string, artifact: Artifact) { + const fs = yield* FSUtil.Service + const path = artifactPath(root, artifact.type, artifact.id) + yield* fs.writeWithDirs(path, JSON.stringify(artifact, null, 2)) +}) + +/** Insert (or replace) an artifact in the persisted manifest index. */ +const upsertManifest = Effect.fn("OCKit.artifact.upsertManifest")(function* (root: string, artifact: Artifact) { + const manifest = yield* loadArtifactManifest(root) + yield* saveArtifactManifest(root, { + version: manifest.version, + artifacts: { ...manifest.artifacts, [artifact.id]: artifact }, + }) +}) + +/** + * Create an artifact record for the file at `input.path`. The record is stored + * at `{root}/.oc/artifacts/{type}/{id}.json`, indexed in the manifest, and + * (when `oc_kit.checkpoint` is enabled) snapshotted as a checkpoint marker. + */ +export const create = Effect.fn("OCKit.artifact.create")(function* (input: { + root: string + id: string + type: string + workflow_id?: string + session_id?: string + path: string +}) { + const fs = yield* FSUtil.Service + const raw = yield* fs.readFileStringSafe(input.path) + const artifact: Artifact = { + id: input.id, + type: input.type, + workflow_id: input.workflow_id, + session_id: input.session_id, + path: input.path, + status: "created", + checksum: raw === undefined ? undefined : Hash.sha256(raw), + } + yield* writeRecord(input.root, artifact) + yield* upsertManifest(input.root, artifact) + + const cfg = yield* readOCKitConfig() + if (cfg.checkpoint) { + const record = JSON.stringify(artifact) + yield* createCheckpoint({ + root: input.root, + kit: input.type, + kitVersion: "1", + operation: "artifact:create", + session: input.session_id, + workflow: input.workflow_id, + files: { [artifactPath(input.root, input.type, input.id)]: record }, + }) + } + return artifact +}) + +/** List recorded artifacts, optionally scoped to one type. */ +export const list = Effect.fn("OCKit.artifact.list")(function* (root: string, type?: string) { + const manifest = yield* loadArtifactManifest(root) + const artifacts = Object.values(manifest.artifacts) + return type ? artifacts.filter((artifact) => artifact.type === type) : artifacts +}) + +/** Read a single artifact record by id (from the manifest index). */ +export const read = Effect.fn("OCKit.artifact.read")(function* (root: string, id: string) { + const fs = yield* FSUtil.Service + const manifest = yield* loadArtifactManifest(root) + const recorded = manifest.artifacts[id] + if (!recorded) { + return yield* new ArtifactError({ path: id, message: `No artifact "${id}"` }) + } + const path = artifactPath(root, recorded.type, id) + const raw = yield* fs.readFileStringSafe(path) + if (raw === undefined) return yield* new ArtifactError({ path, message: "Artifact record missing" }) + const decoded = yield* Schema.decodeUnknownEffect(Artifact)(JSON.parse(raw)).pipe( + Effect.mapError((err) => new ArtifactError({ path, message: String(err) })), + ) + return decoded +}) + +/** + * Recompute the sha256 of the artifact's content file and fail with a typed + * ArtifactError when it no longer matches the checksum recorded at create time + * (the file was tampered with, or is missing). + */ +export const verify = Effect.fn("OCKit.artifact.verify")(function* (root: string, id: string) { + const fs = yield* FSUtil.Service + const artifact = yield* read(root, id) + const raw = yield* fs.readFileStringSafe(artifact.path) + if (raw === undefined) { + return yield* new ArtifactError({ path: artifact.path, message: "Artifact content missing" }) + } + if (artifact.checksum !== undefined && Hash.sha256(raw) !== artifact.checksum) { + return yield* new ArtifactError({ path: artifact.path, message: "Checksum mismatch — file may have been modified" }) + } + return artifact +}) + +/** Mark an artifact verified, updating the record and manifest. */ +export const markVerified = Effect.fn("OCKit.artifact.markVerified")(function* (root: string, id: string) { + const artifact = yield* read(root, id) + const updated: Artifact = { ...artifact, status: "verified" } + yield* writeRecord(root, updated) + yield* upsertManifest(root, updated) + return updated +}) + +/** Mark an artifact failed, updating the record and manifest. */ +export const markFailed = Effect.fn("OCKit.artifact.markFailed")(function* (root: string, id: string) { + const artifact = yield* read(root, id) + const updated: Artifact = { ...artifact, status: "failed" } + yield* writeRecord(root, updated) + yield* upsertManifest(root, updated) + return updated +}) \ No newline at end of file diff --git a/packages/opencode/src/ockit/artifact/manifest.ts b/packages/opencode/src/ockit/artifact/manifest.ts new file mode 100644 index 000000000..f9a35e229 --- /dev/null +++ b/packages/opencode/src/ockit/artifact/manifest.ts @@ -0,0 +1,64 @@ +// OC Kit artifact manifest. The artifact manager persists every artifact record +// under `.oc/artifacts//.json` AND records an `ArtifactManifest` — the +// index of artifacts written — under `manifest.json` so the whole tree can be +// listed without a full directory scan. +// +// The manifest schema is local to this module (the shared `types.ts` schema is +// owned by the domain layer; per the ownership contract we do not extend it). + +import { Effect, Schema } from "effect" +import { FSUtil } from "@opencode-ai/core/fs-util" +import { Artifact } from "../types" + +/** Manifest file name inside the artifacts root. */ +export const ARTIFACT_MANIFEST_FILE = "manifest.json" + +/** Index of artifacts, keyed by artifact id. */ +export const ArtifactManifest = Schema.Struct({ + version: Schema.Literal("1"), + artifacts: Schema.Record(Schema.String, Artifact), +}) + +export type ArtifactManifest = Schema.Schema.Type + +export class ArtifactManifestError extends Schema.TaggedErrorClass()( + "OCKitArtifactManifestError", + { + path: Schema.String, + message: Schema.optional(Schema.String), + }, +) { + override get message(): string { + return `OC Kit artifact manifest: ${this.path}${this.message ? ` — ${this.message}` : ""}` + } +} + +/** The artifacts root directory for a project root. */ +export const artifactsRoot = (root: string) => `${root}/.oc/artifacts` + +/** An empty manifest with no artifacts recorded. */ +export function emptyManifest(): ArtifactManifest { + return { version: "1", artifacts: {} } +} + +/** Load the artifact manifest, returning an empty manifest when absent. */ +export const loadArtifactManifest = Effect.fn("OCKit.artifact.manifest.load")(function* (root: string) { + const fs = yield* FSUtil.Service + const path = `${artifactsRoot(root)}/${ARTIFACT_MANIFEST_FILE}` + const raw = yield* fs.readFileStringSafe(path) + if (raw === undefined) return emptyManifest() + const decoded = yield* Schema.decodeUnknownEffect(ArtifactManifest)(JSON.parse(raw)).pipe( + Effect.mapError((err) => new ArtifactManifestError({ path, message: String(err) })), + ) + return decoded +}) + +/** Persist the artifact manifest, creating parent directories as needed. */ +export const saveArtifactManifest = Effect.fn("OCKit.artifact.manifest.save")(function* ( + root: string, + manifest: ArtifactManifest, +) { + const fs = yield* FSUtil.Service + const path = `${artifactsRoot(root)}/${ARTIFACT_MANIFEST_FILE}` + yield* fs.writeWithDirs(path, JSON.stringify(manifest, null, 2)) +}) \ No newline at end of file diff --git a/packages/opencode/src/ockit/hook/dispatcher.ts b/packages/opencode/src/ockit/hook/dispatcher.ts new file mode 100644 index 000000000..61422c5f4 --- /dev/null +++ b/packages/opencode/src/ockit/hook/dispatcher.ts @@ -0,0 +1,66 @@ +// OC Kit hook dispatcher. Takes a typed lifecycle event and runs the `command` +// of every matching hook via a safe subprocess spawn. This MUST NOT bypass +// OpenCode's permission/security system: a hook command runs exactly as a +// normal subprocess the user already allowed — the dispatcher never reads, +// grants, skips, or fabricates a permission decision. It simply sees the +// already-approved `command` string and hands it to the OS process spawner. +// +// No disk writes are required here; dispatch is fire-and-await on the +// subprocess, with a typed HookError when the command itself fails. + +import { Effect, Schema } from "effect" +import { KitHook, Kit } from "../types" +import { OCEvent } from "./events" +import { matchHooks, HookError } from "./matcher" +import { Process } from "@/util/process" + +/** + * Spawn a hook command string through the host shell and wait for it to exit. + * The command string is shell-parsed exactly like any other host-run command; + * failures surface as a typed HookError carrying the command and exit code. + */ +const runHookCommand = Effect.fn("OCKit.hook.runCommand")(function* (event: OCEvent, hook: KitHook) { + const result = yield* Effect.tryPromise({ + try: async () => { + const proc = Process.spawn([hook.command], { + shell: true, + stdout: "ignore", + stderr: "ignore", + env: { + OC_KIT_EVENT: event._tag, + OC_KIT_HOOK_COMMAND: hook.command, + }, + }) + return await proc.exited + }, + catch: (cause) => new HookError({ event: event._tag, message: String(cause) }), + }) + if (result !== 0) { + return yield* new HookError({ + event: event._tag, + message: `hook command exited with code ${result}`, + }) + } + return result +}) + +/** + * Dispatch a lifecycle event: run the `command` of every hook matching the + * event's name, in order. When no hook matches, the dispatch is a no-op. + * A failing hook command fails the effect with a typed HookError — failures are + * never swallowed. + */ +export const dispatch = Effect.fn("OCKit.hook.dispatch")(function* ( + hooks: readonly KitHook[], + event: OCEvent, +) { + const matched = matchHooks(hooks, event) + for (const hook of matched) { + yield* runHookCommand(event, hook) + } +}) + +/** Dispatch using all hooks declared by a single kit manifest. */ +export const dispatchKit = Effect.fn("OCKit.hook.dispatchKit")(function* (kit: Kit, event: OCEvent) { + yield* dispatch(kit.hooks ?? [], event) +}) \ No newline at end of file diff --git a/packages/opencode/src/ockit/hook/events.ts b/packages/opencode/src/ockit/hook/events.ts new file mode 100644 index 000000000..30ae6a698 --- /dev/null +++ b/packages/opencode/src/ockit/hook/events.ts @@ -0,0 +1,162 @@ +// OC Kit lifecycle events. Each event is an Effect Schema so dispatch payloads +// validate structurally before the hook bus forwards them. Events carry only the +// data a hook command needs to observe the lifecycle moment — never handles to +// elevate permission or bypass OpenCode's security system. + +import { Schema } from "effect" + +const KitInstalled = Schema.Struct({ + _tag: Schema.Literal("kit:install"), + kit: Schema.String, + version: Schema.String, + timestamp: Schema.String, +}) + +const KitUpdated = Schema.Struct({ + _tag: Schema.Literal("kit:update"), + kit: Schema.String, + from: Schema.String, + to: Schema.String, + timestamp: Schema.String, +}) + +const KitRemoved = Schema.Struct({ + _tag: Schema.Literal("kit:remove"), + kit: Schema.String, + timestamp: Schema.String, +}) + +const SessionStarted = Schema.Struct({ + _tag: Schema.Literal("session:start"), + session_id: Schema.String, + timestamp: Schema.String, +}) + +const SessionEnded = Schema.Struct({ + _tag: Schema.Literal("session:end"), + session_id: Schema.String, + timestamp: Schema.String, +}) + +const WorkflowStarted = Schema.Struct({ + _tag: Schema.Literal("workflow:start"), + workflow_id: Schema.String, + session_id: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const WorkflowEnded = Schema.Struct({ + _tag: Schema.Literal("workflow:end"), + workflow_id: Schema.String, + session_id: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const SkillBefore = Schema.Struct({ + _tag: Schema.Literal("skill:before"), + skill: Schema.String, + session_id: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const SkillAfter = Schema.Struct({ + _tag: Schema.Literal("skill:after"), + skill: Schema.String, + session_id: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const ToolBefore = Schema.Struct({ + _tag: Schema.Literal("tool:before"), + tool: Schema.String, + session_id: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const ToolAfter = Schema.Struct({ + _tag: Schema.Literal("tool:after"), + tool: Schema.String, + session_id: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const PermissionRequested = Schema.Struct({ + _tag: Schema.Literal("permission:request"), + action: Schema.String, + resource: Schema.String, + session_id: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const ArtifactCreated = Schema.Struct({ + _tag: Schema.Literal("artifact:created"), + artifact_id: Schema.String, + artifact_type: Schema.String, + session_id: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const CheckpointCreated = Schema.Struct({ + _tag: Schema.Literal("checkpoint:created"), + checkpoint_id: Schema.String, + kit: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const VerificationFailed = Schema.Struct({ + _tag: Schema.Literal("verification:failed"), + artifact_id: Schema.String, + reason: Schema.optional(Schema.String), + timestamp: Schema.String, +}) + +const VerificationPassed = Schema.Struct({ + _tag: Schema.Literal("verification:passed"), + artifact_id: Schema.String, + timestamp: Schema.String, +}) + +/** Union of every OC Kit lifecycle event (discriminated by the `_tag` name). */ +export const OCEvent = Schema.Union([ + KitInstalled, + KitUpdated, + KitRemoved, + SessionStarted, + SessionEnded, + WorkflowStarted, + WorkflowEnded, + SkillBefore, + SkillAfter, + ToolBefore, + ToolAfter, + PermissionRequested, + ArtifactCreated, + CheckpointCreated, + VerificationFailed, + VerificationPassed, +]).annotate({ discriminator: "_tag", identifier: "OCEvent" }) + +export type OCEvent = Schema.Schema.Type + +/** Event name string ("kit:install", "session:start", …). */ +export type OCEventName = OCEvent["_tag"] + +/** The canonical set of lifecycle event names. */ +export const EVENT_NAMES: readonly OCEventName[] = [ + "kit:install", + "kit:update", + "kit:remove", + "session:start", + "session:end", + "workflow:start", + "workflow:end", + "skill:before", + "skill:after", + "tool:before", + "tool:after", + "permission:request", + "artifact:created", + "checkpoint:created", + "verification:failed", + "verification:passed", +] \ No newline at end of file diff --git a/packages/opencode/src/ockit/hook/index.ts b/packages/opencode/src/ockit/hook/index.ts new file mode 100644 index 000000000..1afc8fe99 --- /dev/null +++ b/packages/opencode/src/ockit/hook/index.ts @@ -0,0 +1,12 @@ +// OC Kit hooks subsystem: lifecycle event definitions, the event matcher, and +// the dispatcher that runs a kit's hook commands for matching events. +// +// This index aggregates the three leaf modules AND self-exports the subsystem +// as the `Hook` namespace (same convention as `export * as Checkpoint from +// "./checkpoint"`), so integrators can `import { Hook } from "./hook"`. + +export * from "./events" +export * from "./matcher" +export * from "./dispatcher" + +export * as Hook from "./index" \ No newline at end of file diff --git a/packages/opencode/src/ockit/hook/matcher.ts b/packages/opencode/src/ockit/hook/matcher.ts new file mode 100644 index 000000000..41d1e634f --- /dev/null +++ b/packages/opencode/src/ockit/hook/matcher.ts @@ -0,0 +1,46 @@ +// OC Kit event matcher. Pure — maps a typed lifecycle event to the kit hook +// commands whose declared `event` name matches. Supports exact names +// ("session:start") and trailing wildcards ("session:*" matches every +// session-scoped event). No disk, no side effects, so it is trivially testable. + +import { Schema } from "effect" +import { KitHook } from "../types" +import { EVENT_NAMES, type OCEvent, type OCEventName } from "./events" + +export class HookError extends Schema.TaggedErrorClass()("OCKitHookError", { + event: Schema.String, + message: Schema.optional(Schema.String), +}) { + override get message(): string { + return `OC Kit hook: ${this.event}${this.message ? ` — ${this.message}` : ""}` + } +} + +/** True when `declared` (a hook's event pattern) matches `actual` (an event name). */ +export function matches(declared: string, actual: OCEventName): boolean { + if (declared === actual) return true + if (declared.endsWith("*")) { + return actual.startsWith(declared.slice(0, -1)) + } + return false +} + +/** + * Return the hooks from `hooks` (a kit's `hooks` array) whose declared event + * pattern matches the event's name. Fanning out a lifecycle event can run + * multiple hook commands; an empty list means no hook fired. + */ +export function matchHooks(hooks: readonly KitHook[], event: OCEvent): KitHook[] { + return hooks.filter((hook) => matches(hook.event, event._tag)) +} + +/** Validate that an event name is part of the OC Kit lifecycle. */ +export function isKnownEvent(name: string): name is OCEventName { + return (EVENT_NAMES as readonly string[]).includes(name) +} + +/** Throw a typed HookError for an unknown/unsupported event name. */ +export function knownEventOrThrow(name: string): OCEventName { + if (isKnownEvent(name)) return name + throw new HookError({ event: name, message: "not a known OC Kit lifecycle event" }) +} \ No newline at end of file diff --git a/packages/opencode/test/ockit/artifact/manager.test.ts b/packages/opencode/test/ockit/artifact/manager.test.ts new file mode 100644 index 000000000..1a6f65867 --- /dev/null +++ b/packages/opencode/test/ockit/artifact/manager.test.ts @@ -0,0 +1,182 @@ +import { describe, expect } from "bun:test" +import { Effect, Exit, 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 { TestConfig } from "../../fixture/config" +import { create, list, read, verify, markVerified, markFailed } from "../../../src/ockit/artifact/manager" +import { artifactsRoot } from "../../../src/ockit/artifact/manifest" +import { Hash } from "@opencode-ai/core/util/hash" +import os from "os" +import path from "path" +import fs from "fs/promises" + +const layer = Layer.mergeAll(LayerNode.compile(FSUtil.node), TestConfig.layer()) +const it = testEffect(layer) + +/** 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-artifact-" + 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 artifact manager", () => { + it.effect("creates an artifact record with a sha256 checksum and manifest entry", () => + withRoot((root) => + Effect.gen(function* () { + const contentFile = path.join(root, "out", "report.md") + yield* Effect.promise(() => fs.mkdir(path.dirname(contentFile), { recursive: true })) + yield* Effect.promise(() => fs.writeFile(contentFile, "# report", "utf8")) + + const artifact = yield* create({ + root, + id: "art-1", + type: "report", + workflow_id: "wf-1", + session_id: "sess-1", + path: contentFile, + }) + + expect(artifact.id).toBe("art-1") + expect(artifact.type).toBe("report") + expect(artifact.status).toBe("created") + expect(artifact.checksum).toBe(Hash.sha256("# report")) + + // The record file exists on disk. + const recordPath = `${artifactsRoot(root)}/report/art-1.json` + yield* Effect.promise(() => fs.access(recordPath, fs.constants.F_OK)) + + // The manifest indexes it. + const all = yield* list(root) + expect(all.map((a) => a.id)).toEqual(["art-1"]) + }), + ), + ) + + it.effect("lists only artifacts of a requested type", () => + withRoot((root) => + Effect.gen(function* () { + const contentFile = path.join(root, "out", "a.md") + yield* Effect.promise(() => fs.mkdir(path.dirname(contentFile), { recursive: true })) + yield* Effect.promise(() => fs.writeFile(contentFile, "a", "utf8")) + yield* create({ root, id: "art-1", type: "report", path: contentFile }) + yield* create({ root, id: "art-2", type: "diagram", path: contentFile }) + + const reports = yield* list(root, "report") + expect(reports.map((a) => a.id)).toEqual(["art-1"]) + expect((yield* list(root)).length).toBe(2) + }), + ), + ) + + it.effect("read round-trips the artifact and verify recomputes the checksum", () => + withRoot((root) => + Effect.gen(function* () { + const contentFile = path.join(root, "out", "a.md") + yield* Effect.promise(() => fs.mkdir(path.dirname(contentFile), { recursive: true })) + yield* Effect.promise(() => fs.writeFile(contentFile, "payload", "utf8")) + yield* create({ root, id: "art-1", type: "report", workflow_id: "wf-1", path: contentFile }) + + const readBack = yield* read(root, "art-1") + expect(readBack.id).toBe("art-1") + expect(readBack.workflow_id).toBe("wf-1") + + const verified = yield* verify(root, "art-1") + expect(verified.checksum).toBe(Hash.sha256("payload")) + }), + ), + ) + + it.effect("fails with a typed ArtifactError reading a missing artifact", () => + withRoot((root) => + Effect.gen(function* () { + const exit = yield* read(root, "missing").pipe(Effect.exit) + expect(Exit.isFailure(exit)).toBe(true) + }), + ), + ) + + it.effect("verify fails when the content file was tampered with", () => + withRoot((root) => + Effect.gen(function* () { + const contentFile = path.join(root, "out", "a.md") + yield* Effect.promise(() => fs.mkdir(path.dirname(contentFile), { recursive: true })) + yield* Effect.promise(() => fs.writeFile(contentFile, "original", "utf8")) + yield* create({ root, id: "art-1", type: "report", path: contentFile }) + + yield* Effect.promise(() => fs.writeFile(contentFile, "tampered", "utf8")) + const exit = yield* verify(root, "art-1").pipe(Effect.exit) + expect(Exit.isFailure(exit)).toBe(true) + }), + ), + ) + + it.effect("markVerified and markFailed update the record and manifest", () => + withRoot((root) => + Effect.gen(function* () { + const contentFile = path.join(root, "out", "a.md") + yield* Effect.promise(() => fs.mkdir(path.dirname(contentFile), { recursive: true })) + yield* Effect.promise(() => fs.writeFile(contentFile, "payload", "utf8")) + yield* create({ root, id: "art-1", type: "report", path: contentFile }) + + const verified = yield* markVerified(root, "art-1") + expect(verified.status).toBe("verified") + expect((yield* read(root, "art-1")).status).toBe("verified") + + const failed = yield* markFailed(root, "art-1") + expect(failed.status).toBe("failed") + expect((yield* read(root, "art-1")).status).toBe("failed") + }), + ), + ) + + it.effect("writes a checkpoint marker when oc_kit.checkpoint is enabled (default)", () => + withRoot((root) => + Effect.gen(function* () { + const contentFile = path.join(root, "out", "a.md") + yield* Effect.promise(() => fs.mkdir(path.dirname(contentFile), { recursive: true })) + yield* Effect.promise(() => fs.writeFile(contentFile, "payload", "utf8")) + yield* create({ root, id: "art-1", type: "report", path: contentFile }) + + const checkpointDir = path.join(root, ".oc", "state", "checkpoints") + const entries = yield* Effect.promise(() => fs.readdir(checkpointDir).catch(() => [])) + expect(entries.length).toBeGreaterThan(0) + }), + ), + ) +}) + +describe("ockit artifact manager config-respect", () => { + const disabledLayer = Layer.mergeAll( + LayerNode.compile(FSUtil.node), + TestConfig.layer({ get: () => Effect.succeed({ oc_kit: { checkpoint: false } } as never) }), + ) + const itDisabled = testEffect(disabledLayer) + + itDisabled.effect("does not write a checkpoint marker when oc_kit.checkpoint is disabled", () => + withRoot((root) => + Effect.gen(function* () { + const contentFile = path.join(root, "out", "a.md") + yield* Effect.promise(() => fs.mkdir(path.dirname(contentFile), { recursive: true })) + yield* Effect.promise(() => fs.writeFile(contentFile, "payload", "utf8")) + yield* create({ root, id: "art-1", type: "report", path: contentFile }) + + const checkpointDir = path.join(root, ".oc", "state", "checkpoints") + const exists = yield* Effect.promise(() => + fs + .access(checkpointDir) + .then(() => true) + .catch(() => false), + ) + expect(exists).toBe(false) + }), + ), + ) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/artifact/manifest.test.ts b/packages/opencode/test/ockit/artifact/manifest.test.ts new file mode 100644 index 000000000..04bed5f01 --- /dev/null +++ b/packages/opencode/test/ockit/artifact/manifest.test.ts @@ -0,0 +1,73 @@ +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 { TestConfig } from "../../fixture/config" +import { + artifactsRoot, + emptyManifest, + loadArtifactManifest, + saveArtifactManifest, + ARTIFACT_MANIFEST_FILE, +} from "../../../src/ockit/artifact/manifest" +import type { Artifact } from "../../../src/ockit/types" +import os from "os" +import path from "path" +import fs from "fs/promises" + +const layer = Layer.mergeAll(LayerNode.compile(FSUtil.node), TestConfig.layer()) +const it = testEffect(layer) + +/** 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-manifest-" + 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 })), + ) +} + +const sampleArtifact: Artifact = { + id: "art-1", + type: "report", + workflow_id: "wf-1", + path: "/tmp/report.md", + status: "created", + checksum: "abc123", +} + +describe("ockit artifact manifest", () => { + it.effect("round-trips a manifest through save then load at the artifacts root", () => + withRoot((root) => + Effect.gen(function* () { + yield* saveArtifactManifest(root, { + version: "1", + artifacts: { "art-1": sampleArtifact }, + }) + + const reloaded = yield* loadArtifactManifest(root) + expect(reloaded.version).toBe("1") + expect(reloaded.artifacts["art-1"]).toEqual(sampleArtifact) + + // Verify the file landed under .oc/artifacts/manifest.json. + const filePath = path.join(artifactsRoot(root), ARTIFACT_MANIFEST_FILE) + const raw = yield* Effect.promise(() => fs.readFile(filePath, "utf8")) + expect(JSON.parse(raw).artifacts["art-1"].id).toBe("art-1") + }), + ), + ) + + it.effect("loads an empty manifest when none has been written", () => + withRoot((root) => + Effect.gen(function* () { + const manifest = yield* loadArtifactManifest(root) + expect(manifest).toEqual(emptyManifest()) + }), + ), + ) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/hook/dispatcher.test.ts b/packages/opencode/test/ockit/hook/dispatcher.test.ts new file mode 100644 index 000000000..ffca68999 --- /dev/null +++ b/packages/opencode/test/ockit/hook/dispatcher.test.ts @@ -0,0 +1,66 @@ +import { describe, expect } from "bun:test" +import { Effect, Exit } from "effect" +import { it } from "../../lib/effect" +import { dispatch, dispatchKit } from "../../../src/ockit/hook/dispatcher" +import type { OCEvent } from "../../../src/ockit/hook/events" +import type { Kit, KitHook } from "../../../src/ockit/types" + +// Dispatcher tests spawn real child processes, so they must run on the live +// layer (it.live) — the TestClock's fake time would otherwise leave +// `proc.exited` forever pending. + +const event: OCEvent = { + _tag: "session:start", + session_id: "sess-1", + timestamp: "2026-08-20T00:00:00.000Z", +} + +const kit: Kit = { + id: "engineer", + name: "Engineer Kit", + version: "1.0.0", + hooks: [ + { event: "session:start", command: "echo hello" }, + { event: "session:*", command: "echo wildcard" }, + ], +} + +function failingHook(): KitHook { + // A command that the shell cannot resolve — spawn fails, or it exits non-zero. + return { event: "session:start", command: "ockit-no-such-command-xyzzy" } +} + +describe("ockit hook dispatcher", () => { + it.live("runs the command of every matching hook", () => + Effect.gen(function* () { + const result = yield* dispatch(kit.hooks!, event) + expect(result).toBeUndefined() + }), + ) + + it.live("is a no-op when no hook matches the event", () => + Effect.gen(function* () { + const event: OCEvent = { + _tag: "workflow:end", + workflow_id: "wf-1", + timestamp: "2026-08-20T00:00:00.000Z", + } + const result = yield* dispatch([{ event: "session:start", command: "echo should-not-run" }], event) + expect(result).toBeUndefined() + }), + ) + + it.live("dispatches through a kit's declared hooks", () => + Effect.gen(function* () { + const result = yield* dispatchKit(kit, event) + expect(result).toBeUndefined() + }), + ) + + it.live("fails with a typed HookError when the hook command exits non-zero", () => + Effect.gen(function* () { + const exit = yield* dispatch([failingHook()], event).pipe(Effect.exit) + expect(Exit.isFailure(exit)).toBe(true) + }), + ) +}) \ No newline at end of file diff --git a/packages/opencode/test/ockit/hook/matcher.test.ts b/packages/opencode/test/ockit/hook/matcher.test.ts new file mode 100644 index 000000000..8bdcaa3dc --- /dev/null +++ b/packages/opencode/test/ockit/hook/matcher.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from "bun:test" +import { knownEventOrThrow, matchHooks, matches } from "../../../src/ockit/hook/matcher" +import type { OCEvent } from "../../../src/ockit/hook/events" +import type { KitHook } from "../../../src/ockit/types" + +const sessionStart: OCEvent = { + _tag: "session:start", + session_id: "sess-1", + timestamp: "2026-08-20T00:00:00.000Z", +} + +const workflowEnd: OCEvent = { + _tag: "workflow:end", + workflow_id: "wf-1", + timestamp: "2026-08-20T00:00:00.000Z", +} + +describe("ockit hook matcher", () => { + it("matches an exact event name", () => { + expect(matches("session:start", "session:start")).toBe(true) + expect(matches("workflow:end", "workflow:end")).toBe(true) + }) + + it("treats a trailing wildcard as a prefix match", () => { + expect(matches("session:*", "session:start")).toBe(true) + expect(matches("session:*", "session:end")).toBe(true) + expect(matches("session:*", "workflow:start")).toBe(false) + }) + + it("does not match a different exact event", () => { + expect(matches("session:start", "session:end")).toBe(false) + expect(matches("tool:before", "skill:before")).toBe(false) + }) + + it("selects all hooks matching an event", () => { + const hooks: KitHook[] = [ + { event: "session:*", command: "echo session" }, + { event: "session:end", command: "echo end" }, + { event: "workflow:*", command: "echo workflow" }, + ] + expect(matchHooks(hooks, sessionStart).map((h) => h.command)).toEqual(["echo session"]) + expect(matchHooks(hooks, workflowEnd).map((h) => h.command)).toEqual(["echo workflow"]) + }) + + it("returns an empty list when nothing matches", () => { + expect(matchHooks([{ event: "tool:before", command: "echo tool" }], sessionStart)).toEqual([]) + }) + + it("knownEventOrThrow accepts a known event name", () => { + expect(knownEventOrThrow("session:start")).toBe("session:start") + expect(knownEventOrThrow("artifact:created")).toBe("artifact:created") + }) + + it("knownEventOrThrow rejects an unknown event name with a HookError", () => { + expect(() => knownEventOrThrow("nope:now")).toThrow("not a known OC Kit lifecycle event") + }) +}) \ No newline at end of file