@jagreehal/shepherd 0.15.0 → 0.17.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 (82) hide show
  1. package/AGENTS.md +3 -3
  2. package/README.md +40 -27
  3. package/THIRD_PARTY_NOTICES.md +2 -0
  4. package/gate/.shepherd/gate.schema.json +657 -0
  5. package/gate/.shepherd/gate.yml +123 -0
  6. package/gate/.shepherd/review-guidance.md +95 -0
  7. package/gate/src/actions.ts +32 -0
  8. package/gate/src/cli.ts +1046 -0
  9. package/gate/src/config.ts +102 -0
  10. package/gate/src/delta.ts +29 -0
  11. package/gate/src/env.ts +30 -0
  12. package/gate/src/eval.ts +292 -0
  13. package/gate/src/familiarity.ts +461 -0
  14. package/gate/src/github.ts +761 -0
  15. package/gate/src/inline.ts +59 -0
  16. package/gate/src/isolated-cli.ts +281 -0
  17. package/gate/src/leads.ts +257 -0
  18. package/gate/src/llm.ts +647 -0
  19. package/gate/src/notify.ts +57 -0
  20. package/gate/src/policy.ts +1313 -0
  21. package/gate/src/prices.ts +62 -0
  22. package/gate/src/provider-errors.ts +80 -0
  23. package/gate/src/retention.ts +86 -0
  24. package/gate/src/reviewer.ts +739 -0
  25. package/gate/src/signals.ts +105 -0
  26. package/gate/src/smoke-live.ts +64 -0
  27. package/gate/src/stack.ts +87 -0
  28. package/gate/src/stories.ts +297 -0
  29. package/gate/templates/policy-strict.yml +128 -0
  30. package/gate/templates/reviewer.Dockerfile +8 -0
  31. package/gate/templates/rules/observability/SKILL.md +33 -0
  32. package/gate/templates/shepherd-gate-actions.yml +35 -0
  33. package/gate/templates/shepherd-gate-edited.yml +29 -0
  34. package/gate/templates/shepherd-gate.yml +111 -0
  35. package/lenses/dotnet/SKILL.md +1 -1
  36. package/lenses/go/SKILL.md +1 -1
  37. package/lenses/java/SKILL.md +1 -1
  38. package/lenses/nextjs/SKILL.md +1 -1
  39. package/lenses/node-api/SKILL.md +1 -1
  40. package/lenses/nx-monorepo/SKILL.md +1 -1
  41. package/lenses/observability/SKILL.md +1 -1
  42. package/lenses/owasp-asvs/SKILL.md +1 -1
  43. package/lenses/owasp-llm/SKILL.md +1 -1
  44. package/lenses/pstack/SKILL.md +1 -1
  45. package/lenses/python/SKILL.md +1 -1
  46. package/lenses/react/SKILL.md +1 -1
  47. package/lenses/rust/SKILL.md +1 -1
  48. package/package.json +21 -7
  49. package/schema/config.json +1 -1
  50. package/skills/branch-review/SKILL.md +123 -0
  51. package/skills/ci-repair/SKILL.md +79 -35
  52. package/skills/garden/SKILL.md +8 -8
  53. package/skills/garden/references/telemetry.md +4 -4
  54. package/skills/incident/SKILL.md +9 -9
  55. package/skills/lens-import/SKILL.md +7 -7
  56. package/skills/review-slop/SKILL.md +1 -1
  57. package/skills/shepherd/SKILL.md +43 -41
  58. package/skills/shepherd/references/degradation.md +3 -3
  59. package/skills/shepherd/references/dispatch.md +1 -1
  60. package/skills/shepherd/references/formats.md +5 -5
  61. package/skills/shepherd/references/models.md +2 -2
  62. package/skills/shepherd/references/policy.md +9 -9
  63. package/skills/swarm/SKILL.md +21 -17
  64. package/skills/swarm/references/custom-lenses.md +2 -2
  65. package/skills/swarm/references/formats.md +1 -1
  66. package/skills/triage/SKILL.md +10 -10
  67. package/src/bin.ts +10 -0
  68. package/src/cli.ts +285 -42
  69. package/src/config.ts +26 -25
  70. package/src/doctor.ts +31 -18
  71. package/src/garden-traces.ts +13 -13
  72. package/src/garden.ts +4 -4
  73. package/src/lens.ts +19 -7
  74. package/src/setup.ts +72 -0
  75. package/src/stack.ts +2 -2
  76. package/src/status.ts +80 -0
  77. package/src/summary.ts +52 -9
  78. package/src/trace.ts +4 -4
  79. package/src/working.ts +30 -0
  80. package/templates/shepherd-audit.yml +7 -15
  81. package/templates/shepherd-incident.yml +7 -12
  82. package/templates/shepherd.yml +39 -40
package/src/cli.ts CHANGED
@@ -49,13 +49,13 @@ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFil
49
49
  import { homedir, tmpdir } from "node:os";
50
50
  import path from "node:path";
51
51
  import { parseArgs } from "node:util";
52
- import { parse as parseYaml, stringify } from "yaml";
52
+ import { parse as parseYaml, parseDocument, stringify } from "yaml";
53
53
  import { z } from "zod";
54
- import { branding, CI_DEFAULT_MODEL, ciModel, ciSettings, type Config, ConfigSchema, defaultBranchDir, defaultBranchReader, type Effective, fetchPackLenses, ghFetch, ghFetchDir, loadPolicy, policyProblems, PRESETS, preview, type Read, TEAM_FILES, configJsonSchema, schemaLine } from "./config.ts";
55
- import { commentableLines, renderReview, renderSummary, reviewedTips, roundCoverage } from "./summary.ts";
54
+ import { branding, ciModel, ciSettings, type Config, ConfigSchema, defaultBranchDir, defaultBranchReader, type Effective, fetchPackLenses, ghFetch, ghFetchDir, loadPolicy, policyProblems, PRESETS, preview, type Read, TEAM_FILES, configJsonSchema, schemaLine } from "./config.ts";
55
+ import { commentableLines, type OpenThread, renderReview, renderSummary, reviewedTips, roundCoverage, swarmThreads } from "./summary.ts";
56
56
  import { ghThreads, snapshot, verdict } from "./acceptance.ts";
57
57
  import { doctor } from "./doctor.ts";
58
- import { fileLedger, notify, notifyOn, STATES, statusLedger } from "./notify.ts";
58
+ import { fileLedger, LEDGER_CONTEXT, notify, notifyOn, STATES, statusLedger } from "./notify.ts";
59
59
  import { collect, collectEscapes, score } from "./garden.ts";
60
60
  import { collectTraces, tempoHeaders, traceLimits, traceScores } from "./garden-traces.ts";
61
61
  import { environmentWorkflow, install, type Outcome, pinWorkflow, uninstall, upgradeWorkflow } from "./install.ts";
@@ -66,13 +66,35 @@ import { numberDiff } from "./diff.ts";
66
66
  import { formatLeads, leadsAt } from "./leads.ts";
67
67
  import { prInterdiff, prStack } from "./stack.ts";
68
68
  import { flush, recordEvent, traceFile } from "./trace.ts";
69
- import { addLens, BUILT_IN_LENSES, ciOpencodeConfig, PROVIDER_KEY_ENVS, pluginRoots, lensTemplates, globalLensFile, lensProblems, newLens, opencodeAgents, opencodeModel, providerKeyEnv, setTier, detectStacks, stackLens, pinModel, repoLensFile, resolveSkill, setCi, setLadder, skillDescription, skillDirs, type Lens } from "./lens.ts";
69
+ import { compareDiff, latestVerdict, listReviews, openThreadCount } from "../gate/src/github.ts";
70
+ import { approvedDiffUnchanged } from "../gate/src/retention.ts";
71
+ import { githubSetup, KEY_MODELS, modelProblem, pickModel } from "./setup.ts";
72
+ import { type PrFacts, prStatus } from "./status.ts";
73
+ import { DEFAULT_LOOK, isWorkingNote, WORKING_IMAGE, workingNote } from "./working.ts";
74
+ import { addLens, sharedModelProblem, BUILT_IN_LENSES, ciOpencodeConfig, PROVIDER_KEY_ENVS, pluginRoots, lensTemplates, globalLensFile, lensProblems, newLens, opencodeAgents, opencodeModel, providerKeyEnv, setTier, detectStacks, stackLens, pinModel, repoLensFile, resolveSkill, setCi, setLadder, skillDescription, skillDirs, type Lens } from "./lens.ts";
70
75
 
71
76
  const BUNDLE_ROOT = path.resolve(import.meta.dir, "..");
72
77
 
78
+
73
79
  /** This CLI's version: workflows and the policy's schema line pin to it. */
74
80
  const bundleVersion = () => z.object({ version: z.string() }).parse(JSON.parse(readFileSync(path.join(BUNDLE_ROOT, "package.json"), "utf8"))).version;
75
81
 
82
+ const HELP = `usage: shepherd <command>
83
+
84
+ commands:
85
+ init set up this repository: config, workflows, secrets on GitHub
86
+ doctor check the setup can run, and say what to fix
87
+ review start a review of a PR in GitHub Actions and print the run's URL
88
+ status where a PR is (reviewing, fixing, waiting for CI, needs you, ready) and what to do next
89
+ gate the approval gate's verdict on a PR, here or posted to it
90
+ config inspect the settings and where each comes from (explain, validate)
91
+ models show or set the model for each tier
92
+ lens list or add review lenses
93
+ workflows write or upgrade the workflow files
94
+ local whether a local review covered your branch
95
+
96
+ shepherd help --all lists every command, including those the workflows call.`;
97
+
76
98
  const USAGE = `usage: shepherd install [--project | --target <dir>] [--link] [--force]
77
99
  shepherd uninstall [--project | --target <dir>]
78
100
  shepherd lens new <name> [--from <template>] [--applies <glob>]... [--description <text>]
@@ -86,7 +108,10 @@ const USAGE = `usage: shepherd install [--project | --target <dir>] [--link] [
86
108
  shepherd local finish <record.json> [--base <ref>]
87
109
  shepherd local status [--base <ref>]
88
110
  shepherd local demo [<dir>]
89
- shepherd init [--preset review-only|local-fix|push] [--from <pack>] [--stacks] [--model <id>]
111
+ shepherd init [--preset review-only|local-fix|push] [--from <pack>] [--stacks] [--model <id>] [--yes]
112
+ shepherd review <pr>
113
+ shepherd status <pr>
114
+ shepherd gate <pr> [--post] (shepherd gate --help for its options)
90
115
  shepherd config validate
91
116
  shepherd config schema
92
117
  shepherd config explain [--json] [--working-tree]
@@ -113,12 +138,15 @@ const USAGE = `usage: shepherd install [--project | --target <dir>] [--link] [
113
138
  shepherd eval import <case-id> <comments.json> --config <label> --login <reviewer> [--cost <usd>] [--duration-ms <n>]
114
139
  shepherd model-id <provider:model | provider/model>
115
140
  shepherd workflows [--audit] [--upgrade] [--model <id>] [--environment <name>] [--label <name>] [--aws-region <region>]
141
+ shepherd working --pr <n> --repo <owner/repo> [--head <sha>]
116
142
  shepherd notify --pr <n> --repo <owner/repo> --head <sha> --state success|failure|pending|error --file <description.txt>`;
117
143
 
118
144
  const { values: opts, positionals } = parseArgs({
119
145
  allowPositionals: true,
120
146
  options: {
121
147
  project: { type: "boolean", default: false },
148
+ all: { type: "boolean", default: false }, // help: every command, not only the everyday ones
149
+ help: { type: "boolean", short: "h", default: false },
122
150
  target: { type: "string" },
123
151
  link: { type: "boolean", default: false }, // symlink instead of copy: for a local clone you edit, never for bunx
124
152
  force: { type: "boolean", default: false },
@@ -151,6 +179,7 @@ const { values: opts, positionals } = parseArgs({
151
179
  label: { type: "string" }, // workflows: ci.label, the handoff label
152
180
  "aws-region": { type: "string" }, // workflows: ci.aws_region, for a bedrock: model
153
181
  stacks: { type: "boolean", default: false }, // init: add a lens for each stack the repository uses
182
+ yes: { type: "boolean", short: "y", default: false }, // init: set the secrets and the approval setting without asking
154
183
  pr: { type: "string" }, // acceptance: the PR whose threads must stay as they were; trace: the PR; summary, inline: the PR whose review threads a link may name
155
184
  round: { type: "string" }, // trace: the quality-loop round
156
185
  outcome: { type: "string" }, // trace: how a step or iteration ended
@@ -165,7 +194,7 @@ const { values: opts, positionals } = parseArgs({
165
194
  repo: { type: "string" }, // trace flush: owner/repo
166
195
  "ci-run": { type: "string" },
167
196
  "ci-attempt": { type: "string" },
168
- related: { type: "string", multiple: true }, // trace flush: traceparent of a related trace, such as stamp's review
197
+ related: { type: "string", multiple: true }, // trace flush: traceparent of a related trace, such as gate's review
169
198
  config: { type: "string" }, // eval run: the label runs are grouped and compared under
170
199
  repeat: { type: "string", default: "1" }, // eval run: reviews per case; one run says little about a model
171
200
  out: { type: "string" }, // eval run: where run files go, default evals/runs
@@ -195,10 +224,37 @@ const report = (outcomes: Outcome[]) => {
195
224
 
196
225
  const [command, sub, skillRef, ...rest] = positionals;
197
226
 
227
+ // Before any command runs: `shepherd init --help` must not set anything up.
228
+ if (opts.help) {
229
+ const forms = USAGE.split("\n").filter((l) => command && l.trim().startsWith(`shepherd ${command} `));
230
+
231
+ console.log(forms.length ? `usage:\n${forms.join("\n")}` : HELP);
232
+ process.exit(0);
233
+ }
234
+
198
235
  /**
199
236
  * The URLs of the review comments on the PR as GitHub gives them (`--pr`, or `$PR` in CI, with `$GITHUB_REPOSITORY`), so
200
237
  * a rendered thread link can only name a thread that exists on this PR. Unknown (no PR, gh failing): undefined, and links are kept as the round gave them.
201
238
  */
239
+ /** The PR's open swarm threads (`swarmThreads`), so a finding swarm marked as a repeat joins its thread. */
240
+ function openThreads(): OpenThread[] {
241
+ const pr = opts.pr ?? process.env.PR;
242
+ const [owner, name] = (process.env.GITHUB_REPOSITORY ?? "").split("/");
243
+
244
+ if (!pr || !/^\d+$/.test(pr) || !owner || !name) return [];
245
+ const query = "query($owner:String!,$name:String!,$number:Int!){viewer{login} repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100){nodes{isResolved comments(first:1){nodes{url body author{login __typename}}}}}}}}";
246
+ const Node = z.object({ isResolved: z.boolean(), comments: z.object({ nodes: z.array(z.object({ url: z.string(), body: z.string(), author: z.object({ login: z.string(), __typename: z.string() }).nullable() })) }) });
247
+ const Out = z.object({ viewer: z.object({ login: z.string() }).nullable(), repository: z.object({ pullRequest: z.object({ reviewThreads: z.object({ nodes: z.array(Node) }) }) }) });
248
+
249
+ try {
250
+ const out = Out.parse(JSON.parse(execFileSync("gh", ["api", "graphql", "-f", `query=${query}`, "-F", `owner=${owner}`, "-F", `name=${name}`, "-F", `number=${pr}`, "--jq", ".data"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 30_000 })));
251
+
252
+ return swarmThreads(out.repository.pullRequest.reviewThreads.nodes, out.viewer?.login ?? null);
253
+ } catch {
254
+ return [];
255
+ }
256
+ }
257
+
202
258
  function reviewThreads(): Set<string> | undefined {
203
259
  const pr = opts.pr ?? process.env.PR;
204
260
 
@@ -224,7 +280,7 @@ const orExit = <T>(run: () => T): T => {
224
280
  };
225
281
 
226
282
  // Secrets config explain shows only as set or unset.
227
- const SECRETS = ["SHEPHERD_TOKEN", "SHEPHERD_API_KEY", "SHEPHERD_NOTIFY_WEBHOOK", ...new Set(PROVIDER_KEY_ENVS)];
283
+ const SECRETS = ["SHEPHERD_TOKEN", "SHEPHERD_NOTIFY_WEBHOOK", ...new Set(PROVIDER_KEY_ENVS)];
228
284
 
229
285
  const MERGE_NOTE = "shepherd reads .shepherd/ from the default branch: commit and merge it before it takes effect.";
230
286
 
@@ -411,9 +467,9 @@ if (command === "install") {
411
467
  // Every key the plan's models read, so the workflow can drop the rest before the model runs.
412
468
  const keyEnvs = [...new Set([session, ...Object.values(opencode.agent).map((a) => a.model)].flatMap((m) => providerKeyEnv(m) ?? []))].sort();
413
469
 
414
- console.log(JSON.stringify({ model: session, source, key_env: providerKeyEnv(session), key_envs: keyEnvs, opencode }));
470
+ console.log(JSON.stringify({ model: session, source, key_envs: keyEnvs, opencode }));
415
471
  } else if (command === "model-id" && sub) {
416
- // A model id as OpenCode spells it, so stamp's provider:model spelling works in a local OpenCode run too.
472
+ // A model id as OpenCode spells it, so gate's provider:model spelling works in a local OpenCode run too.
417
473
  console.log(opencodeModel(sub));
418
474
  } else if (command === "stack" && sub) {
419
475
  // Which diff to review: the delta over an open stacked parent, or nothing at all when the base is wrong.
@@ -443,6 +499,13 @@ if (command === "install") {
443
499
  // A later round's focus: the PR's own change since the head swarm last reviewed, without the base's commits.
444
500
  console.log(JSON.stringify(orExit(() => prInterdiff(sub, opts.head ?? "HEAD", skillRef, repoRoot, opts["since-base"])), null, 2));
445
501
  } else if (command === "workflows") {
502
+ const problem = opts.model ? sharedModelProblem(opts.model) : null;
503
+
504
+ if (problem) {
505
+ console.error(problem);
506
+ process.exit(2);
507
+ }
508
+
446
509
  const dest = path.join(repoRoot, ".github", "workflows");
447
510
 
448
511
  mkdirSync(dest, { recursive: true });
@@ -482,12 +545,19 @@ if (command === "install") {
482
545
  console.log(`wrote .github/workflows/${name}`);
483
546
  }
484
547
 
485
- // Settings go in the team policy, reviewed and versioned, rather than in repository variables.
548
+ // Settings go in the team policy, reviewed and versioned, rather than in repository variables. Pinned before the
549
+ // gate's init, which names the key for this model.
486
550
  if (opts.model) {
487
551
  orExit(() => pinModel(repoLensFile(repoRoot), "loop", opts.model!));
488
552
  console.log(`pinned models.loop: ${opts.model} in ${path.relative(repoRoot, repoLensFile(repoRoot))}`);
489
553
  }
490
554
 
555
+ // The approval gate's workflows and policy too, so one command sets up the loop and the gate. No --model: the
556
+ // gate reads models.loop, so a later --model moves both.
557
+ const gateArgs = ["init", ...(opts.upgrade ? ["--upgrade"] : []), ...(opts.environment ? ["--environment", opts.environment] : []), ...(opts["aws-region"] ? ["--region", opts["aws-region"]] : [])];
558
+
559
+ if (spawnSync(process.execPath, [path.join(BUNDLE_ROOT, "gate", "src", "cli.ts"), ...gateArgs], { cwd: repoRoot, stdio: "inherit" }).status !== 0) process.exitCode = 1;
560
+
491
561
  const ci: Record<string, string> = {};
492
562
 
493
563
  if (opts.label) ci.label = opts.label;
@@ -514,7 +584,7 @@ if (command === "install") {
514
584
  const token = pushes ? "add SHEPHERD_TOKEN as a repository secret and " : "";
515
585
  const later = pushes ? "" : "SHEPHERD_TOKEN is not needed until fixes.mode is push.\n";
516
586
 
517
- console.log(`\nNext: name your CI workflow in each file's \`workflows:\` list, ${token}add the model key (SHEPHERD_API_KEY, or the provider's own) ${keys}, then merge.\n${later}${model}Other settings (label, aws_region, notify_on, push_deny...) go under ci: in .shepherd/config.yml; shepherd config explain lists them. Optional secret: SHEPHERD_NOTIFY_WEBHOOK (Slack or any JSON endpoint).`);
587
+ console.log(`\nNext: name your CI workflow in each file's \`workflows:\` list, ${token}add the model key under the provider's own name ${keys}, then merge.\n${later}${model}Other settings (label, aws_region, notify_on, push_deny...) go under ci: in .shepherd/config.yml; shepherd config explain lists them. Optional secret: SHEPHERD_NOTIFY_WEBHOOK (Slack or any JSON endpoint).`);
518
588
  } else if (command === "notify") {
519
589
  const pr = Number(opts.pr);
520
590
  const state = STATES.find((s) => s === opts.state);
@@ -549,46 +619,162 @@ if (command === "install") {
549
619
  process.exit(process.exitCode ?? 0);
550
620
  }
551
621
 
552
- if (existsSync(file)) orExit(() => { throw new Error(`${TEAM_FILES[0]} already exists; edit it, add stack lenses with shepherd init --stacks, then run shepherd config validate`); });
553
- const legacy = workingTree(TEAM_FILES[1]!);
554
- const seed = legacy ? orExit(() => ConfigSchema.parse(parseYaml(legacy) ?? {})) : { lenses: {} };
555
- // Every repository starts review-only, a migration too: push needs SHEPHERD_TOKEN and lets the bot push, so it is
556
- // opted into, never inherited. A pack or a legacy fixes: keeps its mode.
557
- const preset = opts.preset ?? (opts.from || seed.fixes ? undefined : "review-only");
622
+ const presetMode = Object.entries(PRESETS).find(([name]) => name === opts.preset)?.[1];
558
623
 
559
- const mode = Object.entries(PRESETS).find(([name]) => name === preset)?.[1];
624
+ if (opts.preset && !presetMode) orExit(() => { throw new Error(`--preset is one of ${Object.keys(PRESETS).join(", ")}`); });
560
625
 
561
- if (preset && !mode) orExit(() => { throw new Error(`--preset is one of ${Object.keys(PRESETS).join(", ")}`); });
562
- const config: Config = { ...seed };
626
+ // Rerunnable: an existing policy is kept, and the rest of setup still runs. --preset on it changes only fixes.mode.
627
+ const kept = existsSync(file);
563
628
 
564
- if (opts.from) config.extends = [opts.from, ...(seed.extends ?? [])];
629
+ if (kept && presetMode) {
630
+ const doc = parseDocument(readFileSync(file, "utf8"));
565
631
 
566
- if (mode) config.fixes = { mode };
632
+ doc.setIn(["fixes", "mode"], presetMode);
633
+ writeFileSync(file, doc.toString());
634
+ console.log(`set fixes.mode: ${doc.getIn(["fixes", "mode"])} in ${TEAM_FILES[0]}`);
635
+ } else if (kept) console.log(`kept ${TEAM_FILES[0]}`);
636
+ else {
637
+ const legacy = workingTree(TEAM_FILES[1]!);
638
+ const seed = legacy ? orExit(() => ConfigSchema.parse(parseYaml(legacy) ?? {})) : { lenses: {} };
639
+ // Every repository starts review-only, a migration too: push needs SHEPHERD_TOKEN and lets the bot push, so it is
640
+ // opted into, never inherited. A pack or a legacy fixes: keeps its mode.
641
+ const preset = opts.preset ?? (opts.from || seed.fixes ? undefined : "review-only");
567
642
 
568
- if (opts.model) config.models = { ...config.models, loop: opts.model }; // the session model, in the reviewed policy
569
- const stacks = detectStacks(trackedFiles(), workingTree);
643
+ const mode = Object.entries(PRESETS).find(([name]) => name === preset)?.[1];
570
644
 
571
- mkdirSync(path.dirname(file), { recursive: true });
572
- writeFileSync(file, `${schemaLine(bundleVersion())}\n# shepherd team policy. Presets: review-only (fixes.mode suggest), local-fix (local), push.\n${stringify(config)}`);
573
- console.log(`wrote ${TEAM_FILES[0]}${preset ? ` (preset ${preset})` : ""}${opts.model ? ` with models.loop ${opts.model}` : ""}${legacy ? ` from ${TEAM_FILES[1]} (delete it: ${TEAM_FILES[0]} now wins)` : ""}`);
645
+ if (preset && !mode) orExit(() => { throw new Error(`--preset is one of ${Object.keys(PRESETS).join(", ")}`); });
646
+ const config: Config = { ...seed };
574
647
 
575
- if (legacy && !opts.preset && !seed.fixes) console.log(`${TEAM_FILES[1]} pushed fixes; this policy starts review-only. To keep pushing: rm ${TEAM_FILES[0]} && shepherd init --preset push`);
648
+ if (opts.from) config.extends = [opts.from, ...(seed.extends ?? [])];
576
649
 
577
- // After the file exists, so a pack named by --from counts as already providing its lenses.
578
- if (opts.stacks) addStackLenses(file);
579
- else {
580
- if (stacks.length) console.log(`detected ${stacks.join(", ")}: run shepherd init --stacks to add their lenses, or extend github:jagreehal/shepherd/packs/<stack>.yml@<sha>`);
581
- pstackHint("pstack" in policy(true).lenses);
582
- }
650
+ if (mode) config.fixes = { mode };
651
+
652
+ if (opts.model) config.models = { ...config.models, loop: opts.model }; // the session model, in the reviewed policy
653
+ const stacks = detectStacks(trackedFiles(), workingTree);
583
654
 
584
- const named = policy(true);
655
+ mkdirSync(path.dirname(file), { recursive: true });
656
+ writeFileSync(file, `${schemaLine(bundleVersion())}\n# shepherd team policy. Presets: review-only (fixes.mode suggest), local-fix (local), push.\n${stringify(config)}`);
657
+ console.log(`wrote ${TEAM_FILES[0]}${preset ? ` (preset ${preset})` : ""}${opts.model ? ` with models.loop ${opts.model}` : ""}${legacy ? ` from ${TEAM_FILES[1]} (delete it: ${TEAM_FILES[0]} now wins)` : ""}`);
585
658
 
586
- if (!Object.keys(named.tiers).length && !named.ladder && !Object.keys(named.models).length) {
587
- console.log(`models: none named. Locally runners use your harness's models; in CI the session runs on ${CI_DEFAULT_MODEL}.\n Name a cheap and a strong model, then give roles to them:\n shepherd models tier fast <provider:model>\n shepherd models tier smart <provider:model>\n shepherd models ladder fast smart\n shepherd models pin reviewers fast (and: pin fixers smart, pin loop smart)`);
659
+ if (legacy && !opts.preset && !seed.fixes) console.log(`${TEAM_FILES[1]} pushed fixes; this policy starts review-only. To keep pushing: rm ${TEAM_FILES[0]} && shepherd init --preset push`);
660
+
661
+ // After the file exists, so a pack named by --from counts as already providing its lenses.
662
+ if (opts.stacks) addStackLenses(file);
663
+ else {
664
+ if (stacks.length) console.log(`detected ${stacks.join(", ")}: run shepherd init --stacks to add their lenses, or extend github:jagreehal/shepherd/packs/<stack>.yml@<sha>`);
665
+ pstackHint("pstack" in policy(true).lenses);
666
+ }
588
667
  }
589
668
 
590
669
  validate();
591
- console.log(`\nBefore you merge it:\n shepherd config explain --working-tree every setting and where it came from\n shepherd preview --working-tree what would run on your change, and what it can write\n${MERGE_NOTE}`);
670
+
671
+ // The rest of a first run: one model for the loop and the gate, the workflows and the gate's files, then GitHub.
672
+ // Team policy only, packs included and no personal layer: what CI will read, so an inherited model or push mode
673
+ // counts as the repository's own and a personal pin never does.
674
+ const resolved = orExit(() => loadPolicy(workingTree, ghFetch, null));
675
+ const pick = pickModel(opts.model, resolved.models.loop, process.env);
676
+ const problem = pick && modelProblem(pick.model);
677
+
678
+ if (problem) {
679
+ console.error(problem);
680
+ process.exit(2);
681
+ }
682
+
683
+ // Only a new choice is written: a rerun keeps the model the policy names.
684
+ const wf = spawnSync(process.execPath, [path.join(BUNDLE_ROOT, "src", "bin.ts"), "workflows", ...(pick?.chosen ? ["--model", pick.model] : [])], { cwd: repoRoot, encoding: "utf8" });
685
+
686
+ for (const line of `${wf.stdout}${wf.stderr}`.split("\n")) if (/^(wrote|created|upgraded|pinned|scoped|Priced|No list price)\b/.test(line)) console.log(line); // a rerun's kept files are not news
687
+
688
+ if (wf.status !== 0) orExit(() => { throw new Error(`writing the workflows failed:\n${wf.stderr}`); });
689
+ console.log(pick ? `model ${pick.model} (${pick.why})` : `model none found: set ${KEY_MODELS.map(([k]) => k).join(", ")} or pass --model provider/model`);
690
+
691
+ // Push mode publishes fixes with SHEPHERD_TOKEN: without it every fix bundle is refused, so it is part of setup.
692
+ const pushes = resolved.fixes.value.mode === "push";
693
+ const secrets = [...(pick?.key ? [pick.key] : []), ...(pushes ? ["SHEPHERD_TOKEN"] : [])].map((name) => ({ name, value: process.env[name]?.trim() || undefined }));
694
+
695
+ if (pushes) console.log("token push mode needs SHEPHERD_TOKEN: a fine-grained PAT with contents, pull requests and commit statuses (read/write) on this repository");
696
+
697
+ const view = spawnSync("gh", ["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"], { cwd: repoRoot, encoding: "utf8" });
698
+ const repo = view.status === 0 ? view.stdout.trim() : "";
699
+ const ask = () => opts.yes || (process.stdin.isTTY === true && /^(y|yes|)$/i.test((prompt(`\nOn ${repo}: ${secrets.length ? `set ${secrets.map((x) => x.name).join(" and ")}, and ` : ""}let Actions approve PRs? [Y/n]`) ?? "n").trim()));
700
+ const todo: string[] = [];
701
+
702
+ if (repo && ask()) {
703
+ const gh = (args: string[], input?: string) => {
704
+ const r = spawnSync("gh", args, { cwd: repoRoot, encoding: "utf8", input });
705
+
706
+ return { ok: r.status === 0, out: r.stdout ?? "" };
707
+ };
708
+
709
+ const done = githubSetup(gh, { repo, secrets });
710
+
711
+ for (const line of done.lines) console.log(line);
712
+ todo.push(...done.todo);
713
+ } else todo.push(...secrets.map((x) => `gh secret set ${x.name}`), "allow Actions to approve PRs (Settings → Actions → General)");
714
+
715
+ // Committing is the user's, like any change: one command, on a branch of their choosing.
716
+ const fixMode = resolved.fixes.value.mode;
717
+ const changed = spawnSync("git", ["status", "--porcelain", "--untracked-files=all", "--", ".shepherd", ".github/workflows"], { cwd: repoRoot, encoding: "utf8" }).stdout?.split("\n").filter(Boolean).map((l) => l.slice(3)) ?? [];
718
+ const MODES = { suggest: "reviews and suggests fixes, never pushes", local: "fixes stay in your working tree", push: "pushes fixes to the PR's branch" } as const;
719
+
720
+ console.log(`\nmode ${fixMode}: ${MODES[fixMode]} (fixes.mode in ${TEAM_FILES[0]})`);
721
+ console.log(`commit ${changed.length ? changed.join(", ") : "nothing new"}`);
722
+ console.log(`missing ${todo.length ? todo.join("; ") : "nothing"}`);
723
+ console.log(["", "Next", ...(changed.length ? [" git add .shepherd .github/workflows && git commit -m 'Set up shepherd', then open a PR and merge it"] : []), " shepherd doctor once merged: checks the workflows and the model key on GitHub", " shepherd review <pr> on any PR, then shepherd status <pr>"].join("\n"));
724
+
725
+ } else if (command === "working" && opts.pr && opts.repo) {
726
+ // The workflow's "shepherd is reviewing" note: posted, or refreshed for a new run. The finalizer deletes it.
727
+ const api = (args: string[]) => spawnSync("gh", ["api", ...args], { encoding: "utf8" });
728
+ const listed = api([`repos/${opts.repo}/issues/${opts.pr}/comments`, "--paginate", "--jq", ".[] | {id, user: {login: .user.login}, body}"]);
729
+ const note = (listed.stdout ?? "").split("\n").filter(Boolean).map((l) => z.object({ id: z.number(), user: z.object({ login: z.string() }), body: z.string() }).parse(JSON.parse(l))).find(isWorkingNote);
730
+
731
+ // The default branch's branding, as every other comment uses; the defaults when it cannot be read.
732
+ const look = (() => {
733
+ try {
734
+ const b = branding(loadPolicy(defaultBranchReader(repoRoot), ghFetch, null));
735
+
736
+ return b.name === "Shepherd" && !b.avatarUrl ? DEFAULT_LOOK : { name: b.name, header: b.headers.swarm, image: b.avatarUrl || WORKING_IMAGE };
737
+ } catch {
738
+ return DEFAULT_LOOK;
739
+ }
740
+ })();
741
+
742
+ const body = workingNote(opts.head ?? "", `${process.env.GITHUB_SERVER_URL ?? "https://github.com"}/${opts.repo}/actions/runs/${process.env.GITHUB_RUN_ID ?? ""}`, look);
743
+ const posted = api(note ? ["-X", "PATCH", `repos/${opts.repo}/issues/comments/${note.id}`, "-f", `body=${body}`] : [`repos/${opts.repo}/issues/${opts.pr}/comments`, "-f", `body=${body}`]);
744
+
745
+ if (posted.status !== 0) console.error(`could not post the note: ${posted.stderr.trim()}`);
746
+ } else if (command === "status" && sub) {
747
+ const s = prStatus(orExit(() => prFacts(Number(sub))));
748
+
749
+ for (const line of s.lines) console.log(line);
750
+ console.log(`\nstage ${s.stage}\nnext ${s.next}`);
751
+ } else if (command === "review" && sub) {
752
+ // The loop runs in GitHub Actions, not here: a `/shepherd` comment starts it, as one typed on the PR would.
753
+ const since = new Date(Date.now() - 5_000).toISOString();
754
+ const posted = spawnSync("gh", ["pr", "comment", sub, "--body", "/shepherd"], { cwd: repoRoot, encoding: "utf8" });
755
+
756
+ if (posted.status !== 0) orExit(() => { throw new Error(`could not comment on PR ${sub}: ${posted.stderr.trim()}`); });
757
+ console.error(`commented /shepherd on PR #${sub}; the review runs in GitHub Actions. Follow it with: shepherd status ${sub}`);
758
+ // The comment's run checks who asked, then dispatches the iteration for this PR; both carry the PR in their title.
759
+ // The iteration is the one to follow, so wait for it, and fall back to the comment's run, which says why it stopped.
760
+ const Runs = z.array(z.object({ url: z.string(), createdAt: z.string(), displayTitle: z.string(), event: z.string() }));
761
+ let url = "";
762
+ let fallback = "";
763
+
764
+ for (let i = 0; i < 20 && !url; i++) {
765
+ Bun.sleepSync(3_000);
766
+ const r = spawnSync("gh", ["run", "list", "--workflow", "shepherd.yml", "--limit", "30", "--json", "url,createdAt,displayTitle,event"], { cwd: repoRoot, encoding: "utf8" });
767
+ const mine = r.status === 0 ? Runs.parse(JSON.parse(r.stdout)).filter((x) => x.createdAt >= since && x.displayTitle === `shepherd ${sub}`) : [];
768
+
769
+ url = mine.find((x) => x.event === "workflow_dispatch")?.url ?? "";
770
+ fallback ||= mine.find((x) => x.event === "issue_comment")?.url ?? "";
771
+ }
772
+
773
+ url ||= fallback;
774
+
775
+ // Only the URL on stdout, so a script can open or pass it on.
776
+ if (url) console.log(url);
777
+ else console.error("no run for this PR yet: see the repository's Actions tab (workflows from before shepherd workflows --upgrade do not name the PR)");
592
778
  } else if (command === "config" && sub === "schema") {
593
779
  // The JSON Schema editors validate .shepherd/config.yml against; schema/config.json is this output.
594
780
  console.log(JSON.stringify(configJsonSchema(), null, 2));
@@ -636,7 +822,7 @@ if (command === "install") {
636
822
  // Read from the reviewed checkout, as inline does, so both place each suggestion on the same lines.
637
823
  const read = (p: string) => (existsSync(p) ? readFileSync(p, "utf8") : null);
638
824
 
639
- process.stdout.write(orExit(() => renderSummary(input, b.emoji, opts.body ? null : b.headers.swarm, previous, fanout, reviewThreads(), read)));
825
+ process.stdout.write(orExit(() => renderSummary(input, b.emoji, opts.body ? null : b.headers.swarm, previous, fanout, reviewThreads(), read, openThreads())));
640
826
  } else if (command === "inline" && sub) {
641
827
  // Swarm's inline review, rendered from the same round JSON: the payload for POST /pulls/<n>/reviews.
642
828
  const input = orExit(() => JSON.parse(readFileSync(sub, "utf8")));
@@ -649,7 +835,7 @@ if (command === "install") {
649
835
  const diff = opts.diff ? readFileSync(opts.diff, "utf8") : undefined;
650
836
  const [commentable, removable] = diff === undefined ? [] : [commentableLines(diff), commentableLines(diff, "LEFT")];
651
837
 
652
- console.log(JSON.stringify(orExit(() => renderReview(input, b.emoji, b.headers.swarm, read, reviewThreads(), commentable, removable)), null, 2));
838
+ console.log(JSON.stringify(orExit(() => renderReview(input, b.emoji, b.headers.swarm, read, reviewThreads(), commentable, removable, openThreads())), null, 2));
653
839
  } else if (command === "fanout") {
654
840
  // Swarm's first wave, dispatched in one message beside the router: correctness on the whole diff and every custom
655
841
  // lens whose applies_to matches a changed file, with its directory. The CLI lists them so no model skips one.
@@ -775,11 +961,68 @@ if (command === "install") {
775
961
  if (crashed) console.log(`error: ${crashed}`);
776
962
  console.log(problems.length ? `failed fixes.mode ${sub}` : crashed ? "inconclusive: the agent did not finish" : `ok: the run kept to fixes.mode ${sub}`);
777
963
  process.exitCode = problems.length ? 1 : crashed ? 2 : 0;
964
+ } else if (command === "help" || !command) {
965
+ console.log(opts.all ? USAGE : HELP);
778
966
  } else {
779
- console.error(USAGE);
967
+ const known = USAGE.split("\n").filter((l) => l.trim().startsWith(`shepherd ${command} `) || l.trim() === `shepherd ${command}`);
968
+
969
+ console.error(known.length ? `usage:\n${known.join("\n")}` : `unknown command: ${command}\n\n${HELP}`);
780
970
  process.exit(2);
781
971
  }
782
972
 
973
+ /** What `shepherd status` folds into a stage: the PR, the gate's latest verdict, the `shepherd` status and CI on the head. */
974
+ function prFacts(pr: number): PrFacts {
975
+ const run = (args: string[]) => {
976
+ const r = spawnSync("gh", args, { cwd: repoRoot, encoding: "utf8" });
977
+
978
+ if (r.status !== 0) throw new Error(`gh ${args.slice(0, 2).join(" ")} failed: ${r.stderr.trim()}`);
979
+
980
+ return JSON.parse(r.stdout || "null");
981
+ };
982
+
983
+ const view = z.object({ state: z.string(), headRefOid: z.string(), baseRefName: z.string(), url: z.string() }).parse(run(["pr", "view", String(pr), "--json", "state,headRefOid,baseRefName,url"]));
984
+ const head = view.headRefOid;
985
+ const repo = z.string().parse(run(["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner | tojson"]));
986
+ const reviews = listReviews(repo, pr, repoRoot);
987
+ // A person's latest approving or blocking review stands until they review again; a comment changes nothing.
988
+ const latestByPerson = new Map(reviews.filter((r) => !r.user.login.endsWith("[bot]") && /^(APPROVED|CHANGES_REQUESTED|DISMISSED)$/.test(r.state)).map((r) => [r.user.login, r.state]));
989
+
990
+ // Commit statuses, latest per context: shepherd's own, and CI that reports outside Actions.
991
+ const statuses = z.array(z.object({ context: z.string(), state: z.string(), description: z.string().nullable(), target_url: z.string().nullable() })).parse(run(["api", `repos/${repo}/commits/${head}/status`, "--jq", ".statuses"]));
992
+ const own = statuses.find((s) => s.context === "shepherd");
993
+ const external = statuses.flatMap((s) => (s.context === "shepherd" || s.context === LEDGER_CONTEXT ? [] : [{ name: s.context, status: s.state === "pending" ? "in_progress" : "completed", conclusion: s.state === "error" ? "failure" : s.state, url: s.target_url ?? "" }]));
994
+
995
+ // Actions by workflow, newest run each; other apps' check runs (Actions' own are its jobs, already counted).
996
+ const runs = z.array(z.object({ workflowName: z.string(), status: z.string(), conclusion: z.string(), url: z.string() })).parse(run(["run", "list", "--commit", head, "--json", "workflowName,status,conclusion,url"]));
997
+ const workflows = runs.filter((r, i) => runs.findIndex((o) => o.workflowName === r.workflowName) === i);
998
+ const checks = z.array(z.object({ name: z.string(), status: z.string(), conclusion: z.string().nullable(), html_url: z.string().nullable(), app: z.object({ slug: z.string() }).nullable() })).parse(run(["api", `repos/${repo}/commits/${head}/check-runs?per_page=100`, "--jq", ".check_runs"]));
999
+ const otherApps = checks.flatMap((c) => (c.app?.slug === "github-actions" ? [] : [{ name: c.name, status: c.status, conclusion: c.conclusion ?? "", url: c.html_url ?? "" }]));
1000
+
1001
+ // The gate keeps an approval across a push that leaves the PR's diff byte-identical, without a new review: check
1002
+ // the same thing it checks, so a kept approval reads as current and a stale one does not.
1003
+ const verdict = latestVerdict(reviews);
1004
+
1005
+ const kept = verdict?.verdict === "APPROVED" && !head.startsWith(verdict.head) && verdict.base !== "" && !verdict.evidenceUnseen && (() => {
1006
+ try {
1007
+ return approvedDiffUnchanged(compareDiff(repo, verdict.base, verdict.head, repoRoot), compareDiff(repo, view.baseRefName, head, repoRoot));
1008
+ } catch {
1009
+ return false;
1010
+ }
1011
+ })();
1012
+
1013
+ return {
1014
+ pr,
1015
+ state: view.state,
1016
+ head,
1017
+ url: view.url,
1018
+ gate: verdict && { verdict: verdict.verdict, head: verdict.head, kept },
1019
+ shepherd: own && { state: own.state, description: own.description ?? "" },
1020
+ changesRequested: [...latestByPerson].flatMap(([login, state]) => (state === "CHANGES_REQUESTED" ? [login] : [])),
1021
+ openThreads: openThreadCount(repo, pr, repoRoot),
1022
+ runs: [...workflows.map((r) => ({ name: r.workflowName, status: r.status, conclusion: r.conclusion, url: r.url })), ...otherApps, ...external],
1023
+ };
1024
+ }
1025
+
783
1026
  function trackedFiles(): string[] {
784
1027
  try {
785
1028
  return execFileSync("git", ["-C", repoRoot, "ls-files", "-z"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 }).split("\0").filter(Boolean);
package/src/config.ts CHANGED
@@ -20,7 +20,7 @@ export const LensSchema = z
20
20
  skill: z.string().min(1),
21
21
  applies_to: z.array(z.string().min(1)).optional(),
22
22
  description: z.string().min(1).optional(),
23
- gate: z.enum(SEVERITIES).optional(), // stamp's on_break for this lens's untagged rules; swarm reads the tags only
23
+ gate: z.enum(SEVERITIES).optional(), // gate's on_break for this lens's untagged rules; swarm reads the tags only
24
24
  only: z.array(z.string().min(1)).min(1).optional(), // rule id globs to keep
25
25
  disable: z.array(z.string().min(1)).min(1).optional(), // rule id globs to drop
26
26
  })
@@ -32,22 +32,22 @@ export type Lens = z.infer<typeof LensSchema>;
32
32
  const LensLayerSchema = LensSchema.partial({ skill: true });
33
33
 
34
34
  // A model id is whatever the harness's agent tool accepts: `haiku` on Claude Code, `provider/model` on OpenCode.
35
- // stamp's canonical `provider:model` also works: opencode-agents spells it the OpenCode way (lens.ts opencodeModel).
35
+ // gate's canonical `provider:model` also works: opencode-agents spells it the OpenCode way (lens.ts opencodeModel).
36
36
  export const ModelId = z.string().min(1);
37
37
 
38
- /** The steps a recipe can run: shepherd's own runners and stamp's verdict. */
39
- export const STEPS = ["swarm", "triage", "simplify", "ci-repair", "stamp", "incident"] as const;
38
+ /** The steps a recipe can run: shepherd's own runners and gate's verdict. */
39
+ export const STEPS = ["swarm", "triage", "simplify", "ci-repair", "gate", "incident"] as const;
40
40
 
41
41
  type Step = (typeof STEPS)[number];
42
42
 
43
43
  // Steps that change code, and the steps that review it. Success needs a review after the last change.
44
44
  const FIXERS = new Set<Step>(["triage", "simplify", "ci-repair", "incident"]);
45
45
 
46
- const REVIEWS = new Set<Step>(["swarm", "stamp"]);
46
+ const REVIEWS = new Set<Step>(["swarm", "gate"]);
47
47
 
48
48
  /**
49
49
  * The glyphs shepherd posts, by role, as they are today. Not here: the `🤖 Automated comment by` header prefix, which
50
- * triage, garden and stamp match to tell automated comments from people's, and the hidden `<!-- shepherd… -->` markers.
50
+ * triage, garden and gate match to tell automated comments from people's, and the hidden `<!-- shepherd… -->` markers.
51
51
  */
52
52
  export const BRANDING = {
53
53
  name: "Shepherd",
@@ -136,8 +136,8 @@ const BUILT_IN: Config = {
136
136
  recipes: {
137
137
  review: { steps: ["swarm"] },
138
138
  fix: { steps: ["swarm", "triage", "simplify", "swarm"] }, // runs under fixes.mode local: nothing it needs is pushed
139
- pr: { steps: ["swarm", "triage", "simplify", "swarm", "ci-repair", "stamp"] },
140
- incident: { steps: ["incident", "swarm", "triage", "simplify", "swarm", "ci-repair", "stamp"] }, // the fix PR gets the full loop
139
+ pr: { steps: ["swarm", "triage", "simplify", "swarm", "ci-repair", "gate"] },
140
+ incident: { steps: ["incident", "swarm", "triage", "simplify", "swarm", "ci-repair", "gate"] }, // the fix PR gets the full loop
141
141
  },
142
142
  };
143
143
 
@@ -389,15 +389,15 @@ export function recipeProblems(name: string, steps: Step[], mode: Mode): string[
389
389
 
390
390
  if (steps.includes("incident") && at("incident") !== 0) problems.push(`recipe ${name}: incident opens the PR, so it must come first`);
391
391
 
392
- if (steps.includes("stamp") && steps.lastIndexOf("stamp") !== steps.length - 1) problems.push(`recipe ${name}: stamp gives the verdict on the final head, so it must come last`);
392
+ if (steps.includes("gate") && steps.lastIndexOf("gate") !== steps.length - 1) problems.push(`recipe ${name}: gate gives the verdict on the final head, so it must come last`);
393
393
 
394
394
  if (steps.includes("triage") && !steps.slice(0, at("triage")).includes("swarm")) problems.push(`recipe ${name}: triage works the threads swarm posts, so a swarm must come before it`);
395
395
 
396
396
  const lastFix = steps.map((s) => FIXERS.has(s)).lastIndexOf(true);
397
397
 
398
- if (lastFix >= 0 && !steps.slice(lastFix + 1).some((s) => REVIEWS.has(s))) problems.push(`recipe ${name}: ${steps[lastFix]} changes code, so a swarm or stamp must review after it`);
399
- // stamp reviews the pushed head; under local the fixes never reach it, so only a swarm of the working tree counts.
400
- else if (mode === "local" && lastFix >= 0 && !steps.slice(lastFix + 1).includes("swarm")) problems.push(`recipe ${name}: fixes.mode is local, so stamp cannot see ${steps[lastFix]}'s fixes; a swarm must review after it`);
398
+ if (lastFix >= 0 && !steps.slice(lastFix + 1).some((s) => REVIEWS.has(s))) problems.push(`recipe ${name}: ${steps[lastFix]} changes code, so a swarm or gate must review after it`);
399
+ // gate reviews the pushed head; under local the fixes never reach it, so only a swarm of the working tree counts.
400
+ else if (mode === "local" && lastFix >= 0 && !steps.slice(lastFix + 1).includes("swarm")) problems.push(`recipe ${name}: fixes.mode is local, so gate cannot see ${steps[lastFix]}'s fixes; a swarm must review after it`);
401
401
 
402
402
  if (mode === "suggest") {
403
403
  const fixers = steps.filter((s) => FIXERS.has(s));
@@ -417,17 +417,17 @@ export const DEFAULT_RECIPE: Record<Mode, string> = { suggest: "review", local:
417
417
 
418
418
  /** How a recipe finishes, which is not always "ready to merge". */
419
419
  export function completion(steps: Step[], mode: Mode): string {
420
- if (!steps.some((s) => FIXERS.has(s))) return steps.at(-1) === "stamp" ? "ready when stamp approves this head, CI is green and no review thread is open" : "reviewed: findings posted for the author; says nothing about merge readiness";
420
+ if (!steps.some((s) => FIXERS.has(s))) return steps.at(-1) === "gate" ? "ready when gate approves this head, CI is green and no review thread is open" : "reviewed: findings posted for the author; says nothing about merge readiness";
421
421
 
422
422
  if (mode === "local") return "fixes_uncommitted: reviewed in your working tree; commit, push and run again before it can be ready";
423
423
 
424
- return steps.at(-1) === "stamp" ? "ready when stamp approves the final head, CI is green and no review thread is open; else pending" : "reviewed after the last fix; not ready until stamp approves, CI is green and no review thread is open";
424
+ return steps.at(-1) === "gate" ? "ready when gate approves the final head, CI is green and no review thread is open; else pending" : "reviewed after the last fix; not ready until gate approves, CI is green and no review thread is open";
425
425
  }
426
426
 
427
- // What each step can write. Swarm and stamp only post; the fixers' reach is the fix mode.
427
+ // What each step can write. Swarm and gate only post; the fixers' reach is the fix mode.
428
428
  const WRITES: Record<Step, Record<Mode, string>> = {
429
429
  swarm: { suggest: "posts review comments on the PR", local: "posts review comments on the PR", push: "posts review comments on the PR" },
430
- stamp: { suggest: "posts a review (approve or request changes)", local: "posts a review (approve or request changes)", push: "posts a review (approve or request changes)" },
430
+ gate: { suggest: "posts a review (approve or request changes)", local: "posts a review (approve or request changes)", push: "posts a review (approve or request changes)" },
431
431
  triage: { suggest: "replies on threads, changes no code", local: "edits your working tree", push: "commits and pushes to the PR branch, resolves threads" },
432
432
  simplify: { suggest: "reports only", local: "edits your working tree", push: "commits and pushes to the PR branch" },
433
433
  "ci-repair": { suggest: "reports only", local: "edits your working tree", push: "commits and pushes to the PR branch" },
@@ -671,22 +671,23 @@ export function branding(p: Effective) {
671
671
  const avatar = b?.avatar ? `<img src="${html(b.avatar)}" alt="" width="16" height="16"> ` : "";
672
672
  const header = (runner: string) => `> 🤖 Automated comment by ${avatar}**${name} ${runner}**, not written by a human`;
673
673
 
674
- return { name, avatar, emoji: { ...BRANDING.emoji, ...b?.emoji }, headers: { swarm: header("swarm"), incident: header("incident"), audit: header("audit") } };
674
+ return { name, avatar, avatarUrl: b?.avatar ? html(b.avatar) : "", emoji: { ...BRANDING.emoji, ...b?.emoji }, headers: { swarm: header("swarm"), incident: header("incident"), audit: header("audit") } };
675
675
  }
676
676
 
677
677
  /**
678
- * Every CI setting that is not a secret: its repository variable, its key under `ci:`, and the built-in default.
678
+ * Every CI setting that is not a secret: its key under `ci:` and the built-in default. Only AWS_REGION, the AWS
679
+ * standard name, has a variable; everything else is the reviewed config.
679
680
  * `push_deny` has no default here: the built-in deny list lives in the workflow, and config only adds to it.
680
681
  */
681
682
  export const CI_SETTINGS = {
682
- label: { variable: "SHEPHERD_LABEL", default: "" },
683
+ label: { variable: null, default: "" },
683
684
  aws_region: { variable: "AWS_REGION", default: "" },
684
- notify_on: { variable: "SHEPHERD_NOTIFY_ON", default: "success,failure,error" },
685
- max_commits: { variable: "SHEPHERD_MAX_COMMITS", default: "20" },
685
+ notify_on: { variable: null, default: "success,failure,error" },
686
+ max_commits: { variable: null, default: "20" },
686
687
  push_deny: { variable: null, default: "" },
687
- incident_paths: { variable: "INCIDENT_PATHS", default: "^src/" },
688
- audit_plays: { variable: "AUDIT_PLAYS", default: "secrets-scan sca-audit iac-security-review code-review-security" },
689
- audit_public: { variable: "AUDIT_PUBLIC", default: "false" },
688
+ incident_paths: { variable: null, default: "^src/" },
689
+ audit_plays: { variable: null, default: "secrets-scan sca-audit iac-security-review code-review-security" },
690
+ audit_public: { variable: null, default: "false" },
690
691
  } as const;
691
692
 
692
693
  export type CiSetting = { value: string; source: "variable" | "config" | "default"; variable: string | null };
@@ -703,7 +704,7 @@ export function ciSettings(p: Effective, env: Record<string, string | undefined>
703
704
  if (/[\n\r]/.test(setting.value)) throw new Error(`${variable ?? key}: one line only`);
704
705
 
705
706
  // A variable skips ConfigSchema, and a cap that does not parse would let the loop run unbounded.
706
- if (key === "max_commits" && !/^[1-9]\d{0,2}$/.test(setting.value)) throw new Error(`${variable}: a whole number from 1 to 999`);
707
+ if (key === "max_commits" && !/^[1-9]\d{0,2}$/.test(setting.value)) throw new Error(`${variable ?? key}: a whole number from 1 to 999`);
707
708
 
708
709
  return setting;
709
710
  };