@sentry/warden 0.0.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 (199) hide show
  1. package/.agents/skills/find-bugs/SKILL.md +75 -0
  2. package/.agents/skills/vercel-react-best-practices/AGENTS.md +2934 -0
  3. package/.agents/skills/vercel-react-best-practices/SKILL.md +136 -0
  4. package/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md +55 -0
  5. package/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md +42 -0
  6. package/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md +39 -0
  7. package/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md +38 -0
  8. package/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md +80 -0
  9. package/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md +51 -0
  10. package/.agents/skills/vercel-react-best-practices/rules/async-parallel.md +28 -0
  11. package/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md +99 -0
  12. package/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md +59 -0
  13. package/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md +31 -0
  14. package/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md +49 -0
  15. package/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md +35 -0
  16. package/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md +50 -0
  17. package/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md +74 -0
  18. package/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md +71 -0
  19. package/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md +48 -0
  20. package/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md +56 -0
  21. package/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md +107 -0
  22. package/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md +80 -0
  23. package/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md +28 -0
  24. package/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md +70 -0
  25. package/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md +32 -0
  26. package/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md +50 -0
  27. package/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md +45 -0
  28. package/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md +37 -0
  29. package/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md +49 -0
  30. package/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md +82 -0
  31. package/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md +24 -0
  32. package/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md +57 -0
  33. package/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md +26 -0
  34. package/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +47 -0
  35. package/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md +40 -0
  36. package/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md +38 -0
  37. package/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md +46 -0
  38. package/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +82 -0
  39. package/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md +30 -0
  40. package/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md +28 -0
  41. package/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md +75 -0
  42. package/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md +39 -0
  43. package/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md +45 -0
  44. package/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md +40 -0
  45. package/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md +29 -0
  46. package/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md +74 -0
  47. package/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md +58 -0
  48. package/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md +38 -0
  49. package/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md +44 -0
  50. package/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md +45 -0
  51. package/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md +35 -0
  52. package/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md +40 -0
  53. package/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md +73 -0
  54. package/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md +73 -0
  55. package/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md +96 -0
  56. package/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md +41 -0
  57. package/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md +76 -0
  58. package/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md +65 -0
  59. package/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md +83 -0
  60. package/.agents/skills/vercel-react-best-practices/rules/server-serialization.md +38 -0
  61. package/.claude/settings.json +57 -0
  62. package/.claude/settings.local.json +88 -0
  63. package/.claude/skills/agent-prompt/SKILL.md +54 -0
  64. package/.claude/skills/agent-prompt/references/agentic-patterns.md +94 -0
  65. package/.claude/skills/agent-prompt/references/anti-patterns.md +140 -0
  66. package/.claude/skills/agent-prompt/references/context-design.md +124 -0
  67. package/.claude/skills/agent-prompt/references/core-principles.md +75 -0
  68. package/.claude/skills/agent-prompt/references/model-guidance.md +118 -0
  69. package/.claude/skills/agent-prompt/references/output-formats.md +98 -0
  70. package/.claude/skills/agent-prompt/references/skill-structure.md +115 -0
  71. package/.claude/skills/agent-prompt/references/system-prompts.md +115 -0
  72. package/.claude/skills/notseer/SKILL.md +131 -0
  73. package/.claude/skills/skill-writer/SKILL.md +140 -0
  74. package/.claude/skills/testing-guidelines/SKILL.md +132 -0
  75. package/.claude/skills/warden-skill/SKILL.md +250 -0
  76. package/.claude/skills/warden-skill/references/config-schema.md +133 -0
  77. package/.dex/config.toml +2 -0
  78. package/.github/workflows/ci.yml +33 -0
  79. package/.github/workflows/release.yml +54 -0
  80. package/.github/workflows/warden.yml +40 -0
  81. package/AGENTS.md +89 -0
  82. package/CONTRIBUTING.md +60 -0
  83. package/LICENSE +105 -0
  84. package/README.md +43 -0
  85. package/SPEC.md +263 -0
  86. package/action.yml +87 -0
  87. package/assets/favicon.png +0 -0
  88. package/assets/warden-icon-bw.svg +5 -0
  89. package/assets/warden-icon-purple.png +0 -0
  90. package/assets/warden-icon-purple.svg +5 -0
  91. package/docs/.claude/settings.local.json +11 -0
  92. package/docs/astro.config.mjs +43 -0
  93. package/docs/package.json +19 -0
  94. package/docs/pnpm-lock.yaml +4000 -0
  95. package/docs/public/favicon.svg +5 -0
  96. package/docs/src/components/Code.astro +141 -0
  97. package/docs/src/components/PackageManagerTabs.astro +183 -0
  98. package/docs/src/components/Terminal.astro +212 -0
  99. package/docs/src/layouts/Base.astro +380 -0
  100. package/docs/src/pages/cli.astro +167 -0
  101. package/docs/src/pages/config.astro +394 -0
  102. package/docs/src/pages/guide.astro +449 -0
  103. package/docs/src/pages/index.astro +490 -0
  104. package/docs/src/styles/global.css +551 -0
  105. package/docs/tsconfig.json +3 -0
  106. package/docs/vercel.json +5 -0
  107. package/eslint.config.js +33 -0
  108. package/package.json +73 -0
  109. package/src/action/index.ts +1 -0
  110. package/src/action/main.ts +868 -0
  111. package/src/cli/args.test.ts +477 -0
  112. package/src/cli/args.ts +415 -0
  113. package/src/cli/commands/add.ts +447 -0
  114. package/src/cli/commands/init.test.ts +136 -0
  115. package/src/cli/commands/init.ts +132 -0
  116. package/src/cli/commands/setup-app/browser.ts +38 -0
  117. package/src/cli/commands/setup-app/credentials.ts +45 -0
  118. package/src/cli/commands/setup-app/manifest.ts +48 -0
  119. package/src/cli/commands/setup-app/server.ts +172 -0
  120. package/src/cli/commands/setup-app.ts +156 -0
  121. package/src/cli/commands/sync.ts +114 -0
  122. package/src/cli/context.ts +131 -0
  123. package/src/cli/files.test.ts +155 -0
  124. package/src/cli/files.ts +89 -0
  125. package/src/cli/fix.test.ts +310 -0
  126. package/src/cli/fix.ts +387 -0
  127. package/src/cli/git.test.ts +119 -0
  128. package/src/cli/git.ts +318 -0
  129. package/src/cli/index.ts +14 -0
  130. package/src/cli/main.ts +672 -0
  131. package/src/cli/output/box.ts +235 -0
  132. package/src/cli/output/formatters.test.ts +187 -0
  133. package/src/cli/output/formatters.ts +269 -0
  134. package/src/cli/output/icons.ts +13 -0
  135. package/src/cli/output/index.ts +44 -0
  136. package/src/cli/output/ink-runner.tsx +337 -0
  137. package/src/cli/output/jsonl.test.ts +347 -0
  138. package/src/cli/output/jsonl.ts +126 -0
  139. package/src/cli/output/reporter.ts +435 -0
  140. package/src/cli/output/tasks.ts +374 -0
  141. package/src/cli/output/tty.test.ts +117 -0
  142. package/src/cli/output/tty.ts +60 -0
  143. package/src/cli/output/verbosity.test.ts +40 -0
  144. package/src/cli/output/verbosity.ts +31 -0
  145. package/src/cli/terminal.test.ts +148 -0
  146. package/src/cli/terminal.ts +301 -0
  147. package/src/config/index.ts +3 -0
  148. package/src/config/loader.test.ts +313 -0
  149. package/src/config/loader.ts +103 -0
  150. package/src/config/schema.ts +168 -0
  151. package/src/config/writer.test.ts +119 -0
  152. package/src/config/writer.ts +84 -0
  153. package/src/diff/classify.test.ts +162 -0
  154. package/src/diff/classify.ts +92 -0
  155. package/src/diff/coalesce.test.ts +208 -0
  156. package/src/diff/coalesce.ts +133 -0
  157. package/src/diff/context.test.ts +226 -0
  158. package/src/diff/context.ts +201 -0
  159. package/src/diff/index.ts +4 -0
  160. package/src/diff/parser.test.ts +212 -0
  161. package/src/diff/parser.ts +149 -0
  162. package/src/event/context.ts +132 -0
  163. package/src/event/index.ts +2 -0
  164. package/src/event/schedule-context.ts +101 -0
  165. package/src/examples/examples.integration.test.ts +66 -0
  166. package/src/examples/index.test.ts +101 -0
  167. package/src/examples/index.ts +122 -0
  168. package/src/examples/setup.ts +25 -0
  169. package/src/index.ts +115 -0
  170. package/src/output/dedup.test.ts +419 -0
  171. package/src/output/dedup.ts +607 -0
  172. package/src/output/github-checks.test.ts +300 -0
  173. package/src/output/github-checks.ts +476 -0
  174. package/src/output/github-issues.ts +329 -0
  175. package/src/output/index.ts +5 -0
  176. package/src/output/issue-renderer.ts +197 -0
  177. package/src/output/renderer.test.ts +727 -0
  178. package/src/output/renderer.ts +217 -0
  179. package/src/output/stale.test.ts +375 -0
  180. package/src/output/stale.ts +155 -0
  181. package/src/output/types.ts +34 -0
  182. package/src/sdk/index.ts +1 -0
  183. package/src/sdk/runner.test.ts +806 -0
  184. package/src/sdk/runner.ts +1232 -0
  185. package/src/skills/index.ts +36 -0
  186. package/src/skills/loader.test.ts +300 -0
  187. package/src/skills/loader.ts +423 -0
  188. package/src/skills/remote.test.ts +704 -0
  189. package/src/skills/remote.ts +604 -0
  190. package/src/triggers/matcher.test.ts +277 -0
  191. package/src/triggers/matcher.ts +152 -0
  192. package/src/types/index.ts +194 -0
  193. package/src/utils/async.ts +18 -0
  194. package/src/utils/index.test.ts +84 -0
  195. package/src/utils/index.ts +50 -0
  196. package/tsconfig.json +25 -0
  197. package/vitest.config.ts +8 -0
  198. package/vitest.integration.config.ts +11 -0
  199. package/warden.toml +19 -0
@@ -0,0 +1,604 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, renameSync, readdirSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { z } from 'zod';
6
+ import { loadSkillFromMarkdown, SkillLoaderError } from './loader.js';
7
+ import type { SkillDefinition } from '../config/schema.js';
8
+
9
+ /** Default TTL for unpinned remote skills: 24 hours */
10
+ const DEFAULT_TTL_SECONDS = 86400;
11
+
12
+ /** Schema for a single remote entry in state.json */
13
+ const RemoteEntrySchema = z.object({
14
+ sha: z.string(),
15
+ fetchedAt: z.string().datetime(),
16
+ });
17
+
18
+ /** Schema for the entire state.json file */
19
+ const RemoteStateSchema = z.object({
20
+ remotes: z.record(z.string(), RemoteEntrySchema),
21
+ });
22
+
23
+ export type RemoteEntry = z.infer<typeof RemoteEntrySchema>;
24
+ export type RemoteState = z.infer<typeof RemoteStateSchema>;
25
+
26
+ /** Schema for a plugin in marketplace.json */
27
+ const MarketplacePluginSchema = z.object({
28
+ name: z.string(),
29
+ source: z.string(),
30
+ description: z.string().optional(),
31
+ category: z.string().optional(),
32
+ });
33
+
34
+ /** Schema for .claude-plugin/marketplace.json */
35
+ const MarketplaceConfigSchema = z.object({
36
+ $schema: z.string().optional(),
37
+ name: z.string(),
38
+ description: z.string().optional(),
39
+ plugins: z.array(MarketplacePluginSchema),
40
+ });
41
+
42
+ type MarketplaceConfig = z.infer<typeof MarketplaceConfigSchema>;
43
+
44
+ /** Parsed remote reference */
45
+ export interface ParsedRemoteRef {
46
+ owner: string;
47
+ repo: string;
48
+ sha?: string;
49
+ }
50
+
51
+ /**
52
+ * Normalize a GitHub URL to owner/repo format.
53
+ * Returns null if the input is not a recognized GitHub URL.
54
+ *
55
+ * Supports:
56
+ * - https://github.com/owner/repo
57
+ * - https://github.com/owner/repo.git
58
+ * - git@github.com:owner/repo.git
59
+ */
60
+ function normalizeGitHubUrl(input: string): string | null {
61
+ // HTTPS URL: https://github.com/owner/repo or https://github.com/owner/repo.git
62
+ const httpsMatch = input.match(/^https?:\/\/github\.com\/([^/]+)\/([^/@]+?)(?:\.git)?$/);
63
+ if (httpsMatch) {
64
+ return `${httpsMatch[1]}/${httpsMatch[2]}`;
65
+ }
66
+
67
+ // SSH URL: git@github.com:owner/repo.git
68
+ const sshMatch = input.match(/^git@github\.com:([^/]+)\/([^/@]+?)(?:\.git)?$/);
69
+ if (sshMatch) {
70
+ return `${sshMatch[1]}/${sshMatch[2]}`;
71
+ }
72
+
73
+ return null;
74
+ }
75
+
76
+ /**
77
+ * Parse a remote reference string into its components.
78
+ * Supports formats:
79
+ * - "owner/repo" or "owner/repo@sha"
80
+ * - "https://github.com/owner/repo" or "https://github.com/owner/repo@sha"
81
+ * - "https://github.com/owner/repo.git" or "https://github.com/owner/repo.git@sha"
82
+ * - "git@github.com:owner/repo.git" or "git@github.com:owner/repo.git@sha"
83
+ */
84
+ export function parseRemoteRef(ref: string): ParsedRemoteRef {
85
+ let inputRef = ref;
86
+ let sha: string | undefined;
87
+
88
+ // Extract SHA suffix from the input before URL normalization.
89
+ // The SHA is always at the end, after a @ that follows the repo name.
90
+ // For git@github.com URLs, we need to find the @ after the colon.
91
+ if (ref.startsWith('git@')) {
92
+ const colonIndex = ref.indexOf(':');
93
+ if (colonIndex !== -1) {
94
+ const afterColon = ref.slice(colonIndex + 1);
95
+ const shaAtIndex = afterColon.lastIndexOf('@');
96
+ if (shaAtIndex !== -1) {
97
+ sha = afterColon.slice(shaAtIndex + 1);
98
+ inputRef = ref.slice(0, colonIndex + 1 + shaAtIndex);
99
+ }
100
+ }
101
+ } else {
102
+ const lastAtIndex = ref.lastIndexOf('@');
103
+ if (lastAtIndex !== -1) {
104
+ const potentialSha = ref.slice(lastAtIndex + 1);
105
+ // SHA should not contain : or / (those would indicate URL structure)
106
+ if (!potentialSha.includes(':') && !potentialSha.includes('/')) {
107
+ if (!potentialSha) {
108
+ throw new SkillLoaderError(`Invalid remote ref: ${ref} (empty SHA after @)`);
109
+ }
110
+ sha = potentialSha;
111
+ inputRef = ref.slice(0, lastAtIndex);
112
+ }
113
+ }
114
+ }
115
+
116
+ // Normalize GitHub URLs to owner/repo format
117
+ const repoPath = normalizeGitHubUrl(inputRef) ?? inputRef;
118
+
119
+ const slashIndex = repoPath.indexOf('/');
120
+ if (slashIndex === -1) {
121
+ throw new SkillLoaderError(`Invalid remote ref: ${ref} (expected owner/repo format)`);
122
+ }
123
+
124
+ const owner = repoPath.slice(0, slashIndex);
125
+ const repo = repoPath.slice(slashIndex + 1);
126
+
127
+ if (!owner || !repo) {
128
+ throw new SkillLoaderError(`Invalid remote ref: ${ref} (empty owner or repo)`);
129
+ }
130
+
131
+ if (repo.includes('/')) {
132
+ throw new SkillLoaderError(`Invalid remote ref: ${ref} (repo name cannot contain /)`);
133
+ }
134
+
135
+ // Security: Prevent git flag injection by rejecting values starting with '-'
136
+ if (owner.startsWith('-')) {
137
+ throw new SkillLoaderError(`Invalid remote ref: ${ref} (owner cannot start with -)`);
138
+ }
139
+ if (repo.startsWith('-')) {
140
+ throw new SkillLoaderError(`Invalid remote ref: ${ref} (repo cannot start with -)`);
141
+ }
142
+ if (sha?.startsWith('-')) {
143
+ throw new SkillLoaderError(`Invalid remote ref: ${ref} (SHA cannot start with -)`);
144
+ }
145
+
146
+ return { owner, repo, sha };
147
+ }
148
+
149
+ /**
150
+ * Format a parsed remote ref back to string format.
151
+ */
152
+ export function formatRemoteRef(parsed: ParsedRemoteRef): string {
153
+ const base = `${parsed.owner}/${parsed.repo}`;
154
+ return parsed.sha ? `${base}@${parsed.sha}` : base;
155
+ }
156
+
157
+ /**
158
+ * Get the base directory for caching remote skills.
159
+ * Respects WARDEN_STATE_DIR environment variable.
160
+ * Default: ~/.local/warden/skills/
161
+ */
162
+ export function getSkillsCacheDir(): string {
163
+ const stateDir = process.env['WARDEN_STATE_DIR'];
164
+ if (stateDir) {
165
+ return join(stateDir, 'skills');
166
+ }
167
+ return join(homedir(), '.local', 'warden', 'skills');
168
+ }
169
+
170
+ /**
171
+ * Get the cache path for a specific remote ref.
172
+ * - Unpinned: ~/.local/warden/skills/owner/repo/
173
+ * - Pinned: ~/.local/warden/skills/owner/repo@sha/
174
+ */
175
+ export function getRemotePath(ref: string): string {
176
+ const parsed = parseRemoteRef(ref);
177
+ const cacheDir = getSkillsCacheDir();
178
+
179
+ if (parsed.sha) {
180
+ return join(cacheDir, parsed.owner, `${parsed.repo}@${parsed.sha}`);
181
+ }
182
+ return join(cacheDir, parsed.owner, parsed.repo);
183
+ }
184
+
185
+ /**
186
+ * Get the path to the state.json file.
187
+ */
188
+ export function getStatePath(): string {
189
+ return join(getSkillsCacheDir(), 'state.json');
190
+ }
191
+
192
+ /**
193
+ * Load the remote state from state.json.
194
+ * Returns an empty state if the file doesn't exist.
195
+ */
196
+ export function loadState(): RemoteState {
197
+ const statePath = getStatePath();
198
+
199
+ if (!existsSync(statePath)) {
200
+ return { remotes: {} };
201
+ }
202
+
203
+ try {
204
+ const content = readFileSync(statePath, 'utf-8');
205
+ const data = JSON.parse(content);
206
+ return RemoteStateSchema.parse(data);
207
+ } catch (error) {
208
+ // If state is corrupted, start fresh
209
+ const message = error instanceof Error ? error.message : String(error);
210
+ console.warn(`Warning: Failed to load state.json, starting fresh: ${message}`);
211
+ return { remotes: {} };
212
+ }
213
+ }
214
+
215
+ /**
216
+ * Save the remote state to state.json.
217
+ * Uses atomic write (write to temp, then rename).
218
+ */
219
+ export function saveState(state: RemoteState): void {
220
+ const statePath = getStatePath();
221
+ const stateDir = dirname(statePath);
222
+
223
+ // Ensure directory exists
224
+ if (!existsSync(stateDir)) {
225
+ mkdirSync(stateDir, { recursive: true });
226
+ }
227
+
228
+ // Write atomically
229
+ const tempPath = `${statePath}.tmp`;
230
+ writeFileSync(tempPath, JSON.stringify(state, null, 2), 'utf-8');
231
+
232
+ // Rename is atomic on most filesystems
233
+ renameSync(tempPath, statePath);
234
+ }
235
+
236
+ /**
237
+ * Get the TTL for remote skill cache in seconds.
238
+ * Respects WARDEN_SKILL_CACHE_TTL environment variable.
239
+ */
240
+ export function getCacheTtlSeconds(): number {
241
+ const envTtl = process.env['WARDEN_SKILL_CACHE_TTL'];
242
+ if (envTtl) {
243
+ const parsed = parseInt(envTtl, 10);
244
+ if (!isNaN(parsed) && parsed > 0) {
245
+ return parsed;
246
+ }
247
+ }
248
+ return DEFAULT_TTL_SECONDS;
249
+ }
250
+
251
+ /**
252
+ * Check if an unpinned remote ref needs to be refreshed.
253
+ * Pinned refs (with @sha) never need refresh.
254
+ */
255
+ export function shouldRefresh(ref: string, state: RemoteState): boolean {
256
+ const parsed = parseRemoteRef(ref);
257
+
258
+ // Pinned refs are immutable - never refresh
259
+ if (parsed.sha) {
260
+ return false;
261
+ }
262
+
263
+ const entry = state.remotes[ref];
264
+ if (!entry) {
265
+ return true; // Not cached, needs fetch
266
+ }
267
+
268
+ const fetchedAt = new Date(entry.fetchedAt).getTime();
269
+ const now = Date.now();
270
+ const ttl = getCacheTtlSeconds() * 1000;
271
+
272
+ return now - fetchedAt > ttl;
273
+ }
274
+
275
+ export interface FetchRemoteOptions {
276
+ /** Force refresh even if cache is valid */
277
+ force?: boolean;
278
+ /** Skip network operations - only use cache */
279
+ offline?: boolean;
280
+ /** Callback for progress messages */
281
+ onProgress?: (message: string) => void;
282
+ }
283
+
284
+ /**
285
+ * Execute a git command and return stdout.
286
+ * Uses execFileSync to avoid shell injection vulnerabilities.
287
+ * Throws SkillLoaderError on failure.
288
+ */
289
+ function execGit(args: string[], options?: { cwd?: string }): string {
290
+ try {
291
+ return execFileSync('git', args, {
292
+ encoding: 'utf-8',
293
+ cwd: options?.cwd,
294
+ stdio: ['pipe', 'pipe', 'pipe'],
295
+ }).trim();
296
+ } catch (error) {
297
+ const message = error instanceof Error ? error.message : String(error);
298
+ throw new SkillLoaderError(`Git command failed: git ${args.join(' ')}: ${message}`);
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Clone or update a remote repository to the cache.
304
+ * Returns the SHA of the fetched commit.
305
+ */
306
+ export async function fetchRemote(ref: string, options: FetchRemoteOptions = {}): Promise<string> {
307
+ const { force = false, offline = false, onProgress } = options;
308
+ const parsed = parseRemoteRef(ref);
309
+ const remotePath = getRemotePath(ref);
310
+ const state = loadState();
311
+
312
+ const isPinned = !!parsed.sha;
313
+ const isCached = existsSync(remotePath);
314
+ const needsRefresh = shouldRefresh(ref, state);
315
+
316
+ // Check if we have a valid cache (directory exists AND state entry exists)
317
+ const stateEntry = state.remotes[ref];
318
+ const hasValidCache = isCached && !!stateEntry;
319
+
320
+ // Handle offline mode
321
+ if (offline) {
322
+ if (hasValidCache) {
323
+ return stateEntry.sha;
324
+ }
325
+ throw new SkillLoaderError(`Remote skill not cached and offline mode enabled: ${ref}`);
326
+ }
327
+
328
+ // Pinned + valid cache = use cache (SHA is immutable)
329
+ if (isPinned && hasValidCache && !force && parsed.sha) {
330
+ return parsed.sha;
331
+ }
332
+
333
+ // Unpinned + valid cache + fresh = use cache
334
+ if (!isPinned && hasValidCache && !needsRefresh && !force) {
335
+ return stateEntry.sha;
336
+ }
337
+
338
+ const repoUrl = `https://github.com/${parsed.owner}/${parsed.repo}.git`;
339
+
340
+ // Clone or update
341
+ if (!isCached) {
342
+ onProgress?.(`Cloning ${ref}...`);
343
+
344
+ // Ensure parent directory exists
345
+ const parentDir = dirname(remotePath);
346
+ if (!existsSync(parentDir)) {
347
+ mkdirSync(parentDir, { recursive: true });
348
+ }
349
+
350
+ // Clone with minimal depth for unpinned refs
351
+ // Note: '--' separates flags from positional args to prevent flag injection
352
+ if (isPinned && parsed.sha) {
353
+ // For pinned refs, we need full history to checkout the specific SHA
354
+ // Use a shallow clone then deepen if needed
355
+ execGit(['clone', '--depth=1', '--', repoUrl, remotePath]);
356
+
357
+ try {
358
+ // Try to checkout the pinned SHA
359
+ // Note: 'checkout' without '--' treats arg as ref; with '--' it's a file path
360
+ execGit(['fetch', '--depth=1', 'origin', '--', parsed.sha], { cwd: remotePath });
361
+ execGit(['checkout', parsed.sha], { cwd: remotePath });
362
+ } catch {
363
+ // If SHA not found, do a full fetch and retry
364
+ execGit(['fetch', '--unshallow'], { cwd: remotePath });
365
+ execGit(['checkout', parsed.sha], { cwd: remotePath });
366
+ }
367
+ } else if (!isPinned) {
368
+ // For unpinned refs, shallow clone of default branch
369
+ execGit(['clone', '--depth=1', '--', repoUrl, remotePath]);
370
+ }
371
+ } else {
372
+ // Update existing cache
373
+ onProgress?.(`Updating ${ref}...`);
374
+
375
+ if (!isPinned) {
376
+ // For unpinned refs, pull latest
377
+ execGit(['fetch', '--depth=1', 'origin'], { cwd: remotePath });
378
+ execGit(['reset', '--hard', 'origin/HEAD'], { cwd: remotePath });
379
+ }
380
+ // Pinned refs don't need updates - SHA is immutable
381
+ }
382
+
383
+ // Get the current HEAD SHA
384
+ const sha = execGit(['rev-parse', 'HEAD'], { cwd: remotePath });
385
+
386
+ // Update state
387
+ state.remotes[ref] = {
388
+ sha,
389
+ fetchedAt: new Date().toISOString(),
390
+ };
391
+ saveState(state);
392
+
393
+ return sha;
394
+ }
395
+
396
+ export interface DiscoveredRemoteSkill {
397
+ name: string;
398
+ description: string;
399
+ path: string;
400
+ /** Plugin name for marketplace format skills */
401
+ pluginName?: string;
402
+ }
403
+
404
+ /**
405
+ * Parse marketplace.json from a remote repository if it exists.
406
+ * Returns null if the file doesn't exist or is invalid.
407
+ */
408
+ function parseMarketplaceConfig(remotePath: string): MarketplaceConfig | null {
409
+ const marketplacePath = join(remotePath, '.claude-plugin', 'marketplace.json');
410
+
411
+ if (!existsSync(marketplacePath)) {
412
+ return null;
413
+ }
414
+
415
+ try {
416
+ const content = readFileSync(marketplacePath, 'utf-8');
417
+ const data = JSON.parse(content);
418
+ return MarketplaceConfigSchema.parse(data);
419
+ } catch {
420
+ // Invalid or malformed marketplace.json - fall back to traditional discovery
421
+ return null;
422
+ }
423
+ }
424
+
425
+ /** Directories to search for skills in remote repositories */
426
+ const REMOTE_SKILL_DIRECTORIES = [
427
+ '', // root level
428
+ 'skills', // skills/ subdirectory
429
+ '.warden/skills', // Warden-specific
430
+ '.agents/skills', // General agent skills
431
+ '.claude/skills', // Claude Code skills
432
+ ];
433
+
434
+ /**
435
+ * Discover skills using traditional directory layout.
436
+ * Searches root level, skills/, and conventional skill directories.
437
+ */
438
+ async function discoverTraditionalSkills(remotePath: string): Promise<DiscoveredRemoteSkill[]> {
439
+ const skills: DiscoveredRemoteSkill[] = [];
440
+ const seenNames = new Set<string>();
441
+
442
+ for (const subdir of REMOTE_SKILL_DIRECTORIES) {
443
+ const searchPath = subdir ? join(remotePath, subdir) : remotePath;
444
+ if (!existsSync(searchPath)) continue;
445
+
446
+ const entries = readdirSync(searchPath);
447
+
448
+ for (const entry of entries) {
449
+ if (entry.startsWith('.')) continue;
450
+
451
+ const entryPath = join(searchPath, entry);
452
+ const stat = statSync(entryPath);
453
+
454
+ if (stat.isDirectory()) {
455
+ const skillMdPath = join(entryPath, 'SKILL.md');
456
+ if (existsSync(skillMdPath)) {
457
+ try {
458
+ const skill = await loadSkillFromMarkdown(skillMdPath);
459
+ // First occurrence wins (root takes precedence over skills/)
460
+ if (!seenNames.has(skill.name)) {
461
+ seenNames.add(skill.name);
462
+ skills.push({
463
+ name: skill.name,
464
+ description: skill.description,
465
+ path: entryPath,
466
+ });
467
+ }
468
+ } catch {
469
+ // Skip invalid skill directories
470
+ }
471
+ }
472
+ }
473
+ }
474
+ }
475
+
476
+ return skills;
477
+ }
478
+
479
+ /**
480
+ * Discover skills using marketplace format.
481
+ * Searches plugins/{plugin}/skills/ for each plugin defined in marketplace.json.
482
+ */
483
+ async function discoverMarketplaceSkills(
484
+ remotePath: string,
485
+ config: MarketplaceConfig
486
+ ): Promise<DiscoveredRemoteSkill[]> {
487
+ const skills: DiscoveredRemoteSkill[] = [];
488
+ const seenNames = new Set<string>();
489
+
490
+ for (const plugin of config.plugins) {
491
+ // Resolve plugin source path (e.g., "./plugins/sentry-skills" -> "plugins/sentry-skills")
492
+ const pluginSource = plugin.source.replace(/^\.\//, '');
493
+ const skillsPath = join(remotePath, pluginSource, 'skills');
494
+
495
+ if (!existsSync(skillsPath)) continue;
496
+
497
+ const entries = readdirSync(skillsPath);
498
+
499
+ for (const entry of entries) {
500
+ if (entry.startsWith('.')) continue;
501
+
502
+ const entryPath = join(skillsPath, entry);
503
+ const stat = statSync(entryPath);
504
+
505
+ if (stat.isDirectory()) {
506
+ const skillMdPath = join(entryPath, 'SKILL.md');
507
+ if (existsSync(skillMdPath)) {
508
+ try {
509
+ const skill = await loadSkillFromMarkdown(skillMdPath);
510
+ // First plugin wins for duplicate skill names
511
+ if (!seenNames.has(skill.name)) {
512
+ seenNames.add(skill.name);
513
+ skills.push({
514
+ name: skill.name,
515
+ description: skill.description,
516
+ path: entryPath,
517
+ pluginName: plugin.name,
518
+ });
519
+ }
520
+ } catch {
521
+ // Skip invalid skill directories
522
+ }
523
+ }
524
+ }
525
+ }
526
+ }
527
+
528
+ return skills;
529
+ }
530
+
531
+ /**
532
+ * Discover all skills in a cached remote repository.
533
+ * Detects format and delegates to appropriate discovery function:
534
+ * - If .claude-plugin/marketplace.json exists, uses marketplace discovery
535
+ * - Otherwise, uses traditional discovery (root, skills/, .warden/skills, etc.)
536
+ */
537
+ export async function discoverRemoteSkills(ref: string): Promise<DiscoveredRemoteSkill[]> {
538
+ const remotePath = getRemotePath(ref);
539
+
540
+ if (!existsSync(remotePath)) {
541
+ throw new SkillLoaderError(`Remote not cached: ${ref}. Run fetch first.`);
542
+ }
543
+
544
+ // Check for marketplace format
545
+ const marketplaceConfig = parseMarketplaceConfig(remotePath);
546
+ if (marketplaceConfig) {
547
+ return discoverMarketplaceSkills(remotePath, marketplaceConfig);
548
+ }
549
+
550
+ // Fall back to traditional discovery
551
+ return discoverTraditionalSkills(remotePath);
552
+ }
553
+
554
+ /**
555
+ * Resolve a skill from a remote repository.
556
+ * Ensures the remote is fetched/cached, then loads the skill.
557
+ * Matches by skill name (from SKILL.md), not directory name.
558
+ */
559
+ export async function resolveRemoteSkill(
560
+ ref: string,
561
+ skillName: string,
562
+ options: FetchRemoteOptions = {}
563
+ ): Promise<SkillDefinition> {
564
+ await fetchRemote(ref, options);
565
+
566
+ const availableSkills = await discoverRemoteSkills(ref);
567
+ const match = availableSkills.find((s) => s.name === skillName);
568
+
569
+ if (match) {
570
+ return loadSkillFromMarkdown(join(match.path, 'SKILL.md'));
571
+ }
572
+
573
+ if (availableSkills.length === 0) {
574
+ throw new SkillLoaderError(`No skills found in remote: ${ref}`);
575
+ }
576
+
577
+ throw new SkillLoaderError(
578
+ `Skill '${skillName}' not found in remote: ${ref}. Available skills: ${availableSkills.map((s) => s.name).join(', ')}`
579
+ );
580
+ }
581
+
582
+ /**
583
+ * Remove a remote from the cache.
584
+ */
585
+ export function removeRemote(ref: string): void {
586
+ const remotePath = getRemotePath(ref);
587
+
588
+ if (existsSync(remotePath)) {
589
+ rmSync(remotePath, { recursive: true, force: true });
590
+ }
591
+
592
+ const state = loadState();
593
+ const { [ref]: _removed, ...remainingRemotes } = state.remotes;
594
+ state.remotes = remainingRemotes;
595
+ saveState(state);
596
+ }
597
+
598
+ /**
599
+ * List all cached remotes with their metadata.
600
+ */
601
+ export function listCachedRemotes(): { ref: string; entry: RemoteEntry }[] {
602
+ const state = loadState();
603
+ return Object.entries(state.remotes).map(([ref, entry]) => ({ ref, entry }));
604
+ }