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
19 changes: 17 additions & 2 deletions packages/opencode/src/skill/discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ const layer: Layer.Layer<Service, never, FSUtil.Service | Path.Path | HttpClient
(skill) =>
Effect.gen(function* () {
const root = path.join(cache, skill.name)
let availableRoot = root
const versionFile = path.join(root, ".opencode-version")
const version = skill.version
const current =
Expand Down Expand Up @@ -110,7 +111,21 @@ const layer: Layer.Layer<Service, never, FSUtil.Service | Path.Path | HttpClient
yield* fs.rename(staging, root).pipe(
Effect.catch((error) =>
Effect.gen(function* () {
if (cached) yield* fs.rename(backup, root).pipe(Effect.ignore)
if (cached) {
yield* fs.rename(backup, root).pipe(
Effect.catch((rollbackError) =>
Effect.gen(function* () {
// Keep the only previous copy usable when restoration
// fails. Never remove it or silently hide that failure.
availableRoot = backup
yield* Effect.logError("failed to restore skill backup", {
skill: skill.name,
restorationFailed: true,
})
}),
),
)
}
return yield* Effect.fail(error)
}),
),
Expand All @@ -123,7 +138,7 @@ const layer: Layer.Layer<Service, never, FSUtil.Service | Path.Path | HttpClient
Effect.ensuring(fs.remove(staging, { recursive: true, force: true }).pipe(Effect.ignore)),
)
}
return (yield* fs.exists(path.join(root, "SKILL.md")).pipe(Effect.orDie)) ? root : null
return (yield* fs.exists(path.join(availableRoot, "SKILL.md")).pipe(Effect.orDie)) ? availableRoot : null
}),
{ concurrency: skillConcurrency },
)
Expand Down
54 changes: 52 additions & 2 deletions packages/opencode/test/skill/discovery.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { describe, expect, beforeAll, afterAll } from "bun:test"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { FSUtil } from "@opencode-ai/core/fs-util"
import { Effect } from "effect"
import { Effect, Layer } from "effect"
import { PlatformError, SystemError } from "effect/PlatformError"
import { Discovery } from "../../src/skill/discovery"
import { Global } from "@opencode-ai/core/global"
import { Filesystem } from "@/util/filesystem"
Expand All @@ -19,7 +20,29 @@ let mutableFiles = ["SKILL.md"]

const fixturePath = path.join(import.meta.dir, "../fixture/skills")
const cacheDir = path.join(Global.Path.cache, "skills")
const it = testEffect(LayerNode.compile(LayerNode.group([Discovery.node, FSUtil.node])))
let failPromotion = false
let failRollback = false
let removeBackupSkill = false
const promotionFailures: string[] = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: promotionFailures array is populated in the mock but never read or asserted. Remove it or add assertions that use it.

const wrappedFs = Layer.effect(FSUtil.Service, Effect.gen(function* () {
const fs = yield* FSUtil.Service
return { ...fs, rename: (source: string, dest: string) => {
if (failPromotion && source.includes(".tmp-") && dest.endsWith("mutable")) {
failPromotion = false
promotionFailures.push("injected-promotion-failure")
return Effect.fail(new PlatformError(new SystemError({_tag:"Busy",module:"FileSystem",method:"rename",cause:{code:"EBUSY"}})))
}
if (failRollback && source.includes(".old-") && dest.endsWith("mutable")) {
failRollback=false
promotionFailures.push("injected-rollback-failure")
return (removeBackupSkill ? fs.remove(path.join(source,"SKILL.md")) : Effect.void).pipe(
Effect.andThen(Effect.fail(new PlatformError(new SystemError({_tag:"PermissionDenied",module:"FileSystem",method:"rename",cause:{code:"EPERM"}})))),
)
}
return fs.rename(source, dest)
} }
})).pipe(Layer.provide(LayerNode.compile(FSUtil.node)))
const it = testEffect(LayerNode.compile(LayerNode.group([Discovery.node, FSUtil.node]), [[FSUtil.node, wrappedFs]]))

beforeAll(async () => {
await rm(cacheDir, { recursive: true, force: true })
Expand Down Expand Up @@ -183,4 +206,31 @@ describe("Discovery.pull", () => {
expect(mutableDownloadCount).toBe(3)
}),
)
for (const scenario of ["single", "double", "empty-cache", "invalid-backup"] as const) {
it.live(`preserves usable roots after ${scenario} promotion failure`,()=>Effect.gen(function*(){
yield* Effect.promise(()=>rm(cacheDir,{recursive:true,force:true}))
mutableVersion="rollback-1";mutableContent="# Old";mutableFiles=["SKILL.md","old.md"]
promotionFailures.length=0
const discovery=yield* Discovery.Service
const url=`http://localhost:${server.port}/mutable/`
const first=scenario==="empty-cache"?[]:yield* discovery.pull(url)
mutableVersion="rollback-2";mutableContent="# New";mutableFiles=["SKILL.md"]
failPromotion=true;failRollback=scenario==="double"||scenario==="invalid-backup"
removeBackupSkill=scenario==="invalid-backup"
try {
const result=yield* discovery.pull(url)
if(scenario==="double"||scenario==="single"){
expect(result).toHaveLength(1)
expect(result[0].includes(".old-")).toBe(scenario==="double")
expect(yield* Effect.promise(()=>Bun.file(path.join(result[0],"SKILL.md")).text())).toBe("# Old")
expect(yield* Effect.promise(()=>Bun.file(path.join(result[0],"old.md")).text())).toBe("old reference")
if(scenario==="single")expect(result[0]).toBe(first[0])
const recovered=yield* discovery.pull(url)
expect(yield* Effect.promise(()=>Bun.file(path.join(recovered[0],"SKILL.md")).text())).toBe("# New")
if(scenario==="double")expect(yield* Effect.promise(()=>Bun.file(path.join(result[0],"old.md")).text())).toBe("old reference")
}else expect(result).toEqual([])
}finally{failPromotion=false;failRollback=false;removeBackupSkill=false}
}))
}

})
23 changes: 23 additions & 0 deletions packages/opencode/test/skill/skill.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,30 @@ const withHome = <A, E, R>(home: string, self: Effect.Effect<A, E, R>) =>
}),
)

const itWithBackupRoot=testEffect(Layer.mergeAll(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: itWithBackupRoot closure references retainedBackupRoot declared at line 71. Works due to closure capture, but moving the declaration above improves clarity and avoids fragile ordering.

LayerNode.compile(Skill.node,[[Discovery.node,Layer.succeed(Discovery.Service,{
pull:()=>Effect.sync(()=>[retainedBackupRoot]),
})]]),node,testInstanceStoreLayer,
))
let retainedBackupRoot=""

describe("skill", () => {
itWithBackupRoot.live("loads a retained remote backup root and its relative references",()=>provideTmpdirInstance(
dir=>Effect.gen(function*(){
retainedBackupRoot=path.join(dir,"remote-cache","mutable.old-controlled")
yield* Effect.promise(()=>Bun.write(path.join(retainedBackupRoot,"SKILL.md"),"---\nname: retained-remote\ndescription: old cached skill\n---\n\nRead [old reference](old.md).\n"))
yield* Effect.promise(()=>Bun.write(path.join(retainedBackupRoot,"old.md"),"old reference"))
yield* Effect.promise(()=>Bun.write(path.join(dir,"opencode.json"),JSON.stringify({skills:{urls:["https://synthetic.invalid/skills"]}})))
const skill=yield* Skill.Service
const item=yield* skill.get("retained-remote")
expect(item?.location).toBe(path.join(retainedBackupRoot,"SKILL.md"))
expect(item?.content).toContain("old.md")
expect(yield* Effect.promise(()=>Bun.file(path.join(path.dirname(item!.location),"old.md")).text())).toBe("old reference")
expect((yield* skill.all()).filter(item=>item.name==="retained-remote")).toHaveLength(1)
expect(yield* skill.dirs()).toContain(retainedBackupRoot)
}),{git:true},
))

it.effect("formats verbose locations as XML-safe filesystem paths", () =>
Effect.sync(() => {
const output = Skill.fmt(
Expand Down
Loading