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
64 changes: 42 additions & 22 deletions examples/opencode-plugin/lib/v2-plugin.mjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { readFile, readdir } from "node:fs/promises"
import { join } from "node:path"
import { isRecallEnabled } from "./shared/recall-core.mjs"
import { createOpenVikingV2McpConfig, openVikingSkillsDir } from "./mcp-config.mjs"
import { contextMessageEvents, normalizeV2LifecycleEvent } from "./v2-events.mjs"
Expand Down Expand Up @@ -39,15 +41,19 @@ export async function startV2Plugin(ctx, runtime, { pluginRoot }) {
if (config.mcp.enabled && ctx?.mcp?.transform) {
let registered = false
await ctx.mcp.transform((editor) => {
const current = editor.get?.("openviking")
if (current?.disabled === true) return
editor.set("openviking", createOpenVikingV2McpConfig(pluginRoot))
registered = true
registered = editor.get?.("openviking")?.disabled !== true
if (registered) editor.set("openviking", createOpenVikingV2McpConfig(pluginRoot))
})
log("INFO", "mcp", "Registered OpenViking MCP server for OpenCode v2")
if (registered && ctx?.skill?.transform) {
await ctx.skill.transform((draft) => {
draft.source({ type: "directory", path: openVikingSkillsDir(pluginRoot) })
if (ctx?.skill?.transform) {
const skills = await loadBundledSkills(openVikingSkillsDir(pluginRoot))
// Transforms run again after setup, so read the MCP decision on each run.
await ctx.skill.transform((editor) => {
if (!registered) return
// A user skill overrides a bundled one by ID or by name; the host keys
// skills by ID only, so a same-name skill would otherwise be listed twice.
const taken = new Set(editor.list().flatMap((skill) => [skill.id, skill.name]))
for (const skill of skills) if (!taken.has(skill.id) && !taken.has(skill.name)) editor.add(skill)
})
}
} else if (!config.mcp.enabled) {
Expand Down Expand Up @@ -160,6 +166,29 @@ export async function startV2Plugin(ctx, runtime, { pluginRoot }) {
}
}

async function loadBundledSkills(root) {
const entries = await readdir(root, { withFileTypes: true }).catch((error) => {
logHookError("skill.load", error)
return []
})
const skills = []
for (const entry of entries.filter((item) => item.isDirectory())) {
const path = join(root, entry.name, "SKILL.md")
try {
const text = await readFile(path, "utf8")
const frontmatter = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/)
// Bundled descriptions are a plain scalar or a folded (`>`) block.
const [, head = "", folded = ""] = frontmatter?.[1].match(/^description:(.*)((?:\r?\n[ \t]+.*)*)/m) ?? []
const description = (/^\s*>-?\s*$/.test(head) ? folded : head).trim().replace(/\s+/g, " ")
if (!description) throw new Error(`no description in ${path}`)
skills.push({ id: entry.name, name: entry.name, description, path, content: text.slice(frontmatter[0].length) })
} catch (error) {
logHookError("skill.load", error)
}
}
return skills
}

async function consumeEvents(ctx, signal, handle) {
try {
for await (const event of ctx.event.subscribe({ signal })) {
Expand Down Expand Up @@ -187,21 +216,12 @@ export async function prepareV2Prompt(event, {
const text = event?.prompt?.text
const parts = typeof text === "string" && text.trim() ? [{ type: "text", text }] : []
const input = { sessionID, messageID, directory }
const blocks = []
try {
const sessionBlock = await sessionInject.buildSessionContext(input)
if (sessionBlock) blocks.push(sessionBlock)
} catch (error) {
logHookError("session.prompt.profile", error)
}
if (recallEnabled) {
try {
const recallBlock = await recall.buildRelevantMemories(input, parts)
if (recallBlock) blocks.push(recallBlock)
} catch (error) {
logHookError("session.prompt.recall", error)
}
}
const blocks = (await Promise.all([
sessionInject.buildSessionContext(input).catch((error) => logHookError("session.prompt.profile", error)),
recallEnabled
? recall.buildRelevantMemories(input, parts).catch((error) => logHookError("session.prompt.recall", error))
: undefined,
])).filter(Boolean)
if (blocks.length === 0) return

event.metadata = event.metadata && typeof event.metadata === "object" ? event.metadata : {}
Expand Down
2 changes: 1 addition & 1 deletion examples/opencode-plugin/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@openviking/opencode-plugin",
"version": "0.5.25",
"version": "0.5.26",
"author": "@openviking",
"description": "Unified OpenCode plugin for OpenViking repository retrieval and long-term memory",
"type": "module",
Expand Down
84 changes: 80 additions & 4 deletions examples/opencode-plugin/tests/v2-plugin.test.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import test from "node:test"
import assert from "node:assert/strict"
import { resolve } from "node:path"
import { fileURLToPath } from "node:url"
import { captureV2Context, injectV2Context, prepareV2Prompt, startV2Plugin } from "../lib/v2-plugin.mjs"
import { createVikingUriNotice } from "../lib/viking-uri-guard.mjs"

const pluginRoot = fileURLToPath(new URL("..", import.meta.url))
const BUNDLED_SKILLS = ["openviking-memory", "openviking-rule-search", "openviking-skills", "ov-experience-memory"]

function runtimeFixture(overrides = {}) {
const events = []
return {
Expand Down Expand Up @@ -39,7 +42,11 @@ function contextFixture(messages = []) {
skillSources,
ctx: {
skill: {
transform: async (callback) => callback({ source: (source) => skillSources.push(source), list: () => skillSources }),
transform: async (callback) => callback({
list: () => skillSources,
get: (id) => skillSources.find((skill) => skill.id === id),
add: (skill) => skillSources.push(skill),
}),
},
location: { directory: "/tmp/project" },
mcp: {
Expand All @@ -61,16 +68,65 @@ function contextFixture(messages = []) {
test("startV2Plugin registers direct MCP tools and all v2 hooks", async () => {
const { runtime } = runtimeFixture()
const { ctx, hooks, registered, skillSources } = contextFixture()
const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot: "/tmp/ov" })
const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot })

assert.deepEqual(skillSources, [{ type: "directory", path: resolve("/tmp/ov", "skills") }])
assert.deepEqual(skillSources.map((skill) => skill.id).sort(), BUNDLED_SKILLS)
for (const skill of skillSources) {
assert.ok(skill.description.length > 20 && !skill.description.includes("\n"))
assert.match(skill.content, /^\s*# /)
}
assert.equal(registered[0][0], "openviking")
assert.equal(registered[0][1].type, "local")
assert.equal(registered[0][1].codemode, false)
assert.deepEqual(Object.keys(hooks).sort(), ["compaction", "context", "execute.after", "execute.before", "prompt"])
await cleanup()
})

for (const disabled of [false, true]) {
test(`bundled skills follow MCP registration when transforms run after setup, disabled=${disabled}`, async () => {
const { runtime } = runtimeFixture()
const { ctx } = contextFixture()
const transforms = []
ctx.mcp.transform = async (callback) => { transforms.push(callback) }
ctx.skill.transform = async (callback) => { transforms.push(callback) }
const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot })
const [mcp, skill] = transforms
const skills = new Map()
mcp({ get: () => (disabled ? { disabled: true } : undefined), set: () => {} })
skill({ list: () => [...skills.values()], get: (id) => skills.get(id), add: (value) => skills.set(value.id, value) })
assert.deepEqual([...skills.keys()].sort(), disabled ? [] : BUNDLED_SKILLS)
await cleanup()
})
}

test("existing skills override bundled skills by ID or name", async () => {
const { runtime } = runtimeFixture()
const { ctx, skillSources } = contextFixture()
skillSources.push(
{ id: "project-memory", name: "openviking-memory", path: "/tmp/project/.opencode/skills/project-memory/SKILL.md", content: "" },
{ id: "openviking-skills", name: "Custom skills", path: "/tmp/project/.opencode/skills/openviking-skills/SKILL.md", content: "" },
)
const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot })
assert.deepEqual(skillSources.map((skill) => skill.id).sort(), [
"openviking-rule-search",
"openviking-skills",
"ov-experience-memory",
"project-memory",
])
assert.equal(skillSources.find((skill) => skill.id === "openviking-skills").name, "Custom skills")
await cleanup()
})

test("a missing skills directory leaves MCP and hooks registered", async () => {
const { runtime } = runtimeFixture()
const { ctx, hooks, registered, skillSources } = contextFixture()
const cleanup = await startV2Plugin(ctx, runtime, { pluginRoot: "/nonexistent" })
assert.deepEqual(skillSources, [])
assert.equal(registered[0][0], "openviking")
assert.equal(typeof hooks.prompt, "function")
await cleanup()
})

test("compaction captures messages before the host drops them and contains read failures", async () => {
const { runtime, events } = runtimeFixture()
const messages = [
Expand Down Expand Up @@ -126,6 +182,26 @@ test("cleanup waits for background initialization before flushing", async () =>
assert.equal(flushed, true)
})

test("prompt starts session context and recall together and keeps block order", async () => {
const started = []
const pending = {}
const call = (name) => new Promise((resolve) => {
started.push(name)
pending[name] = resolve
})
const event = { sessionID: "ses_1", messageID: "msg_1", prompt: { text: "query" } }
const preparing = prepareV2Prompt(event, {
recallEnabled: true,
sessionInject: { buildSessionContext: () => call("profile") },
recall: { buildRelevantMemories: () => call("recall") },
})
assert.deepEqual(started, ["profile", "recall"])
pending.recall("<recall/>")
pending.profile("<profile/>")
await preparing
assert.deepEqual(event.metadata.openviking.context, ["<profile/>", "<recall/>"])
})

test("prompt metadata is persisted and context injection is stable across model steps", async () => {
let recallCalls = 0
const event = {
Expand Down
Loading