opencastle 1.10.1 → 1.11.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 (65) hide show
  1. package/README.md +1 -1
  2. package/dist/cli/detect.d.ts.map +1 -1
  3. package/dist/cli/detect.js +106 -2
  4. package/dist/cli/detect.js.map +1 -1
  5. package/dist/cli/detect.test.js +76 -0
  6. package/dist/cli/detect.test.js.map +1 -1
  7. package/dist/cli/explain.d.ts.map +1 -1
  8. package/dist/cli/explain.js +7 -0
  9. package/dist/cli/explain.js.map +1 -1
  10. package/dist/cli/init-detect.test.js +18 -0
  11. package/dist/cli/init-detect.test.js.map +1 -1
  12. package/dist/cli/init.d.ts.map +1 -1
  13. package/dist/cli/init.js +1 -0
  14. package/dist/cli/init.js.map +1 -1
  15. package/dist/cli/init.test.js +10 -0
  16. package/dist/cli/init.test.js.map +1 -1
  17. package/dist/cli/mcp-upgrade.test.js +40 -1
  18. package/dist/cli/mcp-upgrade.test.js.map +1 -1
  19. package/dist/cli/mcp.d.ts.map +1 -1
  20. package/dist/cli/mcp.js +6 -2
  21. package/dist/cli/mcp.js.map +1 -1
  22. package/dist/cli/stack-config.d.ts.map +1 -1
  23. package/dist/cli/stack-config.js +14 -1
  24. package/dist/cli/stack-config.js.map +1 -1
  25. package/dist/cli/types.d.ts +3 -1
  26. package/dist/cli/types.d.ts.map +1 -1
  27. package/dist/cli/types.js.map +1 -1
  28. package/dist/cli/update.js +1 -1
  29. package/dist/cli/update.js.map +1 -1
  30. package/dist/orchestrator/plugins/github/config.d.ts +3 -0
  31. package/dist/orchestrator/plugins/github/config.d.ts.map +1 -0
  32. package/dist/orchestrator/plugins/github/config.js +36 -0
  33. package/dist/orchestrator/plugins/github/config.js.map +1 -0
  34. package/dist/orchestrator/plugins/gitlab/config.d.ts +3 -0
  35. package/dist/orchestrator/plugins/gitlab/config.d.ts.map +1 -0
  36. package/dist/orchestrator/plugins/gitlab/config.js +26 -0
  37. package/dist/orchestrator/plugins/gitlab/config.js.map +1 -0
  38. package/dist/orchestrator/plugins/index.d.ts.map +1 -1
  39. package/dist/orchestrator/plugins/index.js +4 -0
  40. package/dist/orchestrator/plugins/index.js.map +1 -1
  41. package/dist/orchestrator/plugins/types.d.ts +15 -1
  42. package/dist/orchestrator/plugins/types.d.ts.map +1 -1
  43. package/package.json +1 -1
  44. package/src/cli/detect.test.ts +88 -0
  45. package/src/cli/detect.ts +100 -3
  46. package/src/cli/explain.ts +6 -0
  47. package/src/cli/init-detect.test.ts +22 -0
  48. package/src/cli/init.test.ts +13 -0
  49. package/src/cli/init.ts +1 -0
  50. package/src/cli/mcp-upgrade.test.ts +45 -2
  51. package/src/cli/mcp.ts +10 -4
  52. package/src/cli/stack-config.ts +18 -1
  53. package/src/cli/types.ts +3 -1
  54. package/src/cli/update.ts +1 -1
  55. package/src/orchestrator/customizations/agents/skill-matrix.json +7 -1
  56. package/src/orchestrator/plugins/github/config.ts +37 -0
  57. package/src/orchestrator/plugins/github/mcp.json +9 -0
  58. package/src/orchestrator/plugins/github/plugin.json +24 -0
  59. package/src/orchestrator/plugins/github/skills/github-platform/SKILL.md +77 -0
  60. package/src/orchestrator/plugins/gitlab/config.ts +27 -0
  61. package/src/orchestrator/plugins/gitlab/mcp.json +9 -0
  62. package/src/orchestrator/plugins/gitlab/plugin.json +21 -0
  63. package/src/orchestrator/plugins/gitlab/skills/gitlab-platform/SKILL.md +72 -0
  64. package/src/orchestrator/plugins/index.ts +4 -0
  65. package/src/orchestrator/plugins/types.ts +17 -1
package/src/cli/detect.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { resolve } from 'node:path';
1
+ import { dirname, resolve } from 'node:path';
2
2
  import { readFile, readdir, access } from 'node:fs/promises';
3
3
  import { existsSync } from 'node:fs';
4
4
  import type { IdeChoice, RepoInfo, StackConfig } from './types.js';
@@ -178,6 +178,18 @@ const CICD: DetectionRule[] = [
178
178
  { label: 'travis', files: ['.travis.yml'] },
179
179
  ];
180
180
 
181
+ // Files only a code host reads. Not `.github/` as a whole: VS Code's Copilot
182
+ // files live there too — `copilot-instructions.md`, `agents/`, `prompts/` —
183
+ // and this tool writes them for every VS Code target, hosted anywhere.
184
+ const CODE_HOSTS: DetectionRule[] = [
185
+ {
186
+ label: 'github',
187
+ files: ['.github/dependabot.yml', '.github/dependabot.yaml', '.github/CODEOWNERS', '.github/pull_request_template.md', '.github/PULL_REQUEST_TEMPLATE.md', '.github/FUNDING.yml'],
188
+ dirs: ['.github/workflows/', '.github/ISSUE_TEMPLATE/', '.github/PULL_REQUEST_TEMPLATE/'],
189
+ },
190
+ { label: 'gitlab', files: ['.gitlab-ci.yml'], dirs: ['.gitlab/'] },
191
+ ];
192
+
181
193
  const STYLING: DetectionRule[] = [
182
194
  { label: 'tailwind', files: ['tailwind.config.js', 'tailwind.config.ts', 'tailwind.config.mjs'] },
183
195
  { label: 'sass', files: [] }, // detected via package.json
@@ -249,6 +261,14 @@ export const PACKAGE_DETECTIONS: Record<string, { category: string; label: strin
249
261
  '@linear/sdk': { category: 'pm', label: 'linear' },
250
262
  '@slack/web-api': { category: 'notifications', label: 'slack' },
251
263
  '@slack/bolt': { category: 'notifications', label: 'slack' },
264
+ // Code hosts (their APIs, and GitHub Actions written in this repository)
265
+ 'octokit': { category: 'codeHosts', label: 'github' },
266
+ '@octokit/rest': { category: 'codeHosts', label: 'github' },
267
+ '@octokit/core': { category: 'codeHosts', label: 'github' },
268
+ '@actions/core': { category: 'codeHosts', label: 'github' },
269
+ '@actions/github': { category: 'codeHosts', label: 'github' },
270
+ '@gitbeaker/rest': { category: 'codeHosts', label: 'gitlab' },
271
+ '@gitbeaker/core': { category: 'codeHosts', label: 'gitlab' },
252
272
  };
253
273
 
254
274
  // ── Helpers ───────────────────────────────────────────────────
@@ -294,6 +314,7 @@ interface RepoInfoInternal {
294
314
  services: string[];
295
315
  pm: string[];
296
316
  notifications: string[];
317
+ codeHosts: string[];
297
318
  mcpConfig?: boolean;
298
319
  configFiles: string[];
299
320
  }
@@ -316,6 +337,7 @@ export async function detectRepoInfo(projectRoot: string): Promise<RepoInfo> {
316
337
  services: [],
317
338
  pm: [],
318
339
  notifications: [],
340
+ codeHosts: [],
319
341
  configFiles: [],
320
342
  };
321
343
 
@@ -350,8 +372,12 @@ export async function detectRepoInfo(projectRoot: string): Promise<RepoInfo> {
350
372
  detectCategory(projectRoot, STYLING, info, 'styling'),
351
373
  detectCategory(projectRoot, AUTH, info, 'auth'),
352
374
  detectCategory(projectRoot, SERVICES, info, 'services'),
375
+ detectCategory(projectRoot, CODE_HOSTS, info, 'codeHosts'),
353
376
  ]);
354
377
 
378
+ // ── 3b. Detect the code host from git remotes ───────────────
379
+ await detectCodeHosts(projectRoot, info);
380
+
355
381
  // ── 4. Detect from package.json deps ────────────────────────
356
382
  await detectFromPackageJson(projectRoot, info);
357
383
 
@@ -411,7 +437,7 @@ export async function detectRepoInfo(projectRoot: string): Promise<RepoInfo> {
411
437
  info.configFiles = [...new Set(info.configFiles)];
412
438
 
413
439
  // Sort arrays for stable output
414
- for (const key of ['frameworks', 'databases', 'cms', 'deployment', 'testing', 'cicd', 'styling', 'auth', 'services', 'pm', 'notifications', 'configFiles'] as const) {
440
+ for (const key of ['frameworks', 'databases', 'cms', 'deployment', 'testing', 'cicd', 'styling', 'auth', 'services', 'pm', 'notifications', 'codeHosts', 'configFiles'] as const) {
415
441
  info[key].sort();
416
442
  }
417
443
 
@@ -445,6 +471,72 @@ async function detectPythonOrGo(root: string, info: RepoInfoInternal): Promise<v
445
471
  for (const [re, label] of PYTHON_FRAMEWORKS) if (re.test(text)) addUnique(info.frameworks, label)
446
472
  }
447
473
 
474
+ /**
475
+ * Where the repository is hosted, from what names the host outright: its git
476
+ * remotes, the `repository` in package.json, and a Go module path. The file
477
+ * rules in CODE_HOSTS cover a checkout with no remote.
478
+ *
479
+ * A self-managed GitLab is recognised by `gitlab` in its host name, the usual
480
+ * convention; one under another name is added with `opencastle add gitlab`.
481
+ */
482
+ async function detectCodeHosts(root: string, info: RepoInfoInternal): Promise<void> {
483
+ const urls: string[] = []
484
+ // Remotes only: a submodule's `url` names where a dependency lives.
485
+ let remote = false
486
+ for (const line of (await readGitConfig(root)).split('\n')) {
487
+ if (/^\s*\[/.test(line)) remote = /^\s*\[remote\s/.test(line)
488
+ const url = remote ? /^\s*url\s*=\s*(\S+)/.exec(line)?.[1] : undefined
489
+ if (url) urls.push(url)
490
+ }
491
+ try {
492
+ const repository = (JSON.parse(await readFile(resolve(root, 'package.json'), 'utf8')) as { repository?: string | { url?: string } }).repository
493
+ const url = typeof repository === 'string' ? repository : repository?.url
494
+ // npm's shorthands: `github:user/repo`, `gitlab:user/repo`, and a bare `user/repo` for GitHub.
495
+ if (url) urls.push(/^[\w.-]+\/[\w.-]+$/.test(url) ? 'github.com/' + url : url.replace(/^(github|gitlab):/, '$1.com/'))
496
+ } catch {
497
+ // No package.json, or not JSON — the other signals still count.
498
+ }
499
+ const goModule = /^module\s+(\S+)/m.exec(await readFile(resolve(root, 'go.mod'), 'utf8').catch(() => ''))?.[1]
500
+ if (goModule) urls.push(goModule)
501
+ for (const url of urls) {
502
+ const host = codeHostOf(url)
503
+ if (host) addUnique(info.codeHosts, host)
504
+ }
505
+ }
506
+
507
+ /** `github` or `gitlab` for a URL, scp-style address or module path on one of them. */
508
+ function codeHostOf(url: string): string | null {
509
+ // https://host/…, ssh://git@host/…, git@host:path and host/path.
510
+ const host = /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:[^@/]+@)?([^:/]+)/i.exec(url)?.[1].toLowerCase() ?? ''
511
+ if (host === 'github.com' || host === 'ssh.github.com') return 'github'
512
+ if (/(^|[.-])gitlab([.-]|$)/.test(host)) return 'gitlab'
513
+ return null
514
+ }
515
+
516
+ /**
517
+ * The git config of the repository the project is in, following `.git` up
518
+ * through parent directories, as git does — a package in a monorepo has no
519
+ * `.git` of its own — and through a `.git` file, which is a worktree or a
520
+ * submodule.
521
+ */
522
+ async function readGitConfig(root: string): Promise<string> {
523
+ let dir = resolve(root)
524
+ while (!(await fileExists(resolve(dir, '.git')))) {
525
+ const parent = dirname(dir)
526
+ if (parent === dir) return ''
527
+ dir = parent
528
+ }
529
+ let gitDir = resolve(dir, '.git')
530
+ const pointer = /^gitdir:\s*(.+)$/m.exec(await readFile(gitDir, 'utf8').catch(() => ''))
531
+ if (pointer) {
532
+ gitDir = resolve(dir, pointer[1].trim())
533
+ // A worktree keeps its remotes in the main repository's config.
534
+ const common = (await readFile(resolve(gitDir, 'commondir'), 'utf8').catch(() => '')).trim()
535
+ if (common) gitDir = resolve(gitDir, common)
536
+ }
537
+ return readFile(resolve(gitDir, 'config'), 'utf8').catch(() => '')
538
+ }
539
+
448
540
  async function checkFiles(root: string, files: string[]): Promise<string[]> {
449
541
  const found: string[] = [];
450
542
  for (const f of files) {
@@ -455,7 +547,7 @@ async function checkFiles(root: string, files: string[]): Promise<string[]> {
455
547
  return found;
456
548
  }
457
549
 
458
- type CategoryKey = 'frameworks' | 'databases' | 'cms' | 'deployment' | 'testing' | 'cicd' | 'styling' | 'auth' | 'services' | 'pm' | 'notifications';
550
+ type CategoryKey = 'frameworks' | 'databases' | 'cms' | 'deployment' | 'testing' | 'cicd' | 'styling' | 'auth' | 'services' | 'pm' | 'notifications' | 'codeHosts';
459
551
 
460
552
  async function detectCategory(
461
553
  root: string,
@@ -695,6 +787,7 @@ export function buildDetectedToolsSet(repoInfo: RepoInfo): Set<string> {
695
787
  ...(repoInfo.services ?? []),
696
788
  ...(repoInfo.pm ?? []),
697
789
  ...(repoInfo.notifications ?? []),
790
+ ...(repoInfo.codeHosts ?? []),
698
791
  ]);
699
792
  }
700
793
 
@@ -719,6 +812,7 @@ function cleanEmpty(info: RepoInfoInternal): RepoInfo {
719
812
  if (info.services.length > 0) result.services = info.services;
720
813
  if (info.pm.length > 0) result.pm = info.pm;
721
814
  if (info.notifications.length > 0) result.notifications = info.notifications;
815
+ if (info.codeHosts.length > 0) result.codeHosts = info.codeHosts;
722
816
  if (info.configFiles.length > 0) result.configFiles = info.configFiles;
723
817
 
724
818
  return result;
@@ -751,6 +845,8 @@ export function mergeStackIntoRepoInfo(info: RepoInfo, stack: StackConfig): Repo
751
845
  merged.pm = addUniqueToArray(merged.pm, tool);
752
846
  } else if (['slack', 'teams'].includes(tool)) {
753
847
  merged.notifications = addUniqueToArray(merged.notifications, tool);
848
+ } else if (['github', 'gitlab'].includes(tool)) {
849
+ merged.codeHosts = addUniqueToArray(merged.codeHosts, tool);
754
850
  }
755
851
  }
756
852
 
@@ -790,6 +886,7 @@ export function formatRepoInfo(info: RepoInfo): string {
790
886
  if (info.services?.length) lines.push(`Services: ${info.services.join(', ')}`);
791
887
  if (info.pm?.length) lines.push(`Project management: ${info.pm.join(', ')}`);
792
888
  if (info.notifications?.length) lines.push(`Notifications: ${info.notifications.join(', ')}`);
889
+ if (info.codeHosts?.length) lines.push(`Code hosting: ${info.codeHosts.join(', ')}`);
793
890
  if (info.deployment?.length) lines.push(`Deployment: ${info.deployment.join(', ')}`);
794
891
  if (info.testing?.length) lines.push(`Testing: ${info.testing.join(', ')}`);
795
892
  if (info.cicd?.length) lines.push(`CI/CD: ${info.cicd.join(', ')}`);
@@ -91,8 +91,14 @@ async function build(pkgRoot: string, projectRoot: string): Promise<ExplainRepor
91
91
  })
92
92
  }
93
93
  for (const [key, s] of Object.entries(lock.mcp)) {
94
+ // A server that takes a token elsewhere signs in with OAuth in some targets.
95
+ const plugin = s.from.startsWith('plugin:') ? PLUGINS[s.from.slice(7)] : undefined
96
+ const oauthIn = (plugin?.tokenAuth?.oauthTargets ?? []).filter((t) => ides.includes(t))
94
97
  if (s.auth === 'oauth') {
95
98
  setup.push({ server: key, need: 'sign-in', ok: true, how: 'your assistant opens a browser to sign in the first time it starts the server' })
99
+ } else if (oauthIn.length > 0) {
100
+ const where = oauthIn.map((t) => IDE_LABELS[t]).join(', ')
101
+ setup.push({ server: key, need: 'sign-in', ok: true, how: `${where} opens a browser to sign in the first time it starts the server` })
96
102
  }
97
103
  }
98
104
  // Codex loads a project's `.codex/config.toml` only once the user has
@@ -144,6 +144,28 @@ describe('detected selection', () => {
144
144
  expect(selection.teamTools).toEqual([])
145
145
  expect(selection.techTools.length).toBeGreaterThan(0)
146
146
  })
147
+
148
+ it.each([
149
+ ['github', 'https://github.com/acme/web.git'],
150
+ ['gitlab', 'git@gitlab.com:acme/web.git'],
151
+ ])('selects %s when the repository is hosted there', async (host, url) => {
152
+ mkdirSync(join(dir, '.git'))
153
+ writeFileSync(join(dir, '.git', 'config'), `[remote "origin"]\n\turl = ${url}\n`)
154
+ writeFileSync(join(dir, 'package.json'), JSON.stringify({ name: 'x' }))
155
+
156
+ const selection = detectSelection(dir, await detectRepoInfo(dir))
157
+
158
+ expect(selection.teamTools).toEqual([host])
159
+ expect(selection.techTools).not.toContain(host)
160
+ })
161
+
162
+ it('selects neither code host for a repository with no sign of one', async () => {
163
+ mkdirSync(join(dir, '.git'))
164
+ writeFileSync(join(dir, '.git', 'config'), '[core]\n\tbare = false\n')
165
+ const selection = detectSelection(dir, await detectRepoInfo(dir))
166
+ expect(selection.teamTools).not.toContain('github')
167
+ expect(selection.teamTools).not.toContain('gitlab')
168
+ })
147
169
  })
148
170
 
149
171
  /**
@@ -219,6 +219,19 @@ describe('stack-config: getRequiredMcpEnvVars', () => {
219
219
  ])
220
220
  )
221
221
  })
222
+
223
+ it('asks for the GitHub token only when a target cannot sign in with OAuth', () => {
224
+ // GitHub's server completes OAuth in VS Code alone; the rest send the token.
225
+ const github = (ides: StackConfig['ides']) =>
226
+ getRequiredMcpEnvVars({ ides, techTools: [], teamTools: ['github'] }).map((v) => v.envVar)
227
+ expect(github(['vscode'])).toEqual([])
228
+ expect(github(['vscode', 'claude-code'])).toEqual(['GITHUB_PERSONAL_ACCESS_TOKEN'])
229
+ expect(github(['cursor'])).toEqual(['GITHUB_PERSONAL_ACCESS_TOKEN'])
230
+ })
231
+
232
+ it('asks for no GitLab token — GitLab’s server signs in with OAuth', () => {
233
+ expect(getRequiredMcpEnvVars({ ides: ['claude-code'], techTools: [], teamTools: ['gitlab'] })).toEqual([])
234
+ })
222
235
  })
223
236
 
224
237
  describe('stack-config: getAgentToolInjections', () => {
package/src/cli/init.ts CHANGED
@@ -51,6 +51,7 @@ const CATEGORY_STEPS: Array<{ title: string; subCategories: string[]; target: 't
51
51
  { title: 'Build Tools', subCategories: ['codebase-tool'], target: 'tech' },
52
52
  { title: 'More Tools', subCategories: ['design', 'email', 'payments', 'observability', 'knowledge-management'], target: 'tech' },
53
53
  { title: 'Project Management', subCategories: ['task-management'], target: 'team' },
54
+ { title: 'Code Hosting', subCategories: ['source-control'], target: 'team' },
54
55
  { title: 'Notifications', subCategories: ['notifications'], target: 'team' },
55
56
  ]
56
57
 
@@ -11,9 +11,10 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
11
11
  import { mkdtempSync, writeFileSync, readFileSync, rmSync, realpathSync, mkdirSync } from 'node:fs'
12
12
  import { join } from 'node:path'
13
13
  import { tmpdir } from 'node:os'
14
- import { upgradeGeneratedServers, rebuildMcpConfig, scaffoldMcpConfig, teamEntryFor } from './mcp.js'
14
+ import { upgradeGeneratedServers, rebuildMcpConfig, scaffoldMcpConfig, teamEntryFor, getMcpConfigRelPath, containerKeyFor } from './mcp.js'
15
15
  import { auditMcpConfig } from './mcp-audit.js'
16
- import type { StackConfig } from './types.js'
16
+ import { parseMcpConfigText } from './mcp-file.js'
17
+ import type { IdeChoice, StackConfig } from './types.js'
17
18
 
18
19
  describe('upgradeGeneratedServers', () => {
19
20
  it('adds the type Claude Code needs to a remote server we wrote without it', () => {
@@ -158,3 +159,45 @@ describe('rebuildMcpConfig on an install from before the fix', () => {
158
159
  }
159
160
  })
160
161
  })
162
+
163
+ /**
164
+ * GitHub's server completes OAuth in VS Code and nowhere else. VS Code gets the
165
+ * bare URL; every other target sends the token, in its own spelling of "this
166
+ * environment variable" — a `${NAME}` Cursor or OpenCode does not expand would
167
+ * reach GitHub as those characters.
168
+ */
169
+ describe('a remote server only some targets sign in to with OAuth', () => {
170
+ let root: string
171
+ beforeEach(() => {
172
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'mcp-token-auth-')))
173
+ })
174
+ afterEach(() => {
175
+ rmSync(root, { recursive: true, force: true })
176
+ })
177
+
178
+ const url = 'https://api.githubcopilot.com/mcp/'
179
+ const written = async (ide: IdeChoice): Promise<unknown> => {
180
+ const rel = getMcpConfigRelPath(ide)
181
+ await scaffoldMcpConfig(root, rel, { ides: [ide], techTools: [], teamTools: ['github'] }, undefined, ide)
182
+ const config = parseMcpConfigText(readFileSync(join(root, rel), 'utf8'), rel)
183
+ return (config[containerKeyFor(ide)] as Record<string, unknown>).GitHub
184
+ }
185
+
186
+ it.each([
187
+ ['vscode', { type: 'http', url }],
188
+ ['claude-code', { type: 'http', url, headers: { Authorization: 'Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}' } }],
189
+ ['cursor', { url, headers: { Authorization: 'Bearer ${env:GITHUB_PERSONAL_ACCESS_TOKEN}' } }],
190
+ ['windsurf', { url, headers: { Authorization: 'Bearer ${env:GITHUB_PERSONAL_ACCESS_TOKEN}' } }],
191
+ ['opencode', { type: 'remote', url, headers: { Authorization: 'Bearer {env:GITHUB_PERSONAL_ACCESS_TOKEN}' } }],
192
+ ['codex', { url, bearer_token_env_var: 'GITHUB_PERSONAL_ACCESS_TOKEN' }],
193
+ ] as const)('%s', async (ide, entry) => {
194
+ expect(await written(ide)).toEqual(entry)
195
+ })
196
+
197
+ it('writes nothing the audit objects to, and nothing a rebuild changes', async () => {
198
+ const entry = await written('claude-code')
199
+ expect(auditMcpConfig({ mcpServers: { GitHub: entry } }, 'claude-code').findings).toEqual([])
200
+ const stack: StackConfig = { ides: ['claude-code'], techTools: [], teamTools: ['github'] }
201
+ expect(await rebuildMcpConfig(root, 'claude-code', stack)).toEqual({ upgraded: [], removed: [], teamWritten: [], teamRemoved: [] })
202
+ })
203
+ })
package/src/cli/mcp.ts CHANGED
@@ -4,7 +4,7 @@ import { existsSync } from 'node:fs';
4
4
  import { getIncludedMcpServers } from './stack-config.js';
5
5
  import { PLUGINS } from '../orchestrator/plugins/index.js';
6
6
  import { UnreadableConfigError } from './types.js';
7
- import type { McpInput, McpServerConfig, EnvVarRequirement } from '../orchestrator/plugins/types.js';
7
+ import type { McpInput, McpServerConfig, EnvVarRequirement, PluginConfig } from '../orchestrator/plugins/types.js';
8
8
  import type { ScaffoldResult, StackConfig, RepoInfo, IdeChoice, CopyResults } from './types.js';
9
9
  import type { TeamMcpPlan } from './layers.js';
10
10
  import { EDITOR_VARIABLES, type TeamMcpServer } from './team-config.js';
@@ -219,14 +219,20 @@ function transformMcpForIde(
219
219
 
220
220
  /**
221
221
  * One plugin's server as the VS Code–format config, with the env vars other
222
- * targets need spelled out — they have no `envFile`.
222
+ * targets need spelled out — they have no `envFile` — and, for a server only
223
+ * some targets can sign in to with OAuth, the token header the others send.
223
224
  */
224
225
  function serverFor(
225
- plugin: { mcpConfig?: McpServerConfig; envVars: EnvVarRequirement[] },
226
+ plugin: { mcpConfig?: McpServerConfig; envVars: EnvVarRequirement[]; tokenAuth?: PluginConfig['tokenAuth'] },
226
227
  ide: IdeChoice,
227
228
  legacyEnv = false,
228
229
  ): VsCodeServer {
229
230
  const serverConfig = { ...plugin.mcpConfig! } as VsCodeServer;
231
+ if (plugin.tokenAuth && !plugin.tokenAuth.oauthTargets.includes(ide)) {
232
+ serverConfig.headers = Object.fromEntries(
233
+ Object.entries(plugin.tokenAuth.headers).map(([k, v]) => [k, legacyEnv ? v : rewriteRefs(v, ide)]),
234
+ );
235
+ }
230
236
  if (ide !== 'vscode' && plugin.envVars.length > 0) {
231
237
  const envBlock: Record<string, string> = { ...(serverConfig.env ?? {}) };
232
238
  for (const ev of plugin.envVars) {
@@ -435,7 +441,7 @@ export function upgradeGeneratedServers(
435
441
  // shape and the env-variable spelling of the time.
436
442
  const earlier: unknown[] = [];
437
443
  const configs = [
438
- { mcpConfig: plugin.mcpConfig, envVars: plugin.envVars },
444
+ { mcpConfig: plugin.mcpConfig, envVars: plugin.envVars, tokenAuth: plugin.tokenAuth },
439
445
  ...(plugin.previousMcpConfigs ?? []).map((p) => ({ mcpConfig: p.mcpConfig, envVars: p.envVars })),
440
446
  ];
441
447
  for (const cfg of configs) {
@@ -233,7 +233,23 @@ export function getIncludedMcpServers(stack: StackConfig, repoInfo?: RepoInfo):
233
233
  */
234
234
  export function getRequiredMcpEnvVars(stack: StackConfig, repoInfo?: RepoInfo): McpEnvRequirement[] {
235
235
  const included = getIncludedMcpServers(stack, repoInfo);
236
- return MCP_ENV_REQUIREMENTS.filter((req) => included.has(req.server));
236
+ return MCP_ENV_REQUIREMENTS.filter((req) => included.has(req.server) && needsToken(req.server, stack));
237
+ }
238
+
239
+ /**
240
+ * Targets that sign in to a server with OAuth, by server key. A project that
241
+ * compiles only for those never sends the token, and asking for it in `.env`
242
+ * and in `doctor` would be asking for a secret nothing reads.
243
+ */
244
+ const OAUTH_TARGETS = new Map(
245
+ Object.values(PLUGINS)
246
+ .filter((p) => p.mcpServerKey && p.tokenAuth)
247
+ .map((p) => [p.mcpServerKey!, p.tokenAuth!.oauthTargets as string[]]),
248
+ );
249
+
250
+ function needsToken(server: string, stack: StackConfig): boolean {
251
+ const oauth = OAUTH_TARGETS.get(server);
252
+ return !oauth || stack.ides.length === 0 || stack.ides.some((ide) => !oauth.includes(ide));
237
253
  }
238
254
 
239
255
  // ── Customization file transforms ─────────────────────────────
@@ -351,6 +367,7 @@ const SUBCATEGORY_TO_SLOT: Record<string, string> = {
351
367
  'codebase-tool': 'codebase-tool',
352
368
  'task-management': 'task-management',
353
369
  'knowledge-management': 'knowledge-management',
370
+ 'source-control': 'source-control',
354
371
  testing: 'testing',
355
372
  'e2e-testing': 'e2e-testing',
356
373
  design: 'design',
package/src/cli/types.ts CHANGED
@@ -5,7 +5,7 @@ import type { CompileSource } from './layers.js';
5
5
 
6
6
  export type IdeChoice = 'vscode' | 'cursor' | 'claude-code' | 'opencode' | 'windsurf' | 'codex' | 'antigravity';
7
7
  export type TechTool = 'sanity' | 'contentful' | 'strapi' | 'supabase' | 'convex' | 'vercel' | 'nx' | 'chrome-devtools' | 'nextjs' | 'astro' | 'netlify' | 'turborepo' | 'prisma' | 'cypress' | 'playwright' | 'vitest' | 'figma' | 'resend' | 'stripe' | 'sentry' | 'drizzle' | 'cloudflare' | 'coolify' | 'expo' | 'hetzner';
8
- export type TeamTool = 'linear' | 'jira' | 'trello' | 'notion' | 'slack' | 'teams';
8
+ export type TeamTool = 'linear' | 'jira' | 'trello' | 'notion' | 'slack' | 'teams' | 'github' | 'gitlab';
9
9
 
10
10
  export interface StackConfig {
11
11
  ides: IdeChoice[];
@@ -134,6 +134,8 @@ export interface RepoInfo {
134
134
  pm?: string[];
135
135
  notifications?: string[];
136
136
  services?: string[];
137
+ /** Where the repository is hosted, `github` or `gitlab`: from its remotes, package metadata and files only a host reads. */
138
+ codeHosts?: string[];
137
139
  mcpConfig?: boolean;
138
140
  configFiles?: string[];
139
141
  }
package/src/cli/update.ts CHANGED
@@ -403,7 +403,7 @@ export default async function update({
403
403
  value: p.id,
404
404
  selected: oldStack
405
405
  ? currentTeam.has(p.id as TeamTool)
406
- : isPreselected(p, repoInfo),
406
+ : isPreselected(p, repoInfo) || detectedTools.has(p.id),
407
407
  }))
408
408
  )
409
409
 
@@ -79,6 +79,10 @@
79
79
  "notifications": {
80
80
  "entries": [],
81
81
  "description": "Team messaging, alerts, bot integrations, channel management"
82
+ },
83
+ "source-control": {
84
+ "entries": [],
85
+ "description": "Pull and merge requests, code review, repository issues, CI status"
82
86
  }
83
87
  },
84
88
  "agents": {
@@ -180,6 +184,7 @@
180
184
  "slots": [
181
185
  "deployment",
182
186
  "observability",
187
+ "source-control",
183
188
  "codebase-tool"
184
189
  ],
185
190
  "directSkills": [
@@ -198,7 +203,8 @@
198
203
  "Team Lead (OpenCastle)": {
199
204
  "slots": [
200
205
  "task-management",
201
- "knowledge-management"
206
+ "knowledge-management",
207
+ "source-control"
202
208
  ],
203
209
  "directSkills": [
204
210
  "validation-gates",
@@ -0,0 +1,37 @@
1
+ import type { PluginConfig } from '../types.js';
2
+
3
+ export const config: PluginConfig = {
4
+ id: 'github',
5
+ name: 'GitHub',
6
+ category: 'team',
7
+ subCategory: 'source-control',
8
+ label: 'GitHub',
9
+ hint: 'Pull requests, reviews, CI and stacked PRs via GitHub\'s MCP server',
10
+ skillName: 'github-platform',
11
+ mcpServerKey: 'GitHub',
12
+ // GitHub's own remote server. VS Code signs in to it with OAuth; GitHub
13
+ // supports no other client's OAuth, so every other target sends a token.
14
+ mcpConfig: {
15
+ type: 'http',
16
+ url: 'https://api.githubcopilot.com/mcp/',
17
+ },
18
+ tokenAuth: {
19
+ oauthTargets: ['vscode'],
20
+ headers: { Authorization: 'Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}' },
21
+ },
22
+ authType: 'env-token',
23
+ envVars: [
24
+ {
25
+ name: 'GITHUB_PERSONAL_ACCESS_TOKEN',
26
+ hint: 'Create at github.com → Settings → Developer settings → Personal access tokens (VS Code signs in with OAuth instead)',
27
+ },
28
+ ],
29
+ // The whole server: GitHub adds and renames tools between releases, and a
30
+ // named tool that does not exist is silently absent.
31
+ agentToolMap: {
32
+ 'team-lead': ['GitHub/*'],
33
+ 'devops-expert': ['GitHub/*'],
34
+ },
35
+ docsUrl: 'https://www.opencastle.dev/docs/plugins#github',
36
+ officialDocs: 'https://github.com/github/github-mcp-server',
37
+ };
@@ -0,0 +1,9 @@
1
+ {
2
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
3
+ "mcpServers": {
4
+ "GitHub": {
5
+ "type": "streamable-http",
6
+ "url": "https://api.githubcopilot.com/mcp/"
7
+ }
8
+ }
9
+ }
@@ -0,0 +1,24 @@
1
+ {
2
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
3
+ "name": "github",
4
+ "description": "GitHub skill and MCP server for AI coding assistants: Pull requests, reviews, CI and stacked PRs via GitHub's MCP server.",
5
+ "homepage": "https://www.opencastle.dev/docs/plugins#github",
6
+ "repository": "https://github.com/monkilabs/opencastle",
7
+ "license": "MIT",
8
+ "keywords": [
9
+ "team",
10
+ "source-control"
11
+ ],
12
+ "extensions": {
13
+ "dev.opencastle": {
14
+ "label": "GitHub",
15
+ "category": "team",
16
+ "subCategory": "source-control",
17
+ "authType": "env-token",
18
+ "env": [
19
+ "GITHUB_PERSONAL_ACCESS_TOKEN"
20
+ ],
21
+ "officialDocs": "https://github.com/github/github-mcp-server"
22
+ }
23
+ }
24
+ }
@@ -0,0 +1,77 @@
1
+ ---
2
+ name: github-platform
3
+ description: "GitHub pull requests, review threads, failing Actions checks and stacked pull requests, through GitHub's MCP server and the gh CLI. Use when opening, reviewing or updating a pull request, fixing a failed check, or splitting a change into a stack."
4
+ ---
5
+
6
+ # GitHub Platform
7
+
8
+ Branch, commit and pull request conventions: the **git-workflow** skill. Docs: https://docs.github.com/en/pull-requests
9
+
10
+ ## The MCP server
11
+
12
+ GitHub's own remote server, `https://api.githubcopilot.com/mcp/`. VS Code signs in with OAuth. Every other assistant sends `GITHUB_PERSONAL_ACCESS_TOKEN`, so the server acts as that token's user — call `get_me` first to know whose name every comment will carry. Tool names change between releases: read the tool list the server offers instead of assuming a name.
13
+
14
+ - **Toolsets.** On by default: `context`, `repos`, `issues`, `pull_requests`, `users`. An `X-MCP-Toolsets` header on the server entry turns on more (`actions` for CI logs), and `X-MCP-Readonly: true` drops every write tool.
15
+ - **Token.** Fine-grained and limited to the repositories the agents work in: **Contents**, **Pull requests** and **Issues** read and write, **Metadata** and **Actions** read. A 404 on a repository you know exists is the token: its repository list, or an organization that has not approved it.
16
+ - **`gh` covers the rest:** review threads, job logs and stacks, below. It signs in on its own (`gh auth status`).
17
+
18
+ ## Gotchas
19
+
20
+ - **A review is pending until submitted.** Comments added to a pending review are invisible to everyone else, and a session that ends before the submit leaves them unsent.
21
+ - **Why a PR cannot merge:** `gh pr view 42 --json mergeStateStatus`. `BEHIND` needs a rebase onto its base, `DIRTY` has conflicts, `BLOCKED` lacks a required review or check, `UNSTABLE` has a non-required check failing.
22
+ - **A person merges**, as git-workflow says. Stop at a reviewed PR with green checks, though both the server and `gh` offer a merge.
23
+ - Open a draft while work remains (`gh pr create --draft`) and mark it ready when it is done (`gh pr ready 42`). `Closes #123` in the body closes the issue only when the PR merges into the default branch.
24
+ - In a review comment, a ```` ```suggestion ```` block replaces the commented lines when the author applies it. Use it for any fix that fits those lines.
25
+ - Search allows 30 requests a minute. Narrow with `repo:` and `is:open` rather than paging.
26
+
27
+ ## Review threads
28
+
29
+ The REST API returns review comments without saying which are resolved. GraphQL says.
30
+
31
+ 1. List the threads:
32
+
33
+ ```sh
34
+ gh api graphql -F owner='{owner}' -F repo='{repo}' -F pr=42 -f query='
35
+ query($owner: String!, $repo: String!, $pr: Int!) {
36
+ repository(owner: $owner, name: $repo) { pullRequest(number: $pr) {
37
+ reviewThreads(first: 100) { nodes { id isResolved isOutdated path line
38
+ comments(first: 20) { nodes { databaseId author { login } body } } } } } } }'
39
+ ```
40
+
41
+ 2. Fix what each unresolved thread asks, then commit and push. An `isOutdated` thread sits on code that has since changed: check that its point still applies.
42
+ 3. Reply in the thread with what changed: `gh api repos/{owner}/{repo}/pulls/42/comments/<databaseId>/replies -f body='Fixed in <sha>: …'`
43
+ 4. Resolve it: `gh api graphql -F id=<thread id> -f query='mutation($id: ID!) { resolveReviewThread(input: {threadId: $id}) { thread { isResolved } } }'`
44
+
45
+ Done when step 1 shows every thread you fixed as resolved. A point you disagree with gets a reply and stays open for the reviewer.
46
+
47
+ ## Failing checks
48
+
49
+ 1. `gh pr checks 42` lists every check on the head commit. `--watch --fail-fast` waits, and stops at the first failure.
50
+ 2. Read the failure with `gh run view <run-id> --log-failed`, which prints only the failed steps (the run ID is in the check's link). Start at the first error, not the last line.
51
+ 3. Reproduce it with the command the step ran, fix it, and push. Done when `gh pr checks 42` passes on the new head commit.
52
+ 4. If your diff cannot explain the failure, run `gh run rerun <run-id> --failed` once. A second failure is real.
53
+
54
+ Causes no log names:
55
+
56
+ - A push made with `GITHUB_TOKEN` inside a workflow starts no other workflow, so a bot's commit gets no checks. Push with a GitHub App token or a personal token when it needs them.
57
+ - A required check whose workflow is skipped by a `paths` filter never reports, and the PR waits for it forever. Run the job and exit early instead.
58
+ - A PR from a fork runs `pull_request` workflows with a read-only token and no secrets. `pull_request_target` has both and runs the base branch's workflow, so checking out the PR's code there runs it with your secrets.
59
+ - Set `permissions:` on each workflow rather than inheriting the repository default, which is read and write on older repositories.
60
+
61
+ ## Stacked pull requests
62
+
63
+ A change too big for one review becomes a stack: a chain of layers, each its own PR on the branch below, with the bottom one on trunk (the default branch). Dependencies point down: shared types and schema at the bottom, the code that uses them above. Each PR is held to trunk's required reviews and checks, so every layer builds and passes CI on its own. With agents, one task per layer.
64
+
65
+ The `gh stack` extension does the bookkeeping: `gh extension install github/gh-stack`. Name every branch on the command line, because a bare command opens a prompt.
66
+
67
+ 1. `gh stack init feat/search-01-schema`, then commit the first layer.
68
+ 2. For each next layer, from the top one: `gh stack add feat/search-02-api`, then commit.
69
+ 3. `gh stack push`, then `gh stack submit --auto`. This opens one draft PR per branch, each based on the one below, linked as a stack. Give each its title and body with `gh pr edit <n> --title "…" --body-file <file>`. Done when `gh stack view --json` lists every branch with its PR.
70
+ 4. To change a lower layer: `gh stack checkout feat/search-01-schema`, commit, then `gh stack rebase --upstack`, `gh stack push` and `gh stack top`.
71
+ 5. After a layer merges, `gh stack sync --prune` rebases what remains onto trunk, pushes, and deletes the merged branches.
72
+
73
+ - Merges go bottom up, and a person does them. Merging a PR merges every layer below it.
74
+ - History stays linear. Rebase rather than merging trunk into a layer, and push with `gh stack push`, which uses `--force-with-lease` per branch.
75
+ - A stack lives in one repository; it cannot span forks.
76
+ - Exit code 3 is a rebase conflict: resolve it, `git add`, then `gh stack rebase --continue`, or `--abort` to restore every branch.
77
+ - Exit code 9 means stacks are not enabled for this repository. Open each PR by hand with `gh pr create --draft --base <branch below>`. After a layer is squash-merged, rebase the next one with `git rebase --onto origin/main <merged branch> <next branch>` so the squashed commits are not replayed.
@@ -0,0 +1,27 @@
1
+ import type { PluginConfig } from '../types.js';
2
+
3
+ export const config: PluginConfig = {
4
+ id: 'gitlab',
5
+ name: 'GitLab',
6
+ category: 'team',
7
+ subCategory: 'source-control',
8
+ label: 'GitLab',
9
+ hint: 'Merge requests, pipelines and stacked MRs via GitLab\'s MCP server',
10
+ skillName: 'gitlab-platform',
11
+ mcpServerKey: 'GitLab',
12
+ // GitLab's own server, signed in with OAuth — it registers each client
13
+ // itself, so no token in .env. A self-managed instance serves the same
14
+ // path on its own host; edit the URL, and `sync` leaves the entry alone.
15
+ mcpConfig: {
16
+ type: 'http',
17
+ url: 'https://gitlab.com/api/v4/mcp',
18
+ },
19
+ authType: 'oauth',
20
+ envVars: [],
21
+ agentToolMap: {
22
+ 'team-lead': ['GitLab/*'],
23
+ 'devops-expert': ['GitLab/*'],
24
+ },
25
+ docsUrl: 'https://www.opencastle.dev/docs/plugins#gitlab',
26
+ officialDocs: 'https://docs.gitlab.com/user/model_context_protocol/mcp_server/',
27
+ };
@@ -0,0 +1,9 @@
1
+ {
2
+ "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json",
3
+ "mcpServers": {
4
+ "GitLab": {
5
+ "type": "streamable-http",
6
+ "url": "https://gitlab.com/api/v4/mcp"
7
+ }
8
+ }
9
+ }