Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/opencode/src/ockit/artifact/index.ts
Original file line number Diff line number Diff line change
@@ -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"
150 changes: 150 additions & 0 deletions packages/opencode/src/ockit/artifact/manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// OC Kit artifact manager. Artifacts persist as typed records under
// `.oc/artifacts/<type>/<id>.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<ArtifactError>()("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
})
64 changes: 64 additions & 0 deletions packages/opencode/src/ockit/artifact/manifest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// OC Kit artifact manifest. The artifact manager persists every artifact record
// under `.oc/artifacts/<type>/<id>.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<typeof ArtifactManifest>

export class ArtifactManifestError extends Schema.TaggedErrorClass<ArtifactManifestError>()(
"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))
})
66 changes: 66 additions & 0 deletions packages/opencode/src/ockit/hook/dispatcher.ts
Original file line number Diff line number Diff line change
@@ -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)
})
Loading
Loading