@srobroek/harness-kit 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -42,6 +42,7 @@ bun must be on `PATH`, because the `harness-kit` bin has a bun shebang. `npm ci`
42
42
  | `harnesses` | all three | Harnesses the repo targets. A plugin may list only these. Claude and OMP each get a marketplace file; OpenCode has none. |
43
43
  | `commonDirs` | `skills`, `rules` | Directories under `plugins/<name>/common/` copied into each harness tree. Add `templates`, `scripts` or `formulas` as needed. |
44
44
  | `kinds` | the eight kinds without `templates` and `styles` | Rows of the inventory tables and keys of `inventory.json`. Any of `skills agents commands rules templates styles hooks tools extensions mcp`. |
45
+ | `sharedDir` | `shared` | Repo-level directory of items that several plugins take; see "Shared items". |
45
46
  | `pluginKey` | `agent-plugins` | Key in each plugin's `package.json` that holds its settings. |
46
47
  | `ompScope` | `@agent-plugins` | npm scope of the generated OMP package name. |
47
48
  | `generatedBy` | `harness-kit build` | Names the generator in the note at the top of generated Markdown. |
@@ -60,6 +61,23 @@ Each plugin's `package.json` carries `name` (equal to the directory), `version`,
60
61
  - An OMP rule with no front matter gets `alwaysApply: true`. A rule with its own front matter, such as `description:`, is copied unchanged.
61
62
  - `__pycache__` directories are ignored.
62
63
 
64
+ ### Shared items
65
+
66
+ When two plugins ship the same agent, skill or rule, keep one copy in the repo's `shared/` directory (`sharedDir` in the config). Its layout follows `commonDirs`: `shared/agents/x.md`, `shared/skills/y/`, `shared/rules/z.md`. A plugin takes items by listing them in its `agent-plugins` key:
67
+
68
+ ```json
69
+ "shared": ["agents/adversarial-challenger", "rules/z"]
70
+ ```
71
+
72
+ `harness-kit build` copies each listed item into every harness tree of the plugin, as if it sat in the plugin's own `common/`: the same `x.<harness>.md` variants, the same OMP `alwaysApply` rule. Each plugin stays complete on its own. Copied Markdown carries a `<!-- Generated by … from shared/… -->` header, placed after the front matter so the front matter still parses; other files copy unchanged. `build --check` fails when the shared file changes and a copy does not, and dropping an item removes its copies.
73
+
74
+ An item names a file without its extension (`agents/x`) or a directory (`skills/y`). Only listed items are copied. These are errors: an item that does not exist, an item whose first segment is not in `commonDirs` (an `agents` item needs `agents` there), and a plugin that also has its own file at the same path in `common/`.
75
+
76
+ #### Two installed plugins with the same agent
77
+
78
+ - **OpenCode:** registering the same agent name twice normally lets the last plugin loaded win. The vendored `agents` module avoids that: `registerAgents(ctx.agent, loadAgentFiles(root))` skips an agent another plugin already registered and logs one debug line (`console.debug`, or the `debug` option). The first plugin loaded wins, so a version skew between the two copies is the same on every start.
79
+ - **Claude Code:** it prefixes each plugin's agents with the plugin name (`plugin-a:challenger`, `plugin-b:challenger`). Both stay available, and harness-kit cannot change that. A version skew shows up as two agents with different text.
80
+
63
81
  ### Vendored runtime modules
64
82
 
65
83
  Several plugins carry the same runtime code. harness-kit ships it as small modules without dependencies and copies them into a plugin's harness trees. A plugin opts in with `runtime` in its `agent-plugins` key: `true` for every module of its harnesses, or a list.
@@ -68,13 +86,14 @@ Several plugins carry the same runtime code. harness-kit ships it as small modul
68
86
  | --- | --- | --- |
69
87
  | `frontmatter` | opencode | `isRecord`, `parseFrontmatter` |
70
88
  | `content` | opencode | `loadSkills`, `loadRules`, `loadPrompt`, `resolveOptions`, `renderTemplate`, `setupContent`: registers `skills/`, `rules/` and `templates/` with the host. Needs `frontmatter`. |
89
+ | `agents` | opencode | `loadAgentFiles`, `registerAgents`: registers `agents/*.md`, skipping an agent another plugin already registered. Needs `frontmatter`. |
71
90
  | `session` | opencode | `createRootResolver`, `rootOf`: resolve a session to its root session |
72
91
  | `render` | claude | `render.mjs`, a SessionStart hook: `node "${CLAUDE_PLUGIN_ROOT}/_kit/render.mjs" <template>` prints `templates/<template>.md` with the options filled in |
73
92
  | `template-extension` | omp | `templateExtension(name)`: an extension that appends the rendered `templates/<name>.md` to the system prompt, with options from `<name>.json` in the OMP agent directory |
74
93
 
75
94
  `harness-kit build` writes the modules to `<harness>/_kit/` as generated files with a `// Generated by …` header. `build --check` catches edits and leftovers, and dropping `runtime` removes the directory. The installed plugin imports only its own copy: nothing loads harness-kit at runtime, and no harness imports another harness's module. A plugin without `runtime` produces the same output as before. Do not list `_kit` in `commonDirs`.
76
95
 
77
- Test helpers are not vendored. `@srobroek/harness-kit/testing` exports `createFakeContext({ options?, existingSkills? })`, a fake OpenCode host context that records the system parts, skills and disposals a plugin registers.
96
+ Test helpers are not vendored. `@srobroek/harness-kit/testing` exports `createFakeContext({ options?, existingSkills?, existingAgents? })`, a fake OpenCode host context that records the system parts, skills, agents and disposals a plugin registers.
78
97
 
79
98
  ## Commands
80
99
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@srobroek/harness-kit",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Shared build tooling for multi-harness agent plugin repos: generator, version stamping, Claude validation, presets and CI workflows.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -0,0 +1,75 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { parseFrontmatter } from "./frontmatter.ts";
4
+
5
+ /**
6
+ * Agent registration for an OpenCode plugin that ships `agents/<id>.md`.
7
+ *
8
+ * Two installed plugins can ship the same agent (a repo-level `shared/` item copied into both). OpenCode would
9
+ * register the id twice and the last plugin loaded would win, so a version skew between the copies would depend on
10
+ * load order in the other direction. `registerAgents` skips an id that is already registered and logs one debug
11
+ * line, so the first plugin loaded wins every time.
12
+ */
13
+
14
+ export interface AgentFile {
15
+ /** The file name without `.md`. */
16
+ id: string;
17
+ path: string;
18
+ /** A `key: value` line of the front matter. */
19
+ field(key: string): string | undefined;
20
+ /** The prompt: the text after the front matter, trimmed. */
21
+ system: string;
22
+ }
23
+
24
+ /** The agent files under `root/agents/*.md`, in name order. */
25
+ export function loadAgentFiles(root: string): AgentFile[] {
26
+ const dir = join(root, "agents");
27
+ if (!existsSync(dir)) return [];
28
+ return readdirSync(dir)
29
+ .filter((file) => file.endsWith(".md"))
30
+ .sort()
31
+ .map((file) => {
32
+ const path = join(dir, file);
33
+ const frontmatter = parseFrontmatter(readFileSync(path, "utf8"));
34
+ const text = frontmatter ? frontmatter.body : readFileSync(path, "utf8");
35
+ return { id: basename(file, ".md"), path, field: (key: string) => frontmatter?.field(key), system: text.trim() };
36
+ });
37
+ }
38
+
39
+ /** The slice of `ctx.agent` this module uses. */
40
+ interface AgentHost {
41
+ transform(change: (editor: { get(id: string): unknown; update(id: string, change: (draft: any) => void): void }) => void): Promise<{ dispose: () => Promise<void> }>;
42
+ }
43
+
44
+ export interface RegisterOptions {
45
+ /** Fill a new agent's draft from its file. Defaults to `description`, `mode` and `system`. */
46
+ apply?: (draft: any, file: AgentFile) => void;
47
+ /** Receives the line logged for a skipped agent. Defaults to `console.debug`. */
48
+ debug?: (line: string) => void;
49
+ }
50
+
51
+ /** Registers the agents the host does not know yet. Returns the registration to dispose, and the ids it skipped. */
52
+ export async function registerAgents(agent: AgentHost, files: AgentFile[], options: RegisterOptions = {}) {
53
+ const apply =
54
+ options.apply ??
55
+ ((draft: any, file: AgentFile) => {
56
+ const description = file.field("description");
57
+ const mode = file.field("mode");
58
+ if (description !== undefined) draft.description = description;
59
+ if (mode !== undefined) draft.mode = mode;
60
+ draft.system = file.system;
61
+ });
62
+ const debug = options.debug ?? ((line: string) => console.debug(line));
63
+ const skipped: string[] = [];
64
+ const registration = await agent.transform((editor) => {
65
+ for (const file of files) {
66
+ if (editor.get(file.id) !== undefined) {
67
+ skipped.push(file.id);
68
+ debug(`agent "${file.id}" is already registered by another plugin; skipping the copy in ${file.path}`);
69
+ continue;
70
+ }
71
+ editor.update(file.id, (draft) => apply(draft, file));
72
+ }
73
+ });
74
+ return { dispose: registration.dispose, skipped };
75
+ }
package/src/config.ts CHANGED
@@ -20,6 +20,8 @@ export type Config = {
20
20
  /** Directories under plugins/<name>/common/ that are copied into each harness tree. */
21
21
  commonDirs: string[]
22
22
  kinds: Kind[]
23
+ /** Repo-level directory whose items plugins list in `shared`; its layout follows `commonDirs` (shared/agents/x.md). */
24
+ sharedDir: string
23
25
  /** Key in plugins/<name>/package.json that holds the plugin's own settings. */
24
26
  pluginKey: string
25
27
  /** npm scope of the generated OMP package name. */
@@ -37,7 +39,7 @@ export type Config = {
37
39
  omp: { packageType?: "module" | "commonjs" }
38
40
  }
39
41
 
40
- const TOP_KEYS = ["marketplace", "harnesses", "commonDirs", "kinds", "pluginKey", "ompScope", "generatedBy", "claude", "omp"]
42
+ const TOP_KEYS = ["marketplace", "harnesses", "commonDirs", "kinds", "sharedDir", "pluginKey", "ompScope", "generatedBy", "claude", "omp"]
41
43
  const DIR_NAME = /^[a-z0-9][a-z0-9._-]*$/
42
44
  const PACKAGE_SCOPE = /^@[a-z0-9][a-z0-9._-]*$/
43
45
 
@@ -86,6 +88,10 @@ export function resolveConfig(raw: unknown, where = CONFIG_FILE): Config {
86
88
 
87
89
  const kinds = raw.kinds === undefined ? DEFAULT_KINDS : pickList(where, "kinds", "kind", raw.kinds, KNOWN_KINDS)
88
90
 
91
+ const sharedDir = raw.sharedDir === undefined ? "shared" : nonEmptyString(where, "sharedDir", raw.sharedDir)
92
+ if (!DIR_NAME.test(sharedDir)) fail(where, `"sharedDir" must be a plain directory name, got "${sharedDir}"`)
93
+ if (["plugins", "_kit", "node_modules"].includes(sharedDir) || commonDirs.includes(sharedDir)) fail(where, `"sharedDir" cannot be "${sharedDir}"`)
94
+
89
95
  const pluginKey = raw.pluginKey === undefined ? "agent-plugins" : nonEmptyString(where, "pluginKey", raw.pluginKey)
90
96
  const ompScope = raw.ompScope === undefined ? "@agent-plugins" : nonEmptyString(where, "ompScope", raw.ompScope)
91
97
  if (!PACKAGE_SCOPE.test(ompScope)) fail(where, `"ompScope" must look like "@scope", got "${ompScope}"`)
@@ -121,6 +127,7 @@ export function resolveConfig(raw: unknown, where = CONFIG_FILE): Config {
121
127
  harnesses,
122
128
  commonDirs,
123
129
  kinds,
130
+ sharedDir,
124
131
  pluginKey,
125
132
  ompScope,
126
133
  generatedBy,
package/src/generate.ts CHANGED
@@ -32,6 +32,8 @@ export type Plugin = {
32
32
  license?: string
33
33
  /** The Claude `userConfig` schema, copied into plugin.json as is. Exclusive with `options`. */
34
34
  userConfig?: Record<string, unknown>
35
+ /** Items of the repo's shared directory this plugin takes, like `agents/x` or `skills/y`. Copied into every harness tree. */
36
+ shared?: string[]
35
37
  /** Runtime modules vendored into the harness trees as `_kit/`, with their dependencies. Absent when the plugin opts out. */
36
38
  runtime?: RuntimeModuleName[]
37
39
  }
@@ -41,6 +43,7 @@ export type Drift = { changed: string[]; extra: string[] }
41
43
 
42
44
  const NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/
43
45
  const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/
46
+ const SHARED_ITEM = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+$/
44
47
  const OPTION_NAME = /^[a-z][a-z0-9_]*$/
45
48
  const OPENCODE_SDK_RANGE = ">=2.1.4 <3"
46
49
  const MODULE_EXTENSION = /\.(?:[cm]?[jt]s)$/
@@ -129,6 +132,7 @@ export function readPlugin(root: string, name: string, config: Config): Plugin {
129
132
  if (options && userConfig) fail(where, `set either "${key}.options" or "${key}.userConfig", not both: options generate the userConfig`)
130
133
  const selectedHarnesses = KNOWN_HARNESSES.filter((h) => harnesses.includes(h))
131
134
  const runtime = readRuntime(where, key, own.runtime, selectedHarnesses)
135
+ const shared = readShared(where, key, own.shared, config)
132
136
  // Keep canonical harness order so output does not depend on how the author ordered the list.
133
137
  return {
134
138
  name,
@@ -143,10 +147,25 @@ export function readPlugin(root: string, name: string, config: Config): Plugin {
143
147
  author,
144
148
  license,
145
149
  userConfig,
150
+ shared,
146
151
  runtime,
147
152
  }
148
153
  }
149
154
 
155
+ function readShared(where: string, key: string, raw: unknown, config: Config): string[] | undefined {
156
+ if (raw === undefined) return undefined
157
+ if (!Array.isArray(raw) || raw.length === 0) fail(where, `"${key}.shared" must be a non-empty list of items like "agents/name"`)
158
+ for (const item of raw) {
159
+ if (typeof item !== "string" || !SHARED_ITEM.test(item) || item.split("/").includes("..")) {
160
+ fail(where, `"${key}.shared" item ${JSON.stringify(item)} must be a relative path like "agents/name"`)
161
+ }
162
+ const dir = item.split("/")[0]!
163
+ if (!config.commonDirs.includes(dir)) fail(where, `shared item "${item}" is in "${dir}", which is not in commonDirs (${config.commonDirs.join(", ")})`)
164
+ }
165
+ if (new Set(raw).size !== raw.length) fail(where, `"${key}.shared" lists an item twice`)
166
+ return raw as string[]
167
+ }
168
+
150
169
  function readRuntime(where: string, key: string, raw: unknown, harnesses: Harness[]): RuntimeModuleName[] | undefined {
151
170
  if (raw === undefined || raw === false) return undefined
152
171
  const valid = raw === true || (Array.isArray(raw) && raw.length > 0 && raw.every((item) => typeof item === "string"))
@@ -203,7 +222,10 @@ function checkOpencodeEntries(root: string, plugin: Plugin): void {
203
222
 
204
223
  export function readPlugins(root: string, config: Config): Plugin[] {
205
224
  const plugins = listDirs(path.join(root, "plugins")).map((name) => readPlugin(root, name, config))
206
- for (const plugin of plugins) checkOpencodeEntries(root, plugin)
225
+ for (const plugin of plugins) {
226
+ checkOpencodeEntries(root, plugin)
227
+ resolveShared(root, plugin, config)
228
+ }
207
229
  return plugins
208
230
  }
209
231
 
@@ -236,16 +258,67 @@ function commonFilesFor(files: string[], harness: Harness): Array<[string, strin
236
258
  return picked
237
259
  }
238
260
 
261
+ /** The plain (variant-free) name of a file: `x.claude.md` and `x.md` both give `x.md`. */
262
+ function plainName(file: string): string {
263
+ const match = VARIANT.exec(path.basename(file))
264
+ return match ? path.join(path.dirname(file), `${match[1]}${match[3]}`) : file
265
+ }
266
+
267
+ /** Whether a file of the shared directory belongs to the item `rest` (the part after the kind directory). */
268
+ function belongsToItem(file: string, rest: string): boolean {
269
+ if (file === rest || file.startsWith(`${rest}/`)) return true
270
+ if (stripExtension(file) === rest) return true
271
+ return stripExtension(plainName(file)) === rest
272
+ }
273
+
274
+ /** Shared files a plugin takes, by kind directory: paths relative to <sharedDir>/<dir>. Throws on a missing item or a clash. */
275
+ function resolveShared(root: string, plugin: Plugin, config: Config): Map<string, string[]> {
276
+ const taken = new Map<string, string[]>()
277
+ const common = path.join(pluginDir(root, plugin), "common")
278
+ for (const item of plugin.shared ?? []) {
279
+ const [dir, ...parts] = item.split("/") as [string, ...string[]]
280
+ const rest = parts.join("/")
281
+ const base = path.join(root, config.sharedDir, dir)
282
+ const files = listFiles(base).filter((file) => belongsToItem(file, rest))
283
+ if (files.length === 0) fail(`plugins/${plugin.name}/package.json`, `shared item "${item}" not found in ${config.sharedDir}/${dir}/`)
284
+ const own = new Set(listFiles(path.join(common, dir)).map(plainName))
285
+ for (const file of files) {
286
+ if (own.has(plainName(file))) {
287
+ fail(`plugins/${plugin.name}`, `shared item "${item}" clashes with its own common/${dir}/${plainName(file)}; remove one of them`)
288
+ }
289
+ }
290
+ taken.set(dir, [...(taken.get(dir) ?? []), ...files])
291
+ }
292
+ return taken
293
+ }
294
+
295
+ /** Header for a copy of a shared Markdown file, placed after any front matter so the front matter still parses. */
296
+ function withSharedHeader(text: string, note: string): string {
297
+ const front = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/.exec(text)
298
+ if (!front) return `${note}\n\n${text}`
299
+ const head = front[0].endsWith("\n") ? front[0] : `${front[0]}\n`
300
+ return `${head}${note}\n${text.slice(front[0].length)}`
301
+ }
302
+
239
303
  function ownedCopies(root: string, plugin: Plugin, config: Config): Output[] {
240
304
  const common = path.join(pluginDir(root, plugin), "common")
305
+ const shared = resolveShared(root, plugin, config)
241
306
  const outputs: Output[] = []
242
307
  for (const harness of plugin.harnesses) {
243
308
  for (const dir of config.commonDirs) {
244
- for (const [source, dest] of commonFilesFor(listFiles(path.join(common, dir)), harness)) {
245
- let contents: string | Buffer = readFileSync(path.join(common, dir, source))
309
+ const own = listFiles(path.join(common, dir))
310
+ const taken = shared.get(dir) ?? []
311
+ for (const [source, dest] of commonFilesFor([...own, ...taken].sort(), harness)) {
312
+ const isShared = taken.includes(source)
313
+ const origin = isShared ? path.join(root, config.sharedDir, dir, source) : path.join(common, dir, source)
314
+ let contents: string | Buffer = readFileSync(origin)
246
315
  if (harness === "omp" && dir === "rules" && !contents.subarray(0, 3).equals(Buffer.from("---"))) {
247
316
  contents = OMP_ALWAYS_APPLY + contents.toString("utf8")
248
317
  }
318
+ if (isShared && source.endsWith(".md")) {
319
+ const note = `<!-- Generated by ${config.generatedBy} from ${config.sharedDir}/${dir}/${source}. Do not edit. -->`
320
+ contents = withSharedHeader(contents.toString("utf8"), note)
321
+ }
249
322
  outputs.push({ file: path.join(harnessDir(root, plugin, harness), dir, dest), contents })
250
323
  }
251
324
  }
package/src/runtime.ts CHANGED
@@ -18,6 +18,7 @@ export const RUNTIME_DIR = "_kit"
18
18
  export const RUNTIME_MODULES = {
19
19
  frontmatter: { harness: "opencode", file: "frontmatter.ts", requires: [] },
20
20
  content: { harness: "opencode", file: "content.ts", requires: ["frontmatter"] },
21
+ agents: { harness: "opencode", file: "agents.ts", requires: ["frontmatter"] },
21
22
  session: { harness: "opencode", file: "session.ts", requires: [] },
22
23
  render: { harness: "claude", file: "render.mjs", requires: [] },
23
24
  "template-extension": { harness: "omp", file: "template-extension.ts", requires: [] },
package/src/testing.ts CHANGED
@@ -5,13 +5,15 @@ export type RegisteredSkill = { id: string; description: string; content: string
5
5
 
6
6
  /**
7
7
  * A fake OpenCode host context that records what a plugin registers: the `system` parts pushed through
8
- * `ctx.session.hook("context")`, the skills added through `ctx.skill.transform`, and how many registrations were disposed.
8
+ * `ctx.session.hook("context")`, the skills added through `ctx.skill.transform`, the agents registered through
9
+ * `ctx.agent.transform` (a draft per id, filled by `editor.update`), and how many registrations were disposed.
9
10
  */
10
- export function createFakeContext(config: { options?: unknown; existingSkills?: string[] } = {}) {
11
+ export function createFakeContext(config: { options?: unknown; existingSkills?: string[]; existingAgents?: string[] } = {}) {
11
12
  const system: SystemPart[] = []
12
13
  const skills = new Map<string, RegisteredSkill>(
13
14
  (config.existingSkills ?? []).map((id) => [id, { id, description: "own", content: "own" }]),
14
15
  )
16
+ const agents = new Map<string, Record<string, unknown>>((config.existingAgents ?? []).map((id) => [id, { system: "own" }]))
15
17
  let disposed = 0
16
18
  const ctx = {
17
19
  options: config.options,
@@ -21,6 +23,21 @@ export function createFakeContext(config: { options?: unknown; existingSkills?:
21
23
  return { dispose: async () => void disposed++ }
22
24
  },
23
25
  },
26
+ agent: {
27
+ transform: async (
28
+ change: (editor: { get(id: string): unknown; update(id: string, change: (draft: Record<string, unknown>) => void): void }) => void,
29
+ ) => {
30
+ change({
31
+ get: (id) => agents.get(id),
32
+ update: (id, edit) => {
33
+ const draft = agents.get(id) ?? {}
34
+ edit(draft)
35
+ agents.set(id, draft)
36
+ },
37
+ })
38
+ return { dispose: async () => void disposed++ }
39
+ },
40
+ },
24
41
  skill: {
25
42
  transform: async (change: (editor: { get(id: string): unknown; add(skill: RegisteredSkill): void }) => void) => {
26
43
  change({ get: (id) => skills.get(id), add: (skill) => void skills.set(skill.id, skill) })
@@ -28,5 +45,5 @@ export function createFakeContext(config: { options?: unknown; existingSkills?:
28
45
  },
29
46
  },
30
47
  }
31
- return { ctx, system, skills, disposed: () => disposed }
48
+ return { ctx, system, skills, agents, disposed: () => disposed }
32
49
  }