All files / src/skill-builder definition.ts

86.66% Statements 65/75
66.66% Branches 28/42
95% Functions 19/20
86.3% Lines 63/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222              6x 6x 6x 6x 6x           6x                                                 7x       1x       1x       1x 1x               1x 1x 1x       1x 1x     1x 1x     1x       1x       4x       4x       8x         2x 2x                             3x 3x 7x 7x 1x     2x             4x 4x     4x 4x         4x 4x         4x       1x 1x                           1x 1x   1x             1x       18x     18x 40x 36x   4x           66x       66x     106x 287x 287x 132x   155x 40x 40x   115x     115x 115x               66x 66x    
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { parse as parseYaml } from 'yaml';
import { z } from 'zod';
import type { SkillDefinition } from '../config/schema.js';
import { isPathLike, resolvePathTarget } from '../utils/path.js';
 
export const GENERATED_SKILLS_DIR = '.warden/skills';
export const GENERATED_SKILL_DEFINITION_FILE = 'warden.yaml';
export const BUILD_STATE_FILE = 'build-state.json';
const DESCRIPTION_MAX_LENGTH = 88;
const EXISTING_GENERATED_SKILL_DIRS = [
  GENERATED_SKILLS_DIR,
  '.agents/skills',
  '.claude/skills',
] as const;
 
export const GeneratedSkillDefinitionSchema = z.object({
  version: z.literal(1),
  kind: z.literal('generated-skill'),
  name: z.string().min(1),
  prompt: z.string().min(1),
  instructions: z.array(z.string().min(1)).optional(),
  coverage: z.array(z.string().min(1)).optional(),
}).passthrough();
 
export type GeneratedSkillDefinition = z.infer<typeof GeneratedSkillDefinitionSchema>;
 
/** A generated skill target resolved from a CLI name or filesystem path. */
export interface GeneratedSkillTarget {
  displayName: string;
  isPath: boolean;
  rootDir: string;
}
 
export interface GeneratedSkillArtifactFile {
  path: string;
  content: string;
  bytes: number;
}
 
function safePathSegment(value: string): string {
  return value.replace(/[^a-zA-Z0-9._-]/g, '-');
}
 
function firstSentence(value: string): string {
  return value.trim().split(/(?<=[.!?])\s+/)[0] ?? value.trim();
}
 
function normalizeOneLine(value: string): string {
  return value.replace(/\s+/g, ' ').trim();
}
 
function ensureSentenceEnding(value: string): string {
  const trimmed = value.trim().replace(/[,;:]+$/, '');
  return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`;
}
 
function firstClause(value: string): string {
  return value.split(/[,;:]\s+/)[0] ?? value;
}
 
export function inferGeneratedSkillDescription(name: string, prompt: string): string {
  const fallback = `${name}.`;
  const sentence = normalizeOneLine(firstSentence(prompt));
  Iif (!sentence) {
    return fallback;
  }
 
  let description = sentence;
  Iif (description.length > DESCRIPTION_MAX_LENGTH && /[,;:]\s+/.test(description)) {
    description = firstClause(description);
  }
  description = ensureSentenceEnding(description);
  Iif (description.length > DESCRIPTION_MAX_LENGTH) {
    description = `${description.slice(0, DESCRIPTION_MAX_LENGTH - 3).trimEnd()}...`;
  }
  return description;
}
 
function yamlBlock(value: string, indent = '  '): string {
  return value.split('\n').map((line) => `${indent}${line}`).join('\n');
}
 
function getGeneratedSkillsRoot(repoRoot: string): string {
  return join(repoRoot, GENERATED_SKILLS_DIR);
}
 
export function getGeneratedSkillRoot(repoRoot: string, skillName: string): string {
  return join(getGeneratedSkillsRoot(repoRoot), safePathSegment(skillName));
}
 
export function generatedSkillDefinitionRootExists(rootDir: string): boolean {
  return existsSync(join(rootDir, GENERATED_SKILL_DEFINITION_FILE));
}
 
/** Resolve a generated skill CLI target using the shared name and path semantics. */
export function resolveGeneratedSkillTarget(repoRoot: string, target: string): GeneratedSkillTarget {
  Eif (isPathLike(target)) {
    return {
      displayName: target,
      isPath: true,
      rootDir: resolvePathTarget(target, repoRoot),
    };
  }
 
  return {
    displayName: target,
    isPath: false,
    rootDir: resolveGeneratedSkillRoot(repoRoot, target),
  };
}
 
export function resolveGeneratedSkillRoot(repoRoot: string, skillName: string): string {
  const safeName = safePathSegment(skillName);
  for (const dir of EXISTING_GENERATED_SKILL_DIRS) {
    const rootDir = join(repoRoot, dir, safeName);
    if (generatedSkillDefinitionRootExists(rootDir)) {
      return rootDir;
    }
  }
  return getGeneratedSkillRoot(repoRoot, skillName);
}
 
export function loadGeneratedSkillDefinition(rootDir: string): {
  content: string;
  data: GeneratedSkillDefinition;
} {
  const definitionPath = join(rootDir, GENERATED_SKILL_DEFINITION_FILE);
  const content = readFileSync(definitionPath, 'utf-8');
 
  let parsed: unknown;
  try {
    parsed = parseYaml(content);
  } catch (error) {
    throw new Error(`Generated skill definition is not valid YAML: ${definitionPath}`, { cause: error });
  }
 
  const validation = GeneratedSkillDefinitionSchema.safeParse(parsed);
  Iif (!validation.success) {
    throw new Error(`Generated skill definition is invalid: ${validation.error.message}`, {
      cause: validation.error,
    });
  }
  return { content, data: validation.data };
}
 
export function buildGeneratedSkillDefinition(rootDir: string): SkillDefinition {
  const { data } = loadGeneratedSkillDefinition(rootDir);
  return {
    name: data.name,
    description: inferGeneratedSkillDescription(data.name, data.prompt),
    prompt: data.prompt,
    rootDir,
  };
}
 
export function createGeneratedSkillDefinition(args: {
  repoRoot: string;
  name: string;
  prompt: string;
  rootDir?: string;
}): SkillDefinition {
  const rootDir = args.rootDir ?? getGeneratedSkillRoot(args.repoRoot, args.name);
  mkdirSync(rootDir, { recursive: true });
 
  writeFileSync(join(rootDir, GENERATED_SKILL_DEFINITION_FILE), `version: 1
kind: generated-skill
name: ${args.name}
prompt: |-
${yamlBlock(args.prompt.trim())}
`, 'utf-8');
 
  return buildGeneratedSkillDefinition(rootDir);
}
 
export function clearGeneratedSkillArtifacts(rootDir: string): void {
  Iif (!existsSync(rootDir)) {
    return;
  }
  for (const entry of readdirSync(rootDir, { withFileTypes: true })) {
    if (entry.name === GENERATED_SKILL_DEFINITION_FILE || entry.name === BUILD_STATE_FILE) {
      continue;
    }
    rmSync(join(rootDir, entry.name), { recursive: true, force: true });
  }
}
 
/** Read generated runtime artifacts while excluding Warden-owned metadata files. */
export function readGeneratedSkillArtifactFiles(rootDir: string): GeneratedSkillArtifactFile[] {
  Iif (!existsSync(rootDir)) {
    return [];
  }
 
  const files: GeneratedSkillArtifactFile[] = [];
 
  function visit(relativeDir: string): void {
    for (const entry of readdirSync(join(rootDir, relativeDir), { withFileTypes: true })) {
      const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
      if (!relativeDir && (entry.name === GENERATED_SKILL_DEFINITION_FILE || entry.name === BUILD_STATE_FILE)) {
        continue;
      }
      if (entry.isDirectory()) {
        visit(relativePath);
        continue;
      }
      Iif (!entry.isFile()) {
        continue;
      }
      const content = readFileSync(join(rootDir, relativePath), 'utf-8');
      files.push({
        path: relativePath,
        content,
        bytes: Buffer.byteLength(content, 'utf-8'),
      });
    }
  }
 
  visit('');
  return files.sort((a, b) => a.path.localeCompare(b.path));
}