@jagreehal/shepherd 0.4.0 → 0.6.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.
Files changed (47) hide show
  1. package/README.md +9 -1
  2. package/THIRD_PARTY_NOTICES.md +41 -0
  3. package/lenses/dotnet/SKILL.md +32 -0
  4. package/lenses/go/SKILL.md +30 -0
  5. package/lenses/java/SKILL.md +31 -0
  6. package/lenses/nextjs/SKILL.md +33 -0
  7. package/lenses/node-api/SKILL.md +32 -0
  8. package/lenses/nx-monorepo/SKILL.md +30 -0
  9. package/lenses/owasp-asvs/SKILL.md +50 -0
  10. package/lenses/owasp-llm/SKILL.md +44 -0
  11. package/lenses/pstack/SKILL.md +33 -0
  12. package/lenses/python/SKILL.md +32 -0
  13. package/lenses/react/SKILL.md +33 -0
  14. package/lenses/rust/SKILL.md +31 -0
  15. package/package.json +2 -1
  16. package/packs/dotnet.yml +6 -0
  17. package/packs/go.yml +6 -0
  18. package/packs/java.yml +6 -0
  19. package/packs/nextjs.yml +7 -0
  20. package/packs/node-api.yml +7 -0
  21. package/packs/nx-monorepo.yml +6 -0
  22. package/packs/observability.yml +6 -0
  23. package/packs/owasp-asvs.yml +6 -0
  24. package/packs/owasp-llm.yml +8 -0
  25. package/packs/pstack.yml +8 -0
  26. package/packs/python.yml +6 -0
  27. package/packs/react.yml +6 -0
  28. package/packs/rust.yml +6 -0
  29. package/skills/ci-repair/SKILL.md +11 -3
  30. package/skills/lens-import/SKILL.md +187 -0
  31. package/skills/lens-import/references/conversion.md +96 -0
  32. package/skills/lens-import/scripts/check-import.mjs +154 -0
  33. package/skills/shepherd/SKILL.md +32 -9
  34. package/skills/shepherd/references/dispatch.md +7 -4
  35. package/skills/shepherd/references/models.md +20 -7
  36. package/skills/shepherd/references/policy.md +9 -5
  37. package/skills/swarm/SKILL.md +11 -1
  38. package/skills/swarm/references/custom-lenses.md +50 -7
  39. package/skills/triage/SKILL.md +15 -0
  40. package/src/cli.ts +109 -13
  41. package/src/config.ts +137 -21
  42. package/src/doctor.ts +16 -13
  43. package/src/lens.ts +217 -14
  44. package/src/stack.ts +121 -0
  45. package/templates/shepherd-audit.yml +180 -0
  46. package/templates/shepherd-incident.yml +30 -4
  47. package/templates/shepherd.yml +34 -4
package/src/config.ts CHANGED
@@ -12,18 +12,26 @@ import { parse } from "yaml";
12
12
 
13
13
  const NAME = /^[a-z][a-z0-9-]*$/;
14
14
 
15
+ export const SEVERITIES = ["refuse", "escalate", "note"] as const;
16
+
15
17
  export const LensSchema = z
16
18
  .object({
17
19
  skill: z.string().min(1),
18
20
  applies_to: z.array(z.string().min(1)).optional(),
19
21
  description: z.string().min(1).optional(),
22
+ gate: z.enum(SEVERITIES).optional(), // stamp's on_break for this lens's untagged rules; swarm reads the tags only
23
+ only: z.array(z.string().min(1)).min(1).optional(), // rule id globs to keep
24
+ disable: z.array(z.string().min(1)).min(1).optional(), // rule id globs to drop
20
25
  })
21
26
  .strict();
22
27
 
23
28
  export type Lens = z.infer<typeof LensSchema>;
24
29
 
25
- // A model id is whatever the harness's agent tool accepts, passed through untouched: `haiku` on Claude Code,
26
- // `provider/model` on OpenCode (`opencode-go/deepseek-v4-flash`). shepherd never maps one to another.
30
+ // In one layer a lens may leave out its skill: it then trims or rescopes the lens of that name an earlier layer defined.
31
+ const LensLayerSchema = LensSchema.partial({ skill: true });
32
+
33
+ // A model id is whatever the harness's agent tool accepts: `haiku` on Claude Code, `provider/model` on OpenCode.
34
+ // stamp's canonical `provider:model` also works: opencode-agents spells it the OpenCode way (lens.ts opencodeModel).
27
35
  export const ModelId = z.string().min(1);
28
36
 
29
37
  /** The steps a recipe can run: shepherd's own runners and stamp's verdict. */
@@ -39,9 +47,10 @@ const REVIEWS = new Set<Step>(["swarm", "stamp"]);
39
47
  export const ConfigSchema = z
40
48
  .object({
41
49
  extends: z.array(z.string().min(1)).optional(),
50
+ tiers: z.record(z.string().regex(NAME), ModelId).optional(), // a name for a model, defined once: ladder and models may use it
42
51
  ladder: z.array(ModelId).min(1).optional(), // cheapest first; replaces the harness's ladder
43
- models: z.record(z.string().regex(NAME), ModelId).optional(), // a lens or runner name -> the model it always runs on
44
- lenses: z.record(z.string().regex(NAME), LensSchema).default({}),
52
+ models: z.record(z.string().regex(NAME), ModelId).optional(), // a runner, lens or role group -> the model or tier it runs on
53
+ lenses: z.record(z.string().regex(NAME), LensLayerSchema).default({}),
45
54
  checks: z.record(z.string().regex(NAME), z.object({ command: z.string().min(1) }).strict()).optional(),
46
55
  fixes: z.object({ mode: z.enum(["suggest", "local", "push"]) }).strict().optional(),
47
56
  escalate: z.object({ paths: z.array(z.string().min(1)).min(1), reason: z.string().min(1).optional() }).strict().optional(),
@@ -74,6 +83,8 @@ type Sourced<T> = { value: T; source: string };
74
83
  type Layer = { source: string; config: Config };
75
84
 
76
85
  export type Effective = {
86
+ /** Named models. The ladder and models below hold them resolved: a model id, never a tier name. */
87
+ tiers: Record<string, Sourced<string>>;
77
88
  ladder: Sourced<string[]> | null;
78
89
  models: Record<string, Sourced<string>>;
79
90
  lenses: Record<string, Sourced<Lens> & { scope: "team" | "personal" }>;
@@ -99,8 +110,17 @@ const parseConfig = (text: string, source: string): Config => {
99
110
  return result.data;
100
111
  };
101
112
 
102
- /** One `extends` entry as a layer. A pack extends nothing itself, so the order stays the one the file lists. */
103
- function readPack(ref: string, read: Read, fetch: Fetch): Layer {
113
+ // How deep packs may extend packs. Enough for org > stack > framework; past it a chain is a mistake.
114
+ const MAX_PACK_DEPTH = 4;
115
+
116
+ /**
117
+ * One `extends` entry as layers: the packs it extends, in order, then the pack itself. A pinned pack's own
118
+ * relative entries name files in its repository at the same commit, so a pack travels with what it builds on.
119
+ */
120
+ function readPack(ref: string, read: Read, fetch: Fetch, chain: string[] = []): Layer[] {
121
+ if (chain.includes(ref)) throw new Error(`${[...chain, ref].join(" > ")}: packs extend each other in a cycle`);
122
+
123
+ if (chain.length >= MAX_PACK_DEPTH) throw new Error(`${[...chain, ref].join(" > ")}: packs extend more than ${MAX_PACK_DEPTH} deep`);
104
124
  const pinned = PINNED.exec(ref);
105
125
  let text: string | null;
106
126
 
@@ -112,26 +132,32 @@ function readPack(ref: string, read: Read, fetch: Fetch): Layer {
112
132
  if (text === null) throw new Error(`${ref}: pack not found`);
113
133
  const config = parseConfig(text, ref);
114
134
 
115
- if (config.extends?.length) throw new Error(`${ref}: a pack cannot extend another pack; list both in the repository's extends`);
135
+ const inner = (config.extends ?? []).map((e) => {
136
+ if (!pinned || e.startsWith("github:")) return e;
137
+
138
+ if (pathEscapes(e)) throw new Error(`${ref}: extends ${e}: a path is relative to the pack's repository, with no leading / and no ..`);
139
+
140
+ return `github:${pinned[1]}/${pinned[2]}/${e}@${pinned[4]}`;
141
+ });
116
142
 
117
143
  // A pinned pack's lens paths name files in the pack's repository at the same commit, so the lens travels with it.
118
144
  if (pinned) {
119
145
  for (const [name, lens] of Object.entries(config.lenses)) {
120
- if (!lens.skill.includes("/")) continue;
146
+ if (!lens.skill?.includes("/")) continue;
121
147
 
122
148
  if (pathEscapes(lens.skill)) throw new Error(`${ref}: lens ${name}: a skill path is relative to the pack's repository, with no leading / and no ..`);
123
149
  lens.skill = `github:${pinned[1]}/${pinned[2]}/${lens.skill.replace(/\/+$/, "")}@${pinned[4]}`;
124
150
  }
125
151
  }
126
152
 
127
- return { source: `pack ${ref}`, config };
153
+ return [...inner.flatMap((e) => readPack(e, read, fetch, [...chain, ref])), { source: `pack ${ref}`, config }];
128
154
  }
129
155
 
130
156
  const pathEscapes = (rel: string) => rel.startsWith("/") || rel.split("/").includes("..");
131
157
 
132
- /** Merge layers in order: a later layer replaces a scalar and merges a map by name. */
158
+ /** Merge layers in order: a later layer replaces a scalar and merges a map by name; a lens merges field by field. */
133
159
  function merge(layers: Layer[]): Effective {
134
- const out: Effective = { ladder: null, models: {}, lenses: {}, checks: {}, fixes: { value: { mode: "push" }, source: "built-in" }, escalate: null, recipes: {}, ignored: [] };
160
+ const out: Effective = { tiers: {}, ladder: null, models: {}, lenses: {}, checks: {}, fixes: { value: { mode: "push" }, source: "built-in" }, escalate: null, recipes: {}, ignored: [] };
135
161
 
136
162
  for (const { source, config } of layers) {
137
163
  const tag = <T>(value: T) => ({ value, source });
@@ -142,9 +168,16 @@ function merge(layers: Layer[]): Effective {
142
168
 
143
169
  if (config.escalate) out.escalate = tag(config.escalate);
144
170
 
171
+ for (const [k, v] of Object.entries(config.tiers ?? {})) out.tiers[k] = tag(v);
172
+
145
173
  for (const [k, v] of Object.entries(config.models ?? {})) out.models[k] = tag(v);
146
174
 
147
- for (const [k, v] of Object.entries(config.lenses)) out.lenses[k] = { ...tag(v), scope: "team" };
175
+ for (const [k, v] of Object.entries(config.lenses)) {
176
+ // SAFETY: a lens without a skill is refused in loadPolicy unless an earlier layer gave it one.
177
+ const lens = { ...out.lenses[k]?.value, ...v } as Lens;
178
+
179
+ out.lenses[k] = { ...tag(lens), scope: "team" };
180
+ }
148
181
 
149
182
  for (const [k, v] of Object.entries(config.checks ?? {})) out.checks[k] = tag(v);
150
183
 
@@ -161,12 +194,16 @@ function merge(layers: Layer[]): Effective {
161
194
  export function loadPolicy(read: Read, fetch: Fetch, personal: Config | null): Effective & { teamFile: string | null } {
162
195
  const teamFile = TEAM_FILES.find((f) => read(f) !== null) ?? null;
163
196
  const team = teamFile ? parseConfig(read(teamFile)!, teamFile) : null;
164
- const packs = (team?.extends ?? []).map((ref) => readPack(ref, read, fetch));
197
+ const packs = (team?.extends ?? []).flatMap((ref) => readPack(ref, read, fetch));
165
198
  const effective = merge([{ source: "built-in", config: BUILT_IN }, ...packs, ...(team ? [{ source: teamFile!, config: team }] : [])]);
166
199
 
200
+ for (const [name, l] of Object.entries(effective.lenses)) {
201
+ if (!l.value.skill) throw new Error(`lens ${name}: no skill; name one, or extend the pack that defines ${name}`);
202
+ }
203
+
167
204
  // A lens may name a pinned pack directly; any skill spelled github: must be one that stays in the cache.
168
205
  for (const [name, l] of [...Object.entries(effective.lenses), ...Object.entries(personal?.lenses ?? {}).map(([k, v]) => [k, { value: v }] as const)]) {
169
- if (l.value.skill.startsWith("github:") && !safePinned(l.value.skill)) throw new Error(`lens ${name}: ${l.value.skill} is not github:owner/repo/<path>@<40-hex sha> with a path that stays in that repository`);
206
+ if (l.value.skill?.startsWith("github:") && !safePinned(l.value.skill)) throw new Error(`lens ${name}: ${l.value.skill} is not github:owner/repo/<path>@<40-hex sha> with a path that stays in that repository`);
170
207
  }
171
208
 
172
209
  if (personal) {
@@ -175,16 +212,88 @@ export function loadPolicy(read: Read, fetch: Fetch, personal: Config | null): E
175
212
  // Personal fills in only what the team left open, and adds lenses that never post.
176
213
  if (!effective.ladder && personal.ladder) effective.ladder = { value: personal.ladder, source };
177
214
 
178
- for (const [k, v] of Object.entries(personal.models ?? {})) effective.models[k] ??= { value: v, source };
215
+ for (const [k, v] of Object.entries(personal.tiers ?? {})) effective.tiers[k] ??= { value: v, source };
179
216
 
180
- for (const [k, v] of Object.entries(personal.lenses)) effective.lenses[k] ??= { value: v, source, scope: "personal" };
217
+ for (const [k, v] of Object.entries(personal.lenses)) {
218
+ if (!v.skill) throw new Error(`personal lens ${k}: no skill`);
219
+ // SAFETY: skill checked on the line above.
220
+ effective.lenses[k] ??= { value: v as Lens, source, scope: "personal" };
221
+ }
181
222
 
182
223
  for (const key of ["extends", "checks", "fixes", "escalate", "recipes"] as const) {
183
224
  if (personal[key] !== undefined) effective.ignored.push(`personal ${key}: team policy, set it in ${TEAM_FILES[0]}`);
184
225
  }
185
226
  }
186
227
 
187
- return { ...effective, teamFile };
228
+ // The team's groups expand before any personal pin, so a personal pin fills only a runner the team left open.
229
+ effective.models = expandGroups(effective, effective.models);
230
+
231
+ if (personal?.models) {
232
+ const own = expandGroups(effective, Object.fromEntries(Object.entries(personal.models).map(([k, v]) => [k, { value: v, source: "personal" }])));
233
+
234
+ for (const [k, v] of Object.entries(own)) effective.models[k] ??= v;
235
+ }
236
+
237
+ return { ...resolveModels(effective), teamFile };
238
+ }
239
+
240
+ /**
241
+ * Role groups a `models` entry can pin at once. A pin on one runner or lens beats its group's, so a team
242
+ * sets `reviewers: fast` and `security: smart` and gets both.
243
+ */
244
+ export const ROLE_GROUPS = {
245
+ reviewers: (p: Effective) => ["router", ...BUILT_IN_REVIEWERS, ...Object.keys(p.lenses)],
246
+ fixers: () => ["triage", "simplify", "ci-repair", "incident"],
247
+ validators: () => ["verifier", "validator"],
248
+ } as const;
249
+
250
+ /** The merged team pins with role groups expanded: a pin on a runner or lens beats its group. */
251
+ function expandGroups(p: Effective, pins: Effective["models"]): Effective["models"] {
252
+ const out: Effective["models"] = {};
253
+
254
+ for (const [group, members] of Object.entries(ROLE_GROUPS)) {
255
+ const pin = pins[group];
256
+
257
+ if (pin) for (const m of members(p)) out[m] = { value: pin.value, source: `${pin.source} (models.${group})` };
258
+ }
259
+
260
+ for (const [k, v] of Object.entries(pins)) if (!(k in ROLE_GROUPS)) out[k] = v;
261
+
262
+ return out;
263
+ }
264
+
265
+ /** Turn every tier name in the ladder and pins into its model id. */
266
+ function resolveModels(p: Effective): Effective {
267
+ const tier = (v: Sourced<string>) => {
268
+ const t = p.tiers[v.value];
269
+
270
+ return t ? { value: t.value, source: `${v.source}, tier ${v.value}` } : v;
271
+ };
272
+
273
+ return {
274
+ ...p,
275
+ ladder: p.ladder && { value: p.ladder.value.map((m) => p.tiers[m]?.value ?? m), source: p.ladder.source },
276
+ models: Object.fromEntries(Object.entries(p.models).map(([k, v]) => [k, tier(v)])),
277
+ };
278
+ }
279
+
280
+ /** The model CI runs the shepherd session on when nothing chooses one. */
281
+ export const CI_DEFAULT_MODEL = "opencode-go/kimi-k3";
282
+
283
+ /**
284
+ * The session model for CI, in order: SHEPHERD_MODEL (a model id or a tier name), the `loop` pin, the top of the
285
+ * ladder, then the default, which says so.
286
+ */
287
+ export type CiModel = { model: string; source: string };
288
+
289
+ export function ciModel(p: Effective, override: string | undefined): CiModel {
290
+ if (override) return p.tiers[override] ? { model: p.tiers[override]!.value, source: `SHEPHERD_MODEL, tier ${override}` } : { model: override, source: "SHEPHERD_MODEL" };
291
+
292
+ if (p.models.loop) return { model: p.models.loop.value, source: `models.loop, ${p.models.loop.source}` };
293
+
294
+ if (p.ladder) return { model: p.ladder.value.at(-1)!, source: `top of the ladder, ${p.ladder.source}` };
295
+
296
+ return { model: CI_DEFAULT_MODEL, source: "default: name one with SHEPHERD_MODEL, models.loop or a ladder" };
188
297
  }
189
298
 
190
299
  type Mode = Effective["fixes"]["value"]["mode"];
@@ -247,11 +356,11 @@ const WRITES: Record<Step, Record<Mode, string>> = {
247
356
  // Built-in reviewers, and the ladder rung each runner starts on (skills/shepherd/references/models.md).
248
357
  const BUILT_IN_REVIEWERS = ["correctness", "security", "simplicity", "maintainability", "slop", "spec"];
249
358
 
250
- const RUNG = new Map([["router", 0], ["verifier", 1], ["triage", 1], ["simplify", 1], ["ci-repair", 1], ["validator", 2]]);
359
+ const RUNG = new Map([["router", 0], ["verifier", 1], ["triage", 1], ["simplify", 1], ["ci-repair", 1], ["validator", 2], ["loop", 99]]); // loop: the top rung
251
360
 
252
361
  /** The model each runner uses: its pin, its rung of the team ladder, or the harness's own ladder. */
253
362
  export function modelPlan(p: Effective): { runner: string; model: string; source: string }[] {
254
- const names = ["router", ...BUILT_IN_REVIEWERS, ...Object.keys(p.lenses), "verifier", "triage", "simplify", "ci-repair", "validator"];
363
+ const names = ["router", ...BUILT_IN_REVIEWERS, ...Object.keys(p.lenses), "verifier", "triage", "simplify", "ci-repair", "validator", "loop"];
255
364
 
256
365
  return [...new Set(names)].map((runner) => {
257
366
  const pin = p.models[runner];
@@ -259,7 +368,13 @@ export function modelPlan(p: Effective): { runner: string; model: string; source
259
368
 
260
369
  if (pin) return { runner, model: pin.value, source: `pinned, ${pin.source}` };
261
370
 
262
- if (p.ladder) return { runner, model: p.ladder.value[Math.min(rung, p.ladder.value.length - 1)]!, source: `rung ${rung}, ${p.ladder.source}` };
371
+ if (p.ladder) {
372
+ const at = Math.min(rung, p.ladder.value.length - 1);
373
+
374
+ return { runner, model: p.ladder.value[at]!, source: `rung ${at}, ${p.ladder.source}` };
375
+ }
376
+
377
+ if (runner === "loop") return { runner, model: "the session model", source: `in CI, SHEPHERD_MODEL or ${CI_DEFAULT_MODEL}` };
263
378
 
264
379
  return { runner, model: `harness rung ${rung}`, source: "Claude Code: haiku > sonnet > opus; OpenCode with no ladder: the session model" };
265
380
  });
@@ -302,7 +417,8 @@ const gitIn = (repoRoot: string) => (...args: string[]) => execFileSync("git", [
302
417
  /** The fetched ref of `origin`'s default branch. The name comes from the remote, since a CI checkout sets no origin/HEAD. */
303
418
  export function defaultBranchRef(repoRoot: string): string {
304
419
  const git = gitIn(repoRoot);
305
- const branch = /^ref: refs\/heads\/(\S+)\s+HEAD/m.exec(git("ls-remote", "--symref", "origin", "HEAD"))?.[1];
420
+ // CI names it (SHEPHERD_DEFAULT_BRANCH), since a checkout without a persisted token cannot ask a private origin.
421
+ const branch = process.env.SHEPHERD_DEFAULT_BRANCH || /^ref: refs\/heads\/(\S+)\s+HEAD/m.exec(git("ls-remote", "--symref", "origin", "HEAD"))?.[1];
306
422
 
307
423
  if (!branch) throw new Error("cannot tell origin's default branch");
308
424
  const ref = `refs/remotes/origin/${branch}`;
package/src/doctor.ts CHANGED
@@ -6,7 +6,7 @@ import { parse } from "yaml";
6
6
  import { z } from "zod";
7
7
  import { defaultBranchReader, defaultBranchRef, fetchPackLenses, ghFetch, ghFetchDir, loadPolicy, type Config } from "./config.ts";
8
8
  import { bundledSkills } from "./install.ts";
9
- import { lensProblems } from "./lens.ts";
9
+ import { lensProblems, pluginRoots, skillDirs } from "./lens.ts";
10
10
 
11
11
  export type Check = { check: string; status: "ok" | "warn" | "fail"; detail: string; fix?: string };
12
12
 
@@ -20,15 +20,8 @@ const attempt = <T>(f: () => T): T | Error => {
20
20
  }
21
21
  };
22
22
 
23
- // Where a harness looks for skills: Claude Code, the shared .agents layout, Codex, OpenCode.
24
- const SKILL_DIRS = (home: string, repo: string) => [
25
- path.join(home, ".claude/skills"),
26
- path.join(repo, ".claude/skills"),
27
- path.join(home, ".agents/skills"),
28
- path.join(repo, ".agents/skills"),
29
- path.join(home, ".codex/skills"),
30
- path.join(home, ".config/opencode/skills"),
31
- ];
23
+ // Where a harness looks for skills: the bare-name directories, plus OpenCode's.
24
+ const SKILL_DIRS = (home: string, repo: string) => [...skillDirs(home, repo), path.join(home, ".config/opencode/skills")];
32
25
 
33
26
  /**
34
27
  * True when a workflow runs stamp on pull requests: a step that uses stamp's action, runs its package, or
@@ -80,10 +73,20 @@ export function doctor(bundleRoot: string, home: string, repo: string, personal:
80
73
  if (read instanceof Error) add("default branch", "fail", read.message, "git fetch origin <default branch>: policy and lenses are read from it");
81
74
  else add("default branch", "ok", "fetched");
82
75
 
83
- const missing = bundledSkills(path.join(bundleRoot, "skills")).filter((s) => !SKILL_DIRS(home, repo).some((d) => existsSync(path.join(d, s, "SKILL.md"))));
76
+ const bundled = bundledSkills(path.join(bundleRoot, "skills"));
77
+ const plugins = pluginRoots(home);
78
+ const asPlugin = plugins.get("shepherd");
79
+ const dirs = [...SKILL_DIRS(home, repo), ...(asPlugin ? [path.join(asPlugin, "skills")] : [])];
80
+ const missing = bundled.filter((s) => !dirs.some((d) => existsSync(path.join(d, s, "SKILL.md"))));
84
81
 
85
- if (missing.length) add("skills", "fail", `not installed: ${missing.join(", ")}`, "bunx @jagreehal/shepherd install (or --project, or --target <your agent's skills dir>)");
86
- else add("skills", "ok", "every bundled skill is installed");
82
+ if (missing.length) add("skills", "fail", `not installed: ${missing.join(", ")}`, "bunx @jagreehal/shepherd install (or --project, or --target <your agent's skills dir>), or install the shepherd plugin");
83
+ else add("skills", "ok", `every bundled skill is installed${asPlugin ? " (as a plugin)" : ""}`);
84
+
85
+ // Another plugin's skill under one of shepherd's names (pstack ships a `swarm`): Cursor does not namespace
86
+ // plugin skills, so `/swarm` there may load either. Shepherd's own loop loads its sub-skills by path.
87
+ const shared = [...plugins].filter(([name]) => name !== "shepherd").flatMap(([name, root]) => bundled.filter((s) => existsSync(path.join(root, "skills", s, "SKILL.md"))).map((s) => `${name}:${s}`));
88
+
89
+ if (shared.length) add("skill names", "warn", `other plugins ship skills under shepherd's names: ${shared.join(", ")}. /shepherd is unaffected; typed on its own, the name may load either`, "in Claude Code type the plugin prefix (/pstack:swarm); in Cursor, pick the skill from the / menu by its description");
87
90
 
88
91
  if (read instanceof Error) return checks;
89
92
 
package/src/lens.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  // Custom lenses: any skill, wrapped by swarm as a review-only reviewer whose `## Fix` section steers
2
2
  // triage. This file reads and writes the lens files and finds skills on disk; swarm itself reads the
3
3
  // repository's file from the default branch at review time (skills/swarm/references/custom-lenses.md).
4
- import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  import { parse, stringify } from "yaml";
7
7
  import { z } from "zod";
8
- import { type Config, ConfigSchema, type Lens, LensSchema, lensCache, ModelId, TEAM_FILES } from "./config.ts";
8
+ import { type Config, ConfigSchema, type Lens, LensSchema, lensCache, ModelId, SEVERITIES, TEAM_FILES } from "./config.ts";
9
+
10
+ type Severity = (typeof SEVERITIES)[number];
9
11
 
10
12
  export const BUILT_IN_LENSES = ["correctness", "security", "simplicity", "maintainability", "slop", "spec"];
11
13
 
@@ -29,7 +31,7 @@ export const repoLensFile = (repoRoot: string) => {
29
31
 
30
32
  const readFile = (file: string): LensFile => (existsSync(file) ? LensFileSchema.parse(parse(readFileSync(file, "utf8")) ?? {}) : { lenses: {} });
31
33
 
32
- export const readLenses = (file: string): Record<string, Lens> => readFile(file).lenses;
34
+ export const readLenses = (file: string) => readFile(file).lenses;
33
35
 
34
36
  /**
35
37
  * OpenCode agents for a harness whose subagent tool takes no model (OpenCode 1.x): one per rung,
@@ -37,7 +39,7 @@ export const readLenses = (file: string): Record<string, Lens> => readFile(file)
37
39
  * OPENCODE_CONFIG_CONTENT; swarm and the loop then dispatch by agent name.
38
40
  */
39
41
  export function opencodeAgents(choice: { ladder: string[] | null; models: Record<string, string> }) {
40
- const agent = (model: string, about: string) => ({ mode: "subagent", model, description: `shepherd runner on ${model} (${about})` });
42
+ const agent = (model: string, about: string) => ({ mode: "subagent", model: opencodeModel(model), description: `shepherd runner on ${model} (${about})` });
41
43
 
42
44
  return {
43
45
  agent: Object.fromEntries([
@@ -47,6 +49,20 @@ export function opencodeAgents(choice: { ladder: string[] | null; models: Record
47
49
  };
48
50
  }
49
51
 
52
+ // stamp's `provider:model` names where OpenCode's provider id differs; every other provider keeps its name.
53
+ const OPENCODE_PROVIDER = new Map([["bedrock", "amazon-bedrock"], ["vertex", "google-vertex"]]);
54
+
55
+ /**
56
+ * A model id as OpenCode spells it. stamp's canonical `provider:model` (`bedrock:eu.anthropic.claude-…-v1:0`)
57
+ * becomes `provider/model` (`amazon-bedrock/eu.anthropic.claude-…-v1:0`), so one ladder serves both tools.
58
+ * An OpenCode id or a Claude Code alias passes through.
59
+ */
60
+ export function opencodeModel(id: string): string {
61
+ const m = /^([a-z][a-z0-9-]*):(.+)$/.exec(id);
62
+
63
+ return m ? `${OPENCODE_PROVIDER.get(m[1]!) ?? m[1]}/${m[2]}` : id;
64
+ }
65
+
50
66
  /** Pin `name` (a lens or runner) to `model`, keeping everything else in the file. */
51
67
  export function pinModel(file: string, name: string, model: string): void {
52
68
  if (!LENS_NAME.test(name)) throw new Error(`"${name}" must be lowercase letters, digits, and dashes`);
@@ -55,6 +71,33 @@ export function pinModel(file: string, name: string, model: string): void {
55
71
  write(file, { ...current, models: { ...current.models, [name]: ModelId.parse(model) } });
56
72
  }
57
73
 
74
+ /** Name a model: `tier` becomes usable in the ladder and in pins, and swapping its model swaps it everywhere. */
75
+ export function setTier(file: string, tier: string, model: string): void {
76
+ if (!LENS_NAME.test(tier)) throw new Error(`"${tier}" must be lowercase letters, digits, and dashes`);
77
+ const current = readFile(file);
78
+
79
+ write(file, { ...current, tiers: { ...current.tiers, [tier]: ModelId.parse(model) } });
80
+ }
81
+
82
+ // The environment variable each OpenCode provider reads its key from. SHEPHERD_API_KEY fills the one the session
83
+ // model's provider needs, so a single-provider team sets one secret.
84
+ const PROVIDER_KEY_ENV = new Map([
85
+ ["opencode", "OPENCODE_API_KEY"],
86
+ ["opencode-go", "OPENCODE_API_KEY"],
87
+ ["anthropic", "ANTHROPIC_API_KEY"],
88
+ ["openai", "OPENAI_API_KEY"],
89
+ ["openrouter", "OPENROUTER_API_KEY"],
90
+ ["deepseek", "DEEPSEEK_API_KEY"],
91
+ ["groq", "GROQ_API_KEY"],
92
+ ["mistral", "MISTRAL_API_KEY"],
93
+ ["google", "GOOGLE_GENERATIVE_AI_API_KEY"],
94
+ ["xai", "XAI_API_KEY"],
95
+ ["amazon-bedrock", "AWS_BEARER_TOKEN_BEDROCK"],
96
+ ]);
97
+
98
+ /** The key variable for an OpenCode model id's provider, or null when shepherd does not know it. */
99
+ export const providerKeyEnv = (opencodeId: string): string | null => PROVIDER_KEY_ENV.get(opencodeId.split("/")[0]!) ?? null;
100
+
58
101
  /** Replace the ladder, cheapest model first. */
59
102
  export function setLadder(file: string, ladder: string[]): void {
60
103
  write(file, { ...readFile(file), ladder: z.array(ModelId).min(1).parse(ladder) });
@@ -97,7 +140,33 @@ fixes by its own rules. Nothing here can loosen shepherd's rules.
97
140
  - Escalate: <changes that go to the author instead of being fixed>.
98
141
  `;
99
142
 
100
- const RULE_ID = /^- \*\*([a-z0-9][a-z0-9-]*)\*\*/gm;
143
+ // `- **<id>**: <rule>`, or `- **<id>** [refuse|escalate|note]: <rule>` to set that rule's severity for stamp.
144
+ const RULE = /^- \*\*([a-z0-9][a-z0-9-]*)\*\*(?: \[(refuse|escalate|note)\])?:/gm;
145
+
146
+ export type LensRule = { id: string; severity?: Severity };
147
+
148
+ /** The rules in a lens's `## Review` section, with any severity tag; null when the section is missing. */
149
+ export function reviewRules(text: string): LensRule[] | null {
150
+ const review = /^## Review\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(text.replace(/\r\n/g, "\n"))?.[1];
151
+
152
+ if (review === undefined) return null;
153
+
154
+ return [...review.matchAll(RULE)].map((m) => {
155
+ const rule: LensRule = { id: m[1]! };
156
+ const severity = z.enum(SEVERITIES).optional().parse(m[2]);
157
+
158
+ if (severity) rule.severity = severity;
159
+
160
+ return rule;
161
+ });
162
+ }
163
+
164
+ /** Whether a lens entry's `only` and `disable` keep this rule. */
165
+ export const keepsRule = (lens: Pick<Lens, "only" | "disable">, id: string) => {
166
+ const hit = (globs: string[]) => globs.some((g) => new Bun.Glob(g).match(id));
167
+
168
+ return (!lens.only || hit(lens.only)) && !(lens.disable && hit(lens.disable));
169
+ };
101
170
 
102
171
  const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---/;
103
172
 
@@ -112,17 +181,25 @@ export function lensProblems(lens: Lens, home: string, repoRoot: string): string
112
181
  const problems: string[] = [];
113
182
 
114
183
  if (front === undefined || !skillDescription(dir)) problems.push(`${file}: frontmatter needs a description`);
184
+ const ownLens = path.posix.normalize(lens.skill.replaceAll("\\", "/")).startsWith(".shepherd/lenses/");
115
185
 
116
- if (!path.posix.normalize(lens.skill.replaceAll("\\", "/")).startsWith(".shepherd/lenses/")) return problems;
117
- const review = /^## Review\n([\s\S]*?)(?=^## |(?![\s\S]))/m.exec(text)?.[1];
186
+ // Rule ids are required under .shepherd/lenses/, and wherever only or disable must match them.
187
+ if (!ownLens && !lens.only && !lens.disable) return problems;
188
+ const rules = reviewRules(text);
118
189
 
119
- if (review === undefined) return [...problems, `${file}: add a "## Review" section`];
120
- const ids = [...review.matchAll(RULE_ID)].map((m) => m[1]);
190
+ if (rules === null) return [...problems, `${file}: add a "## Review" section`];
191
+ const ids = rules.map((r) => r.id);
121
192
 
122
193
  if (ids.length === 0) problems.push(`${file}: "## Review" has no rules; write each as "- **<id>**: <rule>", the id lowercase with dashes`);
123
194
 
124
195
  for (const id of new Set(ids.filter((id, i) => ids.indexOf(id) !== i))) problems.push(`${file}: rule id "${id}" is used more than once`);
125
196
 
197
+ for (const g of [...(lens.only ?? []), ...(lens.disable ?? [])]) {
198
+ if (!ids.some((id) => new Bun.Glob(g).match(id))) problems.push(`${file}: "${g}" in only or disable matches no rule id`);
199
+ }
200
+
201
+ if (ids.length && !ids.some((id) => keepsRule(lens, id))) problems.push(`${file}: only and disable leave no rule`);
202
+
126
203
  return problems;
127
204
  }
128
205
 
@@ -153,16 +230,126 @@ export function newLens(repoRoot: string, name: string, lens: Omit<Lens, "skill"
153
230
  return dir;
154
231
  }
155
232
 
156
- /** The directory holding the skill's SKILL.md: a path against the repository, or a name in the usual skills directories. */
233
+ /** The bundled packs (packs/<name>.yml): one starter lens each, with the files it applies to and its gate. */
234
+ export const PACKS_DIR = path.resolve(import.meta.dir, "..", "packs");
235
+
236
+ /** The lens entry a bundled pack declares for its own lens, minus the skill path. */
237
+ export function packLens(stack: string): Omit<Lens, "skill"> {
238
+ const { skill: _, ...rest } = LensSchema.parse(ConfigSchema.parse(parse(readFileSync(path.join(PACKS_DIR, `${stack}.yml`), "utf8"))).lenses[stack]);
239
+
240
+ return rest;
241
+ }
242
+
243
+ // A dependency in any package.json that marks a stack. next implies react: its pack extends react's.
244
+ const NPM_STACKS: [RegExp, string[]][] = [
245
+ [/^next$/, ["react", "nextjs"]],
246
+ [/^(react|react-dom)$/, ["react"]],
247
+ [/^(express|fastify|hono|koa|@nestjs\/core)$/, ["node-api"]],
248
+ ];
249
+
250
+ // A tracked file, anywhere in the repository, that marks a stack.
251
+ const FILE_STACKS: [RegExp, string][] = [
252
+ [/(^|\/)go\.mod$/, "go"],
253
+ [/(^|\/)Cargo\.toml$/, "rust"],
254
+ [/(^|\/)(pom\.xml|build\.gradle(\.kts)?)$/, "java"],
255
+ [/\.(csproj|fsproj|sln)$/, "dotnet"],
256
+ [/(^|\/)(pyproject\.toml|setup\.py|requirements\.txt)$/, "python"],
257
+ [/(^|\/)nx\.json$/, "nx-monorepo"],
258
+ ];
259
+
260
+ const PackageJson = z.object({ dependencies: z.record(z.string(), z.string()).optional(), devDependencies: z.record(z.string(), z.string()).optional() });
261
+
262
+ /** JSON, or null when malformed: a broken package.json marks nothing. */
263
+ const parseJson = (text: string) => {
264
+ try {
265
+ return JSON.parse(text);
266
+ } catch {
267
+ return null;
268
+ }
269
+ };
270
+
271
+ /** The bundled stack packs this repository's tracked files point at, sorted by name. `files` is `git ls-files`. */
272
+ export function detectStacks(files: string[], read: (rel: string) => string | null): string[] {
273
+ const found = new Set<string>();
274
+
275
+ for (const f of files) {
276
+ for (const [re, stack] of FILE_STACKS) if (re.test(f)) found.add(stack);
277
+
278
+ if (!/(^|\/)package\.json$/.test(f)) continue;
279
+ const pkg = PackageJson.safeParse(parseJson(read(f) ?? "{}"));
280
+ const deps = pkg.success ? Object.keys({ ...pkg.data.dependencies, ...pkg.data.devDependencies }) : [];
281
+
282
+ for (const [re, stacks] of NPM_STACKS) if (deps.some((d) => re.test(d))) for (const s of stacks) found.add(s);
283
+ }
284
+
285
+ // ASVS holds for every language, so any detected stack brings it.
286
+ if (found.size) found.add("owasp-asvs");
287
+
288
+ return lensTemplates().filter((t) => found.has(t));
289
+ }
290
+
291
+ // Claude Code's record of installed plugins, keyed `<plugin>@<marketplace>`.
292
+ const InstallRecord = z.object({ plugins: z.record(z.string(), z.array(z.object({ installPath: z.string() }))) });
293
+
294
+ // A skill an installed plugin ships, as Claude Code names it: `<plugin>:<skill>`, e.g. `pstack:principle-fix-root-causes`.
295
+ const PLUGIN_SKILL = /^([\w.-]+):([\w.-]+)$/;
296
+
297
+ const subdirs = (dir: string) => (existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(dir, d.name)) : []);
298
+
299
+ /** The newest of a plugin's cached versions: harnesses keep old ones beside it until they prune. */
300
+ const newest = (dirs: string[]) => dirs.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];
301
+
302
+ /**
303
+ * Each installed plugin's root, by plugin name: Claude Code's from its install record, Cursor's from its
304
+ * plugin cache (`<marketplace>/<plugin>/<version>`) and local plugins. A plugin keeps its skills in `skills/`.
305
+ */
306
+ export function pluginRoots(home: string): Map<string, string> {
307
+ const roots = new Map<string, string>();
308
+ const file = path.join(home, ".claude", "plugins", "installed_plugins.json");
309
+ const record = InstallRecord.safeParse(existsSync(file) ? parseJson(readFileSync(file, "utf8")) : null);
310
+
311
+ for (const [key, installs] of Object.entries(record.success ? record.data.plugins : {})) {
312
+ const root = installs.at(-1)?.installPath;
313
+
314
+ if (root) roots.set(key.split("@")[0]!, root);
315
+ }
316
+
317
+ const cursor = path.join(home, ".cursor", "plugins");
318
+
319
+ for (const plugin of subdirs(path.join(cursor, "cache")).flatMap(subdirs)) {
320
+ const root = newest(subdirs(plugin));
321
+
322
+ if (root && !roots.has(path.basename(plugin))) roots.set(path.basename(plugin), root);
323
+ }
324
+
325
+ for (const root of subdirs(path.join(cursor, "local"))) if (!roots.has(path.basename(root))) roots.set(path.basename(root), root);
326
+
327
+ return roots;
328
+ }
329
+
330
+ /** Where a harness looks for skills by bare name: Claude Code, the shared .agents layout, Codex, Cursor. */
331
+ export const skillDirs = (home: string, repoRoot: string) =>
332
+ [".claude/skills", ".agents/skills", ".codex/skills", ".cursor/skills"].map((d) => path.join(home, d)).concat([".claude/skills", ".agents/skills", ".cursor/skills"].map((d) => path.join(repoRoot, d)));
333
+
334
+ /**
335
+ * The directory holding the skill's SKILL.md: a pinned pack lens, a path against the repository, an
336
+ * installed plugin's skill (`<plugin>:<skill>`), or a name in the usual skills directories.
337
+ */
157
338
  export function resolveSkill(ref: string, home: string, repoRoot: string): string | null {
158
339
  const pinned = lensCache(home, ref);
159
340
 
160
341
  if (pinned) return existsSync(path.join(pinned, "SKILL.md")) ? pinned : null;
161
- const expanded = ref.startsWith("~/") ? path.join(home, ref.slice(2)) : ref;
342
+ const plugin = PLUGIN_SKILL.exec(ref);
343
+
344
+ if (plugin) {
345
+ const root = pluginRoots(home).get(plugin[1]!);
346
+ const dir = root && path.join(root, "skills", plugin[2]!);
347
+
348
+ return dir && existsSync(path.join(dir, "SKILL.md")) ? dir : null;
349
+ }
162
350
 
163
- const candidates = expanded.includes("/")
164
- ? [path.resolve(repoRoot, expanded)]
165
- : [".claude/skills", ".agents/skills", ".codex/skills"].map((d) => path.join(home, d, expanded)).concat([".claude/skills", ".agents/skills"].map((d) => path.join(repoRoot, d, expanded)));
351
+ const expanded = ref.startsWith("~/") ? path.join(home, ref.slice(2)) : ref;
352
+ const candidates = expanded.includes("/") ? [path.resolve(repoRoot, expanded)] : skillDirs(home, repoRoot).map((d) => path.join(d, expanded));
166
353
 
167
354
  return candidates.find((dir) => existsSync(path.join(dir, "SKILL.md"))) ?? null;
168
355
  }
@@ -176,3 +363,19 @@ export function skillDescription(skillDir: string): string | null {
176
363
 
177
364
  return parsed.success ? parsed.data.description.replace(/\s+/g, " ").trim() : null;
178
365
  }
366
+
367
+ /**
368
+ * A detected stack's lens, copied from its starter into .shepherd/lenses/<stack> so the team owns and trims it,
369
+ * with the pack's applies_to and gate. An existing lens directory is kept as it is.
370
+ */
371
+ export function stackLens(repoRoot: string, stack: string): Lens {
372
+ const skill = path.posix.join(".shepherd", "lenses", stack);
373
+ const dir = path.join(repoRoot, skill);
374
+
375
+ if (!existsSync(path.join(dir, "SKILL.md"))) {
376
+ mkdirSync(dir, { recursive: true });
377
+ writeFileSync(path.join(dir, "SKILL.md"), fromTemplate(stack, stack));
378
+ }
379
+
380
+ return { skill, ...packLens(stack) };
381
+ }