From e73cd907782a8cb909513fae85308e66a2970aa5 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:59:01 -0700 Subject: [PATCH] feat: add project options for skills A skill can ship an options.json file beside its SKILL.md that declares choices, each with a question, the allowed values, and a default. A project records its answers under intent.options in package.json, and intent load appends a Project options section with the recorded choices and the defaults for the rest. intent validate checks the file. Intent reads options.json as data and runs no package code. A skill without the file loads unchanged. --- .changeset/skill-project-options.md | 5 + docs/cli/intent-load.md | 1 + docs/cli/intent-validate.md | 19 ++ docs/concepts/configuration.md | 45 +++++ packages/intent/src/commands/validate.ts | 10 + packages/intent/src/core/excludes.ts | 4 +- packages/intent/src/core/intent-core.ts | 118 ++++++++---- packages/intent/src/core/skill-options.ts | 134 +++++++++++++ packages/intent/tests/cli.test.ts | 48 +++++ packages/intent/tests/core.test.ts | 197 ++++++++++++++++++++ packages/intent/tests/skill-options.test.ts | 52 ++++++ 11 files changed, 597 insertions(+), 36 deletions(-) create mode 100644 .changeset/skill-project-options.md create mode 100644 packages/intent/src/core/skill-options.ts create mode 100644 packages/intent/tests/skill-options.test.ts diff --git a/.changeset/skill-project-options.md b/.changeset/skill-project-options.md new file mode 100644 index 00000000..efaeef30 --- /dev/null +++ b/.changeset/skill-project-options.md @@ -0,0 +1,5 @@ +--- +'@tanstack/intent': patch +--- + +Add project options for skills. A skill can ship an `options.json` file beside its `SKILL.md` that declares choices, each with a question, the allowed values, and a default. A project records its answers under `intent.options` in `package.json`, and `intent load` appends a `## Project options` section with the recorded choices and the defaults for the rest. `intent validate` checks the file. Skills without `options.json` load unchanged. diff --git a/docs/cli/intent-load.md b/docs/cli/intent-load.md index 6e54ecb1..260096b8 100644 --- a/docs/cli/intent-load.md +++ b/docs/cli/intent-load.md @@ -39,6 +39,7 @@ id: intent-load ### Output - Prints raw `SKILL.md` content by default +- Appends a `## Project options` section when the skill ships an `options.json` file; see [Configuration](../concepts/configuration) - Prints the scanner-reported path when `--path` is passed - Prints debug details to stderr when `--debug` is passed diff --git a/docs/cli/intent-validate.md b/docs/cli/intent-validate.md index 80e22886..53341c4c 100644 --- a/docs/cli/intent-validate.md +++ b/docs/cli/intent-validate.md @@ -143,6 +143,25 @@ A skill without reference files needs no `references` key. A skill without a tre Upgrade impact: a repository that already has reference files fails validation when a reference file is not linked directly from its `SKILL.md`, begins with frontmatter, or contains a code example that does not typecheck, or when a matching `skill_tree.yaml` entry does not list the skill's reference files. +### Options file + +A skill can ship an `options.json` file beside its `SKILL.md` to declare choices that a consuming project records in [`intent.options`](../concepts/configuration). When the file exists, it is checked with its skill. + +```json +{ + "framework": { + "question": "Which framework does this app use?", + "choices": ["nextjs", "tanstack-start", "other"], + "default": "other" + } +} +``` + +- The file is a JSON object; each key is an option name +- `question` is a non-empty string +- `choices` is a non-empty array of non-empty strings +- `default` is one of `choices`; it applies when a project has not recorded a choice + ### Artifacts When `/_artifacts` exists, Intent also checks: diff --git a/docs/concepts/configuration.md b/docs/concepts/configuration.md index 9717ed47..f6d45932 100644 --- a/docs/concepts/configuration.md +++ b/docs/concepts/configuration.md @@ -7,6 +7,7 @@ Configure Intent in the `intent` object in `package.json`: - **`skills`** permits packages or individual skills. - **`exclude`** blocks packages or skills after permissions are evaluated. +- **`options`** records this project's choices for skills that declare options. ```json { @@ -28,6 +29,7 @@ Configure Intent in the `intent` object in `package.json`: | --- | --- | | `intent.skills` | Uses the nearest non-null declaration between the current directory and the workspace or project root. A nearer declaration replaces its parent; omitted or null values inherit. | | `intent.exclude` | Combines arrays from the root through the current directory, then adds excludes passed by the caller. | +| `intent.options` | Merges each skill's choices from the root through the current directory. A nearer package replaces a single choice and inherits the rest. | ## `intent.skills` @@ -164,3 +166,46 @@ Use `intent exclude` to manage this list from the CLI: | `@scope/pkg#*` | The whole package, using the `#*` shortcut. | Each segment supports exact names and `*` wildcards only. Excludes apply to both npm and workspace sources with matching names, regardless of source kind. + +## `intent.options` + +Some skills give different guidance depending on choices your project has made, such as which framework it uses. A skill declares those choices in an `options.json` file beside its `SKILL.md`. `intent.options` records your project's answers, so every agent session loads the skill with the same choices. + +```json +{ + "intent": { + "options": { + "@acme/client#setup": { + "framework": "tanstack-start" + } + } + } +} +``` + +Each key is a skill in `#` form. Each value maps an option name to one of the choices the skill declares. + +When a skill has an `options.json` file, `intent load` appends a `## Project options` section to its content. The section lists each recorded choice. For an option you have not recorded, it lists the skill's default with the question and the available choices: + +```text +## Project options + +Choices this project made for `@acme/client#setup`, from `intent.options` in `package.json`. Follow the guidance that matches them. + +- framework: tanstack-start +- fragmentColocation: yes (default, not recorded). Set up fragment colocation? Choices: yes, no. +``` + +Intent reads `options.json` as data. It does not run code from the package. A skill without `options.json` loads unchanged, even when `intent.options` has an entry for it. + +### Option warnings + +`intent load` prints a warning on stderr and continues in these cases: + +| Situation | Result | +| --- | --- | +| A recorded value is not one of the declared choices | The skill's default applies. | +| A recorded option is not declared by the skill | The entry is ignored. | +| The skill's `options.json` is invalid or links outside its package | The skill loads without the section. | + +Maintainers can find the file format under [Options file](../cli/intent-validate#options-file). diff --git a/packages/intent/src/commands/validate.ts b/packages/intent/src/commands/validate.ts index 14de2889..06866f68 100644 --- a/packages/intent/src/commands/validate.ts +++ b/packages/intent/src/commands/validate.ts @@ -10,6 +10,7 @@ import { parseDocument, parse as parseYaml } from 'yaml' import { fail, isCliFailure } from '../shared/cli-error.js' import { readScalarField } from '../shared/utils.js' import { resolveProjectContext } from '../core/project-context.js' +import { SKILL_OPTIONS_FILE, parseSkillOptions } from '../core/skill-options.js' import { findWorkspacePackages } from '../setup/workspace-patterns.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { @@ -629,6 +630,15 @@ async function runValidateCommandInternal( const skillDir = dirname(filePath) const skillName = basename(skillDir) + const optionsPath = join(skillDir, SKILL_OPTIONS_FILE) + if (existsSync(optionsPath)) { + const file = relative(process.cwd(), optionsPath) + for (const message of parseSkillOptions( + readFileSync(optionsPath, 'utf8'), + ).errors) { + errors.push({ file, message }) + } + } const referenceFiles = findReferenceFiles(skillDir) const linked = new Set( referenceFiles.length diff --git a/packages/intent/src/core/excludes.ts b/packages/intent/src/core/excludes.ts index aaa74bf4..94a8a8d9 100644 --- a/packages/intent/src/core/excludes.ts +++ b/packages/intent/src/core/excludes.ts @@ -150,8 +150,8 @@ export function isPackageExcluded( ) } -// A prefixed skill is loadable by its short alias too; an exclude must match either form. -function skillNameVariants( +// A prefixed skill is loadable by its short alias too; config keyed by skill must match either form. +export function skillNameVariants( packageName: string, skillName: string, ): Array { diff --git a/packages/intent/src/core/intent-core.ts b/packages/intent/src/core/intent-core.ts index a84402c2..ce2d81b0 100644 --- a/packages/intent/src/core/intent-core.ts +++ b/packages/intent/src/core/intent-core.ts @@ -1,4 +1,4 @@ -import { isAbsolute, relative, resolve } from 'node:path' +import { dirname, isAbsolute, join, relative, resolve } from 'node:path' import { createIntentFsCache } from '../discovery/fs-cache.js' import { ResolveSkillUseError, resolveSkillUse } from '../skills/resolver.js' import { formatSkillUse, parseSkillUse } from '../skills/use.js' @@ -9,6 +9,11 @@ import { import { rewriteLoadedSkillMarkdownDestinations } from './markdown.js' import { resolveSkillUseFastPath } from './load-resolution.js' import { resolveProjectContext } from './project-context.js' +import { + SKILL_OPTIONS_FILE, + appendProjectOptions, + readRecordedOptions, +} from './skill-options.js' import { checkLoadAllowed, isSourcePermitted, @@ -20,6 +25,7 @@ import type { ResolveSkillResult } from '../skills/resolver.js' import type { IntentFsCache } from '../discovery/fs-cache.js' import type { ReadFs } from '../shared/utils.js' import type { ScanOptions, ScanScope } from '../shared/types.js' +import type { ProjectContext } from './project-context.js' import type { IntentCoreErrorCode, IntentCoreOptions, @@ -267,6 +273,8 @@ function resolveIntentSkillInCwd( use: string, options: IntentCoreOptions = {}, ): { + fsCache: IntentFsCache + projectContext: ProjectContext realPackageRoot: string realResolvedPath: string readFs: ReadFs @@ -318,22 +326,26 @@ function resolveIntentSkillInCwd( const lateRefusal = packageNotListedRefusal(use, parsedUse.packageName) throw new IntentCoreError(lateRefusal.code, lateRefusal.message) } - return toResolvedIntentSkill( - cwd, - use, - fastPathResolved, - fsCache.getReadFs(), - options.debug - ? createLoadedSkillDebug({ - cwd, - excludes: excludePatterns, - resolution: 'fast-path', - resolved: fastPathResolved, - scan: fsCache.getStats(), - scope, - }) - : undefined, - ) + return { + fsCache, + projectContext, + ...toResolvedIntentSkill( + cwd, + use, + fastPathResolved, + fsCache.getReadFs(), + options.debug + ? createLoadedSkillDebug({ + cwd, + excludes: excludePatterns, + resolution: 'fast-path', + resolved: fastPathResolved, + scan: fsCache.getStats(), + scope, + }) + : undefined, + ), + } } const { scan: scanResult, droppedNames } = scanForPolicedIntents({ @@ -358,22 +370,26 @@ function resolveIntentSkillInCwd( throw err } - return toResolvedIntentSkill( - cwd, - use, - resolved, - fsCache.getReadFs(), - options.debug - ? createLoadedSkillDebug({ - cwd, - excludes: excludePatterns, - resolution: 'full-scan', - resolved, - scan: scanResult.stats, - scope, - }) - : undefined, - ) + return { + fsCache, + projectContext, + ...toResolvedIntentSkill( + cwd, + use, + resolved, + fsCache.getReadFs(), + options.debug + ? createLoadedSkillDebug({ + cwd, + excludes: excludePatterns, + resolution: 'full-scan', + resolved, + scan: scanResult.stats, + scope, + }) + : undefined, + ), + } } export function resolveIntentSkill( @@ -395,9 +411,43 @@ export function loadIntentSkill( packageRoot: resolved.realPackageRoot, skillFilePath: resolved.realResolvedPath, }) + const optionsFile = join( + dirname(resolved.realResolvedPath), + SKILL_OPTIONS_FILE, + ) + if (!resolved.readFs.existsSync(optionsFile)) { + return { ...resolved.result, content } + } + + const optionsPath = resolved.readFs.realpathSync.native(optionsFile) + const { packageName, skillName } = resolved.result + const skillUse = formatSkillUse(packageName, skillName) + const projectOptions = isResolvedPathInsidePackageRoot( + optionsPath, + resolved.realPackageRoot, + ) + ? appendProjectOptions( + content, + resolved.readFs.readFileSync(optionsPath, 'utf8'), + skillUse, + readRecordedOptions( + cwd, + resolved.projectContext, + resolved.fsCache, + packageName, + skillName, + ), + ) + : { + content, + warnings: [ + `Ignored ${SKILL_OPTIONS_FILE} for "${skillUse}": the file is outside the package`, + ], + } return { ...resolved.result, - content, + content: projectOptions.content, + warnings: [...resolved.result.warnings, ...projectOptions.warnings], } } diff --git a/packages/intent/src/core/skill-options.ts b/packages/intent/src/core/skill-options.ts new file mode 100644 index 00000000..c8dd4432 --- /dev/null +++ b/packages/intent/src/core/skill-options.ts @@ -0,0 +1,134 @@ +import { formatSkillUse } from '../skills/use.js' +import { getConfigDirs, skillNameVariants } from './excludes.js' +import { readPackageJson } from './package-json.js' +import type { IntentFsCache } from '../discovery/fs-cache.js' +import type { ProjectContext } from './project-context.js' + +export const SKILL_OPTIONS_FILE = 'options.json' + +interface SkillOption { + question: string + choices: Array + default: string +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function isText(value: unknown): value is string { + return typeof value === 'string' && value.trim() !== '' +} + +function optionProblem(value: unknown): string | undefined { + if (!isRecord(value)) return 'must be an object' + if (!isText(value.question)) return '"question" must be a non-empty string' + if ( + !Array.isArray(value.choices) || + value.choices.length === 0 || + !value.choices.every(isText) + ) { + return '"choices" must be a non-empty array of non-empty strings' + } + if ( + typeof value.default !== 'string' || + !value.choices.includes(value.default) + ) { + return '"default" must be one of "choices"' + } + return undefined +} + +export function parseSkillOptions(text: string): { + options: Array<[string, SkillOption]> + errors: Array +} { + let parsed: unknown + try { + parsed = JSON.parse(text) + } catch { + return { options: [], errors: ['Invalid JSON'] } + } + if (!isRecord(parsed)) { + return { options: [], errors: ['Expected a JSON object of options'] } + } + + const options: Array<[string, SkillOption]> = [] + const errors: Array = [] + for (const [name, value] of Object.entries(parsed)) { + const problem = optionProblem(value) + if (problem) errors.push(`Option "${name}": ${problem}`) + else options.push([name, value as SkillOption]) + } + return { options, errors } +} + +export function readRecordedOptions( + cwd: string, + context: ProjectContext, + fsCache: IntentFsCache, + packageName: string, + skillName: string, +): Record { + const keys = skillNameVariants(packageName, skillName).map((name) => + formatSkillUse(packageName, name), + ) + const recorded: Record = {} + + for (const dir of getConfigDirs(cwd, context).reverse()) { + const intent = readPackageJson(dir, fsCache)?.intent + const options = isRecord(intent) ? intent.options : undefined + if (!isRecord(options)) continue + for (const key of keys) { + if (isRecord(options[key])) Object.assign(recorded, options[key]) + } + } + + return recorded +} + +export function appendProjectOptions( + content: string, + optionsText: string, + use: string, + recorded: Record, +): { content: string; warnings: Array } { + const { options, errors } = parseSkillOptions(optionsText) + if (errors.length > 0) { + return { + content, + warnings: [ + `Ignored ${SKILL_OPTIONS_FILE} for "${use}": ${errors.join('; ')}`, + ], + } + } + if (options.length === 0) return { content, warnings: [] } + + const warnings: Array = [] + const declared = new Set(options.map(([name]) => name)) + for (const name of Object.keys(recorded)) { + if (!declared.has(name)) { + warnings.push( + `intent.options for "${use}": "${name}" is not an option of this skill.`, + ) + } + } + + const lines = options.map(([name, option]) => { + const value = recorded[name] + if (typeof value === 'string' && option.choices.includes(value)) { + return `- ${name}: ${value}` + } + if (value !== undefined) { + warnings.push( + `intent.options for "${use}": "${name}" is ${JSON.stringify(value)}, which is not one of: ${option.choices.join(', ')}. Using the default.`, + ) + } + return `- ${name}: ${option.default} (default, not recorded). ${option.question} Choices: ${option.choices.join(', ')}.` + }) + + return { + content: `${content.trimEnd()}\n\n## Project options\n\nChoices this project made for \`${use}\`, from \`intent.options\` in \`package.json\`. Follow the guidance that matches them.\n\n${lines.join('\n')}\n`, + warnings, + } +} diff --git a/packages/intent/tests/cli.test.ts b/packages/intent/tests/cli.test.ts index 9e6510f9..2c07d334 100644 --- a/packages/intent/tests/cli.test.ts +++ b/packages/intent/tests/cli.test.ts @@ -3892,6 +3892,54 @@ describe('cli commands', () => { }) }) + describe('validate options file', () => { + function writeOptionsFixture(options: unknown): void { + const root = mkdtempSync(join(realTmpdir, 'intent-cli-validate-options-')) + tempDirs.push(root) + writeJson(join(root, 'package.json'), { + name: '@acme/library', + devDependencies: { '@tanstack/intent': '^0.0.18' }, + keywords: ['tanstack-intent'], + files: ['skills'], + }) + const skillDir = join(root, 'skills', 'core') + mkdirSync(skillDir, { recursive: true }) + writeFileSync( + join(skillDir, 'SKILL.md'), + '---\nname: core\ndescription: Core guidance\n---\n\nGuide.\n', + ) + writeJson(join(skillDir, 'options.json'), options) + process.chdir(root) + } + + it('rejects an option whose default is not one of its choices', async () => { + writeOptionsFixture({ + framework: { + question: 'Which framework does this app use?', + choices: ['nextjs', 'other'], + default: 'remix', + }, + }) + + expect(await main(['validate'])).toBe(1) + expect(errorSpy.mock.calls.flat().join('\n')).toContain( + `${join('skills', 'core', 'options.json')}: Option "framework": "default" must be one of "choices"`, + ) + }) + + it('accepts a well-formed options file', async () => { + writeOptionsFixture({ + framework: { + question: 'Which framework does this app use?', + choices: ['nextjs', 'other'], + default: 'other', + }, + }) + + expect(await main(['validate'])).toBe(0) + }) + }) + it('skips cleanly when validate is run without a skills directory', async () => { const root = mkdtempSync(join(realTmpdir, 'intent-cli-missing-skills-')) tempDirs.push(root) diff --git a/packages/intent/tests/core.test.ts b/packages/intent/tests/core.test.ts index 6be0edde..4a935bd2 100644 --- a/packages/intent/tests/core.test.ts +++ b/packages/intent/tests/core.test.ts @@ -1306,3 +1306,200 @@ describe('loadIntentSkill — kind-mismatch late gate', () => { ) }) }) + +describe('loadIntentSkill — project options', () => { + const use = '@apollo/client#apollo-client' + const options = { + framework: { + question: 'Which framework does this app use?', + choices: ['nextjs', 'tanstack-start', 'other'], + default: 'other', + }, + fragmentColocation: { + question: 'Set up fragment colocation?', + choices: ['yes', 'no'], + default: 'yes', + }, + } + + function writeApolloSkill(optionsFile?: string): string { + const skillDir = join( + root, + 'node_modules', + '@apollo', + 'client', + 'skills', + 'apollo-client', + ) + writeInstalledIntentPackage(root, { + name: '@apollo/client', + version: '4.0.0', + skillName: 'apollo-client', + description: 'Apollo Client guidance', + }) + if (optionsFile !== undefined) { + writeFileSync(join(skillDir, 'options.json'), optionsFile) + } + return skillDir + } + + it('appends recorded choices and defaults to the loaded content', () => { + writeApolloSkill(JSON.stringify(options)) + writeJson(join(root, 'package.json'), { + name: 'app', + intent: { options: { [use]: { framework: 'tanstack-start' } } }, + }) + + const result = loadIntentSkill(use, { cwd: root }) + + expect(result.content).toBe( + [ + '---', + 'name: "apollo-client"', + 'description: "Apollo Client guidance"', + '---', + '', + 'Skill content here.', + '', + '## Project options', + '', + 'Choices this project made for `@apollo/client#apollo-client`, from `intent.options` in `package.json`. Follow the guidance that matches them.', + '', + '- framework: tanstack-start', + '- fragmentColocation: yes (default, not recorded). Set up fragment colocation? Choices: yes, no.', + '', + ].join('\n'), + ) + expect(result.warnings).toEqual([]) + }) + + it('lets the nearest workspace package override a recorded choice', () => { + const appDir = join(root, 'packages', 'app') + writeApolloSkill(JSON.stringify(options)) + writeJson(join(root, 'package.json'), { + name: 'monorepo', + private: true, + workspaces: ['packages/*'], + intent: { + options: { [use]: { framework: 'nextjs', fragmentColocation: 'no' } }, + }, + }) + writeJson(join(appDir, 'package.json'), { + name: 'app', + intent: { options: { [use]: { framework: 'tanstack-start' } } }, + }) + + const { content } = loadIntentSkill(use, { cwd: appDir }) + + expect(content).toContain('- framework: tanstack-start\n') + expect(content).toContain('- fragmentColocation: no\n') + }) + + it('reads choices recorded under the short skill name', () => { + const pkgDir = join(root, 'node_modules', '@apollo', 'client') + writeJson(join(pkgDir, 'package.json'), { + name: '@apollo/client', + version: '4.0.0', + intent: { + version: 1, + repo: 'apollographql/apollo-client', + docs: 'docs/', + }, + }) + writeSkillMd({ + dir: join(pkgDir, 'skills', 'client', 'setup'), + frontmatter: { name: 'setup', description: 'Apollo Client setup' }, + }) + writeJson( + join(pkgDir, 'skills', 'client', 'setup', 'options.json'), + options, + ) + writeJson(join(root, 'package.json'), { + name: 'app', + intent: { + options: { '@apollo/client#setup': { framework: 'nextjs' } }, + }, + }) + + const { content } = loadIntentSkill('@apollo/client#setup', { cwd: root }) + + expect(content).toContain('for `@apollo/client#client/setup`') + expect(content).toContain('- framework: nextjs\n') + }) + + it('uses the default and warns when a recorded choice is not declared', () => { + writeApolloSkill(JSON.stringify(options)) + writeJson(join(root, 'package.json'), { + name: 'app', + intent: { options: { [use]: { framework: 'remix' } } }, + }) + + const result = loadIntentSkill(use, { cwd: root }) + + expect(result.content).toContain( + '- framework: other (default, not recorded).', + ) + expect(result.warnings).toEqual([ + 'intent.options for "@apollo/client#apollo-client": "framework" is "remix", which is not one of: nextjs, tanstack-start, other. Using the default.', + ]) + }) + + it('warns about a recorded option the skill does not declare', () => { + writeApolloSkill(JSON.stringify(options)) + writeJson(join(root, 'package.json'), { + name: 'app', + intent: { options: { [use]: { codegen: 'client-preset' } } }, + }) + + const result = loadIntentSkill(use, { cwd: root }) + + expect(result.content).not.toContain('codegen') + expect(result.warnings).toEqual([ + 'intent.options for "@apollo/client#apollo-client": "codegen" is not an option of this skill.', + ]) + }) + + it('loads the skill without options and warns when the options file is invalid', () => { + writeApolloSkill( + JSON.stringify({ framework: { question: 'Which framework?' } }), + ) + + const result = loadIntentSkill(use, { cwd: root }) + + expect(result.content).not.toContain('Project options') + expect(result.warnings).toEqual([ + 'Ignored options.json for "@apollo/client#apollo-client": Option "framework": "choices" must be a non-empty array of non-empty strings', + ]) + }) + + it('ignores an options file that links outside the package', () => { + const skillDir = writeApolloSkill() + writeJson(join(root, 'outside', 'options.json'), options) + symlinkSync( + join(root, 'outside', 'options.json'), + join(skillDir, 'options.json'), + ) + + const result = loadIntentSkill(use, { cwd: root }) + + expect(result.content).not.toContain('Project options') + expect(result.warnings).toEqual([ + 'Ignored options.json for "@apollo/client#apollo-client": the file is outside the package', + ]) + }) + + it('returns the skill file unchanged when it has no options file', () => { + writeApolloSkill() + writeJson(join(root, 'package.json'), { + name: 'app', + intent: { options: { [use]: { framework: 'nextjs' } } }, + }) + + const result = loadIntentSkill(use, { cwd: root }) + + expect(result.content).toBe( + '---\nname: "apollo-client"\ndescription: "Apollo Client guidance"\n---\n\nSkill content here.\n', + ) + expect(result.warnings).toEqual([]) + }) +}) diff --git a/packages/intent/tests/skill-options.test.ts b/packages/intent/tests/skill-options.test.ts new file mode 100644 index 00000000..94d17105 --- /dev/null +++ b/packages/intent/tests/skill-options.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it } from 'vitest' +import { parseSkillOptions } from '../src/core/skill-options.js' + +describe('parseSkillOptions', () => { + it('returns declared options in file order', () => { + const framework = { + question: 'Which framework?', + choices: ['nextjs', 'other'], + default: 'other', + } + const masking = { + question: 'Use data masking?', + choices: ['yes', 'no'], + default: 'no', + } + + expect(parseSkillOptions(JSON.stringify({ framework, masking }))).toEqual({ + options: [ + ['framework', framework], + ['masking', masking], + ], + errors: [], + }) + }) + + it.each([ + ['text that is not JSON', '{', 'Invalid JSON'], + ['a root that is not an object', '[]', 'Expected a JSON object of options'], + [ + 'an option that is not an object', + '{"framework":"nextjs"}', + 'Option "framework": must be an object', + ], + [ + 'an option without a question', + '{"framework":{"choices":["a"],"default":"a"}}', + 'Option "framework": "question" must be a non-empty string', + ], + [ + 'an option with an empty choice', + '{"framework":{"question":"Which?","choices":["a",""],"default":"a"}}', + 'Option "framework": "choices" must be a non-empty array of non-empty strings', + ], + [ + 'an option without a default', + '{"framework":{"question":"Which?","choices":["a"]}}', + 'Option "framework": "default" must be one of "choices"', + ], + ])('rejects %s', (_case, text, error) => { + expect(parseSkillOptions(text)).toEqual({ options: [], errors: [error] }) + }) +})