From 6b560ccdc1bfa253626f480dbc6dbc7bafda617b Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:42:53 -0700 Subject: [PATCH 01/12] refactor: remove dead code, duplicate helpers, and comments Delete helpers and exports that nothing calls, share one copy of isRecord, errorMessage, stringArray, and isWithinOrEqual, and drop comments that restate the code. Command output, exit codes, and the public API stay as they are. Tests of the deleted exports go with them. One test is new: validate reads a tracked type entry of a workspace package that is its own git repository. --- packages/intent/src/cli.ts | 2 +- packages/intent/src/commands/exclude.ts | 22 +- .../intent/src/commands/install/command.ts | 34 +-- .../intent/src/commands/install/guidance.ts | 11 +- .../commands/install/permission-prompts.ts | 6 +- .../src/commands/install/permissions.ts | 8 +- packages/intent/src/commands/list.ts | 42 +--- packages/intent/src/commands/load.ts | 29 +-- packages/intent/src/commands/maintainer.ts | 82 ++----- packages/intent/src/commands/meta.ts | 18 +- packages/intent/src/commands/repair.ts | 12 +- packages/intent/src/commands/review.ts | 14 +- packages/intent/src/commands/stale.ts | 43 ++-- packages/intent/src/commands/support.ts | 37 +-- packages/intent/src/commands/validate.ts | 109 ++++---- packages/intent/src/core/excludes.ts | 19 +- packages/intent/src/core/intent-core.ts | 72 ++---- packages/intent/src/core/load-resolution.ts | 50 +--- packages/intent/src/core/markdown.ts | 6 +- packages/intent/src/core/package-json.ts | 3 +- packages/intent/src/core/project-context.ts | 8 +- packages/intent/src/core/skill-sources.ts | 14 +- packages/intent/src/core/source-policy.ts | 30 +-- packages/intent/src/core/types.ts | 18 -- packages/intent/src/discovery/fs-cache.ts | 5 +- .../intent/src/discovery/package-manager.ts | 20 +- packages/intent/src/discovery/register.ts | 7 +- packages/intent/src/discovery/scanner.ts | 158 +++--------- packages/intent/src/hooks/agents/claude.ts | 25 -- packages/intent/src/hooks/agents/codex.ts | 25 -- packages/intent/src/hooks/agents/copilot.ts | 19 -- packages/intent/src/hooks/install.ts | 129 +++------- packages/intent/src/hooks/policy.ts | 76 +----- packages/intent/src/hooks/types.ts | 14 -- packages/intent/src/maintainer/add.ts | 11 +- .../intent/src/maintainer/distribution.ts | 38 +-- packages/intent/src/maintainer/existing.ts | 18 +- packages/intent/src/maintainer/project.ts | 11 +- packages/intent/src/maintainer/sync.ts | 12 +- packages/intent/src/review/review.ts | 120 ++++----- packages/intent/src/setup/project-setup.ts | 232 ++++++------------ .../intent/src/setup/workspace-patterns.ts | 46 +--- packages/intent/src/shared/display.ts | 12 +- packages/intent/src/shared/types.ts | 13 +- packages/intent/src/shared/utils.ts | 115 ++++----- packages/intent/src/skills/paths.ts | 4 - packages/intent/src/skills/resolver.ts | 6 +- packages/intent/src/skills/use.ts | 4 + .../intent/src/staleness/artifact-coverage.ts | 25 +- packages/intent/src/staleness/check.ts | 72 +----- packages/intent/src/validate/blocks.ts | 201 +++++++++------ packages/intent/src/validate/repairs.ts | 9 +- packages/intent/tests/core-types.test.ts | 45 ---- packages/intent/tests/hooks.test.ts | 93 +------ packages/intent/tests/skill-paths.test.ts | 19 -- packages/intent/tests/skill-sources.test.ts | 3 +- packages/intent/tests/validate-blocks.test.ts | 59 +++++ .../intent/tests/workspace-patterns.test.ts | 8 - 58 files changed, 760 insertions(+), 1583 deletions(-) delete mode 100644 packages/intent/src/hooks/agents/claude.ts delete mode 100644 packages/intent/src/hooks/agents/codex.ts delete mode 100644 packages/intent/src/hooks/agents/copilot.ts delete mode 100644 packages/intent/tests/core-types.test.ts diff --git a/packages/intent/src/cli.ts b/packages/intent/src/cli.ts index 9c52251f..a575b862 100644 --- a/packages/intent/src/cli.ts +++ b/packages/intent/src/cli.ts @@ -100,7 +100,7 @@ function createCli( import('./commands/support.js'), import('./commands/meta.js'), ]) - await runMetaCommand(name, getMetaDir()) + runMetaCommand(name, getMetaDir()) }) cli diff --git a/packages/intent/src/commands/exclude.ts b/packages/intent/src/commands/exclude.ts index 503d573b..f7bce0ca 100644 --- a/packages/intent/src/commands/exclude.ts +++ b/packages/intent/src/commands/exclude.ts @@ -1,6 +1,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { fail } from '../shared/cli-error.js' +import { errorMessage } from '../shared/utils.js' import { compileExcludePatterns } from '../core/excludes.js' export interface ExcludeCommandOptions { @@ -16,12 +17,8 @@ function normalizeAction(action: string | undefined): ExcludeAction { fail(`Unknown exclude action: ${action}. Expected list, add, or remove.`) } -function getPackageJsonPath(cwd: string): string { - return join(cwd, 'package.json') -} - function readPackageJson(cwd: string): Record { - const packageJsonPath = getPackageJsonPath(cwd) + const packageJsonPath = join(cwd, 'package.json') if (!existsSync(packageJsonPath)) { fail(`No package.json found in ${cwd}`) } @@ -32,9 +29,7 @@ function readPackageJson(cwd: string): Record { unknown > } catch (err) { - fail( - `Failed to parse ${packageJsonPath}: ${err instanceof Error ? err.message : String(err)}`, - ) + fail(`Failed to parse ${packageJsonPath}: ${errorMessage(err)}`) } } @@ -77,8 +72,11 @@ function setConfiguredExcludes( } function writePackageJson(cwd: string, pkg: Record): void { - const packageJsonPath = getPackageJsonPath(cwd) - writeFileSync(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8') + writeFileSync( + join(cwd, 'package.json'), + `${JSON.stringify(pkg, null, 2)}\n`, + 'utf8', + ) } function normalizePattern( @@ -103,9 +101,7 @@ function validatePattern(pattern: string): void { try { compileExcludePatterns([pattern]) } catch (err) { - fail( - `Invalid exclude pattern "${pattern}": ${err instanceof Error ? err.message : String(err)}`, - ) + fail(`Invalid exclude pattern "${pattern}": ${errorMessage(err)}`) } } diff --git a/packages/intent/src/commands/install/command.ts b/packages/intent/src/commands/install/command.ts index 2072c425..e867eaf6 100644 --- a/packages/intent/src/commands/install/command.ts +++ b/packages/intent/src/commands/install/command.ts @@ -7,6 +7,7 @@ import { } from '../../shared/command-runner.js' import { coreOptionsFromGlobalFlags, + failureMessage, noticeOptionsFromGlobalFlags, printNotices, printWarnings, @@ -23,7 +24,7 @@ import { setupInitialPermissions } from './permissions.js' import type { GlobalScanFlags } from '../support.js' import type { IntentCoreOptions } from '../../core/index.js' import type { ScanResult } from '../../shared/types.js' -import type { PermissionPrompts } from './permissions.js' +import type { PermissionPrompts, PermissionSetupResult } from './permissions.js' export const INSTALL_PROMPT = `You are an AI assistant helping a developer set up skill-to-task mappings for their project. @@ -289,9 +290,7 @@ export async function runInstallCommand( if (!options.map) { const policy = readSkillSourcesConfig(process.cwd()) - let permissions: Awaited< - ReturnType - > | null = null + let permissions: PermissionSetupResult | null = null if (policy.mode === 'absent' || options.review) { const isTTY = runtime.isTTY ?? process.stdin.isTTY === true @@ -307,7 +306,6 @@ export async function runInstallCommand( review: options.review, root: process.cwd(), runtime: { - // Loaded on demand: @clack/prompts is only needed when prompting. prompts: runtime.permissionPrompts ?? ( @@ -316,11 +314,7 @@ export async function runInstallCommand( }, }) } catch (error) { - const message = - error && typeof error === 'object' && 'message' in error - ? String(error.message) - : String(error) - fail(`Permissions: failed: ${message}`) + fail(`Permissions: failed: ${failureMessage(error)}`) } if ( permissions.status === 'canceled' || @@ -334,9 +328,8 @@ export async function runInstallCommand( ) } - const generated = buildIntentSkillGuidanceBlock( - detectIntentCommandPackageManager(), - ) + const packageManager = detectIntentCommandPackageManager() + const generated = buildIntentSkillGuidanceBlock(packageManager) if (options.dryRun) { const targetPath = resolveIntentSkillsBlockTargetPath(process.cwd(), 1) @@ -379,9 +372,8 @@ export async function runInstallCommand( console.log(`Guidance: ${result.status} ${target}.`) } else { printWriteResult(result) - } - if (!permissions) console.log('To change permissions, run intent install --review.') + } printPlacementTip(result.targetPath) if (permissions && (available || permissions.available)) { const packages = @@ -394,22 +386,14 @@ export async function runInstallCommand( `Available: ${skillCount} ${skillCount === 1 ? 'skill' : 'skills'} from ${packageCount} ${packageCount === 1 ? 'package' : 'packages'}.`, ) if (skillCount > 0) { - console.log( - `Next: ${formatIntentCommand(detectIntentCommandPackageManager(), 'list')}`, - ) + console.log(`Next: ${formatIntentCommand(packageManager, 'list')}`) } else { console.log('To change permissions, run intent install --review.') } } return } catch (error) { - if (permissions) { - const message = - error && typeof error === 'object' && 'message' in error - ? String(error.message) - : String(error) - fail(`Guidance: failed: ${message}`) - } + if (permissions) fail(`Guidance: failed: ${failureMessage(error)}`) throw error } } diff --git a/packages/intent/src/commands/install/guidance.ts b/packages/intent/src/commands/install/guidance.ts index 7d4ff4cb..3a9372f7 100644 --- a/packages/intent/src/commands/install/guidance.ts +++ b/packages/intent/src/commands/install/guidance.ts @@ -3,6 +3,7 @@ import { join } from 'node:path' import { parse as parseYaml } from 'yaml' import { formatIntentCommand } from '../../shared/command-runner.js' import { repositoryWritePath } from '../../shared/write-path.js' +import { errorMessage } from '../../shared/utils.js' import { writeChanges } from '../../maintainer/files.js' import { parseIntentInvocation } from '../../hooks/policy.js' import { isGeneratedMappingSkill } from '../../skills/categories.js' @@ -128,9 +129,7 @@ function parseSkillsList(block: string): { return { errors: [], mappings: parsed.tanstackIntent } } catch (err) { return { - errors: [ - `Managed block contains invalid YAML: ${err instanceof Error ? err.message : String(err)}`, - ], + errors: [`Managed block contains invalid YAML: ${errorMessage(err)}`], mappings: [], } } @@ -229,7 +228,7 @@ export function verifyIntentSkillsBlockFile({ try { parsedId = parseSkillUse(mapping.id) } catch (err) { - errors.push(err instanceof Error ? err.message : String(err)) + errors.push(errorMessage(err)) } if (containsLocalPathValue(mapping.id)) { @@ -464,7 +463,9 @@ export function planIntentSkillsBlock({ } const existingTarget = findExistingConfigWithManagedBlock(root, namespace) - const targetPath = resolveIntentSkillsBlockTargetPath(root, 1, namespace)! + const targetPath = + existingTarget?.filePath ?? + resolveIntentSkillsBlockTargetPath(root, 1, namespace)! if (existingTarget) { const nextContent = replaceManagedBlock( diff --git a/packages/intent/src/commands/install/permission-prompts.ts b/packages/intent/src/commands/install/permission-prompts.ts index 2f7642ed..47edee37 100644 --- a/packages/intent/src/commands/install/permission-prompts.ts +++ b/packages/intent/src/commands/install/permission-prompts.ts @@ -36,7 +36,6 @@ export function createPermissionPrompts( }, ): PermissionPrompts { const io = { input: stdin, output: stdout } - // Let Clack own search, scrolling, terminal sizing, and keyboard controls. const picker = { ...io, maxItems: 6 } const searchablePicker = { ...picker, @@ -215,8 +214,7 @@ export function createPermissionPrompts( parsed.mode === 'allow-all' && !selection.skills.includes('*') ) const source = parsed.sources[0]! - if (source.kind === 'git' || 'pattern' in source) - return !selection.skills.includes('*') + if ('pattern' in source) return !selection.skills.includes('*') // A collection of exact skills does not grant future package skills. return ( !policy.matchers.some( @@ -421,7 +419,7 @@ export function createPermissionPrompts( const config = parseSkillSources([rule]) if (config.mode !== 'explicit') return true const source = config.sources[0]! - if (source.kind === 'git' || 'pattern' in source) return true + if ('pattern' in source) return true const id = `${source.kind === 'workspace' ? 'workspace:' : ''}${source.id}#${source.skill}` // Keep undiscovered and excluded rules, and preserve unchanged raw entries. if (reviewedIds.has(id) && !selected.has(id)) return false diff --git a/packages/intent/src/commands/install/permissions.ts b/packages/intent/src/commands/install/permissions.ts index 4637aff1..3602c601 100644 --- a/packages/intent/src/commands/install/permissions.ts +++ b/packages/intent/src/commands/install/permissions.ts @@ -130,7 +130,7 @@ function normalizePermissions(selected: Array): Array { const config = parseSkillSources([value]) if (config.mode !== 'explicit') return true const source = config.sources[0]! - if (source.kind === 'git' || 'pattern' in source) return true + if ('pattern' in source) return true const others = parseSkillSources( values.filter( (other) => @@ -340,9 +340,9 @@ export async function setupInitialPermissions({ status: unchanged ? 'unchanged' : writePreparedPackageSkillsUpdate(update), - ...(review - ? { available: { skills: enabled.length, packages: packageCount } } - : {}), + available: review + ? { skills: enabled.length, packages: packageCount } + : undefined, } } } diff --git a/packages/intent/src/commands/list.ts b/packages/intent/src/commands/list.ts index f5d4201a..2a04ef87 100644 --- a/packages/intent/src/commands/list.ts +++ b/packages/intent/src/commands/list.ts @@ -9,12 +9,7 @@ import { printWarnings, } from './support.js' import type { GlobalScanFlags } from './support.js' -import type { - IntentPackageSummary, - IntentSkillList, - IntentSkillSummary, -} from '../core/index.js' -import type { ScanResult } from '../shared/types.js' +import type { IntentSkillList, IntentSkillSummary } from '../core/index.js' export interface ListCommandOptions extends GlobalScanFlags { json?: boolean @@ -74,25 +69,6 @@ function groupSkillsByPackageRoot( return grouped } -function getPackageSkills( - pkg: IntentPackageSummary, - skillsByPackageRoot: Map>, -): Array { - return skillsByPackageRoot.get(pkg.packageRoot) ?? [] -} - -function formatLoadCommand( - skill: IntentSkillSummary, - packageManager: ScanResult['packageManager'], - scopeFlag: string, -): string { - return formatIntentCommand(packageManager, [ - 'load', - `${skill.packageName}#${skill.skillName}`, - ...(scopeFlag ? [scopeFlag.trim()] : []), - ]) -} - function printHiddenSources(result: IntentSkillList, audience: string): void { if (audience === 'agent') { console.log( @@ -168,7 +144,7 @@ export async function runListCommand( const skillsByPackageRoot = groupSkillsByPackageRoot(result.skills) const allSkills = result.packages.map((pkg) => - getPackageSkills(pkg, skillsByPackageRoot).map((skill) => ({ + (skillsByPackageRoot.get(pkg.packageRoot) ?? []).map((skill) => ({ name: skill.skillName, description: skill.description, type: skill.type, @@ -177,19 +153,23 @@ export async function runListCommand( const nameWidth = computeSkillNameWidth(allSkills) const showTypes = result.skills.some((skill) => skill.type) const scopeFlag = options.globalOnly - ? ' --global-only' + ? '--global-only' : options.global - ? ' --global' - : '' + ? '--global' + : undefined console.log(`\nSkills:\n`) for (const pkg of result.packages) { console.log(` ${pkg.name}`) printSkillTree( - getPackageSkills(pkg, skillsByPackageRoot).map((skill) => ({ + (skillsByPackageRoot.get(pkg.packageRoot) ?? []).map((skill) => ({ name: skill.skillName, description: skill.description, - loadCommand: formatLoadCommand(skill, result.packageManager, scopeFlag), + loadCommand: formatIntentCommand(result.packageManager, [ + 'load', + `${skill.packageName}#${skill.skillName}`, + ...(scopeFlag ? [scopeFlag] : []), + ]), type: skill.type, })), { nameWidth, packageName: pkg.name, showTypes }, diff --git a/packages/intent/src/commands/load.ts b/packages/intent/src/commands/load.ts index a0160416..8991b1d6 100644 --- a/packages/intent/src/commands/load.ts +++ b/packages/intent/src/commands/load.ts @@ -32,6 +32,15 @@ function printLoadDebug(loaded: LoadedIntentSkill | ResolvedIntentSkill): void { ]) } +function orFail(run: () => T): T { + try { + return run() + } catch (err) { + if (err instanceof IntentCoreError) fail(err.message) + throw err + } +} + export function runLoadCommand( use: string | undefined, options: LoadCommandOptions, @@ -47,15 +56,7 @@ export function runLoadCommand( const coreOptions = coreOptionsFromGlobalFlags(options) if (options.path) { - let resolved: ResolvedIntentSkill - try { - resolved = resolveIntentSkill(use, coreOptions) - } catch (err) { - if (err instanceof IntentCoreError) { - fail(err.message) - } - throw err - } + const resolved = orFail(() => resolveIntentSkill(use, coreOptions)) printLoadDebug(resolved) console.log(resolved.path) @@ -65,15 +66,7 @@ export function runLoadCommand( return } - let loaded: LoadedIntentSkill - try { - loaded = loadIntentSkill(use, coreOptions) - } catch (err) { - if (err instanceof IntentCoreError) { - fail(err.message) - } - throw err - } + const loaded = orFail(() => loadIntentSkill(use, coreOptions)) printLoadDebug(loaded) if (options.json) { diff --git a/packages/intent/src/commands/maintainer.ts b/packages/intent/src/commands/maintainer.ts index 71370e5e..5499b6a2 100644 --- a/packages/intent/src/commands/maintainer.ts +++ b/packages/intent/src/commands/maintainer.ts @@ -4,6 +4,7 @@ import { isCI } from 'std-env' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { fail } from '../shared/cli-error.js' +import { errorMessage } from '../shared/utils.js' import { planSetupRecords, readRecord, @@ -35,14 +36,7 @@ export interface MaintainerCommandRuntime { reviewPrompts?: ReviewPrompts } -interface MaintainerAction { - usage: string - summary: string - writes: string - options: Array<[flag: string, description: string]> -} - -const optionHelp: Record = { +const optionHelp = { artifacts: [ '--artifacts ', 'Planning record directory, relative to the repository root', @@ -86,6 +80,15 @@ const optionHelp: Record = { '--github-summary', 'Write a GitHub Actions step summary when GITHUB_STEP_SUMMARY is set', ], +} satisfies Record + +type MaintainerOption = keyof typeof optionHelp + +interface MaintainerAction { + usage: string + summary: string + writes: string + options: Array } // Ordered as a maintainer runs them. `maintainer --help` prints this table and @@ -97,13 +100,7 @@ export const maintainerActions: Record = { 'Initialize planning records, register existing skills, install agent instructions and CI.', writes: 'skill_tree.yaml, domain_map.yaml, skill_spec.md (registering any SKILL.md under skills/ that is not yet recorded), the intent-maintainer block in AGENTS.md (or the existing agent instruction file), and .github/workflows/check-skills.yml when it does not exist.', - options: [ - 'artifacts', - 'distribution', - 'repository', - 'pluginName', - 'skill', - ].map((key) => optionHelp[key]!), + options: ['artifacts', 'distribution', 'repository', 'pluginName', 'skill'], }, add: { usage: @@ -120,20 +117,20 @@ export const maintainerActions: Record = { 'source', 'requires', 'task', - ].map((key) => optionHelp[key]!), + ], }, remove: { usage: 'maintainer remove [--package ]', summary: 'Retire a registered skill without deleting its guidance.', writes: 'The entry status in skill_tree.yaml and a note in skill_spec.md. Delete the SKILL.md yourself once its guidance is no longer needed.', - options: ['artifacts', 'package'].map((key) => optionHelp[key]!), + options: ['artifacts', 'package'], }, status: { usage: 'maintainer status [--json] [--base ]', summary: 'Report authoring gaps, files to sync, and pending reviews.', writes: 'Nothing.', - options: ['artifacts', 'base', 'json'].map((key) => optionHelp[key]!), + options: ['artifacts', 'base', 'json'], }, sync: { usage: 'maintainer sync', @@ -141,30 +138,21 @@ export const maintainerActions: Record = { 'Align the skill tree and package metadata with SKILL.md frontmatter.', writes: 'skill_tree.yaml, package.json keywords and files, and generated distribution files when repository distribution is selected.', - options: ['artifacts'].map((key) => optionHelp[key]!), + options: ['artifacts'], }, review: { usage: 'maintainer review [--unchanged | --updated | --json | --interactive | --record ] [--base ]', summary: 'Find guidance affected by Git changes and record outcomes.', writes: '.intent/review-state.json when recording; nothing otherwise.', - options: [ - 'base', - 'unchanged', - 'updated', - 'json', - 'record', - 'interactive', - ].map((key) => optionHelp[key]!), + options: ['base', 'unchanged', 'updated', 'json', 'record', 'interactive'], }, check: { usage: 'maintainer check [--base ] [--github-summary]', summary: 'Fail when authoring issues, stale generated files, or pending reviews remain.', writes: 'Nothing. Use it as the CI gate.', - options: ['artifacts', 'base', 'githubSummary'].map( - (key) => optionHelp[key]!, - ), + options: ['artifacts', 'base', 'githubSummary'], }, } @@ -187,8 +175,10 @@ export function maintainerHelp(action?: string): string { lines.push(` Writes: ${entry.writes}`) if (action) { lines.push('', 'Options:') - for (const [flag, description] of entry.options) + for (const key of entry.options) { + const [flag, description] = optionHelp[key] lines.push(` ${flag.padEnd(28)} ${description}`) + } } else lines.push('') } if (!action) @@ -241,32 +231,16 @@ export async function runMaintainerCommand( options: MaintainerCommandOptions, runtime: MaintainerCommandRuntime = {}, ): Promise { - const allowed: Record> = { - setup: ['artifacts', 'distribution', 'repository', 'pluginName', 'skill'], - add: [ - 'artifacts', - 'package', - 'path', - 'domain', - 'description', - 'source', - 'requires', - 'task', - ], - remove: ['artifacts', 'package'], - status: ['artifacts', 'base', 'json'], - sync: ['artifacts'], - review: ['base', 'json', 'record', 'interactive', 'unchanged', 'updated'], - check: ['artifacts', 'base', 'githubSummary'], - } - if (!allowed[action]) + const allowed: ReadonlyArray | undefined = + maintainerActions[action]?.options + if (!allowed) fail( `Unknown maintainer action: ${action}. Expected setup, add, remove, status, sync, review, or check.`, ) if (name !== undefined && action !== 'add' && action !== 'remove') fail(`maintainer ${action} does not take a skill name.`) for (const key of Object.keys(options)) { - if (key !== '--' && !allowed[action].includes(key)) + if (key !== '--' && !allowed.includes(key)) fail( `--${kebab(key)} is not supported by maintainer ${action}. Run intent maintainer ${action} --help for its options.`, ) @@ -302,7 +276,7 @@ export async function runMaintainerCommand( ) console.log(`Recorded ${count} review outcome(s) as ${oneShot}.`) } catch (error) { - fail(error instanceof Error ? error.message : String(error)) + fail(errorMessage(error)) } return } @@ -354,9 +328,7 @@ export async function runMaintainerCommand( // setup has no --domain flag to point the maintainer at. candidate.problems.push( candidate.domain.trim() - ? error instanceof Error - ? error.message - : String(error) + ? errorMessage(error) : `Set a non-empty domain for ${candidate.name} in ${project.artifacts}/domain_map.yaml, then run intent maintainer setup again.`, ) }, diff --git a/packages/intent/src/commands/meta.ts b/packages/intent/src/commands/meta.ts index 1090ef90..c351bab9 100644 --- a/packages/intent/src/commands/meta.ts +++ b/packages/intent/src/commands/meta.ts @@ -1,12 +1,13 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs' import { dirname, join } from 'node:path' import { fail } from '../shared/cli-error.js' +import { errorMessage, parseFrontmatter } from '../shared/utils.js' import { rewriteLoadedSkillMarkdownDestinations } from '../core/markdown.js' -export async function runMetaCommand( +export function runMetaCommand( name: string | undefined, metaDir: string, -): Promise { +): void { if (!existsSync(metaDir)) { fail('Meta-skills directory not found.') } @@ -33,17 +34,19 @@ export async function runMetaCommand( }), ) } catch (err) { - const msg = err instanceof Error ? err.message : String(err) - fail(`Failed to read meta-skill "${name}": ${msg}`) + fail(`Failed to read meta-skill "${name}": ${errorMessage(err)}`) } return } - const { parseFrontmatter } = await import('../shared/utils.js') const entries = readdirSync(metaDir, { withFileTypes: true }) .filter((entry) => entry.isDirectory()) - .filter((entry) => existsSync(join(metaDir, entry.name, 'SKILL.md'))) + .map((entry) => ({ + name: entry.name, + skillFile: join(metaDir, entry.name, 'SKILL.md'), + })) + .filter((entry) => existsSync(entry.skillFile)) if (entries.length === 0) { console.log('No meta-skills found.') @@ -53,8 +56,7 @@ export async function runMetaCommand( console.log('Meta-skills (for library maintainers):\n') for (const entry of entries) { - const skillFile = join(metaDir, entry.name, 'SKILL.md') - const fm = parseFrontmatter(skillFile) + const fm = parseFrontmatter(entry.skillFile) let description = '' if (typeof fm?.description === 'string') { description = fm.description.replace(/\s+/g, ' ').trim() diff --git a/packages/intent/src/commands/repair.ts b/packages/intent/src/commands/repair.ts index 79a3db86..8551dbfb 100644 --- a/packages/intent/src/commands/repair.ts +++ b/packages/intent/src/commands/repair.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync } from 'node:fs' -import { relative, resolve } from 'node:path' +import { relative } from 'node:path' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { writeChanges } from '../maintainer/files.js' @@ -8,7 +8,7 @@ import { repositoryWritePath } from '../shared/write-path.js' import { renderRepairPatch } from '../shared/patch.js' import { planExampleRepairs } from '../validate/blocks.js' import { planFrontmatterRepair } from '../validate/repairs.js' -import { collectDefaultSkillsDirs } from './validate.js' +import { collectDefaultSkillsDirs, resolveSkillsDir } from './validate.js' import type { FileChange } from '../maintainer/files.js' export interface RepairCommandOptions { @@ -30,13 +30,7 @@ export async function runRepairCommand( const directories = dir === undefined ? collectDefaultSkillsDirs(context, findSkillFiles, fsCache) - : [ - resolveProjectContext({ - cwd: process.cwd(), - targetPath: dir, - fsCache, - }).targetSkillsDir ?? resolve(dir), - ] + : [resolveSkillsDir(dir, fsCache)] if (dir !== undefined && !existsSync(directories[0]!)) fail(`Skills directory not found: ${dir}`) const paths = [...new Set(directories.flatMap(findSkillFiles))] diff --git a/packages/intent/src/commands/review.ts b/packages/intent/src/commands/review.ts index ed866e7e..c7bad0e1 100644 --- a/packages/intent/src/commands/review.ts +++ b/packages/intent/src/commands/review.ts @@ -2,6 +2,7 @@ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { createReview, recordReview } from '../review/review.js' import { fail, isCliFailure } from '../shared/cli-error.js' +import { errorMessage, isRecord } from '../shared/utils.js' import { writeStaleReviewWorkflowFiles } from '../staleness/workflow-review.js' export interface ReviewCommandOptions { @@ -34,12 +35,9 @@ export function runReviewCommand( const input: unknown = JSON.parse( readFileSync(resolve(options.record), 'utf8'), ) - if ( - typeof input === 'object' && - input !== null && - Array.isArray((input as { items?: unknown }).items) - ) { - const items = (input as { items: Array }).items + const items: Array | null = + isRecord(input) && Array.isArray(input.items) ? input.items : null + if (items) { const annotated = items.filter( (item) => typeof item === 'object' && @@ -121,7 +119,7 @@ export function runReviewCommand( type: 'review-check-failed', library: options.packageLabel ?? 'workspace', subject: 'intent review', - reasons: [error instanceof Error ? error.message : String(error)], + reasons: [errorMessage(error)], }, ]) console.log( @@ -129,6 +127,6 @@ export function runReviewCommand( ) return } - fail(error instanceof Error ? error.message : String(error)) + fail(errorMessage(error)) } } diff --git a/packages/intent/src/commands/stale.ts b/packages/intent/src/commands/stale.ts index ccdb637a..986b0b7a 100644 --- a/packages/intent/src/commands/stale.ts +++ b/packages/intent/src/commands/stale.ts @@ -10,11 +10,11 @@ import { compileSkillSourcePolicy, readSkillSourcesConfig, } from '../core/source-policy.js' -import { isCliFailure } from '../shared/cli-error.js' import { detectIntentCommandPackageManager, formatIntentCommand, } from '../shared/command-runner.js' +import { failureMessage } from './support.js' import type { IntentFsCache } from '../discovery/fs-cache.js' import type { StalenessReport } from '../shared/types.js' @@ -24,16 +24,18 @@ export interface StaleCommandOptions { packageLabel?: string } +type StaleTargetResolver = ( + targetDir?: string, + fsCache?: IntentFsCache, +) => Promise<{ + reports: Array + workflowAdvisories?: Array +}> + export async function runStaleCommand( targetDir: string | undefined, options: StaleCommandOptions, - resolveStaleTargets: ( - targetDir?: string, - fsCache?: IntentFsCache, - ) => Promise<{ - reports: Array - workflowAdvisories?: Array - }>, + resolveStaleTargets: StaleTargetResolver, ): Promise { if (options.githubReview) { await runGithubReview(targetDir, options, resolveStaleTargets) @@ -62,6 +64,7 @@ export async function runStaleCommand( return } + let needsReview = false for (const report of reports) { const driftLabel = report.versionDrift ? ` [${report.versionDrift} drift]` @@ -77,6 +80,7 @@ export async function runStaleCommand( if (stale.length === 0 && signals.length === 0) { console.log(' All skills up-to-date') } else { + needsReview = true for (const skill of stale) { console.log(` ⚠ ${skill.name}: ${skill.reasons.join(', ')}`) } @@ -99,13 +103,7 @@ export async function runStaleCommand( console.log() } - if ( - reports.some( - (report) => - report.skills.some((skill) => skill.needsReview) || - report.signals.some((signal) => signal.needsReview), - ) - ) { + if (needsReview) { const command = formatIntentCommand( detectIntentCommandPackageManager(targetDir), 'meta generate-skill', @@ -119,13 +117,7 @@ export async function runStaleCommand( async function runGithubReview( targetDir: string | undefined, options: StaleCommandOptions, - resolveStaleTargets: ( - targetDir?: string, - fsCache?: IntentFsCache, - ) => Promise<{ - reports: Array - workflowAdvisories?: Array - }>, + resolveStaleTargets: StaleTargetResolver, ): Promise { const { collectStaleReviewItems, @@ -157,12 +149,7 @@ async function runGithubReview( } catch (err) { const item = createFailedStaleReviewItem(packageLabel) writeStaleReviewWorkflowFiles([item]) - const message = isCliFailure(err) - ? err.message - : err instanceof Error - ? err.message - : String(err) - console.log(`Intent stale check failed: ${message}`) + console.log(`Intent stale check failed: ${failureMessage(err)}`) console.log('Wrote a review PR body so maintainers can inspect the logs.') } } diff --git a/packages/intent/src/commands/support.ts b/packages/intent/src/commands/support.ts index 7500d747..8365edf7 100644 --- a/packages/intent/src/commands/support.ts +++ b/packages/intent/src/commands/support.ts @@ -1,7 +1,8 @@ import { existsSync, readFileSync, statSync } from 'node:fs' import { dirname, join, relative, resolve } from 'node:path' import { fileURLToPath } from 'node:url' -import { fail } from '../shared/cli-error.js' +import { fail, isCliFailure } from '../shared/cli-error.js' +import { errorMessage } from '../shared/utils.js' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { @@ -23,7 +24,6 @@ export interface GlobalScanFlags { global?: boolean globalOnly?: boolean notices?: boolean - noNotices?: boolean } export interface StaleTargetResult { @@ -33,30 +33,21 @@ export interface StaleTargetResult { export const INTENT_CHECK_SKILLS_WORKFLOW_VERSION = 5 +// Startup keeps shared/cli-error.ts free of imports, so this lives with the commands. +export function failureMessage(err: unknown): string { + return isCliFailure(err) ? err.message : errorMessage(err) +} + export function getMetaDir(): string { return findMetaDir(dirname(fileURLToPath(import.meta.url))) } -/** - * Resolve the package `meta/` directory by walking up from `startDir`. - * - * The CLI module sits at `src/commands/` in source but is bundled flat into - * `dist/` in the published package, so the depth from the module to the - * package root differs between the two layouts. A hardcoded `..` count is - * correct for only one of them and breaks `setup` / `meta` / `scaffold` in the - * other. Walking up to the first `meta/` directory handles both layouts (and - * symlinked installs such as pnpm) without depending on the build output - * depth. Falls back to the historical `../../meta` resolution if no `meta/` - * is found, so behaviour is never worse than before. - */ +// Walks up to the first meta/ directory so the same code works from +// src/commands/ and the flat bundled dist/. Falls back to ../../meta. export function findMetaDir(startDir: string): string { let dir = startDir - // Sanity cap: a package is never this many dirs deep; the root check below - // also stops the walk at the filesystem root. for (let limit = 0; limit < 10; limit++) { const candidate = join(dir, 'meta') - // Check it's a directory, not just that something named `meta` exists — a - // stray file named `meta` in an ancestor must not short-circuit the walk. if (existsSync(candidate) && statSync(candidate).isDirectory()) return candidate const parent = dirname(dir) @@ -68,8 +59,6 @@ export function findMetaDir(startDir: string): string { export function getCheckSkillsWorkflowAdvisories(root: string): Array { const workflowPath = join(root, '.github', 'workflows', 'check-skills.yml') - if (!existsSync(workflowPath)) return [] - let content: string try { content = readFileSync(workflowPath, 'utf8') @@ -101,15 +90,11 @@ export async function scanIntentsOrFail( }) return scan } catch (err) { - fail(err instanceof Error ? err.message : String(err)) + fail(errorMessage(err)) } } function scanOptionsFromGlobalFlags(options: GlobalScanFlags): ScanOptions { - if (options.global && options.globalOnly) { - fail('Use either --global or --global-only, not both.') - } - if (options.globalOnly) { return { scope: 'global' } } @@ -138,7 +123,7 @@ export function coreOptionsFromGlobalFlags( export function noticeOptionsFromGlobalFlags(options: GlobalScanFlags): { noNotices?: boolean } { - return { noNotices: options.noNotices || options.notices === false } + return { noNotices: options.notices === false } } function formatDebugValue(value: string | number | Array): string { diff --git a/packages/intent/src/commands/validate.ts b/packages/intent/src/commands/validate.ts index 14de2889..89e06085 100644 --- a/packages/intent/src/commands/validate.ts +++ b/packages/intent/src/commands/validate.ts @@ -7,8 +7,8 @@ import { } from 'node:fs' import { basename, dirname, join, relative, resolve } from 'node:path' import { parseDocument, parse as parseYaml } from 'yaml' -import { fail, isCliFailure } from '../shared/cli-error.js' -import { readScalarField } from '../shared/utils.js' +import { fail } from '../shared/cli-error.js' +import { errorMessage, isRecord, readScalarField } from '../shared/utils.js' import { resolveProjectContext } from '../core/project-context.js' import { findWorkspacePackages } from '../setup/workspace-patterns.js' import { createIntentFsCache } from '../discovery/fs-cache.js' @@ -24,19 +24,14 @@ import { agentSkillNamePattern, planFrontmatterRepair, } from '../validate/repairs.js' -import { printWarnings } from './support.js' +import { failureMessage, printWarnings } from './support.js' import type { SkillBlockCache } from '../validate/blocks.js' import type { IntentFsCache } from '../discovery/fs-cache.js' import type { FileChange } from '../maintainer/files.js' import type { ProjectContext } from '../core/project-context.js' import type { IntentArtifactSkill } from '../shared/types.js' -interface ValidationError { - file: string - message: string -} - -interface ValidationWarning { +interface ValidationIssue { file: string message: string } @@ -81,7 +76,7 @@ function isScalarValue(value: unknown): boolean { } function buildValidationFailure( - errors: Array, + errors: Array, warnings: Array, ): string { const lines = ['', `❌ Validation failed with ${errors.length} error(s):`, ''] @@ -130,11 +125,7 @@ function collectPackagingWarnings( if (pkgResult.error) { const code = (pkgResult.error as NodeJS.ErrnoException).code if (code === 'ENOENT') return [] - const msg = - pkgResult.error instanceof Error - ? pkgResult.error.message - : String(pkgResult.error) - return [`Could not parse package.json: ${msg}`] + return [`Could not parse package.json: ${errorMessage(pkgResult.error)}`] } return [] } @@ -150,11 +141,7 @@ function collectPackagingWarnings( if (!wsResult.packageJson && wsResult.error) { const code = (wsResult.error as NodeJS.ErrnoException).code if (code !== 'ENOENT') { - const msg = - wsResult.error instanceof Error - ? wsResult.error.message - : String(wsResult.error) - return [`Could not parse package.json: ${msg}`] + return [`Could not parse package.json: ${errorMessage(wsResult.error)}`] } } if (wsResult.packageJson) { @@ -267,14 +254,6 @@ function readTreeEntries( return entries } -function formatWarning({ file, message }: ValidationWarning): string { - return `${file}: ${message}` -} - -function isRecord(value: unknown): value is Record { - return !!value && typeof value === 'object' && !Array.isArray(value) -} - function normalizeLineEndings(value: string, lineEnding: string): string { return lineEnding === '\r\n' ? value.replace(/\r?\n/g, '\r\n') : value } @@ -286,7 +265,7 @@ function repairRoot(fsCache?: IntentFsCache): string { function applyFrontmatterFixes( plans: Array, - root = repairRoot(), + root: string, ): void { writeChanges( root, @@ -300,7 +279,7 @@ function applyFrontmatterFixes( function applySetVersion( plans: Array, version: string, - root = repairRoot(), + root: string, ): void { const changes: Array = [] @@ -312,20 +291,14 @@ function applySetVersion( ) if (!match) continue - const openingLineEnding = match[1] - const frontmatter = match[2] - const closingLineEnding = match[3] - const afterClose = match[4] - const body = match[5] - if ( - openingLineEnding === undefined || - frontmatter === undefined || - closingLineEnding === undefined || - afterClose === undefined || - body === undefined - ) { - continue - } + const [ + , + openingLineEnding = '', + frontmatter = '', + closingLineEnding = '', + afterClose = '', + body = '', + ] = match const doc = parseDocument(frontmatter) if (doc.errors.length > 0) continue @@ -348,8 +321,8 @@ function collectAgentSkillSpecWarnings({ }: { fm: Record rel: string -}): Array { - const warnings: Array = [] +}): Array { + const warnings: Array = [] if ( fm.license !== undefined && @@ -437,7 +410,7 @@ export async function runValidateCommand( } catch (err) { writeGithubValidationSummary({ ok: false, - message: validationErrorMessage(err), + message: failureMessage(err), }) throw err } @@ -455,11 +428,7 @@ async function runValidateCommandInternal( // skills roots gets every error in one report and one summary. const explicitDirs = [ ...new Set([...(dir === undefined ? [] : [dir].flat()), ...additionalDirs]), - ].map( - (target) => - resolveProjectContext({ cwd: process.cwd(), targetPath: target, fsCache }) - .targetSkillsDir ?? resolve(process.cwd(), target), - ) + ].map((target) => resolveSkillsDir(target, fsCache)) const skillsDirs = [ ...new Set([ ...(dir === undefined @@ -478,7 +447,7 @@ async function runValidateCommandInternal( if (findSkillFiles(skillsDir).length === 0) fail('No SKILL.md files found') } - const errors: Array = [] + const errors: Array = [] const warnings: Array = [] const skippedBlockChecks = new Set() const blockCache: SkillBlockCache = {} @@ -487,6 +456,7 @@ async function runValidateCommandInternal( let validatedCount = 0 const validatedFiles = new Set() const artifacts = new Map>() + const treeDeclarations = new Map() if (skillsDirs.length === 0) { console.log('No skills/ directory found — skipping validation.') @@ -513,7 +483,15 @@ async function runValidateCommandInternal( }> = [] let treeEntries: Map | undefined const declaresReferences = [skillsDir, validateContext.workspaceRoot].some( - (root) => root && treeDeclaresReferences(root), + (root) => { + if (!root) return false + let declares = treeDeclarations.get(root) + if (declares === undefined) { + declares = treeDeclaresReferences(root) + treeDeclarations.set(root, declares) + } + return declares + }, ) for (const filePath of skillFiles) { const rel = relative(process.cwd(), filePath) @@ -624,7 +602,9 @@ async function runValidateCommandInternal( } warnings.push( - ...collectAgentSkillSpecWarnings({ fm, rel }).map(formatWarning), + ...collectAgentSkillSpecWarnings({ fm, rel }).map( + ({ file, message }) => `${file}: ${message}`, + ), ) const skillDir = dirname(filePath) @@ -809,10 +789,9 @@ async function runValidateCommandInternal( try { parseYaml(content) } catch (err) { - const detail = err instanceof Error ? err.message : String(err) errors.push({ file: relative(process.cwd(), artifactPath), - message: `Invalid YAML in artifact file: ${detail}`, + message: `Invalid YAML in artifact file: ${errorMessage(err)}`, }) } } @@ -886,12 +865,6 @@ async function runValidateCommandInternal( printWarnings(warnings) } -function validationErrorMessage(err: unknown): string { - if (isCliFailure(err)) return err.message - if (err instanceof Error) return err.message - return String(err) -} - function writeGithubValidationSummary({ message, ok, @@ -932,6 +905,16 @@ function writeGithubValidationSummary({ appendFileSync(summaryPath, lines.join('\n')) } +export function resolveSkillsDir( + target: string, + fsCache: IntentFsCache, +): string { + return ( + resolveProjectContext({ cwd: process.cwd(), targetPath: target, fsCache }) + .targetSkillsDir ?? resolve(process.cwd(), target) + ) +} + export function collectDefaultSkillsDirs( context: ProjectContext, findSkillFiles: (dir: string) => Array, diff --git a/packages/intent/src/core/excludes.ts b/packages/intent/src/core/excludes.ts index aaa74bf4..d26db68e 100644 --- a/packages/intent/src/core/excludes.ts +++ b/packages/intent/src/core/excludes.ts @@ -1,4 +1,6 @@ -import { dirname, isAbsolute, relative, resolve } from 'node:path' +import { dirname, resolve } from 'node:path' +import { isRecord, isWithinOrEqual } from '../shared/utils.js' +import { getPackageShortName } from '../skills/use.js' import { resolveProjectContext } from './project-context.js' import { readPackageJson } from './package-json.js' import type { ProjectContext } from './project-context.js' @@ -23,20 +25,12 @@ function normalizeExcludePatterns(value: unknown): Array { .filter(Boolean) } -function isWithinOrEqual(path: string, parentDir: string): boolean { - const rel = relative(parentDir, path) - return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)) -} - function readPackageExcludes( dir: string, fsCache?: IntentFsCache, ): Array { - const pkg = readPackageJson(dir, fsCache) - const intent = pkg?.intent - if (!intent || typeof intent !== 'object') return [] - - return normalizeExcludePatterns((intent as Record).exclude) + const intent = readPackageJson(dir, fsCache)?.intent + return isRecord(intent) ? normalizeExcludePatterns(intent.exclude) : [] } export function getConfigDirs( @@ -155,8 +149,7 @@ function skillNameVariants( packageName: string, skillName: string, ): Array { - const shortName = packageName.split('/').pop() ?? packageName - const prefix = `${shortName}/` + const prefix = `${getPackageShortName(packageName)}/` if (skillName.startsWith(prefix)) { return [skillName, skillName.slice(prefix.length)] } diff --git a/packages/intent/src/core/intent-core.ts b/packages/intent/src/core/intent-core.ts index a84402c2..67c35876 100644 --- a/packages/intent/src/core/intent-core.ts +++ b/packages/intent/src/core/intent-core.ts @@ -1,5 +1,6 @@ -import { isAbsolute, relative, resolve } from 'node:path' +import { resolve } from 'node:path' import { createIntentFsCache } from '../discovery/fs-cache.js' +import { errorMessage, isWithinOrEqual } from '../shared/utils.js' import { ResolveSkillUseError, resolveSkillUse } from '../skills/resolver.js' import { formatSkillUse, parseSkillUse } from '../skills/use.js' import { @@ -17,9 +18,8 @@ import { scanForPolicedIntents, } from './source-policy.js' 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 { ScanScope } from '../shared/types.js' import type { IntentCoreErrorCode, IntentCoreOptions, @@ -60,7 +60,7 @@ export class IntentCoreError extends Error { } } -function toScanOptions(options: IntentCoreOptions): ScanOptions { +function toScanScope(options: IntentCoreOptions): ScanScope { if (options.global && options.globalOnly) { throw new IntentCoreError( 'invalid-options', @@ -68,26 +68,9 @@ function toScanOptions(options: IntentCoreOptions): ScanOptions { ) } - if (options.globalOnly) { - return { scope: 'global' } - } - - if (options.global) { - return { scope: 'local-and-global' } - } - - return { scope: 'local' } -} - -function getScanScope(options: ScanOptions): ScanScope { - return options.scope ?? (options.includeGlobal ? 'local-and-global' : 'local') -} - -function withFsCache( - options: ScanOptions, - fsCache: IntentFsCache, -): ScanOptions & { fsCache: IntentFsCache } { - return { ...options, fsCache } + if (options.globalOnly) return 'global' + if (options.global) return 'local-and-global' + return 'local' } function resolveCoreCwd(options: IntentCoreOptions): string { @@ -98,13 +81,13 @@ export function listIntentSkills( options: IntentCoreOptions = {}, ): IntentSkillList { const cwd = resolveCoreCwd(options) - const scanOptions = toScanOptions(options) + const scope = toScanScope(options) const fsCache = createIntentFsCache() const projectContext = resolveProjectContext({ cwd, fsCache }) const { hiddenSourceCount, hiddenSources, scan, excludePatterns } = scanForPolicedIntents({ cwd, - scanOptions: withFsCache(scanOptions, fsCache), + scanOptions: { scope, fsCache }, coreOptions: options, context: projectContext, }) @@ -146,7 +129,7 @@ export function listIntentSkills( if (options.debug) { result.debug = { cwd, - scope: getScanScope(scanOptions), + scope, excludes: excludePatterns, packageCount: result.packages.length, skillCount: result.skills.length, @@ -160,21 +143,6 @@ export function listIntentSkills( return result } -function resolveFromCwd(cwd: string, path: string): string { - return resolve(cwd, path) -} - -function isResolvedPathInsidePackageRoot( - path: string, - packageRoot: string, -): boolean { - const relativePath = relative(packageRoot, path) - return ( - relativePath === '' || - (!relativePath.startsWith('..') && !isAbsolute(relativePath)) - ) -} - function toResolvedIntentSkill( cwd: string, use: string, @@ -189,9 +157,7 @@ function toResolvedIntentSkill( } { let realResolvedPath: string try { - realResolvedPath = readFs.realpathSync.native( - resolveFromCwd(cwd, resolved.path), - ) + realResolvedPath = readFs.realpathSync.native(resolve(cwd, resolved.path)) } catch { throw new IntentCoreError( 'skill-file-not-found', @@ -199,10 +165,10 @@ function toResolvedIntentSkill( ) } const realPackageRoot = readFs.realpathSync.native( - resolveFromCwd(cwd, resolved.packageRoot), + resolve(cwd, resolved.packageRoot), ) - if (!isResolvedPathInsidePackageRoot(realResolvedPath, realPackageRoot)) { + if (!isWithinOrEqual(realResolvedPath, realPackageRoot)) { throw new IntentCoreError( 'skill-path-outside-package', `Resolved skill path for "${use}" is outside package root: ${resolved.path}`, @@ -276,10 +242,7 @@ function resolveIntentSkillInCwd( try { parsedUse = parseSkillUse(use) } catch (err) { - throw new IntentCoreError( - 'invalid-skill-use', - err instanceof Error ? err.message : String(err), - ) + throw new IntentCoreError('invalid-skill-use', errorMessage(err)) } const fsCache = createIntentFsCache() @@ -297,8 +260,7 @@ function resolveIntentSkillInCwd( throw new IntentCoreError(refusal.code, refusal.message) } - const scanOptions = toScanOptions(options) - const scope = getScanScope(scanOptions) + const scope = toScanScope(options) const fastPathResolved = resolveSkillUseFastPath( parsedUse, options, @@ -338,9 +300,11 @@ function resolveIntentSkillInCwd( const { scan: scanResult, droppedNames } = scanForPolicedIntents({ cwd, - scanOptions: withFsCache(scanOptions, fsCache), + scanOptions: { scope, fsCache }, coreOptions: options, context: projectContext, + config, + excludePatterns, }) if (droppedNames.includes(parsedUse.packageName)) { const lateRefusal = packageNotListedRefusal(use, parsedUse.packageName) diff --git a/packages/intent/src/core/load-resolution.ts b/packages/intent/src/core/load-resolution.ts index bed6a6c7..84fbf854 100644 --- a/packages/intent/src/core/load-resolution.ts +++ b/packages/intent/src/core/load-resolution.ts @@ -1,12 +1,10 @@ import { existsSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' -import { createIntentFsCache } from '../discovery/fs-cache.js' import { resolveSkillEntry } from '../skills/resolver.js' import { scanIntentPackageAtRoot } from '../discovery/scanner.js' import { findWorkspacePackages } from '../setup/workspace-patterns.js' -import { getDeps, resolveDepDir } from '../shared/utils.js' +import { getDeps } from '../shared/utils.js' import { warningMentionsPackage } from './excludes.js' -import { resolveProjectContext } from './project-context.js' import type { ResolveSkillResult } from '../skills/resolver.js' import type { IntentFsCache } from '../discovery/fs-cache.js' import type { ProjectContext } from './project-context.js' @@ -83,23 +81,6 @@ function findVisibleDependencyDir( return null } -function resolveDependencyPackageDir( - packageName: string, - fromDir: string, -): string | null { - return ( - findVisibleDependencyDir(packageName, fromDir) ?? - resolveDepDir(packageName, fromDir) - ) -} - -function workspacePackageDeclaresDependency( - packageJson: Record, - packageName: string, -): boolean { - return getDeps(packageJson).includes(packageName) -} - function hasYarnPnpFile(dir: string | null): boolean { return ( dir !== null && @@ -107,13 +88,6 @@ function hasYarnPnpFile(dir: string | null): boolean { ) } -function shouldSkipFastPathForYarnPnp( - context: ProjectContext, - cwd: string, -): boolean { - return hasYarnPnpFile(cwd) || hasYarnPnpFile(context.workspaceRoot) -} - function getDirectLoadFastPathCandidateDirs( packageName: string, context: ProjectContext, @@ -126,7 +100,7 @@ function getDirectLoadFastPathCandidateDirs( addCandidateDir( candidates, seen, - resolveDependencyPackageDir(packageName, context.packageRoot ?? cwd), + findVisibleDependencyDir(packageName, context.packageRoot ?? cwd), ) return candidates } @@ -134,17 +108,17 @@ function getDirectLoadFastPathCandidateDirs( addCandidateDir( candidates, seen, - resolveDependencyPackageDir( + findVisibleDependencyDir( packageName, context.packageRoot ?? context.workspaceRoot, ), ) - if (context.workspaceRoot && context.workspaceRoot !== context.packageRoot) { + if (context.workspaceRoot !== context.packageRoot) { addCandidateDir( candidates, seen, - resolveDependencyPackageDir(packageName, context.workspaceRoot), + findVisibleDependencyDir(packageName, context.workspaceRoot), ) } @@ -167,14 +141,12 @@ function getWorkspaceLoadFastPathCandidateDirs( } for (const pkg of workspacePackages) { - if (!workspacePackageDeclaresDependency(pkg.packageJson, packageName)) { - continue - } + if (!getDeps(pkg.packageJson).includes(packageName)) continue addCandidateDir( candidates, seen, - resolveDependencyPackageDir(packageName, pkg.dir), + findVisibleDependencyDir(packageName, pkg.dir), ) } @@ -251,12 +223,12 @@ function resolveFromPackageRoots( export function resolveSkillUseFastPath( parsedUse: SkillUse, options: IntentCoreOptions, - context = resolveProjectContext({ cwd: process.cwd() }), - cwd = context.cwd, - fsCache = createIntentFsCache(), + context: ProjectContext, + cwd: string, + fsCache: IntentFsCache, ): FastPathResolveResult | null { if (options.globalOnly) return null - if (shouldSkipFastPathForYarnPnp(context, cwd)) return null + if (hasYarnPnpFile(cwd) || hasYarnPnpFile(context.workspaceRoot)) return null const directResolved = resolveFromPackageRoots( getDirectLoadFastPathCandidateDirs(parsedUse.packageName, context, cwd), diff --git a/packages/intent/src/core/markdown.ts b/packages/intent/src/core/markdown.ts index cb9cb40b..71f73a6b 100644 --- a/packages/intent/src/core/markdown.ts +++ b/packages/intent/src/core/markdown.ts @@ -13,10 +13,6 @@ function pickPlaceholder(text: string): string { return String.fromCharCode(codePoint) } -function resolveFromCwd(path: string): string { - return resolve(process.cwd(), path) -} - function splitDestinationSuffix(destination: string): { pathPart: string suffix: string @@ -305,7 +301,7 @@ export function rewriteLoadedSkillMarkdownDestinations({ }): string { const context: MarkdownDestinationRewriteContext = { cwd, - resolvedPackageRoot: resolveFromCwd(packageRoot), + resolvedPackageRoot: resolve(cwd, packageRoot), skillDir: dirname(skillFilePath), rewrittenDestinations: new Map(), } diff --git a/packages/intent/src/core/package-json.ts b/packages/intent/src/core/package-json.ts index 8be2e9f9..1b81d5a5 100644 --- a/packages/intent/src/core/package-json.ts +++ b/packages/intent/src/core/package-json.ts @@ -1,5 +1,6 @@ import { join } from 'node:path' import { createIntentFsCache } from '../discovery/fs-cache.js' +import { errorMessage } from '../shared/utils.js' /** * Reads a project policy manifest, returning null only when the file is absent. @@ -24,7 +25,7 @@ export function readPackageJson( return null } throw new Error( - `Failed to read Intent policy from ${filePath}: ${error instanceof Error ? error.message : String(error)}`, + `Failed to read Intent policy from ${filePath}: ${errorMessage(error)}`, ) } diff --git a/packages/intent/src/core/project-context.ts b/packages/intent/src/core/project-context.ts index d4c56878..4e2c8651 100644 --- a/packages/intent/src/core/project-context.ts +++ b/packages/intent/src/core/project-context.ts @@ -1,5 +1,6 @@ import { existsSync, statSync } from 'node:fs' -import { dirname, join, relative, resolve } from 'node:path' +import { dirname, join, resolve } from 'node:path' +import { isWithinOrEqual } from '../shared/utils.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { findWorkspaceRoot, @@ -129,8 +130,3 @@ function resolveTargetSkillsDir( return null } - -function isWithinOrEqual(path: string, parentDir: string): boolean { - const rel = relative(parentDir, path) - return rel === '' || (!rel.startsWith('..') && !rel.startsWith('/')) -} diff --git a/packages/intent/src/core/skill-sources.ts b/packages/intent/src/core/skill-sources.ts index 3a3dfeb6..c0e2f515 100644 --- a/packages/intent/src/core/skill-sources.ts +++ b/packages/intent/src/core/skill-sources.ts @@ -1,11 +1,9 @@ // Static-discovery invariant: this module only inspects strings. It never // resolves, requires, or executes any discovered package. -type SkillSource = - | ({ raw: string; kind: 'npm' | 'workspace' } & ( - { id: string; skill?: string } | { pattern: string } - )) - | { raw: string; id: string; kind: 'git'; ref: string } +type SkillSource = { raw: string; kind: 'npm' | 'workspace' } & ( + { id: string; skill?: string } | { pattern: string } +) /** * `absent` (key missing, v0 upgrade path) and `empty` (`[]`) are deliberately @@ -32,12 +30,6 @@ export class SkillSourcesParseError extends Error { } } -export function isSkillSourcesParseError( - error: unknown, -): error is SkillSourcesParseError { - return error instanceof SkillSourcesParseError -} - /** * Strictness is fail-whole-list: every malformed entry is collected and * reported together, and a single bad entry rejects the entire list rather diff --git a/packages/intent/src/core/source-policy.ts b/packages/intent/src/core/source-policy.ts index 5d565bd4..667860e5 100644 --- a/packages/intent/src/core/source-policy.ts +++ b/packages/intent/src/core/source-policy.ts @@ -2,6 +2,7 @@ import { scanForIntents } from '../discovery/scanner.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { detectIntentAudience } from '../shared/environment.js' import { ALLOW_ALL_NOTICE } from '../shared/cli-output.js' +import { isRecord } from '../shared/utils.js' import { compileExcludePatterns, compileWildcardPattern, @@ -14,9 +15,10 @@ import { import { readPackageJson } from './package-json.js' import { parseSkillSources } from './skill-sources.js' import { resolveProjectContext } from './project-context.js' +import type { ScanOptionsWithFsCache } from '../discovery/scanner.js' import type { IntentFsCache } from '../discovery/fs-cache.js' import type { SkillUse } from '../skills/use.js' -import type { IntentPackage, ScanOptions, ScanResult } from '../shared/types.js' +import type { IntentPackage, ScanResult } from '../shared/types.js' import type { ExcludeMatcher } from './excludes.js' import type { ProjectContext } from './project-context.js' import type { SkillSourcesConfig } from './skill-sources.js' @@ -64,10 +66,6 @@ interface SkillSourceMatcher { function compileSkillSourceMatcher( source: ExplicitSkillSource, ): SkillSourceMatcher { - if (source.kind === 'git') { - return { source, matchesPackage: () => false } - } - const matchesName = 'pattern' in source ? compileWildcardPattern(source.pattern) @@ -280,10 +278,10 @@ export function readSkillSourcesConfig( ): SkillSourcesConfig { for (const dir of getConfigDirs(cwd, context)) { const intent = readPackageJson(dir, fsCache)?.intent - if (!intent || typeof intent !== 'object') continue + if (!isRecord(intent)) continue if ('skills' in intent) { - const skills = (intent as Record).skills + const skills = intent.skills if (skills === null || skills === undefined) continue return parseSkillSources(skills) } @@ -302,24 +300,22 @@ export interface PolicedScan { export function scanForPolicedIntents(params: { cwd: string - scanOptions: ScanOptions + scanOptions: ScanOptionsWithFsCache coreOptions: IntentCoreOptions context?: ProjectContext + config?: SkillSourcesConfig + excludePatterns?: Array }): PolicedScan { const { cwd, scanOptions, coreOptions } = params - const fsCache = - (scanOptions as ScanOptions & { fsCache?: IntentFsCache }).fsCache ?? - createIntentFsCache() + const fsCache = scanOptions.fsCache ?? createIntentFsCache() const context = params.context ?? resolveProjectContext({ cwd, fsCache }) const audience = detectIntentAudience(coreOptions.audience) const cachedScanOptions = { ...scanOptions, fsCache } const scanResult = scanForIntents(cwd, cachedScanOptions) - const config = readSkillSourcesConfig(cwd, context, fsCache) - const excludePatterns = getEffectiveExcludePatterns( - coreOptions, - context, - fsCache, - ) + const config = params.config ?? readSkillSourcesConfig(cwd, context, fsCache) + const excludePatterns = + params.excludePatterns ?? + getEffectiveExcludePatterns(coreOptions, context, fsCache) const excludeMatchers = compileExcludePatterns(excludePatterns) const policy = applySourcePolicy(scanResult, { diff --git a/packages/intent/src/core/types.ts b/packages/intent/src/core/types.ts index eb675b4c..6cf66fad 100644 --- a/packages/intent/src/core/types.ts +++ b/packages/intent/src/core/types.ts @@ -97,24 +97,6 @@ export interface LoadedIntentSkillDebug { scan: ScanStats } -// `npm:foo` and `workspace:foo` are distinct sources; name-only comparison -// would collapse them onto one lockfile entry/approval. -export interface SourceIdentity { - kind: 'npm' | 'workspace' - id: string -} - -export function sourceIdentityKey(s: SourceIdentity): string { - return `${s.kind}\u0000${s.id}` -} - -export function sourceIdentityEquals( - a: SourceIdentity, - b: SourceIdentity, -): boolean { - return a.kind === b.kind && a.id === b.id -} - export type IntentCoreErrorCode = | 'invalid-options' | 'invalid-skill-use' diff --git a/packages/intent/src/discovery/fs-cache.ts b/packages/intent/src/discovery/fs-cache.ts index 60981209..f47f51a2 100644 --- a/packages/intent/src/discovery/fs-cache.ts +++ b/packages/intent/src/discovery/fs-cache.ts @@ -2,6 +2,7 @@ import { join } from 'node:path' import { createFsIdentityCache, findSkillFiles as findSkillFilesUncached, + isRecord, nodeReadFs, } from '../shared/utils.js' import type { ReadFs } from '../shared/utils.js' @@ -36,10 +37,6 @@ export type IntentFsCache = { exists: (path: string) => boolean } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - export function createIntentFsCache(): IntentFsCache { const packageJsonCache = new Map() const skillFilesCache = new Map>() diff --git a/packages/intent/src/discovery/package-manager.ts b/packages/intent/src/discovery/package-manager.ts index 55c92089..6383f5bc 100644 --- a/packages/intent/src/discovery/package-manager.ts +++ b/packages/intent/src/discovery/package-manager.ts @@ -9,21 +9,13 @@ function readPackageManagerField( fsCache: IntentFsCache, ): PackageManager | null { if (!existsSync(join(dir, 'package.json'))) return null - try { - const parsed = fsCache.readPackageJson(dir) - if (!parsed) return null - - const value = parsed.packageManager - if (typeof value !== 'string') return null - - if (value.startsWith('pnpm@')) return 'pnpm' - if (value.startsWith('yarn@')) return 'yarn' - if (value.startsWith('bun@')) return 'bun' - if (value.startsWith('npm@')) return 'npm' - } catch { - return null - } + const value = fsCache.readPackageJson(dir)?.packageManager + if (typeof value !== 'string') return null + if (value.startsWith('pnpm@')) return 'pnpm' + if (value.startsWith('yarn@')) return 'yarn' + if (value.startsWith('bun@')) return 'bun' + if (value.startsWith('npm@')) return 'npm' return null } diff --git a/packages/intent/src/discovery/register.ts b/packages/intent/src/discovery/register.ts index 14807664..d552d191 100644 --- a/packages/intent/src/discovery/register.ts +++ b/packages/intent/src/discovery/register.ts @@ -1,4 +1,3 @@ -import { existsSync } from 'node:fs' import { join, sep } from 'node:path' import { rewriteSkillLoadPaths } from '../skills/paths.js' import { listNodeModulesPackageDirs } from '../shared/utils.js' @@ -36,7 +35,7 @@ export interface CreatePackageRegistrarOptions { */ exists: (path: string) => boolean rememberVariant: (pkg: IntentPackage) => void - validateIntentField: (pkgName: string, intent: unknown) => IntentConfig | null + validateIntentField: (intent: unknown) => IntentConfig | null warnings: Array } @@ -57,8 +56,6 @@ export function createPackageRegistrar(opts: CreatePackageRegistrarOptions) { nodeModulesDir: string, source: IntentPackage['source'] = 'local', ): void { - if (!existsSync(nodeModulesDir)) return - const key = opts.getFsIdentity(nodeModulesDir) if (scannedNodeModulesDirs.has(key)) return scannedNodeModulesDirs.add(key) @@ -100,7 +97,7 @@ export function createPackageRegistrar(opts: CreatePackageRegistrarOptions) { const version = typeof pkgJson.version === 'string' ? pkgJson.version : '0.0.0' const intent = - opts.validateIntentField(name, pkgJson.intent) ?? + opts.validateIntentField(pkgJson.intent) ?? opts.deriveIntentConfig(pkgJson) if (!intent) { opts.warnings.push( diff --git a/packages/intent/src/discovery/scanner.ts b/packages/intent/src/discovery/scanner.ts index 93406be9..3aaf6926 100644 --- a/packages/intent/src/discovery/scanner.ts +++ b/packages/intent/src/discovery/scanner.ts @@ -15,7 +15,8 @@ import { } from 'node:path' import { detectGlobalNodeModules, - nodeReadFs, + isRecord, + isWithinOrEqual, parseFrontmatter, readScalarField, toPosixPath, @@ -42,7 +43,7 @@ import type { VersionConflict, } from '../shared/types.js' -type ScanOptionsWithFsCache = ScanOptions & { +export type ScanOptionsWithFsCache = ScanOptions & { fsCache?: IntentFsCache } @@ -132,7 +133,7 @@ function loadPnpApi(root: string): LoadedPnp | null { // reference becomes patched without routing a post-setup `require('node:fs')` // through Yarn's resolver hook (which rejects the `node:fs` specifier under // Yarn 1 PnP). - const readFs = requireFromHere('node:fs') as unknown as ReadFs + const readFs: ReadFs = requireFromHere('node:fs') try { // eslint-disable-next-line no-restricted-syntax -- sanctioned PnP runtime load @@ -190,14 +191,7 @@ function getPnpDependencyLocator( return { name: dependencyName, reference: target } } -// --------------------------------------------------------------------------- -// Intent field validation -// --------------------------------------------------------------------------- - -function validateIntentField( - _pkgName: string, - intent: unknown, -): IntentConfig | null { +function validateIntentField(intent: unknown): IntentConfig | null { if (!intent || typeof intent !== 'object') return null const pb = intent as Record @@ -226,35 +220,28 @@ function validateIntentField( function deriveIntentConfig( pkgJson: Record, ): IntentConfig | null { - // Derive repo from repository field + const { repository } = pkgJson let repo: string | null = null - if (typeof pkgJson.repository === 'string') { - repo = pkgJson.repository - } else if ( - pkgJson.repository && - typeof pkgJson.repository === 'object' && - typeof (pkgJson.repository as Record).url === 'string' - ) { - repo = (pkgJson.repository as Record).url as string + if (typeof repository === 'string') { + repo = repository + } else if (isRecord(repository) && typeof repository.url === 'string') { // Normalize git+https://github.com/foo/bar.git → foo/bar - repo = repo + repo = repository.url .replace(/^git\+/, '') .replace(/\.git$/, '') .replace(/^https?:\/\/github\.com\//, '') } - // Derive docs from homepage field const docs = typeof pkgJson.homepage === 'string' ? pkgJson.homepage : undefined - // Need at least a repo to be useful if (!repo) return null - // Derive requires from intent.requires if partially present - const intentPartial = pkgJson.intent as Record | undefined const requires = - intentPartial && Array.isArray(intentPartial.requires) - ? intentPartial.requires.filter((r): r is string => typeof r === 'string') + isRecord(pkgJson.intent) && Array.isArray(pkgJson.intent.requires) + ? pkgJson.intent.requires.filter( + (r): r is string => typeof r === 'string', + ) : undefined return { @@ -265,10 +252,6 @@ function deriveIntentConfig( } } -// --------------------------------------------------------------------------- -// Skill discovery within a package -// --------------------------------------------------------------------------- - /** * Real path of the package root that owns `skillsDir`, or null when it cannot * be resolved. Computed once per package: every skill entry is checked against @@ -290,7 +273,7 @@ function readSkillEntry( realPackageRoot: string | null, childDir: string, skillFile: string, - readFs: ReadFs = nodeReadFs, + readFs: ReadFs, ): SkillEntry | null { if (!readFs.openSync || !readFs.fstatSync || !readFs.closeSync) return null if (realPackageRoot === null) return null @@ -341,8 +324,8 @@ function discoverSkillByNameHint( skillsDir: string, packageName: string, skillNameHint: string, - readFs: ReadFs = nodeReadFs, - includeMetadata = true, + readFs: ReadFs, + includeMetadata: boolean, ): Array { const skills: Array = [] const seen = new Set() @@ -417,11 +400,6 @@ function getPackageShortName(packageName: string): string { return packageName.split('/').pop() ?? packageName } -function isWithinOrEqual(path: string, parentDir: string): boolean { - const rel = relative(parentDir, path) - return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)) -} - function resolveSkillNameHintPath( skillsDir: string, hint: string, @@ -460,10 +438,6 @@ function getSkillNameHints( return [skillNameHint, `${packageShortName}/${skillNameHint}`] } -// --------------------------------------------------------------------------- -// Topological sort on requires -// --------------------------------------------------------------------------- - function topoSort(packages: Array): Array { const byName = new Map(packages.map((p) => [p.name, p])) const visited = new Set() @@ -503,43 +477,6 @@ function comparePackageVersions(a: string, b: string): number { return compareVersions(versionA, versionB) } -function formatVariantWarning( - name: string, - variants: Array, - chosen: IntentPackage, -): string | null { - const uniqueVersions = new Set(variants.map((variant) => variant.version)) - if (uniqueVersions.size <= 1) return null - - const details = variants - .map((variant) => `${variant.version} at ${variant.packageRoot}`) - .join(', ') - - return `Found ${variants.length} installed variants of ${name} across ${uniqueVersions.size} versions (${details}). Using ${chosen.version} from ${chosen.packageRoot}.` -} - -function toVersionConflict( - packageName: string, - variants: Array, - chosen: IntentPackage, -): VersionConflict | null { - const uniqueVersions = new Set(variants.map((variant) => variant.version)) - if (uniqueVersions.size <= 1) return null - - return { - packageName, - chosen: { - version: chosen.version, - packageRoot: chosen.packageRoot, - }, - variants, - } -} - -// --------------------------------------------------------------------------- -// Main scanner -// --------------------------------------------------------------------------- - function getScanScope(options: ScanOptions): ScanScope { return options.scope ?? (options.includeGlobal ? 'local-and-global' : 'local') } @@ -675,12 +612,8 @@ export function scanForIntents( : undefined, }, } - // Track registered package names to avoid duplicates across phases const packageIndexes = new Map() - const packageVariants = new Map< - string, - Map - >() + const packageVariants = new Map>() let pnpApi: PnpApi | null | undefined const getPackageKind = createPackageKindResolver( @@ -700,10 +633,6 @@ export function scanForIntents( return pnpApi } - function getStats(): ScanResult['stats'] { - return fsCache.getStats() - } - function rememberVariant(pkg: IntentPackage): void { let variants = packageVariants.get(pkg.name) if (!variants) { @@ -717,7 +646,7 @@ export function scanForIntents( } function ensureGlobalNodeModules(): void { - if (!nodeModules.global.path && !explicitGlobalNodeModules) { + if (!nodeModules.global.path) { const detected = detectGlobalNodeModules(packageManager) nodeModules.global.path = detected.path nodeModules.global.source = detected.source @@ -728,10 +657,6 @@ export function scanForIntents( } } - function readPkgJson(dirPath: string): Record | null { - return fsCache.readPackageJson(dirPath) - } - const { scanNodeModulesDir, scanTarget, tryRegister } = createPackageRegistrar({ comparePackageVersions, @@ -745,7 +670,7 @@ export function scanForIntents( packageIndexes, packages, projectRoot, - readPkgJson, + readPkgJson: fsCache.readPackageJson, rememberVariant, validateIntentField, warnings, @@ -762,7 +687,7 @@ export function scanForIntents( primeFsIdentity: fsCache.primeFsIdentity, packages, projectRoot, - readPkgJson, + readPkgJson: fsCache.readPackageJson, scanNodeModulesDir, tryRegister, warnings, @@ -867,36 +792,35 @@ export function scanForIntents( notices: [], conflicts, nodeModules, - stats: getStats(), + stats: fsCache.getStats(), } } for (const pkg of packages) { - const variants = packageVariants.get(pkg.name) - if (!variants) continue - - const conflict = toVersionConflict(pkg.name, [...variants.values()], pkg) - if (conflict) { - conflicts.push(conflict) - } - - const warning = formatVariantWarning(pkg.name, [...variants.values()], pkg) - if (warning) { - warnings.push(warning) - } + const variants = [...(packageVariants.get(pkg.name)?.values() ?? [])] + const versions = new Set(variants.map((v) => v.version)) + if (versions.size <= 1) continue + conflicts.push({ + packageName: pkg.name, + chosen: { version: pkg.version, packageRoot: pkg.packageRoot }, + variants, + }) + const details = variants + .map((v) => `${v.version} at ${v.packageRoot}`) + .join(', ') + warnings.push( + `Found ${variants.length} installed variants of ${pkg.name} across ${versions.size} versions (${details}). Using ${pkg.version} from ${pkg.packageRoot}.`, + ) } - // Sort by dependency order - const sorted = topoSort(packages) - return { packageManager, - packages: sorted, + packages: topoSort(packages), warnings, notices: [], conflicts, nodeModules, - stats: getStats(), + stats: fsCache.getStats(), } } @@ -932,10 +856,6 @@ export function scanIntentPackageAtRoot( fsCache.getFsIdentity, ) - function readPkgJson(dirPath: string): Record | null { - return fsCache.readPackageJson(dirPath) - } - const { tryRegister } = createPackageRegistrar({ comparePackageVersions, deriveIntentConfig, @@ -957,7 +877,7 @@ export function scanIntentPackageAtRoot( packageIndexes, packages, projectRoot, - readPkgJson, + readPkgJson: fsCache.readPackageJson, rememberVariant() {}, validateIntentField, warnings, diff --git a/packages/intent/src/hooks/agents/claude.ts b/packages/intent/src/hooks/agents/claude.ts deleted file mode 100644 index 44bb71f1..00000000 --- a/packages/intent/src/hooks/agents/claude.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { HookDecision } from '../types.js' - -export type ClaudeHookOutput = { - hookSpecificOutput: { - hookEventName: 'PreToolUse' - permissionDecision: 'deny' - permissionDecisionReason: string - } -} - -export function formatClaudePreToolUseOutput( - decision: HookDecision, -): ClaudeHookOutput | undefined { - if (decision.decision === 'allow') { - return undefined - } - - return { - hookSpecificOutput: { - hookEventName: 'PreToolUse', - permissionDecision: 'deny', - permissionDecisionReason: decision.reason, - }, - } -} diff --git a/packages/intent/src/hooks/agents/codex.ts b/packages/intent/src/hooks/agents/codex.ts deleted file mode 100644 index ccc13e87..00000000 --- a/packages/intent/src/hooks/agents/codex.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { HookDecision } from '../types.js' - -export type CodexHookOutput = { - hookSpecificOutput: { - hookEventName: 'PreToolUse' - permissionDecision: 'deny' - permissionDecisionReason: string - } -} - -export function formatCodexPreToolUseOutput( - decision: HookDecision, -): CodexHookOutput | undefined { - if (decision.decision === 'allow') { - return undefined - } - - return { - hookSpecificOutput: { - hookEventName: 'PreToolUse', - permissionDecision: 'deny', - permissionDecisionReason: decision.reason, - }, - } -} diff --git a/packages/intent/src/hooks/agents/copilot.ts b/packages/intent/src/hooks/agents/copilot.ts deleted file mode 100644 index c2231075..00000000 --- a/packages/intent/src/hooks/agents/copilot.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { HookDecision } from '../types.js' - -export type CopilotHookOutput = { - permissionDecision: 'deny' - permissionDecisionReason: string -} - -export function formatCopilotPreToolUseOutput( - decision: HookDecision, -): CopilotHookOutput | undefined { - if (decision.decision === 'allow') { - return undefined - } - - return { - permissionDecision: 'deny', - permissionDecisionReason: decision.reason, - } -} diff --git a/packages/intent/src/hooks/install.ts b/packages/intent/src/hooks/install.ts index 49b9b2cb..80665ed9 100644 --- a/packages/intent/src/hooks/install.ts +++ b/packages/intent/src/hooks/install.ts @@ -4,6 +4,7 @@ import { dirname, relative } from 'node:path' import { detectPackageManager } from '../discovery/package-manager.js' import { fail } from '../shared/cli-error.js' import { formatIntentCommand } from '../shared/command-runner.js' +import { errorMessage } from '../shared/utils.js' import { ALL_HOOK_AGENTS, HOOK_AGENT_ADAPTERS } from './adapters.js' import { EDIT_TOOLS_BY_AGENT, @@ -65,15 +66,20 @@ export function validateHookInstallOptions({ export function buildHookRunnerScript( agent: HookAgent, - catalogCommand = formatIntentCommand( - detectPackageManager(), - 'list --json --no-notices', - ), - loadCommand = formatIntentCommand( - detectPackageManager(), - 'load #', - ), + catalogCommand?: string, + loadCommand?: string, ): string { + if (catalogCommand === undefined || loadCommand === undefined) { + const packageManager = detectPackageManager() + catalogCommand ??= formatIntentCommand( + packageManager, + 'list --json --no-notices', + ) + loadCommand ??= formatIntentCommand( + packageManager, + 'load #', + ) + } const editTools = [...EDIT_TOOLS_BY_AGENT[agent]].sort() return `#!/usr/bin/env node @@ -428,31 +434,6 @@ function installAgentHook({ }), ) - return hookInstallResult({ - agent, - configPath, - scope, - scriptPath, - scriptStatus, - configStatus, - }) -} - -function hookInstallResult({ - agent, - configPath, - configStatus, - scope, - scriptPath, - scriptStatus, -}: { - agent: HookAgent - configPath: string - configStatus: HookInstallStatus - scope: HookInstallScope - scriptPath: string - scriptStatus: HookInstallStatus -}): HookInstallResult { return { agent, configPath, @@ -480,24 +461,7 @@ function upsertAdapterHooks({ }): Record { switch (configKind) { case 'claude-settings': - return upsertClaudeHooks(config, project, scriptPath) - case 'codex-hooks': - return upsertCodexHooks(config, project, scriptPath) - case 'copilot-hooks': - return upsertCopilotHooks(config, scriptPath) - } -} - -function upsertClaudeHooks( - config: Record, - project: boolean, - scriptPath: string, -): Record { - const hooks = objectValue(config.hooks) - hooks.SessionStart = upsertHookGroup(arrayValue(hooks.SessionStart), { - matcher: 'startup|resume|clear|compact', - hooks: [ - { + return upsertGateHooks(config, 'Bash|Write|Edit|MultiEdit|NotebookEdit', { type: 'command', command: 'node', args: [ @@ -506,60 +470,33 @@ function upsertClaudeHooks( : scriptPath, ], timeout: 10, - statusMessage: CATALOG_STATUS_MESSAGE, - }, - ], - }) - hooks.PreToolUse = upsertHookGroup(arrayValue(hooks.PreToolUse), { - matcher: 'Bash|Write|Edit|MultiEdit|NotebookEdit', - hooks: [ - { + }) + case 'codex-hooks': + return upsertGateHooks(config, 'Bash|apply_patch|Edit|Write', { type: 'command', - command: 'node', - args: [ - project - ? '${CLAUDE_PROJECT_DIR}/.intent/hooks/intent-claude-gate.mjs' - : scriptPath, - ], + command: project + ? 'node "$(git rev-parse --show-toplevel)/.intent/hooks/intent-codex-gate.mjs"' + : `node ${quoteShell(scriptPath)}`, timeout: 10, - statusMessage: GATE_STATUS_MESSAGE, - }, - ], - }) - return { ...config, hooks } + }) + case 'copilot-hooks': + return upsertCopilotHooks(config, scriptPath) + } } -function upsertCodexHooks( +function upsertGateHooks( config: Record, - project: boolean, - scriptPath: string, + matcher: string, + entry: Record, ): Record { const hooks = objectValue(config.hooks) hooks.SessionStart = upsertHookGroup(arrayValue(hooks.SessionStart), { matcher: 'startup|resume|clear|compact', - hooks: [ - { - type: 'command', - command: project - ? 'node "$(git rev-parse --show-toplevel)/.intent/hooks/intent-codex-gate.mjs"' - : `node ${quoteShell(scriptPath)}`, - timeout: 10, - statusMessage: CATALOG_STATUS_MESSAGE, - }, - ], + hooks: [{ ...entry, statusMessage: CATALOG_STATUS_MESSAGE }], }) hooks.PreToolUse = upsertHookGroup(arrayValue(hooks.PreToolUse), { - matcher: 'Bash|apply_patch|Edit|Write', - hooks: [ - { - type: 'command', - command: project - ? 'node "$(git rev-parse --show-toplevel)/.intent/hooks/intent-codex-gate.mjs"' - : `node ${quoteShell(scriptPath)}`, - timeout: 10, - statusMessage: GATE_STATUS_MESSAGE, - }, - ], + matcher, + hooks: [{ ...entry, statusMessage: GATE_STATUS_MESSAGE }], }) return { ...config, hooks } } @@ -682,9 +619,7 @@ function parseJsonObject( return parsed as Record } } catch (err) { - fail( - `Failed to parse ${formatPath(filePath)}: ${err instanceof Error ? err.message : String(err)}`, - ) + fail(`Failed to parse ${formatPath(filePath)}: ${errorMessage(err)}`) } fail(`Failed to parse ${formatPath(filePath)}: expected a JSON object.`) diff --git a/packages/intent/src/hooks/policy.ts b/packages/intent/src/hooks/policy.ts index c99fa013..082f4c43 100644 --- a/packages/intent/src/hooks/policy.ts +++ b/packages/intent/src/hooks/policy.ts @@ -1,10 +1,4 @@ -import type { - HookAgent, - HookDecision, - IntentInvocation, - IntentObservation, - ToolEvent, -} from './types.js' +import type { HookAgent, IntentInvocation } from './types.js' export const EDIT_TOOLS_BY_AGENT: Record> = { claude: new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']), @@ -48,71 +42,3 @@ export function parseIntentInvocation( return action === 'load' ? { action, skillUse } : { action } } - -export function observationFromEvent( - event: ToolEvent | undefined, -): IntentObservation | undefined { - if (!event || typeof event !== 'object') { - return undefined - } - - const toolName = event.tool_name ?? event.toolName - const toolInput = event.tool_input ?? event.toolArgs - - if (toolName !== 'Bash') { - return undefined - } - - const command = - typeof toolInput === 'string' - ? safeCommandFromString(toolInput) - : commandFromObject(toolInput) - - const parsed = parseIntentInvocation(command) - - if (!parsed || typeof command !== 'string') { - return undefined - } - - return { action: parsed.action, skillUse: parsed.skillUse, raw: command } -} - -export function gateDecision({ - agent, - hasLoaded, - toolName, -}: { - agent: HookAgent - hasLoaded: boolean - toolName: string -}): HookDecision { - if (EDIT_TOOLS_BY_AGENT[agent].has(toolName) && !hasLoaded) { - return { decision: 'deny', reason: GATE_DENY_REASON } - } - - return { decision: 'allow' } -} - -export function hasIntentCheckFromObservations( - observations: Array | undefined>, -): boolean { - return observations.some( - (entry) => entry?.action === 'list' || entry?.action === 'load', - ) -} - -function commandFromObject(value: unknown): unknown { - return value && typeof value === 'object' - ? (value as { command?: unknown }).command - : undefined -} - -function safeCommandFromString(value: string): string { - try { - const parsed = JSON.parse(value) as unknown - const command = commandFromObject(parsed) - return typeof command === 'string' ? command : value - } catch { - return value - } -} diff --git a/packages/intent/src/hooks/types.ts b/packages/intent/src/hooks/types.ts index cf2141d5..b6b284a7 100644 --- a/packages/intent/src/hooks/types.ts +++ b/packages/intent/src/hooks/types.ts @@ -6,17 +6,3 @@ export type IntentInvocation = { action: 'list' | 'load' skillUse?: string } - -export type IntentObservation = IntentInvocation & { - raw: string -} - -export type HookDecision = - { decision: 'allow' } | { decision: 'deny'; reason: string } - -export type ToolEvent = { - tool_name?: unknown - toolName?: unknown - tool_input?: unknown - toolArgs?: unknown -} diff --git a/packages/intent/src/maintainer/add.ts b/packages/intent/src/maintainer/add.ts index 81eecf71..3ef0d60b 100644 --- a/packages/intent/src/maintainer/add.ts +++ b/packages/intent/src/maintainer/add.ts @@ -3,10 +3,9 @@ import { basename, dirname, join, relative } from 'node:path' import { stringify } from 'yaml' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' -import { parseFrontmatter } from '../shared/utils.js' +import { isRecord, parseFrontmatter } from '../shared/utils.js' import { authoringMarker, - isObject, projectPath, readRecord, recordPath, @@ -123,7 +122,7 @@ export function planAddSkills( slug: name, domain: options.domain, description: entry.purpose ?? entry.description, - ...(packageDir ? { packages: [manifestName] } : {}), + packages: packageDir ? [manifestName] : undefined, tasks, covers: [], }) @@ -177,7 +176,7 @@ function prepareAddition( name, slug: name, domain: options.domain, - ...(packageDir ? { package: packageDir } : {}), + package: packageDir, path: options.path ?? `skills/${name}/SKILL.md`, } const path = skillPath(project, entry, checked) @@ -215,7 +214,7 @@ function prepareAddition( 'To register an existing skill, supply its --path and --domain; edit its frontmatter directly before running sync.', ) const parsed = existingFrontmatter ?? parseFrontmatter(path) - if (!isObject(parsed) || parsed.name !== name) + if (!isRecord(parsed) || parsed.name !== name) throw new Error( 'Existing skill has invalid frontmatter or a different name.', ) @@ -253,7 +252,7 @@ function prepareAddition( entry.sources = stringList(frontmatter.sources ?? [], 'sources') entry.requires = stringList(frontmatter.requires ?? [], 'requires') if ( - isObject(frontmatter.metadata) && + isRecord(frontmatter.metadata) && typeof frontmatter.metadata.purpose === 'string' ) entry.purpose = frontmatter.metadata.purpose diff --git a/packages/intent/src/maintainer/distribution.ts b/packages/intent/src/maintainer/distribution.ts index 19f5da24..1778486b 100644 --- a/packages/intent/src/maintainer/distribution.ts +++ b/packages/intent/src/maintainer/distribution.ts @@ -1,11 +1,10 @@ import { existsSync, readFileSync } from 'node:fs' import { dirname, relative } from 'node:path' import { applyEdits, modify } from 'jsonc-parser' -import { parseFrontmatter } from '../shared/utils.js' +import { isRecord, parseFrontmatter } from '../shared/utils.js' import { stringList } from './add.js' import { authoringMarker, - isObject, projectPath, readRecord, skillEntries, @@ -32,12 +31,8 @@ const repositoryPattern = /^[a-zA-Z0-9][a-zA-Z0-9-]*\/[a-zA-Z0-9][a-zA-Z0-9_.-]*$/ const namePattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ -export function readDistribution( - tree: ReturnType, -): Distribution | undefined { - const value: unknown = tree.document.toJS().distribution - if (value === undefined) return undefined - if (!isObject(value) || !['repo', 'none'].includes(String(value.mode))) +function isDistribution(value: unknown): value is Distribution { + if (!isRecord(value) || !['repo', 'none'].includes(String(value.mode))) throw new Error('skill_tree.yaml distribution.mode must be repo or none.') if (value.mode === 'repo' || value.name !== undefined) { if ( @@ -52,18 +47,26 @@ export function readDistribution( if (!stringList(value.skills, 'distribution.skills').length) throw new Error('Choose at least one distribution skill.') } - return value as unknown as Distribution + return true +} + +export function readDistribution( + tree: ReturnType, +): Distribution | undefined { + const value: unknown = tree.document.toJS().distribution + if (value === undefined || !isDistribution(value)) return undefined + return value } function readJson(path: string): Record { const value: unknown = JSON.parse(readFileSync(path, 'utf8')) - if (!isObject(value)) throw new Error(`Expected a JSON object: ${path}`) + if (!isRecord(value)) throw new Error(`Expected a JSON object: ${path}`) return value } function inferDistributionRepository(project: MaintainerProject): string { const manifest = readJson(projectPath(project.root, 'package.json')) - const declared = isObject(manifest.repository) + const declared = isRecord(manifest.repository) ? manifest.repository.url : manifest.repository return typeof declared === 'string' @@ -218,10 +221,9 @@ export function planDistribution( // explicit opt-in through maintainer setup --distribution repo. const config = readDistribution(tree) ?? { mode: 'none' as const } const changes: Array = [] - const problems: Array = [] const commands: Array = [] if (config.mode === 'none' && !config.name) - return { changes, problems, commands, mode: config.mode } + return { changes, commands, mode: config.mode } const { name, repository } = config const selected = config.mode === 'repo' ? config.skills! : [] const exported: Array<{ name: string; path: string }> = [] @@ -232,7 +234,7 @@ export function planDistribution( const path = skillPath(project, entry) const fm = parseFrontmatter(path) if ( - !isObject(fm) || + !isRecord(fm) || fm.name !== selectedName || !namePattern.test(selectedName) ) @@ -288,7 +290,7 @@ export function planDistribution( const change = jsonChange(project, marketplacePath, (current) => { if ( current.metadata !== undefined && - (!isObject(current.metadata) || + (!isRecord(current.metadata) || (current.metadata.pluginRoot !== undefined && !['', '.', './'].includes(String(current.metadata.pluginRoot)))) ) @@ -302,7 +304,7 @@ export function planDistribution( throw new Error(`Invalid marketplace name in ${marketplacePath}.`) if ( current.owner !== undefined && - (!isObject(current.owner) || + (!isRecord(current.owner) || typeof current.owner.name !== 'string' || !current.owner.name.trim()) ) @@ -310,7 +312,7 @@ export function planDistribution( if ( current.plugins !== undefined && (!Array.isArray(current.plugins) || - current.plugins.some((plugin) => !isObject(plugin))) + current.plugins.some((plugin) => !isRecord(plugin))) ) throw new Error(`Invalid plugins array in ${marketplacePath}.`) const plugins = (current.plugins ?? []) as Array< @@ -396,5 +398,5 @@ export function planDistribution( `/plugin install ${name}@${String(marketplaceName)}`, ) } - return { changes, problems, commands, mode: config.mode } + return { changes, commands, mode: config.mode } } diff --git a/packages/intent/src/maintainer/existing.ts b/packages/intent/src/maintainer/existing.ts index 4f2087c2..dcdf6669 100644 --- a/packages/intent/src/maintainer/existing.ts +++ b/packages/intent/src/maintainer/existing.ts @@ -5,10 +5,14 @@ import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { reviewIgnorePatterns } from '../review/review.js' import { resolveWorkspacePackages } from '../setup/workspace-patterns.js' -import { isDefaultSkillPath, parseFrontmatter } from '../shared/utils.js' +import { + errorMessage, + isDefaultSkillPath, + isRecord, + parseFrontmatter, +} from '../shared/utils.js' import { stringList } from './add.js' import { - isObject, projectPath, readRecord, recordPath, @@ -150,9 +154,7 @@ export function findExistingSkills( skill.frontmatter = frontmatter skill.domain = inferDomain(frontmatter, mapped, id) } catch (error) { - skill.problems.push( - error instanceof Error ? error.message : String(error), - ) + skill.problems.push(errorMessage(error)) } return [skill] }) @@ -180,14 +182,14 @@ function inferDomain( ): string { const metadata = frontmatter.metadata if ( - isObject(metadata) && + isRecord(metadata) && typeof metadata.domain === 'string' && metadata.domain.trim() ) return metadata.domain.trim() const name = basename(dirname(id)) - const mapping = mapped.find((value) => isObject(value) && value.slug === name) - if (isObject(mapping) && typeof mapping.domain === 'string') + const mapping = mapped.find((value) => isRecord(value) && value.slug === name) + if (isRecord(mapping) && typeof mapping.domain === 'string') return mapping.domain const parent = basename(dirname(dirname(id))) return parent === 'skills' ? defaultDomain : parent diff --git a/packages/intent/src/maintainer/project.ts b/packages/intent/src/maintainer/project.ts index 1e79702b..85155360 100644 --- a/packages/intent/src/maintainer/project.ts +++ b/packages/intent/src/maintainer/project.ts @@ -2,6 +2,7 @@ import { execFileSync } from 'node:child_process' import { existsSync, lstatSync, readFileSync } from 'node:fs' import { basename, dirname, join, relative, resolve } from 'node:path' import { parseDocument, stringify } from 'yaml' +import { isRecord } from '../shared/utils.js' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import type { IntentFsCache } from '../discovery/fs-cache.js' @@ -117,7 +118,7 @@ export function readRecord( const parsed: unknown = document.toJS() if ( document.errors.length || - !isObject(parsed) || + !isRecord(parsed) || !Array.isArray(parsed.skills) ) throw new Error( @@ -126,10 +127,6 @@ export function readRecord( return { path, source, document } } -export function isObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - export interface SkillEntry extends Record { name: string path: string @@ -146,7 +143,7 @@ export function skillEntries( const paths = new Set() return entries.map((entry) => { if ( - !isObject(entry) || + !isRecord(entry) || typeof entry.name !== 'string' || !entry.name || typeof entry.path !== 'string' || @@ -204,7 +201,7 @@ export function planSetupRecords( throw error ?? new Error(`Invalid package.json: ${context.packageRoot}`) const library = { name: manifest.name ?? basename(root), - ...(manifest.version ? { version: manifest.version } : {}), + version: manifest.version || undefined, } const defaults: Record = { 'domain_map.yaml': stringify({ diff --git a/packages/intent/src/maintainer/sync.ts b/packages/intent/src/maintainer/sync.ts index 95bfc7de..3e2236f8 100644 --- a/packages/intent/src/maintainer/sync.ts +++ b/packages/intent/src/maintainer/sync.ts @@ -3,12 +3,11 @@ import { dirname, relative } from 'node:path' import { applyEdits, modify, parse } from 'jsonc-parser' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' -import { parseFrontmatter } from '../shared/utils.js' +import { isRecord, parseFrontmatter } from '../shared/utils.js' import { stringList } from './add.js' import { planDistribution } from './distribution.js' import { authoringMarker, - isObject, projectPath, readRecord, recordPath, @@ -71,7 +70,7 @@ export function planMaintainerSync(project: MaintainerProject) { } const fm = parseFrontmatter(path) if ( - !isObject(fm) || + !isRecord(fm) || typeof fm.description !== 'string' || !fm.description.trim() ) @@ -100,7 +99,7 @@ export function planMaintainerSync(project: MaintainerProject) { } for (const [field, value] of Object.entries({ description: fm.description, - purpose: isObject(fm.metadata) ? fm.metadata.purpose : undefined, + purpose: isRecord(fm.metadata) ? fm.metadata.purpose : undefined, sources, requires, })) { @@ -111,7 +110,7 @@ export function planMaintainerSync(project: MaintainerProject) { if (readFileSync(path, 'utf8').includes(authoringMarker)) problems.push(`${name}: skill still needs authoring.`) const candidates: Array> = map.skills.filter( - (skill: unknown) => isObject(skill) && skill.slug === name, + (skill: unknown) => isRecord(skill) && skill.slug === name, ) const mapped = candidates.find((skill) => skill.domain === entry.domain) ?? candidates[0] @@ -170,7 +169,7 @@ export function planMaintainerSync(project: MaintainerProject) { const manifest: unknown = parse(source, errors, { allowTrailingComma: true, }) - if (errors.length || !isObject(manifest)) + if (errors.length || !isRecord(manifest)) throw new Error(`Invalid package.json: ${path}`) let content = source const indent = source.match(/\n([\t ]+)"/)?.[1] ?? ' ' @@ -224,6 +223,5 @@ export function planMaintainerSync(project: MaintainerProject) { problems.push('skill_spec.md still needs authored coverage and decisions.') const distribution = planDistribution(project, tree, entries) changes.push(...distribution.changes) - problems.push(...distribution.problems) return { changes, problems, skills, distribution } } diff --git a/packages/intent/src/review/review.ts b/packages/intent/src/review/review.ts index 7d4a91a9..434c9e7b 100644 --- a/packages/intent/src/review/review.ts +++ b/packages/intent/src/review/review.ts @@ -14,7 +14,13 @@ import { import { basename, dirname, join, relative, resolve } from 'node:path' import { parse as parseYaml } from 'yaml' import { resolveProjectContext } from '../core/project-context.js' -import { isDefaultSkillPath, parseFrontmatter } from '../shared/utils.js' +import { createIntentFsCache } from '../discovery/fs-cache.js' +import { + errorMessage, + isDefaultSkillPath, + isRecord, + parseFrontmatter, +} from '../shared/utils.js' type Snapshot = Record type Outcome = 'updated' | 'no-change' | 'out-of-scope' | 'unresolved' @@ -208,10 +214,6 @@ function safePath(root: string, path: string): string { return current } -function isObject(value: unknown): value is Record { - return !!value && typeof value === 'object' && !Array.isArray(value) -} - function isHash(value: unknown): value is string { return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value) } @@ -235,6 +237,31 @@ function resolvedOutcome(value: unknown): value is ReviewRecord['outcome'] { ) } +function isReviewRecord(value: unknown): value is ReviewRecord { + return ( + isRecord(value) && + isHash(value.fingerprint) && + isRecord(value.snapshot) && + Object.values(value.snapshot).every( + (hash) => hash === null || isHash(hash), + ) && + typeof value.head === 'string' && + /^[a-f0-9]{40,64}$/.test(value.head) && + resolvedOutcome(value.outcome) && + hasEvidence(value) + ) +} + +function isReviewState(value: unknown): value is ReviewState { + return ( + isRecord(value) && + value.schemaVersion === 1 && + typeof value.baseline === 'string' && + /^[a-f0-9]{40,64}$/.test(value.baseline) && + isRecord(value.items) + ) +} + function readState(root: string): { state: ReviewState | null content: string | null @@ -244,37 +271,17 @@ function readState(root: string): { const content = readFileSync(path, 'utf8') try { const value: unknown = JSON.parse(content) - if ( - !isObject(value) || - value.schemaVersion !== 1 || - typeof value.baseline !== 'string' || - !/^[a-f0-9]{40,64}$/.test(value.baseline) || - !isObject(value.items) - ) - throw new Error() - for (const [id, item] of Object.entries(value.items)) { - if ( - !isObject(item) || - !isHash(item.fingerprint) || - !isObject(item.snapshot) || - !Object.values(item.snapshot).every( - (hash) => hash === null || isHash(hash), - ) || - typeof item.head !== 'string' || - !/^[a-f0-9]{40,64}$/.test(item.head) || - !resolvedOutcome(item.outcome) || - !hasEvidence(item) - ) - throw new Error() - for (const path of Object.keys(item.snapshot)) validatePath(path) - const record = item as unknown as ReviewRecord + if (!isReviewState(value)) throw new Error() + for (const [id, record] of Object.entries(value.items)) { + if (!isReviewRecord(record)) throw new Error() + for (const path of Object.keys(record.snapshot)) validatePath(path) if ( record.fingerprint !== reviewFingerprint(id, record.snapshot, []) && record.fingerprint !== legacyReviewFingerprint(id, record.snapshot, []) ) throw new Error() } - return { state: value as unknown as ReviewState, content } + return { state: value, content } } catch { throw new Error( `Invalid review state at ${statePath}. Restore or repair it before recording another review.`, @@ -283,7 +290,7 @@ function readState(root: string): { } function repositoryName(value: unknown): string | undefined { - if (isObject(value)) return repositoryName(value.url) + if (isRecord(value)) return repositoryName(value.url) if (typeof value !== 'string') return undefined let path = value if (value.startsWith('git@github.com:')) { @@ -316,7 +323,7 @@ function repositoryNames(root: string): Set { const manifest: unknown = JSON.parse( readFileSync(safePath(root, 'package.json'), 'utf8'), ) - const name = isObject(manifest) + const name = isRecord(manifest) ? repositoryName(manifest.repository) : undefined if (name) names.add(name) @@ -367,9 +374,9 @@ export function reviewIgnorePatterns( path: string, ) { if (tree.review === undefined) return [] - const ignore = isObject(tree.review) ? tree.review.ignore : undefined + const ignore = isRecord(tree.review) ? tree.review.ignore : undefined if ( - !isObject(tree.review) || + !isRecord(tree.review) || (ignore !== undefined && (!Array.isArray(ignore) || ignore.some((entry) => typeof entry !== 'string' || !entry.trim()))) @@ -427,6 +434,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { ]), ) const files = sorted(list()) + const fileSet = new Set(files) const untracked = splitPaths( git(root, [ 'ls-files', @@ -438,6 +446,8 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { ]), ) const changed = sorted([...diff(), ...untracked]) + const changedSet = new Set(changed) + const fsCache = createIntentFsCache() const names = repositoryNames(root) const covered = new Set() const items: Array = [] @@ -471,7 +481,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { try { return [file, fileHash(file)] } catch (error) { - problems.push(error instanceof Error ? error.message : String(error)) + problems.push(errorMessage(error)) return [file, null] } }), @@ -508,7 +518,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { ]).filter((file) => previous ? (current[file] ?? null) !== (previous.snapshot[file] ?? null) - : (changedSinceIntroduced?.has(file) ?? changed.includes(file)), + : (changedSinceIntroduced?.has(file) ?? changedSet.has(file)), ) items.push({ id, @@ -532,7 +542,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { const customRoots = existingArtifactDirs .filter((dir) => basename(dir) === '_artifacts') .map((dir) => dirname(dir)) - .filter((dir) => dir !== '.' && !files.includes(`${dir}/package.json`)) + .filter((dir) => dir !== '.' && !fileSet.has(`${dir}/package.json`)) const declaredSkills = new Set() const treeIgnorePatterns: Array = [] for (const dir of existingArtifactDirs) { @@ -544,11 +554,11 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { // Missing or invalid trees remain unresolved in planning validation below. continue } - if (!isObject(tree)) continue + if (!isRecord(tree)) continue treeIgnorePatterns.push(...reviewIgnorePatterns(tree, treePath)) if (Array.isArray(tree.skills)) { for (const entry of tree.skills) { - if (!isObject(entry) || typeof entry.path !== 'string') continue + if (!isRecord(entry) || typeof entry.path !== 'string') continue declaredSkills.add( typeof entry.package === 'string' ? `${entry.package}/${entry.path}` @@ -596,12 +606,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { if (skillHash === null) continue frontmatter = parseFrontmatter(safePath(root, file)) } catch (error) { - add( - 'skill', - file, - [file], - [error instanceof Error ? error.message : String(error)], - ) + add('skill', file, [file], [errorMessage(error)]) continue } const sources = frontmatter?.sources @@ -616,6 +621,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { const { packageRoot } = resolveProjectContext({ cwd: root, targetPath: safePath(root, file), + fsCache, }) const packageDir = relative(root, packageRoot ?? root).replaceAll( '\\', @@ -635,7 +641,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { throw new Error(`Source matched no available files: ${source}`) sourceFiles.push(...matches) } catch (error) { - problems.push(error instanceof Error ? error.message : String(error)) + problems.push(errorMessage(error)) } } } @@ -649,7 +655,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { '.github/copilot-instructions.md', ].some( (path) => - files.includes(path) && + fileSet.has(path) && fileHash(path) !== null && readFileSync(safePath(root, path), 'utf8').includes( '', @@ -659,7 +665,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { const dirs = existingArtifactDirs.length ? existingArtifactDirs : [ - resolveProjectContext({ cwd: root }).isMonorepo + resolveProjectContext({ cwd: root, fsCache }).isMonorepo ? '_artifacts' : 'skills/_artifacts', ] @@ -670,7 +676,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { const problems: Array = [] for (const path of paths) { try { - if (!files.includes(path)) { + if (!fileSet.has(path)) { problems.push( existsSync(safePath(root, path)) ? `Planning record must be visible to Git: ${path}` @@ -687,15 +693,13 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { problems.push(`Planning record is empty: ${path}`) } else if (path.endsWith('.yaml')) { const parsed: unknown = parseYaml(content) - if (!isObject(parsed) || !Array.isArray(parsed.skills)) + if (!isRecord(parsed) || !Array.isArray(parsed.skills)) problems.push( `Planning record requires an object with a skills array: ${path}`, ) } } catch (error) { - problems.push( - `${path}: ${error instanceof Error ? error.message : String(error)}`, - ) + problems.push(`${path}: ${errorMessage(error)}`) } } // The shared record must be reviewed again when its source or guidance changes. @@ -705,7 +709,7 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { [ ...covered, ...skillFiles, - ...paths.filter((path) => files.includes(path)), + ...paths.filter((path) => fileSet.has(path)), ], problems, ) @@ -719,8 +723,8 @@ export function createReview(cwd: string, baseRef?: string): ReviewReport { for (const id of Object.keys(state?.items ?? {})) { if (!id.startsWith('skill:')) continue const path = id.slice('skill:'.length) - if (files.includes(path)) continue - if (fileHash(path) === null && !changed.includes(path)) { + if (fileSet.has(path)) continue + if (fileHash(path) === null && !changedSet.has(path)) { add('source', path, [path], []) } } @@ -751,7 +755,7 @@ export function recordPendingReview( export function recordReview(cwd: string, input: unknown): number { if ( - !isObject(input) || + !isRecord(input) || input.schemaVersion !== 1 || typeof input.base !== 'string' || !Array.isArray(input.items) @@ -769,7 +773,7 @@ export function recordReview(cwd: string, input: unknown): number { const seen = new Set() let count = 0 for (const value of input.items) { - if (!isObject(value) || typeof value.id !== 'string' || seen.has(value.id)) + if (!isRecord(value) || typeof value.id !== 'string' || seen.has(value.id)) throw new Error('Invalid or duplicate review item.') seen.add(value.id) if (value.outcome === undefined || value.outcome === 'unresolved') continue diff --git a/packages/intent/src/setup/project-setup.ts b/packages/intent/src/setup/project-setup.ts index c646dc49..4875c43a 100644 --- a/packages/intent/src/setup/project-setup.ts +++ b/packages/intent/src/setup/project-setup.ts @@ -1,18 +1,17 @@ import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' import { basename, join, relative } from 'node:path' import { repositoryWritePath } from '../shared/write-path.js' +import { errorMessage, isRecord } from '../shared/utils.js' import { writeChanges } from '../maintainer/files.js' import { resolveProjectContext } from '../core/project-context.js' +import { createIntentFsCache } from '../discovery/fs-cache.js' import { findPackagesWithSkills, findWorkspaceRoot, readWorkspacePatterns, } from './workspace-patterns.js' import type { FileChange } from '../maintainer/files.js' - -// --------------------------------------------------------------------------- -// Types -// --------------------------------------------------------------------------- +import type { IntentFsCache } from '../discovery/fs-cache.js' export interface EditPackageJsonResult { added: Array @@ -102,14 +101,11 @@ function deriveWorkspacePackageName( return repoName } -// --------------------------------------------------------------------------- -// Variable detection from package.json -// --------------------------------------------------------------------------- - function readPackageJson(root: string): Record { const pkgPath = join(root, 'package.json') try { - return JSON.parse(readFileSync(pkgPath, 'utf8')) as Record + const parsed: unknown = JSON.parse(readFileSync(pkgPath, 'utf8')) + return isRecord(parsed) ? parsed : {} } catch (err: unknown) { const isNotFound = err && @@ -117,9 +113,7 @@ function readPackageJson(root: string): Record { 'code' in err && (err as NodeJS.ErrnoException).code === 'ENOENT' if (!isNotFound) { - console.error( - `Warning: could not read ${pkgPath}: ${err instanceof Error ? err.message : err}`, - ) + console.error(`Warning: could not read ${pkgPath}: ${errorMessage(err)}`) } return {} } @@ -129,24 +123,15 @@ function detectRepo( pkgJson: Record, fallback: string, ): string { - const intent = pkgJson.intent as Record | undefined + const intent = isRecord(pkgJson.intent) ? pkgJson.intent : undefined if (typeof intent?.repo === 'string') { return intent.repo } - if (typeof pkgJson.repository === 'string') { - return pkgJson.repository - .replace(/^git\+/, '') - .replace(/\.git$/, '') - .replace(/^https?:\/\/github\.com\//, '') - } - - if ( - pkgJson.repository && - typeof pkgJson.repository === 'object' && - typeof (pkgJson.repository as Record).url === 'string' - ) { - return ((pkgJson.repository as Record).url as string) + const { repository } = pkgJson + const url = isRecord(repository) ? repository.url : repository + if (typeof url === 'string') { + return url .replace(/^git\+/, '') .replace(/\.git$/, '') .replace(/^https?:\/\/github\.com\//, '') @@ -180,9 +165,11 @@ function buildWatchPaths(root: string, packageDirs: Array): string { paths.add(`${relDir}/src/**`) } - const pkgJson = readPackageJson(packageDir) - const intent = pkgJson.intent as Record | undefined - const docs = typeof intent?.docs === 'string' ? intent.docs : 'docs/' + const { intent } = readPackageJson(packageDir) + const docs = + isRecord(intent) && typeof intent.docs === 'string' + ? intent.docs + : 'docs/' const docsPattern = localDocsPattern(docs) if (docsPattern) { paths.add( @@ -205,11 +192,8 @@ function buildWatchPaths(root: string, packageDirs: Array): string { function detectVars(root: string, packageDirs?: Array): TemplateVars { const pkgJson = readPackageJson(root) const rawName = typeof pkgJson.name === 'string' ? pkgJson.name : 'unknown' - const docs = - typeof (pkgJson.intent as Record | undefined)?.docs === - 'string' - ? ((pkgJson.intent as Record).docs as string) - : 'docs/' + const intent = isRecord(pkgJson.intent) ? pkgJson.intent : undefined + const docs = typeof intent?.docs === 'string' ? intent.docs : 'docs/' const isMonorepo = packageDirs !== undefined const monorepoFallbackPkg = packageDirs?.[0] ? readPackageJson(packageDirs[0]) @@ -224,7 +208,6 @@ function detectVars(root: string, packageDirs?: Array): TemplateVars { packageName = deriveWorkspacePackageName(root, repo, packageDirs) } - // Derive srcPath: monorepos use a wildcard; single packages use the short name or fall back to root src/ const shortName = packageName.replace(/^@[^/]+\//, '') let srcPath = isMonorepo ? 'packages/*/src/**' @@ -254,87 +237,28 @@ function detectVars(root: string, packageDirs?: Array): TemplateVars { } } -// --------------------------------------------------------------------------- -// Template variable substitution -// --------------------------------------------------------------------------- - -function applyVars(content: string, vars: TemplateVars): string { - return content - .replace(/\{\{PACKAGE_NAME\}\}/g, vars.PACKAGE_NAME) - .replace(/\{\{PACKAGE_LABEL\}\}/g, vars.PACKAGE_LABEL) - .replace(/\{\{PAYLOAD_PACKAGE\}\}/g, vars.PAYLOAD_PACKAGE) - .replace(/\{\{REPO\}\}/g, vars.REPO) - .replace(/\{\{DOCS_PATH\}\}/g, vars.DOCS_PATH) - .replace(/\{\{SRC_PATH\}\}/g, vars.SRC_PATH) - .replace(/\{\{WATCH_PATHS\}\}/g, vars.WATCH_PATHS) - .replace(/\{\{INTENT_WORKFLOW_REF\}\}/g, vars.INTENT_WORKFLOW_REF) - .replace(/\{\{INTENT_ARTIFACTS\}\}/g, vars.INTENT_ARTIFACTS) -} - -// --------------------------------------------------------------------------- -// Copy helpers -// --------------------------------------------------------------------------- - -function templatesUse( - srcDir: string, - destDir: string, - placeholder: string, -): boolean { - if (!existsSync(srcDir)) return false - return readdirSync(srcDir).some( - (entry) => - !existsSync(join(destDir, entry)) && - readFileSync(join(srcDir, entry), 'utf8').includes(placeholder), +function applyTemplate(content: string, vars: TemplateVars): string { + if (vars.WATCH_PATHS) { + content = content.replace( + /\s+- '?\{\{DOCS_PATH\}\}'?\n\s+- '?\{\{SRC_PATH\}\}'?/, + vars.WATCH_PATHS, + ) + } + return content.replace(/\{\{([A-Z_]+)\}\}/g, (match, key: string) => + key in vars ? vars[key as keyof TemplateVars] : match, ) } -function planTemplates( - srcDir: string, - destDir: string, - vars: TemplateVars, - root: string, -): { - changes: Array - copied: Array - skipped: Array -} { - const copied: Array = [] - const skipped: Array = [] - const changes: Array = [] - - if (!existsSync(srcDir)) return { changes, copied, skipped } - - for (const entry of readdirSync(srcDir)) { - const srcPath = join(srcDir, entry) - const destPath = repositoryWritePath(root, join(destDir, entry)) - - if (existsSync(destPath)) { - skipped.push(destPath) - continue - } - - let content = readFileSync(srcPath, 'utf8') - if (vars.WATCH_PATHS) { - content = content.replace( - /\s+- '?\{\{DOCS_PATH\}\}'?\n\s+- '?\{\{SRC_PATH\}\}'?/, - vars.WATCH_PATHS, - ) - } - const substituted = applyVars(content, vars) - changes.push({ path: destPath, source: null, content: substituted }) - copied.push(destPath) - } - - return { changes, copied, skipped } +export function runEditPackageJson(root: string): EditPackageJsonResult { + return editPackageJson(root, createIntentFsCache()) } -// --------------------------------------------------------------------------- -// Command: edit-package-json -// --------------------------------------------------------------------------- - -export function runEditPackageJson(root: string): EditPackageJsonResult { +function editPackageJson( + root: string, + fsCache: IntentFsCache, +): EditPackageJsonResult { const result: EditPackageJsonResult = { added: [], alreadyPresent: [] } - const context = resolveProjectContext({ cwd: root }) + const context = resolveProjectContext({ cwd: root, fsCache }) const packageRoot = context.packageRoot ?? root const pkgPath = join(packageRoot, 'package.json') @@ -355,15 +279,13 @@ export function runEditPackageJson(root: string): EditPackageJsonResult { return result } - // Detect indent size from existing file const indentMatch = raw.match(/^(\s+)"/m) const indentSize = indentMatch?.[1] ? indentMatch[1].length : 2 - // --- keywords array --- - if (!Array.isArray(pkg.keywords)) { - pkg.keywords = [] - } - const keywords = pkg.keywords as Array + const keywords: Array = Array.isArray(pkg.keywords) + ? pkg.keywords + : [] + pkg.keywords = keywords if (keywords.includes('tanstack-intent')) { result.alreadyPresent.push('keywords: "tanstack-intent"') } else { @@ -371,11 +293,8 @@ export function runEditPackageJson(root: string): EditPackageJsonResult { result.added.push('keywords: "tanstack-intent"') } - // --- files array --- - if (!Array.isArray(pkg.files)) { - pkg.files = [] - } - const files = pkg.files as Array + const files: Array = Array.isArray(pkg.files) ? pkg.files : [] + pkg.files = files // In monorepos, _artifacts lives at repo root, not under packages — // the negation pattern is a no-op and shouldn't be added. @@ -394,34 +313,21 @@ export function runEditPackageJson(root: string): EditPackageJsonResult { writeFileSync(pkgPath, JSON.stringify(pkg, null, indentSize) + '\n') - // Print results for (const a of result.added) console.log(`✓ Added ${a}`) for (const a of result.alreadyPresent) console.log(` Already present: ${a}`) return result } -// --------------------------------------------------------------------------- -// Monorepo-aware command runner -// --------------------------------------------------------------------------- - -/** - * When run from a monorepo root, finds all workspace packages with SKILL.md - * files and runs the given command on each. Falls back to single-package - * behavior only when no workspace config is detected. If workspace config - * exists but no packages have skills, warns and returns empty. - */ -function runForEachPackage( +export function runEditPackageJsonAll( root: string, - runOne: (dir: string) => T, -): Array> | T { - const isMonorepo = readWorkspacePatterns(root) !== null - const pkgsWithSkills = isMonorepo ? findPackagesWithSkills(root) : [] - - if (!isMonorepo) { - return runOne(root) +): Array> | EditPackageJsonResult { + const fsCache = createIntentFsCache() + if (readWorkspacePatterns(root, fsCache) === null) { + return editPackageJson(root, fsCache) } + const pkgsWithSkills = findPackagesWithSkills(root, fsCache) if (pkgsWithSkills.length === 0) { console.log('No workspace packages with skills found.') return [] @@ -430,27 +336,18 @@ function runForEachPackage( return pkgsWithSkills.map((pkgDir) => { const rel = relative(root, pkgDir) || '.' console.log(`\n── ${rel} ──`) - return { package: rel, result: runOne(pkgDir) } + return { package: rel, result: editPackageJson(pkgDir, fsCache) } }) } -export function runEditPackageJsonAll( - root: string, -): Array> | EditPackageJsonResult { - return runForEachPackage(root, runEditPackageJson) -} - -// --------------------------------------------------------------------------- -// Command: setup-github-actions -// --------------------------------------------------------------------------- - export function planSetupGithubActions( root: string, metaDir: string, artifacts = '', ) { - const workspaceRoot = findWorkspaceRoot(root) ?? root - const packageDirs = findPackagesWithSkills(workspaceRoot) + const fsCache = createIntentFsCache() + const workspaceRoot = findWorkspaceRoot(root, fsCache) ?? root + const packageDirs = findPackagesWithSkills(workspaceRoot, fsCache) const vars = detectVars( workspaceRoot, packageDirs.length > 0 ? packageDirs : undefined, @@ -466,20 +363,31 @@ export function planSetupGithubActions( vars.INTENT_ARTIFACTS = artifacts const srcDir = join(metaDir, 'templates', 'workflows') const destDir = join(workspaceRoot, '.github', 'workflows') - if (existsSync(srcDir)) - for (const entry of readdirSync(srcDir)) - repositoryWritePath(workspaceRoot, join(destDir, entry)) + const skipped: Array = [] + const templates: Array<{ path: string; content: string }> = [] + for (const entry of existsSync(srcDir) ? readdirSync(srcDir) : []) { + const path = repositoryWritePath(workspaceRoot, join(destDir, entry)) + if (existsSync(path)) skipped.push(path) + else + templates.push({ + path, + content: readFileSync(join(srcDir, entry), 'utf8'), + }) + } // Existing workflows are preserved even in a development build with no pin. - if (templatesUse(srcDir, destDir, '{{INTENT_WORKFLOW_REF}}')) + if ( + templates.some(({ content }) => content.includes('{{INTENT_WORKFLOW_REF}}')) + ) vars.INTENT_WORKFLOW_REF = (process.env.INTENT_WORKFLOW_REF ? validateWorkflowRef(process.env.INTENT_WORKFLOW_REF) : undefined) || resolveIntentWorkflowRef(join(metaDir, '..')) - const { - changes, - copied: workflows, - skipped, - } = planTemplates(srcDir, destDir, vars, workspaceRoot) + const changes: Array = templates.map(({ path, content }) => ({ + path, + source: null, + content: applyTemplate(content, vars), + })) + const workflows = changes.map((change) => change.path) const messages = [ ...workflows.map((file) => `✓ Copied workflow: ${file}`), ...skipped.map((file) => ` Already exists: ${file}`), diff --git a/packages/intent/src/setup/workspace-patterns.ts b/packages/intent/src/setup/workspace-patterns.ts index 2979f380..1e6ef958 100644 --- a/packages/intent/src/setup/workspace-patterns.ts +++ b/packages/intent/src/setup/workspace-patterns.ts @@ -2,7 +2,7 @@ import { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs' import { dirname, join } from 'node:path' import { parse as parseJsonc } from 'jsonc-parser/lib/esm/main.js' import { parse as parseYaml } from 'yaml' -import { hasAnySkillFile } from '../shared/utils.js' +import { errorMessage, hasAnySkillFile, isRecord } from '../shared/utils.js' import { readPackageJson } from '../core/package-json.js' import type { ParseError } from 'jsonc-parser/lib/esm/main.js' import type { IntentFsCache } from '../discovery/fs-cache.js' @@ -26,10 +26,6 @@ function normalizeWorkspacePatterns(patterns: Array): Array { ].sort(compareCodeUnits) } -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - function parseWorkspacePatternList( value: unknown, fieldName: string, @@ -108,9 +104,7 @@ function readJsoncFile(path: string): unknown { function warnConfigError(path: string, err: unknown): void { const verb = err instanceof SyntaxError ? 'parse' : 'read' - console.error( - `Warning: failed to ${verb} ${path}: ${err instanceof Error ? err.message : err}`, - ) + console.error(`Warning: failed to ${verb} ${path}: ${errorMessage(err)}`) } type WorkspacePatternSource = { @@ -119,13 +113,6 @@ type WorkspacePatternSource = { getPatterns: (config: unknown) => Array | null } -export type WorkspaceInfo = { - root: string - patterns: Array - packageDirs: Array - packageDirsWithSkills: Array -} - const workspacePatternSources: Array = [ { fileName: 'pnpm-workspace.yaml', @@ -245,23 +232,6 @@ export function findWorkspacePackages( return packageDirs } -export function getWorkspaceInfo(root: string): WorkspaceInfo | null { - const patterns = readWorkspacePatterns(root) - if (!patterns) return null - - const packageDirs = resolveWorkspacePackages(root, patterns) - const packageDirsWithSkills = packageDirs.filter((dir) => { - const skillsDir = join(dir, 'skills') - return existsSync(skillsDir) && hasAnySkillFile(skillsDir) - }) - return { - root, - patterns, - packageDirs, - packageDirsWithSkills, - } -} - export function resolveWorkspacePackages( root: string, patterns: Array, @@ -338,7 +308,7 @@ function readChildDirectories(dir: string): Array { .map((entry) => join(dir, entry.name)) } catch (err: unknown) { console.error( - `Warning: could not read directory ${dir}: ${err instanceof Error ? err.message : err}`, + `Warning: could not read directory ${dir}: ${errorMessage(err)}`, ) return [] } @@ -377,6 +347,12 @@ export function findWorkspaceRoot( return null } -export function findPackagesWithSkills(root: string): Array { - return getWorkspaceInfo(root)?.packageDirsWithSkills ?? [] +export function findPackagesWithSkills( + root: string, + fsCache?: IntentFsCache, +): Array { + return findWorkspacePackages(root, fsCache).filter((dir) => { + const skillsDir = join(dir, 'skills') + return existsSync(skillsDir) && hasAnySkillFile(skillsDir) + }) } diff --git a/packages/intent/src/shared/display.ts b/packages/intent/src/shared/display.ts index 1cf7be52..6d19a9d0 100644 --- a/packages/intent/src/shared/display.ts +++ b/packages/intent/src/shared/display.ts @@ -1,7 +1,3 @@ -// --------------------------------------------------------------------------- -// Shared display helpers for CLI output -// --------------------------------------------------------------------------- - import { formatRuntimeSkillLookupHint, isStableLoadPath, @@ -15,10 +11,6 @@ export interface SkillDisplay { path?: string } -function padColumn(text: string, width: number): string { - return text.length >= width ? text + ' ' : text.padEnd(width) -} - export function printTable( headers: Array, rows: Array>, @@ -27,13 +19,13 @@ export function printTable( (h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)) + 2, ) - const headerLine = headers.map((h, i) => padColumn(h, widths[i]!)).join('') + const headerLine = headers.map((h, i) => h.padEnd(widths[i]!)).join('') const separator = widths.map((w) => '─'.repeat(w)).join('') console.log(headerLine) console.log(separator) for (const row of rows) { - console.log(row.map((cell, i) => padColumn(cell, widths[i]!)).join('')) + console.log(row.map((cell, i) => cell.padEnd(widths[i]!)).join('')) } } diff --git a/packages/intent/src/shared/types.ts b/packages/intent/src/shared/types.ts index f2e1a388..b04b3fb5 100644 --- a/packages/intent/src/shared/types.ts +++ b/packages/intent/src/shared/types.ts @@ -1,7 +1,4 @@ -// --------------------------------------------------------------------------- -// Intent config (lives in library package.json under "intent" key) -// --------------------------------------------------------------------------- - +// Lives in a library's package.json under the "intent" key. export interface IntentConfig { version: number repo: string @@ -9,10 +6,6 @@ export interface IntentConfig { requires?: Array } -// --------------------------------------------------------------------------- -// Scanner types -// --------------------------------------------------------------------------- - export interface ScanResult { packageManager: PackageManager packages: Array @@ -78,10 +71,6 @@ export interface SkillEntry { framework?: string } -// --------------------------------------------------------------------------- -// Staleness types -// --------------------------------------------------------------------------- - export interface StalenessReport { library: string currentVersion: string | null diff --git a/packages/intent/src/shared/utils.ts b/packages/intent/src/shared/utils.ts index 8e47165a..1c5b1c66 100644 --- a/packages/intent/src/shared/utils.ts +++ b/packages/intent/src/shared/utils.ts @@ -11,7 +11,15 @@ import { readlinkSync, realpathSync, } from 'node:fs' -import { basename, dirname, join, resolve, sep } from 'node:path' +import { + basename, + dirname, + isAbsolute, + join, + relative, + resolve, + sep, +} from 'node:path' import { parse as parseYaml } from 'yaml' import type { Dirent } from 'node:fs' @@ -51,9 +59,25 @@ export const nodeReadFs: ReadFs = { fstatSync, } -/** - * Convert a path to use forward slashes (for cross-platform consistency). - */ +export function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +export function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +export function stringArray(value: unknown): Array { + return Array.isArray(value) + ? value.filter((entry): entry is string => typeof entry === 'string') + : [] +} + +export function isWithinOrEqual(path: string, parentDir: string): boolean { + const rel = relative(parentDir, path) + return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)) +} + export function toPosixPath(p: string): string { return p.split(sep).join('/') } @@ -113,9 +137,6 @@ export function createFsIdentityCache( return getIdentity } -/** - * Recursively find all SKILL.md files under a directory. - */ export function findSkillFiles( dir: string, fs: ReadFs = nodeReadFs, @@ -194,64 +215,48 @@ export function getDeps( return [...deps] } -export function listNodeModulesPackageDirs( - nodeModulesDir: string, -): Array { - let topEntries: Array> +function readPackageEntries(dir: string): Array> { try { - topEntries = readdirSync(nodeModulesDir, { - withFileTypes: true, - encoding: 'utf8', - }) + return readdirSync(dir, { withFileTypes: true, encoding: 'utf8' }).filter( + (entry) => entry.isDirectory() || entry.isSymbolicLink(), + ) } catch { return [] } +} - const packageDirs: Array = [] - - for (const entry of topEntries) { - if (!entry.isDirectory() && !entry.isSymbolicLink()) continue +function forEachPackageDir( + nodeModulesDir: string, + visit: (packageDir: string) => void, +): void { + for (const entry of readPackageEntries(nodeModulesDir)) { const dirPath = join(nodeModulesDir, entry.name) - if (entry.name.startsWith('@')) { - let scopedEntries: Array> - try { - scopedEntries = readdirSync(dirPath, { - withFileTypes: true, - encoding: 'utf8', - }) - } catch { - continue - } - - for (const scoped of scopedEntries) { - if (!scoped.isDirectory() && !scoped.isSymbolicLink()) continue - packageDirs.push(join(dirPath, scoped.name)) + for (const scoped of readPackageEntries(dirPath)) { + visit(join(dirPath, scoped.name)) } } else if (!entry.name.startsWith('.')) { - packageDirs.push(dirPath) + visit(dirPath) } } +} +export function listNodeModulesPackageDirs( + nodeModulesDir: string, +): Array { + const packageDirs: Array = [] + forEachPackageDir(nodeModulesDir, (dir) => packageDirs.push(dir)) return packageDirs } export function listNestedNodeModulesPackageDirs( nodeModulesDir: string, - getFsIdentity: (path: string) => string = createFsIdentityCache(), + getFsIdentity: (path: string) => string, ): Array { const packageDirs: Array = [] const visitedNodeModulesDirs = new Set() const visitedPackageDirs = new Set() - function readDir(dir: string): Array> { - try { - return readdirSync(dir, { withFileTypes: true, encoding: 'utf8' }) - } catch { - return [] - } - } - function addPackageDir(packageDir: string): void { const key = getFsIdentity(packageDir) if (visitedPackageDirs.has(key)) return @@ -268,21 +273,7 @@ export function listNestedNodeModulesPackageDirs( const key = getFsIdentity(dir) if (visitedNodeModulesDirs.has(key)) return visitedNodeModulesDirs.add(key) - - for (const entry of readDir(dir)) { - if (!entry.isDirectory() && !entry.isSymbolicLink()) continue - const dirPath = join(dir, entry.name) - - if (entry.name.startsWith('@')) { - for (const scoped of readDir(dirPath)) { - if (!scoped.isDirectory() && !scoped.isSymbolicLink()) continue - addPackageDir(join(dirPath, scoped.name)) - } - continue - } - - if (!entry.name.startsWith('.')) addPackageDir(dirPath) - } + forEachPackageDir(dir, addPackageDir) } scanNodeModulesDir(nodeModulesDir) @@ -295,14 +286,6 @@ export function detectGlobalNodeModules(packageManager: string): { path: string | null source?: string } { - const envPath = process.env.INTENT_GLOBAL_NODE_MODULES?.trim() - if (envPath) { - return { - path: envPath, - source: 'INTENT_GLOBAL_NODE_MODULES', - } - } - const commands: Array<{ command: string args: Array diff --git a/packages/intent/src/skills/paths.ts b/packages/intent/src/skills/paths.ts index 7092140a..f4a6f30a 100644 --- a/packages/intent/src/skills/paths.ts +++ b/packages/intent/src/skills/paths.ts @@ -24,10 +24,6 @@ function isPackageManagerInternalSegment(segment: string): boolean { return segment === '.pnpm' || segment === '.bun' || segment === '.yarn' } -export function hasPackageManagerInternalPath(path: string): boolean { - return getPathSegments(path).some(isPackageManagerInternalSegment) -} - export function isStableLoadPath(path: string): boolean { const normalized = path.trim() const segments = getPathSegments(normalized) diff --git a/packages/intent/src/skills/resolver.ts b/packages/intent/src/skills/resolver.ts index 93f0142d..80811ce6 100644 --- a/packages/intent/src/skills/resolver.ts +++ b/packages/intent/src/skills/resolver.ts @@ -1,5 +1,5 @@ import { warningMentionsPackage } from '../core/excludes.js' -import { parseSkillUse } from './use.js' +import { getPackageShortName, parseSkillUse } from './use.js' import type { IntentPackage, ScanResult, @@ -79,10 +79,6 @@ export interface ResolveSkillEntryResult { suggestedSkills: Array } -function getPackageShortName(packageName: string): string { - return packageName.split('/').pop() ?? packageName -} - function getPackagePrefixedSkillAlias( packageName: string, skillName: string, diff --git a/packages/intent/src/skills/use.ts b/packages/intent/src/skills/use.ts index 6c3968b1..3dbc2e9f 100644 --- a/packages/intent/src/skills/use.ts +++ b/packages/intent/src/skills/use.ts @@ -24,6 +24,10 @@ export function isSkillUseParseError( return error instanceof SkillUseParseError } +export function getPackageShortName(packageName: string): string { + return packageName.split('/').pop() ?? packageName +} + export function formatSkillUse(packageName: string, skillName: string): string { const pkg = packageName.trim() const skill = skillName.trim() diff --git a/packages/intent/src/staleness/artifact-coverage.ts b/packages/intent/src/staleness/artifact-coverage.ts index 5084345e..a67bec63 100644 --- a/packages/intent/src/staleness/artifact-coverage.ts +++ b/packages/intent/src/staleness/artifact-coverage.ts @@ -1,6 +1,8 @@ -import { existsSync, readFileSync, readdirSync } from 'node:fs' +import { readFileSync, readdirSync } from 'node:fs' import { join } from 'node:path' import { parse as parseYaml } from 'yaml' +import { errorMessage, isRecord, stringArray } from '../shared/utils.js' +import type { Dirent } from 'node:fs' import type { IntentArtifactCoverageIgnore, IntentArtifactFile, @@ -11,19 +13,10 @@ import type { type ArtifactKind = IntentArtifactFile['kind'] -function isRecord(value: unknown): value is Record { - return !!value && typeof value === 'object' && !Array.isArray(value) -} - function stringValue(value: unknown): string | undefined { return typeof value === 'string' && value.trim() ? value : undefined } -function stringArray(value: unknown): Array { - if (!Array.isArray(value)) return [] - return value.filter((entry): entry is string => typeof entry === 'string') -} - function detectArtifactKind(fileName: string): ArtifactKind | null { if (fileName.endsWith('skill_tree.yaml')) return 'skill-tree' if (fileName.endsWith('domain_map.yaml')) return 'domain-map' @@ -40,7 +33,7 @@ function readArtifactYaml( } catch (err) { warnings.push({ artifactPath, - message: `Invalid YAML: ${err instanceof Error ? err.message : String(err)}`, + message: `Invalid YAML: ${errorMessage(err)}`, }) return null } @@ -137,7 +130,13 @@ function parseCoverageIgnores( export function readIntentArtifacts(root: string): IntentArtifactSet | null { const artifactsDir = join(root, '_artifacts') - if (!existsSync(artifactsDir)) return null + let entries: Array + try { + entries = readdirSync(artifactsDir, { withFileTypes: true }) + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null + throw err + } const warnings: Array = [] const skillTrees: Array = [] @@ -145,7 +144,7 @@ export function readIntentArtifacts(root: string): IntentArtifactSet | null { const skills: Array = [] const ignoredPackages: Array = [] - for (const entry of readdirSync(artifactsDir, { withFileTypes: true })) { + for (const entry of entries) { if (!entry.isFile()) continue const kind = detectArtifactKind(entry.name) diff --git a/packages/intent/src/staleness/check.ts b/packages/intent/src/staleness/check.ts index 6a4cd584..dfc8d5c1 100644 --- a/packages/intent/src/staleness/check.ts +++ b/packages/intent/src/staleness/check.ts @@ -22,10 +22,6 @@ import type { StalenessSignal, } from '../shared/types.js' -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - interface SkillMeta { relName: string filePath: string @@ -81,10 +77,6 @@ function normalizeVersion(version: string): string | null { return coerce(version)?.version ?? null } -// --------------------------------------------------------------------------- -// Version resolution -// --------------------------------------------------------------------------- - const NPM_REGISTRY_FETCH_TIMEOUT_MS = 5_000 async function fetchNpmVersion(packageName: string): Promise { @@ -110,10 +102,6 @@ async function fetchCurrentVersion( return typeof version === 'string' ? version : fetchNpmVersion(packageName) } -// --------------------------------------------------------------------------- -// Sync state -// --------------------------------------------------------------------------- - interface SyncState { library_version?: string skills?: Record }> @@ -178,21 +166,6 @@ export function readPackageName( : relative(process.cwd(), packageDir) || 'unknown' } -// --------------------------------------------------------------------------- -// Artifact signals -// --------------------------------------------------------------------------- - -function normalizeFilePath(path: string): string { - return toPosixPath(resolve(path)) -} - -function getRelativePackageDir( - artifactRoot: string, - packageDir: string, -): string { - return toPosixPath(relative(artifactRoot, packageDir)) -} - function normalizeList(values: Array | undefined): Array { return [...new Set(values ?? [])].sort((a, b) => a.localeCompare(b)) } @@ -241,7 +214,7 @@ function resolveArtifactSkillPaths( candidatePaths.push(join(artifactRoot, artifact.package, artifact.path)) } - return [...new Set(candidatePaths.map(normalizeFilePath))] + return [...new Set(candidatePaths.map((path) => toPosixPath(resolve(path))))] } function findMatchingSkill( @@ -285,7 +258,7 @@ function buildArtifactSignals({ if (!artifacts) return [] const skillsByPath = new Map( - skillMetas.map((skill) => [normalizeFilePath(skill.filePath), skill]), + skillMetas.map((skill) => [toPosixPath(resolve(skill.filePath)), skill]), ) const skillsByName = new Map( skillMetas.map((skill) => [skill.relName, skill]), @@ -307,7 +280,7 @@ function buildArtifactSignals({ artifactPath: warning.artifactPath, })) - const relPackageDir = getRelativePackageDir(artifactRoot, packageDir) + const relPackageDir = toPosixPath(relative(artifactRoot, packageDir)) for (const artifact of artifacts.skills) { if (!artifactPackageMatches(artifact, library, relPackageDir)) { @@ -396,18 +369,6 @@ function artifactCoversPackage( ) } -function artifactIgnoresPackage( - artifacts: IntentArtifactSet, - packageName: string, - relPackageDir: string, -): boolean { - return artifacts.ignoredPackages.some( - (ignored) => - ignored.packageName === packageName || - ignored.packageName === relPackageDir, - ) -} - export function buildWorkspaceCoverageSignals({ artifactRoot, artifacts, @@ -431,10 +392,13 @@ export function buildWorkspaceCoverageSignals({ if (hasGeneratedSkill) continue const packageName = readPackageName(packageDir, fsCache) - const relPackageDir = getRelativePackageDir(artifactRoot, packageDir) - if (artifactIgnoresPackage(artifacts, packageName, relPackageDir)) { - continue - } + const relPackageDir = toPosixPath(relative(artifactRoot, packageDir)) + const ignored = artifacts.ignoredPackages.some( + (ignore) => + ignore.packageName === packageName || + ignore.packageName === relPackageDir, + ) + if (ignored) continue const hasArtifactCoverage = artifacts.skills.some((artifact) => artifactCoversPackage(artifact, packageName, relPackageDir), @@ -458,10 +422,6 @@ export function buildWorkspaceCoverageSignals({ return signals } -// --------------------------------------------------------------------------- -// Main -// --------------------------------------------------------------------------- - export async function checkStaleness( packageDir: string, packageName?: string, @@ -477,7 +437,6 @@ export async function checkStaleness( const skillsDir = join(packageDir, 'skills') const library = packageName ?? readPackageName(packageDir, fsCache) - // Find all skills const skillFiles = fsCache.findSkillFiles(skillsDir) const skillMetas: Array = skillFiles.map((filePath) => { const fm = parseFrontmatter(filePath) @@ -495,27 +454,21 @@ export async function checkStaleness( } }) - // Get the version from frontmatter (use first skill that has it) const skillVersion = skillMetas.find((s) => s.libraryVersion)?.libraryVersion ?? null - // Resolve current version: prefer local package.json, fall back to npm registry const currentVersion = await fetchCurrentVersion(packageDir, library, fsCache) - // Classify drift const versionDrift = skillVersion && currentVersion ? classifyVersionDrift(skillVersion, currentVersion) : null - // Read sync state const syncState = readSyncState(packageDir) - // Build per-skill staleness const skills: Array = skillMetas.map((skill) => { const reasons: Array = [] - // Version drift if ( currentVersion && skill.libraryVersion && @@ -526,12 +479,9 @@ export async function checkStaleness( ) } - // Source SHA changes (from sync-state) const storedShas = syncState?.skills?.[skill.relName]?.sources_sha ?? {} - // We only flag if there are stored SHAs but we can't check remote - // (actual remote checking requires GitHub API — deferred to agent) + // Remote SHA comparison needs the GitHub API; the agent does it. if (skill.sources && Object.keys(storedShas).length > 0) { - // Mark sources as needing review — agent will do the actual comparison for (const source of skill.sources) { if (!storedShas[source]) { reasons.push(`new source (${source})`) diff --git a/packages/intent/src/validate/blocks.ts b/packages/intent/src/validate/blocks.ts index 31faaa49..10826f7f 100644 --- a/packages/intent/src/validate/blocks.ts +++ b/packages/intent/src/validate/blocks.ts @@ -5,7 +5,12 @@ import { dirname, join, relative, resolve } from 'node:path' import { pathToFileURL } from 'node:url' import { resolveProjectContext } from '../core/project-context.js' import { resolveWorkspacePackages } from '../setup/workspace-patterns.js' -import { parseFrontmatter, readScalarField } from '../shared/utils.js' +import { + errorMessage, + isRecord, + parseFrontmatter, + readScalarField, +} from '../shared/utils.js' import type TS from 'typescript' import type * as NativeApi from 'typescript7/unstable/async' import type * as NativeAst from 'typescript7/unstable/ast' @@ -36,17 +41,22 @@ interface CodeBlock { expectError?: Array } +interface CodeFence { + start: number + end: number + language: string + properties: Array + code: string +} + +// Indexed by the opening fence's indentation (0 to 3 spaces). +const fenceDedents = [/^/, /^ ?/, /^ {0,2}/, /^ {0,3}/] + // Scan whole fences before selecting languages: a Markdown example can contain // shorter fences, closing fences may be longer, and EOF also closes a fence. -function codeFences(content: string) { +function codeFences(content: string): Array { const lines = content.split(/\r?\n/) - const fences: Array<{ - start: number - end: number - language: string - properties: Array - code: string - }> = [] + const fences: Array = [] for (let start = 0; start < lines.length; start++) { const opening = /^( {0,3})(`{3,}|~{3,})(.*)$/.exec(lines[start]!) if (!opening || (opening[2]![0] === '`' && opening[3]!.includes('`'))) @@ -62,7 +72,7 @@ function codeFences(content: string) { ) break } - const dedent = new RegExp(`^ {0,${opening[1]!.length}}`) + const dedent = fenceDedents[opening[1]!.length]! const [language, ...properties] = opening[3]!.trim().split(/\s+/) fences.push({ start, @@ -140,7 +150,7 @@ function loadTypeScript(root: string): typeof TS | null { try { ts = load('typescript') as typeof TS } catch { - continue // Try the next location. + continue } if (hasCompilerApi(ts)) return ts // TypeScript 7 exports no compiler API. Its documented side-by-side @@ -175,9 +185,7 @@ async function loadNativeTypeScript( is: await entry('ast/is'), scanner: await entry('ast/scanner'), } - } catch { - // Try the next location. - } + } catch {} } return null } @@ -251,12 +259,12 @@ function nativeMessage(diagnostic: NativeDiagnostic, indent = 0): string { ].join('') } -const errorMessage = (error: unknown) => - error instanceof Error ? error.message : String(error) - -function extractCodeBlocks(file: string, content: string): Array { +function extractCodeBlocks( + file: string, + fences: Array, +): Array { const blocks: Array = [] - for (const fence of codeFences(content)) { + for (const fence of fences) { const language = fence.language if (!checkedLanguages.has(language)) continue if (fence.properties.includes('no-check')) continue @@ -460,11 +468,12 @@ async function splitExamples( export function skillLinks( content: string, + fences = codeFences(content), ): Array<{ target: string; path: string; line: number }> { const links: Array<{ target: string; path: string; line: number }> = [] // Blank out fenced examples, keeping newlines so line numbers still match. const lines = content.split(/\r?\n/) - for (const fence of codeFences(content)) + for (const fence of fences) for ( let index = fence.start; index <= fence.end && index < lines.length; @@ -472,16 +481,16 @@ export function skillLinks( ) lines[index] = '' const prose = lines.join('\n') + let line = 1 + let scanned = 0 for (const match of prose.matchAll(markdownLink)) { + for (; scanned < match.index; scanned++) + if (prose.charCodeAt(scanned) === 10) line++ const target = match[1] ?? match[2]! if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.startsWith('#')) continue const path = target.replace(/[#?].*$/, '') if (!path) continue - links.push({ - target, - path, - line: prose.slice(0, match.index).split('\n').length, - }) + links.push({ target, path, line }) } return links } @@ -491,10 +500,11 @@ function checkSkillLinks( packageDir: string, file: string, content: string, + fences: Array, ): Array { const findings: Array = [] const absolute = resolve(root, file) - for (const { target, path, line } of skillLinks(content)) { + for (const { target, path, line } of skillLinks(content, fences)) { const resolved = resolve(dirname(absolute), path) const outside = relative(packageDir, resolved).startsWith('..') if (outside || !existsSync(resolved)) @@ -510,22 +520,23 @@ function checkSkillLinks( return findings } -// The file that declares the library's public types. A declared entry that -// Git tracks is hand-written and used as-is; a missing or ignored one is -// build output, so the matching source file stands in for it. -function libraryEntry(packageDir: string): string | null { - let manifest: Record = {} +function readManifest(packageDir: string): Record | null { try { - manifest = JSON.parse( + const manifest: unknown = JSON.parse( readFileSync(join(packageDir, 'package.json'), 'utf8'), ) + return isRecord(manifest) ? manifest : null } catch { - // Fall through to the conventional source entry. + return null } +} + +// The entry the manifest declares for the library's public types. +function declaredEntry(manifest: Record): string | undefined { const exportsRoot = isRecord(manifest.exports) ? (manifest.exports['.'] ?? manifest.exports) : manifest.exports - const declared = [ + return [ manifest.types, manifest.typings, isRecord(exportsRoot) ? exportsRoot.types : undefined, @@ -542,10 +553,22 @@ function libraryEntry(packageDir: string): string | null { manifest.module, manifest.main, ].find((value): value is string => typeof value === 'string') +} + +// The file that declares the library's public types. A declared entry that +// Git tracks is hand-written and used as-is; a missing or ignored one is +// build output, so the matching source file stands in for it. +function libraryEntry( + packageDir: string, + manifest: Record, + tracked?: Set, +): string | null { + const declared = declaredEntry(manifest) const candidates: Array = [] if (declared) { const path = resolve(packageDir, declared) - if (existsSync(path) && isTracked(packageDir, path)) return path + if (existsSync(path) && (tracked?.has(path) || isTracked(packageDir, path))) + return path const name = declared .split('/') .at(-1)! @@ -591,19 +614,27 @@ function workspacePaths(root: string): Record> { const context = resolveProjectContext({ cwd: root }) const workspaceRoot = context.workspaceRoot ?? root const paths: Record> = {} - for (const dir of resolveWorkspacePackages( + const packages = resolveWorkspacePackages( workspaceRoot, context.workspacePatterns, - )) { - let name: unknown - try { - name = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name - } catch { - continue - } - const entry = typeof name === 'string' ? libraryEntry(dir) : null + ).flatMap((dir) => { + const manifest = readManifest(dir) + if (!manifest || typeof manifest.name !== 'string') return [] + return [{ dir, name: manifest.name, manifest }] + }) + // One git call answers for most declared entries. A package that is its own + // repository is not listed by it, so libraryEntry asks from that package. + const tracked = trackedFiles( + workspaceRoot, + packages.flatMap(({ dir, manifest }) => { + const declared = declaredEntry(manifest) + return declared ? [resolve(dir, declared)] : [] + }), + ) + for (const { dir, name, manifest } of packages) { + const entry = libraryEntry(dir, manifest, tracked) if (!entry) continue - paths[name as string] = [slash(entry)] + paths[name] = [slash(entry)] paths[`${name}/*`] = [ slash(join(dirname(entry), '*')), slash(join(dir, '*')), @@ -612,6 +643,28 @@ function workspacePaths(root: string): Record> { return paths } +// The absolute paths among `paths` that Git tracks from `cwd`; none when Git +// cannot answer there. Git prints paths relative to `cwd`, so each is resolved +// back against it. +function trackedFiles(cwd: string, paths: Array): Set { + if (paths.length === 0) return new Set() + try { + const listed = execFileSync( + 'git', + ['-c', 'core.fsmonitor=false', 'ls-files', '-z', '--', ...paths], + { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }, + ) + return new Set( + listed + .split('\0') + .filter(Boolean) + .map((path) => resolve(cwd, path)), + ) + } catch { + return new Set() + } +} + function isTracked(packageDir: string, path: string): boolean { try { execFileSync( @@ -625,25 +678,10 @@ function isTracked(packageDir: string, path: string): boolean { } } -function packageName(packageDir: string): string | undefined { - try { - const name: unknown = JSON.parse( - readFileSync(join(packageDir, 'package.json'), 'utf8'), - ).name - return typeof name === 'string' ? name : undefined - } catch { - return undefined - } -} - // TypeScript normalizes every path it hands back to forward slashes, so the // virtual files and path mappings are keyed the same way on Windows. const slash = (path: string) => path.replace(/\\/g, '/') -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - export interface SkillBlockCache { workspacePaths?: Record> sourceFiles?: Map @@ -661,12 +699,19 @@ export async function checkSkillBlocks( ts?: typeof TS | null, ): Promise { const { root, packageDir, library, cache = {} } = options - const findings = options.skills.flatMap((skill) => - checkSkillLinks(root, packageDir, skill.file, skill.content), - ) - const blocks = [...options.skills, ...(options.references ?? [])].flatMap( - (skill) => extractCodeBlocks(skill.file, skill.content), - ) + const findings: Array = [] + const blocks: Array = [] + for (const skill of options.skills) { + const fences = codeFences(skill.content) + findings.push( + ...checkSkillLinks(root, packageDir, skill.file, skill.content, fences), + ) + blocks.push(...extractCodeBlocks(skill.file, fences)) + } + for (const reference of options.references ?? []) + blocks.push( + ...extractCodeBlocks(reference.file, codeFences(reference.content)), + ) const result = (skipped?: string): SkillBlockCheck => ({ blocks: blocks.length, findings, @@ -686,8 +731,9 @@ export async function checkSkillBlocks( return result( `TypeScript ${ts.version} has no compiler API that Intent can use; install @typescript/typescript6 beside it`, ) - const entry = libraryEntry(packageDir) - const ownsLibrary = packageName(packageDir) === library + const manifest = readManifest(packageDir) ?? {} + const entry = libraryEntry(packageDir, manifest) + const ownsLibrary = manifest.name === library if (ownsLibrary && !entry) return result( `no type entry found for ${library} in ${relative(root, packageDir) || '.'}`, @@ -978,20 +1024,12 @@ export async function describeSkillExamples( targetPath: absolute, }) if (!packageRoot) continue - let library: unknown = readScalarField( - parseFrontmatter(absolute), - 'library', - ) + let library = readScalarField(parseFrontmatter(absolute), 'library') if (!library) { - try { - library = JSON.parse( - readFileSync(join(packageRoot, 'package.json'), 'utf8'), - ).name - } catch { - continue - } + const name = readManifest(packageRoot)?.name + if (typeof name !== 'string') continue + library = name } - if (typeof library !== 'string') continue const key = `${packageRoot}\0${library}` const group = groups.get(key) ?? { packageDir: packageRoot, @@ -1030,7 +1068,8 @@ export function summarizeSkillExamples( const summaries = new Map() if (result.skipped) return summaries for (const skill of skills) { - if (!extractCodeBlocks(skill.file, skill.content).length) continue + if (!extractCodeBlocks(skill.file, codeFences(skill.content)).length) + continue const errors = result.findings.filter( (finding) => finding.file === skill.file && finding.severity === 'error', ) diff --git a/packages/intent/src/validate/repairs.ts b/packages/intent/src/validate/repairs.ts index 54d3fe01..fcb2268a 100644 --- a/packages/intent/src/validate/repairs.ts +++ b/packages/intent/src/validate/repairs.ts @@ -1,6 +1,7 @@ import { basename, dirname } from 'node:path' import { isDeepStrictEqual } from 'node:util' import { parseDocument } from 'yaml' +import { errorMessage, isRecord } from '../shared/utils.js' import type { FileChange } from '../maintainer/files.js' export const agentSkillNamePattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ @@ -33,14 +34,12 @@ export function planFrontmatterRepair(path: string, source: string) { } catch (error) { return { changes, - problems: [ - `Invalid YAML frontmatter: ${error instanceof Error ? error.message : String(error)}`, - ], + problems: [`Invalid YAML frontmatter: ${errorMessage(error)}`], } } - if (!fields || typeof fields !== 'object' || Array.isArray(fields)) + if (!isRecord(fields)) return { changes, problems: ['Frontmatter must be a mapping'] } - const fm = fields as Record + const fm = fields const expected = { ...fm } const metadata = fm.metadata const canMove = diff --git a/packages/intent/tests/core-types.test.ts b/packages/intent/tests/core-types.test.ts deleted file mode 100644 index d8a238e5..00000000 --- a/packages/intent/tests/core-types.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { sourceIdentityEquals, sourceIdentityKey } from '../src/core/types.js' - -describe('sourceIdentityKey', () => { - it('distinguishes npm:foo from workspace:foo', () => { - expect(sourceIdentityKey({ kind: 'npm', id: 'foo' })).not.toBe( - sourceIdentityKey({ kind: 'workspace', id: 'foo' }), - ) - }) - - it('is stable for the same kind and id', () => { - expect(sourceIdentityKey({ kind: 'npm', id: 'foo' })).toBe( - sourceIdentityKey({ kind: 'npm', id: 'foo' }), - ) - }) -}) - -describe('sourceIdentityEquals', () => { - it('returns false when kind differs but id matches', () => { - expect( - sourceIdentityEquals( - { kind: 'npm', id: 'foo' }, - { kind: 'workspace', id: 'foo' }, - ), - ).toBe(false) - }) - - it('returns false when id differs but kind matches', () => { - expect( - sourceIdentityEquals( - { kind: 'npm', id: 'foo' }, - { kind: 'npm', id: 'bar' }, - ), - ).toBe(false) - }) - - it('returns true when kind and id both match', () => { - expect( - sourceIdentityEquals( - { kind: 'npm', id: 'foo' }, - { kind: 'npm', id: 'foo' }, - ), - ).toBe(true) - }) -}) diff --git a/packages/intent/tests/hooks.test.ts b/packages/intent/tests/hooks.test.ts index 64fe5eb7..2bd6b4cd 100644 --- a/packages/intent/tests/hooks.test.ts +++ b/packages/intent/tests/hooks.test.ts @@ -1,13 +1,7 @@ import { describe, expect, it } from 'vitest' -import { formatClaudePreToolUseOutput } from '../src/hooks/agents/claude.js' -import { formatCodexPreToolUseOutput } from '../src/hooks/agents/codex.js' -import { formatCopilotPreToolUseOutput } from '../src/hooks/agents/copilot.js' import { EDIT_TOOLS_BY_AGENT, GATE_DENY_REASON, - gateDecision, - hasIntentCheckFromObservations, - observationFromEvent, parseIntentInvocation, } from '../src/hooks/policy.js' @@ -59,99 +53,14 @@ describe('intent hook policy', () => { expect(parseIntentInvocation(undefined)).toBeUndefined() }) - it('observes intent commands only from Bash tool calls', () => { - expect( - observationFromEvent({ - tool_name: 'Bash', - tool_input: { command: 'intent load @tanstack/router#routing' }, - }), - ).toEqual({ - action: 'load', - skillUse: '@tanstack/router#routing', - raw: 'intent load @tanstack/router#routing', - }) - expect( - observationFromEvent({ - toolName: 'Bash', - toolArgs: JSON.stringify({ command: 'intent list' }), - }), - ).toEqual({ action: 'list', raw: 'intent list', skillUse: undefined }) - expect( - observationFromEvent({ - tool_name: 'Edit', - tool_input: { command: 'intent load @tanstack/router#routing' }, - }), - ).toBeUndefined() - }) - - it('denies edit tools until guidance is checked', () => { - expect( - gateDecision({ agent: 'copilot', toolName: 'Edit', hasLoaded: false }), - ).toEqual({ decision: 'deny', reason: GATE_DENY_REASON }) - expect( - gateDecision({ agent: 'claude', toolName: 'Write', hasLoaded: false }), - ).toEqual({ decision: 'deny', reason: GATE_DENY_REASON }) - expect( - gateDecision({ - agent: 'codex', - toolName: 'apply_patch', - hasLoaded: false, - }), - ).toEqual({ decision: 'deny', reason: GATE_DENY_REASON }) - expect( - gateDecision({ agent: 'copilot', toolName: 'Edit', hasLoaded: true }), - ).toEqual({ decision: 'allow' }) - expect( - gateDecision({ agent: 'codex', toolName: 'Bash', hasLoaded: false }), - ).toEqual({ decision: 'allow' }) + it('lists the edit tools gated per agent', () => { expect(EDIT_TOOLS_BY_AGENT.copilot.has('Write')).toBe(true) expect(EDIT_TOOLS_BY_AGENT.claude.has('Edit')).toBe(true) expect(EDIT_TOOLS_BY_AGENT.codex.has('apply_patch')).toBe(true) }) - it('detects a prior guidance check from observation records', () => { - expect(hasIntentCheckFromObservations([{ action: 'list' }])).toBe(true) - expect( - hasIntentCheckFromObservations([{ action: 'list' }, { action: 'load' }]), - ).toBe(true) - }) - it('keeps the deny reason free of parseable intent commands', () => { expect(parseIntentInvocation(GATE_DENY_REASON)).toBeUndefined() expect(/intent\s+(list|load)/i.test(GATE_DENY_REASON)).toBe(false) }) }) - -describe('intent hook agent adapters', () => { - const deny = { decision: 'deny' as const, reason: GATE_DENY_REASON } - - it('formats Copilot PreToolUse denial output', () => { - expect(formatCopilotPreToolUseOutput(deny)).toEqual({ - permissionDecision: 'deny', - permissionDecisionReason: GATE_DENY_REASON, - }) - expect(formatCopilotPreToolUseOutput({ decision: 'allow' })).toBeUndefined() - }) - - it('formats Claude PreToolUse denial output', () => { - expect(formatClaudePreToolUseOutput(deny)).toEqual({ - hookSpecificOutput: { - hookEventName: 'PreToolUse', - permissionDecision: 'deny', - permissionDecisionReason: GATE_DENY_REASON, - }, - }) - expect(formatClaudePreToolUseOutput({ decision: 'allow' })).toBeUndefined() - }) - - it('formats Codex PreToolUse denial output', () => { - expect(formatCodexPreToolUseOutput(deny)).toEqual({ - hookSpecificOutput: { - hookEventName: 'PreToolUse', - permissionDecision: 'deny', - permissionDecisionReason: GATE_DENY_REASON, - }, - }) - expect(formatCodexPreToolUseOutput({ decision: 'allow' })).toBeUndefined() - }) -}) diff --git a/packages/intent/tests/skill-paths.test.ts b/packages/intent/tests/skill-paths.test.ts index 4759608a..e70b0e51 100644 --- a/packages/intent/tests/skill-paths.test.ts +++ b/packages/intent/tests/skill-paths.test.ts @@ -5,7 +5,6 @@ import { afterEach, describe, expect, it } from 'vitest' import { formatRuntimeSkillLookupComment, formatRuntimeSkillLookupHint, - hasPackageManagerInternalPath, isAbsolutePath, isRuntimeSkillLookupComment, isStableLoadPath, @@ -46,24 +45,6 @@ describe('skill path helpers', () => { ).toBe(false) }) - it('detects package-manager-internal paths', () => { - expect( - hasPackageManagerInternalPath( - 'node_modules/.pnpm/@tanstack+query@1.0.0/node_modules/@tanstack/query/skills/core/SKILL.md', - ), - ).toBe(true) - expect( - hasPackageManagerInternalPath( - 'node_modules\\.bun\\@tanstack-query\\skills\\core\\SKILL.md', - ), - ).toBe(true) - expect( - hasPackageManagerInternalPath( - 'node_modules/@tanstack/query/skills/core/SKILL.md', - ), - ).toBe(false) - }) - it('allows only stable repo-relative load paths', () => { expect( isStableLoadPath('node_modules/@tanstack/query/skills/core/SKILL.md'), diff --git a/packages/intent/tests/skill-sources.test.ts b/packages/intent/tests/skill-sources.test.ts index d310241c..8836044c 100644 --- a/packages/intent/tests/skill-sources.test.ts +++ b/packages/intent/tests/skill-sources.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import { SkillSourcesParseError, - isSkillSourcesParseError, parseSkillSources, } from '../src/core/skill-sources.js' @@ -9,7 +8,7 @@ function expectParseError(value: unknown): SkillSourcesParseError { try { parseSkillSources(value) } catch (err) { - if (isSkillSourcesParseError(err)) return err + if (err instanceof SkillSourcesParseError) return err throw err } throw new Error('Expected parseSkillSources to throw') diff --git a/packages/intent/tests/validate-blocks.test.ts b/packages/intent/tests/validate-blocks.test.ts index b80d879f..8583f2c0 100644 --- a/packages/intent/tests/validate-blocks.test.ts +++ b/packages/intent/tests/validate-blocks.test.ts @@ -611,6 +611,65 @@ describe.each(['TypeScript 6', 'TypeScript 7'])('with %s', (compiler) => { ]) }) + it('uses a tracked declaration of a sibling package that is its own git repository', async () => { + write('pnpm-workspace.yaml', 'packages:\n - packages/*\n') + write('packages/client/package.json', '{"name":"@acme/client"}\n') + write('packages/client/src/index.ts', 'export const client = 1\n') + write( + 'packages/adapter/package.json', + '{"name":"@acme/adapter","types":"types/index.d.ts"}\n', + ) + write( + 'packages/adapter/src/index.ts', + 'export function openai(): void {}\nexport function gemini(): void {}\n', + ) + write( + 'packages/adapter/types/index.d.ts', + 'export declare function openai(): void\n', + ) + execFileSync('git', ['-c', 'core.fsmonitor=false', 'init', '-q'], { + cwd: root, + }) + execFileSync('git', ['-c', 'core.fsmonitor=false', 'init', '-q'], { + cwd: join(root, 'packages/adapter'), + }) + execFileSync('git', ['-c', 'core.fsmonitor=false', 'add', 'types'], { + cwd: join(root, 'packages/adapter'), + }) + write( + 'packages/client/skills/adapters/SKILL.md', + [ + '---', + 'name: adapters', + 'description: Use when choosing an adapter.', + '---', + '```ts', + "import { openai, gemini } from '@acme/adapter'", + '```', + '', + ].join('\n'), + ) + const findings = ( + await checkSkillBlocks({ + root, + packageDir: join(root, 'packages/client'), + library: '@acme/adapter', + skills: [ + { + file: 'packages/client/skills/adapters/SKILL.md', + content: read('packages/client/skills/adapters/SKILL.md'), + }, + ], + }) + ).findings + expect(findings).toEqual([ + expect.objectContaining({ + line: 6, + message: expect.stringMatching(/TS2305: .*'gemini'/), + }), + ]) + }) + it('skips typechecking with a reason when TypeScript or a type entry is unavailable', async () => { skill("```ts\nimport { retry } from '@acme/client'\n```\n") expect( diff --git a/packages/intent/tests/workspace-patterns.test.ts b/packages/intent/tests/workspace-patterns.test.ts index 3c9c6a6c..cc75c554 100644 --- a/packages/intent/tests/workspace-patterns.test.ts +++ b/packages/intent/tests/workspace-patterns.test.ts @@ -12,7 +12,6 @@ import { findPackagesWithSkills, findWorkspacePackages, findWorkspaceRoot, - getWorkspaceInfo, readWorkspacePatterns, resolveWorkspacePackages, } from '../src/setup/workspace-patterns.js' @@ -362,13 +361,6 @@ describe('workspace helpers', () => { withCwd(nestedDir) expect(findWorkspaceRoot(process.cwd())).toBe(root) - expect(getWorkspaceInfo(root)?.packageDirs).toEqual([ - join(root, 'packages', 'alpha'), - join(root, 'packages', 'beta'), - ]) - expect(getWorkspaceInfo(root)?.packageDirsWithSkills).toEqual([ - join(root, 'packages', 'alpha'), - ]) expect(findPackagesWithSkills(root)).toEqual([ join(root, 'packages', 'alpha'), ]) From 22c62ed27d9bf49ff460e705a4e6df0935f6113e Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:43:37 -0700 Subject: [PATCH 02/12] test: reduce duplication in test setup and fixtures Share the permission prompt fixture and the global package fixture, use vi.stubEnv and vi.restoreAllMocks in place of manual save and restore, and merge cases that differ by one argument into it.each. Drop one load --path test that repeated the test before it. --- packages/intent/tests/cli.test.ts | 554 +++++------------- packages/intent/tests/core.test.ts | 44 +- packages/intent/tests/fixtures/permissions.ts | 48 ++ packages/intent/tests/install-writer.test.ts | 35 +- .../integration/load-integration.test.ts | 33 +- .../tests/integration/packed-release.test.ts | 76 +-- .../integration/pnp-berry-corepack.test.ts | 29 +- packages/intent/tests/integration/scaffold.ts | 136 ++--- .../integration/scanner-integration.test.ts | 35 +- packages/intent/tests/permissions.test.ts | 51 +- packages/intent/tests/scanner.test.ts | 260 +++----- packages/intent/tests/setup.test.ts | 16 +- packages/intent/tests/stale-command.test.ts | 126 ++-- packages/intent/tests/staleness.test.ts | 36 +- packages/intent/tests/support.test.ts | 4 - 15 files changed, 433 insertions(+), 1050 deletions(-) create mode 100644 packages/intent/tests/fixtures/permissions.ts diff --git a/packages/intent/tests/cli.test.ts b/packages/intent/tests/cli.test.ts index 9e6510f9..d005a9ce 100644 --- a/packages/intent/tests/cli.test.ts +++ b/packages/intent/tests/cli.test.ts @@ -16,6 +16,7 @@ import * as discovery from '../src/discovery/scanner.js' import { INSTALL_PROMPT } from '../src/commands/install/command.js' import { isMainModule, main } from '../src/cli.js' import { runValidateCommand } from '../src/commands/validate.js' +import { permissionPrompts } from './fixtures/permissions.js' import type { PermissionPrompts } from '../src/commands/install/permissions.js' const thisDir = dirname(fileURLToPath(import.meta.url)) @@ -69,21 +70,30 @@ function writeInstalledIntentPackage( }) } -function permissionPrompts({ - confirmWrite = true, - selection = [], -}: { - confirmWrite?: boolean | null - selection?: Array | null -} = {}): PermissionPrompts { - return { - selectPermissions: vi.fn(async () => selection), - reviewPermissions: vi.fn((_groups, selection) => - Promise.resolve(selection), - ), - editPermissions: vi.fn((_groups, selection) => Promise.resolve(selection)), - confirmWrite: vi.fn(async () => confirmWrite), - } +function writeGlobalIntentPackage( + globalRoot: string, + version: string, + frontmatter: Record = {}, +): string { + const pkgDir = join(globalRoot, '@tanstack', 'query') + writeJson(join(pkgDir, 'package.json'), { + name: '@tanstack/query', + version, + intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, + }) + writeSkillMd(join(pkgDir, 'skills', 'fetching'), { + name: 'fetching', + description: 'Global fetching skill', + ...frontmatter, + }) + return pkgDir +} + +function mockFetchVersion(version: string) { + return vi.spyOn(globalThis, 'fetch').mockResolvedValue({ + ok: true, + json: () => Promise.resolve({ version }), + } as Response) } let originalCwd: string @@ -92,9 +102,6 @@ let infoSpy: ReturnType let errorSpy: ReturnType let stdoutWriteSpy: ReturnType let tempDirs: Array -let previousGlobalNodeModules: string | undefined -let previousNoNotices: string | undefined -let previousIntentAudience: string | undefined function getHelpOutput(): string { return [...infoSpy.mock.calls, ...logSpy.mock.calls] @@ -105,12 +112,9 @@ function getHelpOutput(): string { beforeEach(() => { originalCwd = process.cwd() tempDirs = [] - previousGlobalNodeModules = process.env.INTENT_GLOBAL_NODE_MODULES - previousNoNotices = process.env.INTENT_NO_NOTICES - previousIntentAudience = process.env.INTENT_AUDIENCE - delete process.env.INTENT_GLOBAL_NODE_MODULES - delete process.env.INTENT_NO_NOTICES - delete process.env.INTENT_AUDIENCE + vi.stubEnv('INTENT_GLOBAL_NODE_MODULES', undefined) + vi.stubEnv('INTENT_NO_NOTICES', undefined) + vi.stubEnv('INTENT_AUDIENCE', undefined) logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) infoSpy = vi.spyOn(console, 'info').mockImplementation(() => {}) errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) @@ -121,25 +125,8 @@ beforeEach(() => { afterEach(() => { process.chdir(originalCwd) - if (previousGlobalNodeModules === undefined) { - delete process.env.INTENT_GLOBAL_NODE_MODULES - } else { - process.env.INTENT_GLOBAL_NODE_MODULES = previousGlobalNodeModules - } - if (previousNoNotices === undefined) { - delete process.env.INTENT_NO_NOTICES - } else { - process.env.INTENT_NO_NOTICES = previousNoNotices - } - if (previousIntentAudience === undefined) { - delete process.env.INTENT_AUDIENCE - } else { - process.env.INTENT_AUDIENCE = previousIntentAudience - } - logSpy.mockRestore() - infoSpy.mockRestore() - errorSpy.mockRestore() - stdoutWriteSpy.mockRestore() + vi.unstubAllEnvs() + vi.restoreAllMocks() for (const dir of tempDirs) { if (existsSync(dir)) { rmSync(dir, { recursive: true, force: true }) @@ -212,7 +199,6 @@ describe('intent meta', () => { ) const format = join('generate-skill', 'references', 'skill-format.md') const distribution = join('generate-skill', 'references', 'distribution.md') - // Rewritten destinations always use forward slashes, on every platform. const posix = (path: string) => path.split(sep).join('/') expect(output).toContain(`](${posix(join(metaDir, format))})`) expect(output).toContain(`](${posix(join(metaDir, distribution))})`) @@ -1126,16 +1112,7 @@ describe('cli commands', () => { ) tempDirs.push(root, globalRoot) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + writeGlobalIntentPackage(globalRoot, '5.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -1155,16 +1132,7 @@ describe('cli commands', () => { ) tempDirs.push(root, globalRoot) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + writeGlobalIntentPackage(globalRoot, '5.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -1193,16 +1161,7 @@ describe('cli commands', () => { skillName: 'local-skill', description: 'Local skill', }) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + writeGlobalIntentPackage(globalRoot, '5.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -1246,47 +1205,29 @@ describe('cli commands', () => { expect(output).toContain('Added keywords: "tanstack-intent"') }) - it('copies github workflow templates', async () => { - const root = mkdtempSync(join(realTmpdir, 'intent-cli-setup-gha-')) - tempDirs.push(root) - writeJson(join(root, 'package.json'), { - name: '@scope/pkg', - version: '1.0.0', - intent: { version: 1, repo: 'scope/pkg', docs: 'docs/' }, - }) - - process.chdir(root) - - const exitCode = await main(['setup-github-actions']) - const workflowsDir = join(root, '.github', 'workflows') - const output = logSpy.mock.calls.flat().join('\n') - - expect(exitCode).toBe(0) - expect(existsSync(workflowsDir)).toBe(true) - expect(output).toContain('Copied workflow:') - expect(output).toContain('Template variables applied:') - }) - - it('copies github workflow templates with the setup alias', async () => { - const root = mkdtempSync(join(realTmpdir, 'intent-cli-setup-alias-')) - tempDirs.push(root) - writeJson(join(root, 'package.json'), { - name: '@scope/pkg', - version: '1.0.0', - intent: { version: 1, repo: 'scope/pkg', docs: 'docs/' }, - }) + it.each(['setup-github-actions', 'setup'])( + 'copies github workflow templates with %s', + async (command) => { + const root = mkdtempSync(join(realTmpdir, 'intent-cli-setup-gha-')) + tempDirs.push(root) + writeJson(join(root, 'package.json'), { + name: '@scope/pkg', + version: '1.0.0', + intent: { version: 1, repo: 'scope/pkg', docs: 'docs/' }, + }) - process.chdir(root) + process.chdir(root) - const exitCode = await main(['setup']) - const workflowsDir = join(root, '.github', 'workflows') - const output = logSpy.mock.calls.flat().join('\n') + const exitCode = await main([command]) + const workflowsDir = join(root, '.github', 'workflows') + const output = logSpy.mock.calls.flat().join('\n') - expect(exitCode).toBe(0) - expect(existsSync(workflowsDir)).toBe(true) - expect(output).toContain('Copied workflow:') - expect(output).toContain('Template variables applied:') - }) + expect(exitCode).toBe(0) + expect(existsSync(workflowsDir)).toBe(true) + expect(output).toContain('Copied workflow:') + expect(output).toContain('Template variables applied:') + }, + ) it('copies github workflow templates to the workspace root', async () => { const root = mkdtempSync(join(realTmpdir, 'intent-cli-setup-gha-mono-')) @@ -1763,16 +1704,7 @@ describe('cli commands', () => { ) tempDirs.push(root, globalRoot) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + writeGlobalIntentPackage(globalRoot, '5.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -1794,16 +1726,7 @@ describe('cli commands', () => { ) tempDirs.push(root, globalRoot) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + writeGlobalIntentPackage(globalRoot, '5.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -1850,16 +1773,7 @@ describe('cli commands', () => { ) tempDirs.push(root, globalRoot) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + const globalPkgDir = writeGlobalIntentPackage(globalRoot, '5.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -1893,16 +1807,7 @@ describe('cli commands', () => { description: 'Local fetching skill', }) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '4.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + writeGlobalIntentPackage(globalRoot, '4.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -1941,16 +1846,7 @@ describe('cli commands', () => { }) writeFileSync(join(root, '.pnp.cjs'), 'module.exports = {}\n') - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '4.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + writeGlobalIntentPackage(globalRoot, '4.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -2156,29 +2052,6 @@ describe('cli commands', () => { expect(output).toBe('node_modules/@tanstack/query/skills/fetching/SKILL.md') }) - it('prints a skill path without reading skill content', async () => { - const root = mkdtempSync(join(realTmpdir, 'intent-cli-load-path-only-')) - tempDirs.push(root) - const pkgDir = join(root, 'node_modules', '@tanstack', 'query') - writeJson(join(pkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(pkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Query data fetching patterns', - }) - - process.chdir(root) - - const exitCode = await main(['load', '@tanstack/query#fetching', '--path']) - const output = logSpy.mock.calls.flat().join('\n') - - expect(exitCode).toBe(0) - expect(output).toBe('node_modules/@tanstack/query/skills/fetching/SKILL.md') - }) - it('prints load debug details to stderr without changing path stdout', async () => { const root = mkdtempSync(join(realTmpdir, 'intent-cli-load-debug-')) tempDirs.push(root) @@ -2293,16 +2166,7 @@ describe('cli commands', () => { ) tempDirs.push(root, globalRoot) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + const globalPkgDir = writeGlobalIntentPackage(globalRoot, '5.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -2333,16 +2197,7 @@ describe('cli commands', () => { description: 'Local fetching skill', }) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '4.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - }) + const globalPkgDir = writeGlobalIntentPackage(globalRoot, '4.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -3909,32 +3764,23 @@ describe('cli commands', () => { it('writes a GitHub summary when validation fails', async () => { const root = mkdtempSync(join(realTmpdir, 'intent-cli-validate-summary-')) tempDirs.push(root) - const previousSummary = process.env.GITHUB_STEP_SUMMARY const summaryPath = join(root, 'summary.md') writeSkillMd(join(root, 'skills', 'db-core'), { name: 'wrong-name', description: 'Core database concepts', }) process.chdir(root) - process.env.GITHUB_STEP_SUMMARY = summaryPath + vi.stubEnv('GITHUB_STEP_SUMMARY', summaryPath) - try { - const exitCode = await main(['validate', '--github-summary']) - const summary = readFileSync(summaryPath, 'utf8') - - expect(exitCode).toBe(1) - expect(summary).toContain('Skill validation failed.') - expect(summary).toContain('Why this failed:') - expect(summary).toContain( - 'name "wrong-name" does not match parent directory "db-core"', - ) - } finally { - if (previousSummary === undefined) { - delete process.env.GITHUB_STEP_SUMMARY - } else { - process.env.GITHUB_STEP_SUMMARY = previousSummary - } - } + const exitCode = await main(['validate', '--github-summary']) + const summary = readFileSync(summaryPath, 'utf8') + + expect(exitCode).toBe(1) + expect(summary).toContain('Skill validation failed.') + expect(summary).toContain('Why this failed:') + expect(summary).toContain( + 'name "wrong-name" does not match parent directory "db-core"', + ) }) it('fails cleanly when the Yarn PnP API cannot be loaded', async () => { @@ -3986,10 +3832,7 @@ describe('cli commands', () => { library_version: '1.0.0', }) - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) + mockFetchVersion('1.0.0') process.chdir(root) @@ -4000,8 +3843,6 @@ describe('cli commands', () => { expect(exitCode).toBe(0) expect(reports).toHaveLength(1) expect(reports[0]!.library).toBe('@tanstack/router') - - fetchSpy.mockRestore() }) it('prefers workspace package staleness when the workspace root has a skills directory', async () => { @@ -4039,10 +3880,7 @@ describe('cli commands', () => { ].join('\n'), ) - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) + mockFetchVersion('1.0.0') process.chdir(root) @@ -4069,8 +3907,6 @@ describe('cli commands', () => { }), ]), ) - - fetchSpy.mockRestore() }) it('flags workspace packages missing skill and artifact coverage', async () => { @@ -4107,10 +3943,7 @@ describe('cli commands', () => { ].join('\n'), ) - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) + mockFetchVersion('1.0.0') process.chdir(root) @@ -4131,8 +3964,6 @@ describe('cli commands', () => { packageName: '@tanstack/react-start-rsc', }), ]) - - fetchSpy.mockRestore() }) it('does not flag workspace packages ignored in artifact coverage', async () => { @@ -4174,10 +4005,7 @@ describe('cli commands', () => { ].join('\n'), ) - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) + mockFetchVersion('1.0.0') process.chdir(root) @@ -4200,8 +4028,6 @@ describe('cli commands', () => { }), ]), ) - - fetchSpy.mockRestore() }) it('does not flag private workspace packages as missing coverage', async () => { @@ -4244,10 +4070,7 @@ describe('cli commands', () => { ].join('\n'), ) - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) + mockFetchVersion('1.0.0') process.chdir(root) @@ -4276,8 +4099,6 @@ describe('cli commands', () => { }), ]), ) - - fetchSpy.mockRestore() }) it('flags missing coverage even when no workspace package has generated skills yet', async () => { @@ -4302,10 +4123,7 @@ describe('cli commands', () => { ].join('\n'), ) - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) + mockFetchVersion('1.0.0') process.chdir(root) @@ -4326,8 +4144,6 @@ describe('cli commands', () => { packageName: '@tanstack/react-start-rsc', }), ]) - - fetchSpy.mockRestore() }) it('ignores configured global intent packages when checking staleness', async () => { @@ -4337,17 +4153,7 @@ describe('cli commands', () => { ) tempDirs.push(root, globalRoot) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - library_version: '5.0.0', - }) + writeGlobalIntentPackage(globalRoot, '5.0.0', { library_version: '5.0.0' }) process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -4379,22 +4185,9 @@ describe('cli commands', () => { library_version: '1.0.0', }) - const globalPkgDir = join(globalRoot, '@tanstack', 'query') - writeJson(join(globalPkgDir, 'package.json'), { - name: '@tanstack/query', - version: '5.0.0', - intent: { version: 1, repo: 'TanStack/query', docs: 'docs/' }, - }) - writeSkillMd(join(globalPkgDir, 'skills', 'fetching'), { - name: 'fetching', - description: 'Global fetching skill', - library_version: '5.0.0', - }) + writeGlobalIntentPackage(globalRoot, '5.0.0', { library_version: '5.0.0' }) - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) + mockFetchVersion('1.0.0') process.env.INTENT_GLOBAL_NODE_MODULES = globalRoot process.chdir(root) @@ -4406,143 +4199,65 @@ describe('cli commands', () => { expect(exitCode).toBe(0) expect(reports).toHaveLength(1) expect(reports[0]!.library).toBe('@tanstack/router') - - fetchSpy.mockRestore() }) - it('checks only the targeted workspace package for staleness', async () => { - const root = mkdtempSync(join(realTmpdir, 'intent-cli-stale-target-')) - tempDirs.push(root) - - writeJson(join(root, 'package.json'), { - private: true, - workspaces: ['packages/*'], - }) - writeJson(join(root, 'packages', 'router', 'package.json'), { - name: '@tanstack/router', - }) - writeJson(join(root, 'packages', 'query', 'package.json'), { - name: '@tanstack/query', - }) - writeSkillMd(join(root, 'packages', 'router', 'skills', 'routing'), { - name: 'routing', - description: 'Routing skill', - library_version: '1.0.0', - }) - writeSkillMd(join(root, 'packages', 'query', 'skills', 'cache'), { - name: 'cache', - description: 'Caching skill', - library_version: '1.0.0', - }) - - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) - - process.chdir(root) - - const exitCode = await main(['stale', 'packages/router/skills', '--json']) - const output = logSpy.mock.calls.at(-1)?.[0] - const reports = JSON.parse(String(output)) as Array<{ library: string }> - - expect(exitCode).toBe(0) - expect(reports).toHaveLength(1) - expect(reports[0]!.library).toBe('@tanstack/router') - expect(fetchSpy).toHaveBeenCalledTimes(1) - - fetchSpy.mockRestore() - }) - - it('checks only the targeted workspace package when path omits /skills suffix', async () => { - const root = mkdtempSync( - join(realTmpdir, 'intent-cli-stale-target-nosuffix-'), - ) - tempDirs.push(root) - - writeJson(join(root, 'package.json'), { - private: true, - workspaces: ['packages/*'], - }) - writeJson(join(root, 'packages', 'router', 'package.json'), { - name: '@tanstack/router', - }) - writeJson(join(root, 'packages', 'query', 'package.json'), { - name: '@tanstack/query', - }) - writeSkillMd(join(root, 'packages', 'router', 'skills', 'routing'), { - name: 'routing', - description: 'Routing skill', - library_version: '1.0.0', - }) - writeSkillMd(join(root, 'packages', 'query', 'skills', 'cache'), { - name: 'cache', - description: 'Caching skill', - library_version: '1.0.0', - }) - - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) - - process.chdir(root) - - const exitCode = await main(['stale', 'packages/router', '--json']) - const output = logSpy.mock.calls.at(-1)?.[0] - const reports = JSON.parse(String(output)) as Array<{ library: string }> - - expect(exitCode).toBe(0) - expect(reports).toHaveLength(1) - expect(reports[0]!.library).toBe('@tanstack/router') - expect(fetchSpy).toHaveBeenCalledTimes(1) - - fetchSpy.mockRestore() - }) - - it('checks the current workspace package for staleness from package cwd', async () => { - const root = mkdtempSync(join(realTmpdir, 'intent-cli-stale-package-cwd-')) - tempDirs.push(root) - - writeJson(join(root, 'package.json'), { - private: true, - workspaces: ['packages/*'], - }) - writeJson(join(root, 'packages', 'router', 'package.json'), { - name: '@tanstack/router', - }) - writeJson(join(root, 'packages', 'query', 'package.json'), { - name: '@tanstack/query', - }) - writeSkillMd(join(root, 'packages', 'router', 'skills', 'routing'), { - name: 'routing', - description: 'Routing skill', - library_version: '1.0.0', - }) - writeSkillMd(join(root, 'packages', 'query', 'skills', 'cache'), { - name: 'cache', - description: 'Caching skill', - library_version: '1.0.0', - }) + it.each([ + { + name: 'a skills path', + args: ['stale', 'packages/router/skills', '--json'], + cwd: '.', + }, + { + name: 'a package path', + args: ['stale', 'packages/router', '--json'], + cwd: '.', + }, + { + name: 'the package cwd', + args: ['stale', '--json'], + cwd: 'packages/router', + }, + ])( + 'checks only the targeted workspace package for staleness from $name', + async ({ args, cwd }) => { + const root = mkdtempSync(join(realTmpdir, 'intent-cli-stale-target-')) + tempDirs.push(root) - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) + writeJson(join(root, 'package.json'), { + private: true, + workspaces: ['packages/*'], + }) + writeJson(join(root, 'packages', 'router', 'package.json'), { + name: '@tanstack/router', + }) + writeJson(join(root, 'packages', 'query', 'package.json'), { + name: '@tanstack/query', + }) + writeSkillMd(join(root, 'packages', 'router', 'skills', 'routing'), { + name: 'routing', + description: 'Routing skill', + library_version: '1.0.0', + }) + writeSkillMd(join(root, 'packages', 'query', 'skills', 'cache'), { + name: 'cache', + description: 'Caching skill', + library_version: '1.0.0', + }) - process.chdir(join(root, 'packages', 'router')) + const fetchSpy = mockFetchVersion('1.0.0') - const exitCode = await main(['stale', '--json']) - const output = logSpy.mock.calls.at(-1)?.[0] - const reports = JSON.parse(String(output)) as Array<{ library: string }> + process.chdir(join(root, cwd)) - expect(exitCode).toBe(0) - expect(reports).toHaveLength(1) - expect(reports[0]!.library).toBe('@tanstack/router') - expect(fetchSpy).toHaveBeenCalledTimes(1) + const exitCode = await main(args) + const output = logSpy.mock.calls.at(-1)?.[0] + const reports = JSON.parse(String(output)) as Array<{ library: string }> - fetchSpy.mockRestore() - }) + expect(exitCode).toBe(0) + expect(reports).toHaveLength(1) + expect(reports[0]!.library).toBe('@tanstack/router') + expect(fetchSpy).toHaveBeenCalledTimes(1) + }, + ) it('handles absolute targetDir path correctly', async () => { const root = mkdtempSync(join(realTmpdir, 'intent-cli-stale-abs-')) @@ -4558,10 +4273,7 @@ describe('cli commands', () => { library_version: '1.0.0', }) - const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ version: '1.0.0' }), - } as Response) + mockFetchVersion('1.0.0') const elsewhere = mkdtempSync(join(realTmpdir, 'intent-cli-stale-abs-cwd-')) tempDirs.push(elsewhere) @@ -4574,8 +4286,6 @@ describe('cli commands', () => { expect(exitCode).toBe(0) expect(reports).toHaveLength(1) expect(reports[0]!.library).toBe('@tanstack/router') - - fetchSpy.mockRestore() }) }) diff --git a/packages/intent/tests/core.test.ts b/packages/intent/tests/core.test.ts index 6be0edde..476e8b9a 100644 --- a/packages/intent/tests/core.test.ts +++ b/packages/intent/tests/core.test.ts @@ -1167,17 +1167,15 @@ describe('loadIntentSkill — kind-mismatch late gate', () => { description: 'Query data fetching patterns', }) - let thrown: unknown - try { - loadIntentSkill('@tanstack/query#fetching', { cwd: root, debug: true }) - } catch (err) { - thrown = err - } - - expect(thrown).toBeInstanceOf(IntentCoreError) - expect((thrown as IntentCoreError).code).toBe('package-not-listed') - expect((thrown as Error).message).toBe( - 'Cannot load skill use "@tanstack/query#fetching": package "@tanstack/query" is not listed in intent.skills.', + expect(() => + loadIntentSkill('@tanstack/query#fetching', { cwd: root, debug: true }), + ).toThrow( + expect.objectContaining({ + name: 'IntentCoreError', + code: 'package-not-listed', + message: + 'Cannot load skill use "@tanstack/query#fetching": package "@tanstack/query" is not listed in intent.skills.', + }), ) }) @@ -1195,21 +1193,15 @@ describe('loadIntentSkill — kind-mismatch late gate', () => { description: 'Query data fetching patterns', }) - let thrown: unknown - try { - const result = loadIntentSkill('@tanstack/query#fetching', { - cwd: root, - debug: true, - }) - thrown = result - } catch (err) { - thrown = err - } - - expect(thrown).toBeInstanceOf(IntentCoreError) - expect((thrown as IntentCoreError).code).toBe('package-not-listed') - expect((thrown as Error).message).toBe( - 'Cannot load skill use "@tanstack/query#fetching": package "@tanstack/query" is not listed in intent.skills.', + expect(() => + loadIntentSkill('@tanstack/query#fetching', { cwd: root, debug: true }), + ).toThrow( + expect.objectContaining({ + name: 'IntentCoreError', + code: 'package-not-listed', + message: + 'Cannot load skill use "@tanstack/query#fetching": package "@tanstack/query" is not listed in intent.skills.', + }), ) }) diff --git a/packages/intent/tests/fixtures/permissions.ts b/packages/intent/tests/fixtures/permissions.ts new file mode 100644 index 00000000..87c5de55 --- /dev/null +++ b/packages/intent/tests/fixtures/permissions.ts @@ -0,0 +1,48 @@ +import { vi } from 'vitest' +import type { + PermissionPackage, + PermissionPrompts, +} from '../../src/commands/install/permissions.js' +import type { IntentPackage, ScanResult } from '../../src/shared/types.js' + +export function permissionPrompts({ + confirmWrite = true, + selection = [], +}: { + confirmWrite?: boolean | null + selection?: Array | null +} = {}): PermissionPrompts & { groups: Array } { + const result = { + groups: [] as Array, + selectPermissions: vi.fn(async (groups: Array) => { + result.groups = groups + return selection + }), + reviewPermissions: vi.fn((_groups, selection) => + Promise.resolve(selection), + ), + editPermissions: vi.fn((_groups, selection) => Promise.resolve(selection)), + confirmWrite: vi.fn(async () => confirmWrite), + } + return result +} + +export function scanResult(packages: Array): ScanResult { + return { + packageManager: 'pnpm', + packages, + warnings: [], + notices: [], + conflicts: [], + nodeModules: { + local: { + path: 'node_modules', + detected: true, + exists: true, + scanned: true, + }, + global: { path: null, detected: false, exists: false, scanned: false }, + }, + stats: { packageJsonCacheHits: 0, packageJsonReadCount: 0 }, + } +} diff --git a/packages/intent/tests/install-writer.test.ts b/packages/intent/tests/install-writer.test.ts index bd56f5ec..3104dcb4 100644 --- a/packages/intent/tests/install-writer.test.ts +++ b/packages/intent/tests/install-writer.test.ts @@ -21,11 +21,8 @@ import { preparePackageSkillsUpdate, writePreparedPackageSkillsUpdate, } from '../src/commands/install/package-json.js' -import type { - IntentPackage, - ScanResult, - SkillEntry, -} from '../src/shared/types.js' +import { scanResult } from './fixtures/permissions.js' +import type { IntentPackage, SkillEntry } from '../src/shared/types.js' const tempDirs: Array = [] @@ -63,34 +60,6 @@ function pkg(overrides: Partial): IntentPackage { } } -function scanResult(packages: Array): ScanResult { - return { - packageManager: 'pnpm', - packages, - warnings: [], - notices: [], - conflicts: [], - nodeModules: { - local: { - path: 'node_modules', - detected: true, - exists: true, - scanned: true, - }, - global: { - path: null, - detected: false, - exists: false, - scanned: false, - }, - }, - stats: { - packageJsonCacheHits: 0, - packageJsonReadCount: 0, - }, - } -} - const exampleBlock = ` # TanStack Intent - before editing files, run the matching guidance command. tanstackIntent: diff --git a/packages/intent/tests/integration/load-integration.test.ts b/packages/intent/tests/integration/load-integration.test.ts index 913a6d0b..d0c99b46 100644 --- a/packages/intent/tests/integration/load-integration.test.ts +++ b/packages/intent/tests/integration/load-integration.test.ts @@ -49,11 +49,7 @@ describe.each(PACKAGE_MANAGERS)('intent load via installed bin (%s)', (pm) => { const result = runLoad(cwd, SKILL_USE) - if (result.exitCode !== 0) { - throw new Error( - `intent load failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, - ) - } + expect(result.exitCode, result.stderr).toBe(0) expectSkillContent(result.stdout) }, 60_000, @@ -72,11 +68,7 @@ describe('intent load resolution variants', () => { const result = runLoad(cwd, SKILL_USE, { path: true }) - if (result.exitCode !== 0) { - throw new Error( - `intent load --path failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, - ) - } + expect(result.exitCode, result.stderr).toBe(0) expect(result.stdout.trim()).toMatch(/skills[/\\]core[/\\]SKILL\.md\s*$/) }, 60_000) @@ -91,18 +83,13 @@ describe('intent load resolution variants', () => { const result = runLoad(cwd, SKILL_USE, { json: true }) - if (result.exitCode !== 0) { - throw new Error( - `intent load --json failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, - ) - } + expect(result.exitCode, result.stderr).toBe(0) expect(result.parsed).toMatchObject({ package: '@test-intent/skills-leaf', skill: 'core', version: '1.0.0', + content: expect.stringContaining('# Core Skill'), }) - expect(typeof result.parsed.content).toBe('string') - expect(result.parsed.content).toContain('# Core Skill') }, 60_000) it.skipIf(!canSymlink())( @@ -118,11 +105,7 @@ describe('intent load resolution variants', () => { const result = runLoad(cwd, SKILL_USE, { method: 'symlink' }) - if (result.exitCode !== 0) { - throw new Error( - `intent load via symlink failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, - ) - } + expect(result.exitCode, result.stderr).toBe(0) expectSkillContent(result.stdout) }, 60_000, @@ -139,11 +122,7 @@ describe('intent load resolution variants', () => { const result = runLoad(cwd, SKILL_USE) - if (result.exitCode !== 0) { - throw new Error( - `intent load in monorepo-workspace failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, - ) - } + expect(result.exitCode, result.stderr).toBe(0) expectSkillContent(result.stdout) }, 60_000) }) diff --git a/packages/intent/tests/integration/packed-release.test.ts b/packages/intent/tests/integration/packed-release.test.ts index 0f474378..28407c5b 100644 --- a/packages/intent/tests/integration/packed-release.test.ts +++ b/packages/intent/tests/integration/packed-release.test.ts @@ -34,6 +34,28 @@ function run(args: Array) { }) } +function initRepo(dir: string): void { + execFileSync('git', ['-c', 'core.fsmonitor=false', 'init', '-q'], { + cwd: dir, + }) + execFileSync( + 'git', + [ + '-c', + 'core.fsmonitor=false', + '-c', + 'user.name=Fixture', + '-c', + 'user.email=fixture@example.invalid', + 'commit', + '--allow-empty', + '-qm', + 'fixture', + ], + { cwd: dir }, + ) +} + beforeAll(() => { root = realpathSync(mkdtempSync(join(tmpdir(), 'intent-packed-release-'))) const packed = JSON.parse( @@ -303,23 +325,7 @@ describe('packed release', () => { }) it('sets up and registers a skill through the packed CLI and includes it in the owning npm package', () => { - execFileSync('git', ['-c', 'core.fsmonitor=false', 'init', '-q'], { cwd }) - execFileSync( - 'git', - [ - '-c', - 'core.fsmonitor=false', - '-c', - 'user.name=Fixture', - '-c', - 'user.email=fixture@example.invalid', - 'commit', - '--allow-empty', - '-qm', - 'fixture', - ], - { cwd }, - ) + initRepo(cwd) writeFileSync( join(cwd, 'package.json'), '{"name":"consumer","version":"1.0.0","files":["dist"]}\n', @@ -581,23 +587,7 @@ Existing fixture guidance, pending source review. }) it('requires the planning records after maintainer setup in the packed CLI', () => { - execFileSync('git', ['-c', 'core.fsmonitor=false', 'init', '-q'], { cwd }) - execFileSync( - 'git', - [ - '-c', - 'core.fsmonitor=false', - '-c', - 'user.name=Fixture', - '-c', - 'user.email=fixture@example.invalid', - 'commit', - '--allow-empty', - '-qm', - 'fixture', - ], - { cwd }, - ) + initRepo(cwd) expect(run(['install', '--maintainer']).status).toBe(0) const missingRecords = JSON.parse(run(['review', '--json']).stdout) expect( @@ -611,23 +601,7 @@ Existing fixture guidance, pending source review. it.each(['skills', '.agents/knowledge'])( 'installs the maintainer workflow and reviews sources under %s with the packed CLI', (skillRoot) => { - execFileSync('git', ['-c', 'core.fsmonitor=false', 'init', '-q'], { cwd }) - execFileSync( - 'git', - [ - '-c', - 'core.fsmonitor=false', - '-c', - 'user.name=Fixture', - '-c', - 'user.email=fixture@example.invalid', - 'commit', - '--allow-empty', - '-qm', - 'fixture', - ], - { cwd }, - ) + initRepo(cwd) const installed = run(['install', '--maintainer']) expect(installed.status, installed.stderr).toBe(0) expect(readFileSync(join(cwd, 'AGENTS.md'), 'utf8')).toContain( diff --git a/packages/intent/tests/integration/pnp-berry-corepack.test.ts b/packages/intent/tests/integration/pnp-berry-corepack.test.ts index 193cc64d..bd555188 100644 --- a/packages/intent/tests/integration/pnp-berry-corepack.test.ts +++ b/packages/intent/tests/integration/pnp-berry-corepack.test.ts @@ -13,21 +13,15 @@ import { fileURLToPath } from 'node:url' import { afterAll, describe, expect, it } from 'vitest' /** - * Regression guard for discussion #119: skill discovery in a real Yarn Berry - * (v4) project that uses `nodeLinker: pnp` and has no `node_modules`, where - * dependencies live inside `.yarn/cache/*.zip`. The project is generated with - * `corepack` at test time and a skill-bearing dependency is installed as a - * tarball so Yarn stores it in the zip cache (the shape that triggered #119). - * - * Reading inside the zip cache requires Yarn's libzip-patched `fs`. A synthetic - * `.pnp.cjs` with a no-op `setup()` does not reproduce that, so this uses a real - * Yarn install. The built CLI is run from the project cwd while Intent itself - * lives outside the project's PnP graph — the exact `npx`/`dlx` invocation from - * the report. - * - * On CI this test must run (it does not skip silently), so a #119 regression - * always surfaces. Locally it is skipped only when corepack/Yarn Berry cannot be - * set up (e.g. offline), to keep the suite runnable without network. + * Regression guard for discussion #119: a real Yarn Berry project with + * `nodeLinker: pnp` and no `node_modules`, where a skill-bearing dependency is + * installed from a tarball so Yarn keeps it inside `.yarn/cache/*.zip`. + * Reading that cache needs Yarn's libzip-patched `fs`, which a synthetic + * `.pnp.cjs` with a no-op `setup()` cannot reproduce, so the project is + * generated with `corepack` and installed for real. The built CLI runs from the + * project cwd while Intent lives outside the PnP graph, as `npx`/`dlx` do. + * On CI this always runs; locally it is skipped when corepack or Yarn Berry + * cannot be set up (offline). */ const YARN_VERSION = '4.12.0' @@ -57,8 +51,6 @@ function berryAvailable(): boolean { } } -// On CI, always run so a regression is loud. Locally, skip when Berry is -// unavailable (offline) instead of failing the suite. const shouldRun = isCI || berryAvailable() const tempDirs: Array = [] @@ -77,8 +69,7 @@ function scaffoldBerryProject(): string { const dir = mkdtempSync(join(realTmpdir, 'intent-berry-corepack-')) tempDirs.push(dir) - // A skill-bearing package, packed to a tarball so Yarn stores it in the zip - // cache (the shape that triggered discussion #119). + // Packed to a tarball so Yarn stores it in the zip cache. const pkgSrc = join(dir, 'leaf-src') mkdirSync(join(pkgSrc, 'skills', 'core'), { recursive: true }) writeJson(join(pkgSrc, 'package.json'), { diff --git a/packages/intent/tests/integration/scaffold.ts b/packages/intent/tests/integration/scaffold.ts index e17db6d6..0250c2ff 100644 --- a/packages/intent/tests/integration/scaffold.ts +++ b/packages/intent/tests/integration/scaffold.ts @@ -11,6 +11,7 @@ import { createServer } from 'node:net' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' +import type { SpawnSyncReturns } from 'node:child_process' const thisDir = dirname(fileURLToPath(import.meta.url)) const fixturesDir = join(thisDir, '..', 'fixtures', 'integration') @@ -30,10 +31,6 @@ function getFreePort(): Promise { }) } -// --------------------------------------------------------------------------- -// Verdaccio lifecycle -// --------------------------------------------------------------------------- - export interface Registry { url: string stop: () => Promise @@ -138,10 +135,6 @@ export async function startRegistry(): Promise { }) } -// --------------------------------------------------------------------------- -// Publishing fixtures -// --------------------------------------------------------------------------- - export function publishFixtures(registryUrl: string): void { const host = new URL(registryUrl).host const npmrc = `//${host}/:_authToken=test-token\nregistry=${registryUrl}\n` @@ -170,10 +163,6 @@ export function publishFixtures(registryUrl: string): void { } } -// --------------------------------------------------------------------------- -// Project scaffolding -// --------------------------------------------------------------------------- - export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun' export type ProjectStructure = 'single' | 'monorepo-root' | 'monorepo-workspace' @@ -201,23 +190,24 @@ export function scaffoldProject(opts: { writeFileSync(join(root, lockfiles[opts.pm]), '') if (opts.structure === 'single') { - writeJson(join(root, 'package.json'), { + const manifest: Record = { name: 'test-project', private: true, - ...(opts.pnp ? { installConfig: { pnp: true } } : {}), dependencies: { [opts.dependency]: '1.0.0' }, - }) + } + if (opts.pnp) manifest.installConfig = { pnp: true } + writeJson(join(root, 'package.json'), manifest) install(root, opts.pm, opts.registryUrl, opts) return { root, cwd: root } } - // Monorepo - writeJson(join(root, 'package.json'), { + const manifest: Record = { name: 'test-monorepo', private: true, - ...(opts.pm !== 'pnpm' ? { workspaces: ['packages/*'] } : {}), - ...(opts.pnp ? { installConfig: { pnp: true } } : {}), - }) + } + if (opts.pm !== 'pnpm') manifest.workspaces = ['packages/*'] + if (opts.pnp) manifest.installConfig = { pnp: true } + writeJson(join(root, 'package.json'), manifest) if (opts.pm === 'pnpm') { writeFileSync( join(root, 'pnpm-workspace.yaml'), @@ -328,12 +318,12 @@ function formatInstallError( lines.push(`signal: ${processError.signal}`) } - const stdout = commandOutputToString(processError.stdout) + const stdout = processError.stdout?.toString().trim() ?? '' if (stdout) { lines.push(`stdout:\n${stdout}`) } - const stderr = commandOutputToString(processError.stderr) + const stderr = processError.stderr?.toString().trim() ?? '' if (stderr) { lines.push(`stderr:\n${stderr}`) } @@ -345,23 +335,11 @@ function formatInstallError( return lines.join('\n') } -function commandOutputToString(output: Buffer | string | undefined): string { - if (!output) { - return '' - } - - return output.toString().trim() -} - -// --------------------------------------------------------------------------- -// CLI invocation -// --------------------------------------------------------------------------- - export interface CliResult { stdout: string stderr: string exitCode: number - parsed: any + parsed: unknown } const packageManagerAvailability = new Map() @@ -402,40 +380,54 @@ export function canSymlink(): boolean { return symlinkCapable } +let yarnClassic: boolean | undefined + export function isYarnClassic(): boolean { + if (yarnClassic !== undefined) return yarnClassic + try { const version = execSync('yarn --version', { encoding: 'utf8', cwd: realTmpdir, }).trim() - return Number.parseInt(version.split('.')[0]!, 10) === 1 + yarnClassic = Number.parseInt(version.split('.')[0]!, 10) === 1 } catch { - return false + yarnClassic = false } + + return yarnClassic } -export function runScanner( +type InvokeMethod = 'direct' | 'symlink' + +function runCli( cwd: string, - method: 'direct' | 'symlink' = 'direct', + args: Array, + opts: { method?: InvokeMethod; json?: boolean }, ): CliResult { let binPath = cliPath let linkDir: string | undefined - if (method === 'symlink') { + if (opts.method === 'symlink') { linkDir = mkdtempSync(join(realTmpdir, 'intent-link-')) - const linkPath = join(linkDir, 'intent-cli.mjs') - symlinkSync(cliPath, linkPath) - binPath = linkPath + binPath = join(linkDir, 'intent-cli.mjs') + symlinkSync(cliPath, binPath) } try { - const stdout = execFileSync('node', [binPath, 'list', '--json'], { + const stdout = execFileSync('node', [binPath, ...args], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], }) - return { stdout, stderr: '', exitCode: 0, parsed: JSON.parse(stdout) } - } catch (err: any) { + return { + stdout, + stderr: '', + exitCode: 0, + parsed: opts.json ? JSON.parse(stdout) : null, + } + } catch (error) { + const err = error as Partial> return { stdout: err.stdout ?? '', stderr: err.stderr ?? '', @@ -449,8 +441,15 @@ export function runScanner( } } +export function runScanner( + cwd: string, + method: InvokeMethod = 'direct', +): CliResult { + return runCli(cwd, ['list', '--json'], { method, json: true }) +} + export interface RunLoadOptions { - method?: 'direct' | 'symlink' + method?: InvokeMethod path?: boolean json?: boolean } @@ -460,51 +459,12 @@ export function runLoad( use: string, options: RunLoadOptions = {}, ): CliResult { - const method = options.method ?? 'direct' - let binPath = cliPath - let linkDir: string | undefined - - if (method === 'symlink') { - linkDir = mkdtempSync(join(realTmpdir, 'intent-link-')) - const linkPath = join(linkDir, 'intent-cli.mjs') - symlinkSync(cliPath, linkPath) - binPath = linkPath - } - - const args: Array = [binPath, 'load', use] + const args = ['load', use] if (options.path) args.push('--path') if (options.json) args.push('--json') - - try { - const stdout = execFileSync('node', args, { - cwd, - encoding: 'utf8', - stdio: ['ignore', 'pipe', 'pipe'], - }) - return { - stdout, - stderr: '', - exitCode: 0, - parsed: options.json ? JSON.parse(stdout) : null, - } - } catch (err: any) { - return { - stdout: err.stdout ?? '', - stderr: err.stderr ?? '', - exitCode: err.status ?? 1, - parsed: null, - } - } finally { - if (linkDir) { - rmSync(linkDir, { recursive: true, force: true }) - } - } + return runCli(cwd, args, options) } -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - function writeJson(filePath: string, data: unknown): void { mkdirSync(dirname(filePath), { recursive: true }) writeFileSync(filePath, JSON.stringify(data, null, 2)) diff --git a/packages/intent/tests/integration/scanner-integration.test.ts b/packages/intent/tests/integration/scanner-integration.test.ts index 489d82ba..7b1daf14 100644 --- a/packages/intent/tests/integration/scanner-integration.test.ts +++ b/packages/intent/tests/integration/scanner-integration.test.ts @@ -34,23 +34,21 @@ let registry: Registry | undefined const tempDirs: Array = [] function expectLeafCoreSkill(parsed: CliResult['parsed']): void { - expect(parsed.packages).toEqual( - expect.arrayContaining([ + expect(parsed).toMatchObject({ + packages: expect.arrayContaining([ expect.objectContaining({ name: '@test-intent/skills-leaf', version: '1.0.0', }), ]), - ) - expect(parsed.skills).toEqual( - expect.arrayContaining([ + skills: expect.arrayContaining([ expect.objectContaining({ packageName: '@test-intent/skills-leaf', skillName: 'core', type: 'core', }), ]), - ) + }) } beforeAll(async () => { @@ -106,8 +104,11 @@ describe('symlink invocation', () => { const result = runScanner(cwd, 'symlink') expect(result.exitCode).toBe(0) - expect(result.parsed.packages).toHaveLength(1) - expect(result.parsed.packages[0].name).toBe('@test-intent/skills-leaf') + expect(result.parsed).toMatchObject({ + packages: [ + expect.objectContaining({ name: '@test-intent/skills-leaf' }), + ], + }) }, 60_000, ) @@ -131,11 +132,7 @@ describe.skipIf(!isYarnClassic())('Yarn PnP', () => { const result = runScanner(cwd) - if (result.exitCode !== 0) { - throw new Error( - `intent list failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, - ) - } + expect(result.exitCode, result.stderr).toBe(0) expectLeafCoreSkill(result.parsed) }, 60_000) @@ -156,11 +153,7 @@ describe.skipIf(!isYarnClassic())('Yarn PnP', () => { const result = runScanner(cwd) - if (result.exitCode !== 0) { - throw new Error( - `intent list failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, - ) - } + expect(result.exitCode, result.stderr).toBe(0) expectLeafCoreSkill(result.parsed) }, 60_000) @@ -182,11 +175,7 @@ describe.skipIf(!isYarnClassic())('Yarn PnP', () => { const result = runScanner(cwd) - if (result.exitCode !== 0) { - throw new Error( - `intent list failed\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}`, - ) - } + expect(result.exitCode, result.stderr).toBe(0) expectLeafCoreSkill(result.parsed) }, 60_000) }) diff --git a/packages/intent/tests/permissions.test.ts b/packages/intent/tests/permissions.test.ts index 0c36c10e..42a22a78 100644 --- a/packages/intent/tests/permissions.test.ts +++ b/packages/intent/tests/permissions.test.ts @@ -18,11 +18,16 @@ import { } from '../src/core/source-policy.js' import { setupInitialPermissions } from '../src/commands/install/permissions.js' import { ALLOW_ALL_NOTICE } from '../src/shared/cli-output.js' +import { + permissionPrompts as prompts, + scanResult as scan, +} from './fixtures/permissions.js' import type { PermissionPackage, PermissionPrompts, + PermissionSetupResult, } from '../src/commands/install/permissions.js' -import type { IntentPackage, ScanResult } from '../src/shared/types.js' +import type { IntentPackage } from '../src/shared/types.js' const tempDirs: Array = [] @@ -52,48 +57,6 @@ function packageCandidate( } } -function scan(packages: Array): ScanResult { - return { - packageManager: 'pnpm', - packages, - warnings: [], - notices: [], - conflicts: [], - nodeModules: { - local: { - path: 'node_modules', - detected: true, - exists: true, - scanned: true, - }, - global: { path: null, detected: false, exists: false, scanned: false }, - }, - stats: { packageJsonCacheHits: 0, packageJsonReadCount: 0 }, - } -} - -function prompts({ - confirmWrite = true, - selection = [], -}: { - confirmWrite?: boolean | null - selection?: Array | null -} = {}): PermissionPrompts & { groups: Array } { - const result = { - groups: [] as Array, - selectPermissions: vi.fn(async (groups: Array) => { - result.groups = groups - return selection - }), - reviewPermissions: vi.fn((_groups, selection) => - Promise.resolve(selection), - ), - editPermissions: vi.fn((_groups, selection) => Promise.resolve(selection)), - confirmWrite: vi.fn(async () => confirmWrite), - } - return result -} - async function configure({ dryRun = false, exclude = [], @@ -114,7 +77,7 @@ async function configure({ permissionPrompts: PermissionPrompts & { groups?: Array } - result: Awaited> + result: PermissionSetupResult }> { const root = mkdtempSync(join(tmpdir(), 'intent-permissions-')) tempDirs.push(root) diff --git a/packages/intent/tests/scanner.test.ts b/packages/intent/tests/scanner.test.ts index 970016c3..56c92f06 100644 --- a/packages/intent/tests/scanner.test.ts +++ b/packages/intent/tests/scanner.test.ts @@ -16,8 +16,6 @@ import { scanIntentPackageAtRoot, } from '../src/discovery/scanner.js' -// ── Helpers ── - function createDir(...segments: Array): string { const dir = join(...segments) mkdirSync(dir, { recursive: true }) @@ -38,8 +36,6 @@ function writeSkillMd(dir: string, frontmatter: Record): void { ) } -// ── Setup / Teardown ── - let root: string let globalRoot: string let previousGlobalNodeModules: string | undefined @@ -62,8 +58,6 @@ afterEach(() => { } }) -// ── Tests ── - describe('scanForIntents', () => { it('returns empty packages when no node_modules exists', () => { const result = scanForIntents(root) @@ -170,7 +164,6 @@ describe('scanForIntents', () => { type: 'core', }) - // Create the scoped dir, then symlink the package (like pnpm does) createDir(root, 'node_modules', '@tanstack') symlinkSync(store, join(root, 'node_modules', '@tanstack', 'db')) @@ -394,7 +387,6 @@ describe('scanForIntents', () => { version: '0.5.2', intent: { version: 1, repo: 'TanStack/db', docs: 'docs/' }, }) - // intermediate directory has no SKILL.md const groupDir = createDir(pkgDir, 'skills', 'group') const nestedDir = createDir(groupDir, 'nested-skill') writeSkillMd(nestedDir, { @@ -413,7 +405,6 @@ describe('scanForIntents', () => { writeJson(join(pkgDir, 'package.json'), { name: 'bad-pkg', version: '1.0.0', - // no intent field }) createDir(pkgDir, 'skills', 'some-skill') @@ -438,7 +429,6 @@ describe('scanForIntents', () => { }) it('sorts packages by dependency order (requires)', () => { - // Create core package (no requires) const coreDir = createDir(root, 'node_modules', '@tanstack', 'db') writeJson(join(coreDir, 'package.json'), { name: '@tanstack/db', @@ -448,7 +438,6 @@ describe('scanForIntents', () => { const coreSkill = createDir(coreDir, 'skills', 'db-core') writeSkillMd(coreSkill, { name: 'db-core', description: 'Core' }) - // Create framework package (requires core) const reactDir = createDir(root, 'node_modules', '@tanstack', 'react-db') writeJson(join(reactDir, 'package.json'), { name: '@tanstack/react-db', @@ -468,7 +457,6 @@ describe('scanForIntents', () => { const result = scanForIntents(root) expect(result.packages).toHaveLength(2) - // Core should come first expect(result.packages[0]!.name).toBe('@tanstack/db') expect(result.packages[1]!.name).toBe('@tanstack/react-db') }) @@ -480,7 +468,6 @@ describe('scanForIntents', () => { version: '1.0.0', intent: { version: 1, repo: 'foo/bar', docs: 'docs/' }, }) - // No skills/ directory const result = scanForIntents(root) expect(result.packages).toHaveLength(0) @@ -866,7 +853,6 @@ describe('scanForIntents', () => { dependencies: { '@tanstack/db': '0.5.0' }, }) - // Dep is hoisted to root, NOT in app's node_modules createDir(root, 'node_modules', '@tanstack', 'db') createDir(root, 'node_modules', '@tanstack', 'db', 'skills', 'db-core') const dbDir = join(root, 'node_modules', '@tanstack', 'db') @@ -884,7 +870,6 @@ describe('scanForIntents', () => { description: 'Core database concepts', }) - // Scan from the workspace package subdir (not root) const result = scanForIntents(appDir) expect(result.packages).toHaveLength(1) expect(result.packages[0]!.name).toBe('@tanstack/db') @@ -951,7 +936,6 @@ describe('scanForIntents', () => { dependencies: { wrapper: '1.0.0' }, }) - // wrapper has no skills, but depends on skills-pkg createDir(appDir, 'node_modules', 'wrapper') writeJson(join(appDir, 'node_modules', 'wrapper', 'package.json'), { name: 'wrapper', @@ -959,7 +943,6 @@ describe('scanForIntents', () => { dependencies: { 'skills-pkg': '1.0.0' }, }) - // skills-pkg is a transitive dep (sibling in node_modules) createDir(appDir, 'node_modules', 'skills-pkg') createDir(appDir, 'node_modules', 'skills-pkg', 'skills', 'core') writeJson(join(appDir, 'node_modules', 'skills-pkg', 'package.json'), { @@ -1062,7 +1045,10 @@ describe('scanForIntents', () => { expect(result.warnings).toEqual([]) }) - it('falls back to Yarn PnP when stale node_modules has no intent packages', () => { + function writeReactStartFixture( + root: string, + opts: { intent?: boolean; extraSkills?: boolean }, + ): string { const reactStartDir = createDir( root, '.yarn', @@ -1075,59 +1061,61 @@ describe('scanForIntents', () => { '@tanstack', 'react-start', ) - - writeJson(join(root, 'package.json'), { - name: 'tanstack-intent-pnp-repro', - version: '0.0.0', - private: true, - packageManager: 'yarn@4.12.0', - dependencies: { - '@tanstack/react-start': '1.167.52', - }, - }) - writeFileSync(join(root, '.yarnrc.yml'), 'nodeLinker: pnp\n') - writeJson(join(reactStartDir, 'package.json'), { + const pkgJson: Record = { name: '@tanstack/react-start', version: '1.167.52', - intent: { - version: 1, - repo: 'TanStack/router', - docs: 'https://tanstack.com/start', - }, repository: { type: 'git', url: 'git+https://github.com/TanStack/router.git', directory: 'packages/react-start', }, homepage: 'https://tanstack.com/start', - }) + } + if (opts.intent) { + pkgJson.intent = { + version: 1, + repo: 'TanStack/router', + docs: 'https://tanstack.com/start', + } + } + writeJson(join(reactStartDir, 'package.json'), pkgJson) writeSkillMd(createDir(reactStartDir, 'skills', 'react-start'), { name: 'react-start', description: 'React Start skill', }) - writeSkillMd( - createDir(reactStartDir, 'skills', 'lifecycle', 'migrate-from-nextjs'), - { - name: 'lifecycle/migrate-from-nextjs', - description: 'Migration skill', - }, - ) - writeSkillMd( - createDir(reactStartDir, 'skills', 'react-start', 'server-components'), - { - name: 'react-start/server-components', - description: 'Server components skill', - }, - ) + if (opts.extraSkills) { + writeSkillMd( + createDir(reactStartDir, 'skills', 'lifecycle', 'migrate-from-nextjs'), + { + name: 'lifecycle/migrate-from-nextjs', + description: 'Migration skill', + }, + ) + writeSkillMd( + createDir(reactStartDir, 'skills', 'react-start', 'server-components'), + { + name: 'react-start/server-components', + description: 'Server components skill', + }, + ) + } + return reactStartDir + } + function writePnpStub( + root: string, + opts: { rootName: string; reactStartDir: string; setup?: boolean }, + ): void { + const rootName = JSON.stringify(opts.rootName) writeFileSync( join(root, '.pnp.cjs'), [ `const projectRoot = ${JSON.stringify(`${root}${sep}`)}`, - `const reactStartRoot = ${JSON.stringify(`${reactStartDir}${sep}`)}`, - "const rootLocator = { name: 'tanstack-intent-pnp-repro', reference: 'workspace:.' }", + `const reactStartRoot = ${JSON.stringify(`${opts.reactStartDir}${sep}`)}`, + `const rootLocator = { name: ${rootName}, reference: 'workspace:.' }`, "const reactStartLocator = { name: '@tanstack/react-start', reference: 'virtual:test#npm:1.167.52' }", 'module.exports = {', + ...(opts.setup ? [' setup() {},'] : []), ' getDependencyTreeRoots() { return [rootLocator] },', ' findPackageLocator(location) {', ' if (location.startsWith(projectRoot)) return rootLocator', @@ -1135,7 +1123,7 @@ describe('scanForIntents', () => { ' return null', ' },', ' getPackageInformation(locator) {', - " if (locator.name === 'tanstack-intent-pnp-repro') {", + ` if (locator.name === ${rootName}) {`, ' return {', ' packageLocation: projectRoot,', " packageDependencies: new Map([['@tanstack/react-start', 'virtual:test#npm:1.167.52']]),", @@ -1153,6 +1141,24 @@ describe('scanForIntents', () => { '', ].join('\n'), ) + } + + it('falls back to Yarn PnP when stale node_modules has no intent packages', () => { + writeJson(join(root, 'package.json'), { + name: 'tanstack-intent-pnp-repro', + version: '0.0.0', + private: true, + packageManager: 'yarn@4.12.0', + dependencies: { + '@tanstack/react-start': '1.167.52', + }, + }) + writeFileSync(join(root, '.yarnrc.yml'), 'nodeLinker: pnp\n') + const reactStartDir = writeReactStartFixture(root, { + intent: true, + extraSkills: true, + }) + writePnpStub(root, { rootName: 'tanstack-intent-pnp-repro', reactStartDir }) createDir(root, 'node_modules') const result = scanForIntents(root) @@ -1173,19 +1179,6 @@ describe('scanForIntents', () => { }) it('uses the project Yarn PnP API when another PnP API is active', () => { - const reactStartDir = createDir( - root, - '.yarn', - '__virtual__', - '@tanstack-react-start-virtual', - '0', - 'cache', - '@tanstack-react-start-npm-1.167.52.zip', - 'node_modules', - '@tanstack', - 'react-start', - ) - writeJson(join(root, 'package.json'), { name: 'tanstack-intent-pnp-repro', version: '0.0.0', @@ -1196,69 +1189,12 @@ describe('scanForIntents', () => { }, }) writeFileSync(join(root, '.yarnrc.yml'), 'nodeLinker: pnp\n') - writeJson(join(reactStartDir, 'package.json'), { - name: '@tanstack/react-start', - version: '1.167.52', - repository: { - type: 'git', - url: 'git+https://github.com/TanStack/router.git', - directory: 'packages/react-start', - }, - homepage: 'https://tanstack.com/start', - }) - writeSkillMd(createDir(reactStartDir, 'skills', 'react-start'), { - name: 'react-start', - description: 'React Start skill', + const reactStartDir = writeReactStartFixture(root, { extraSkills: true }) + writePnpStub(root, { + rootName: 'tanstack-intent-pnp-repro', + reactStartDir, + setup: true, }) - writeSkillMd( - createDir(reactStartDir, 'skills', 'lifecycle', 'migrate-from-nextjs'), - { - name: 'lifecycle/migrate-from-nextjs', - description: 'Migration skill', - }, - ) - writeSkillMd( - createDir(reactStartDir, 'skills', 'react-start', 'server-components'), - { - name: 'react-start/server-components', - description: 'Server components skill', - }, - ) - - writeFileSync( - join(root, '.pnp.cjs'), - [ - `const projectRoot = ${JSON.stringify(`${root}${sep}`)}`, - `const reactStartRoot = ${JSON.stringify(`${reactStartDir}${sep}`)}`, - "const rootLocator = { name: 'tanstack-intent-pnp-repro', reference: 'workspace:.' }", - "const reactStartLocator = { name: '@tanstack/react-start', reference: 'virtual:test#npm:1.167.52' }", - 'module.exports = {', - ' setup() {},', - ' getDependencyTreeRoots() { return [rootLocator] },', - ' findPackageLocator(location) {', - ' if (location.startsWith(projectRoot)) return rootLocator', - ' if (location.startsWith(reactStartRoot)) return reactStartLocator', - ' return null', - ' },', - ' getPackageInformation(locator) {', - " if (locator.name === 'tanstack-intent-pnp-repro') {", - ' return {', - ' packageLocation: projectRoot,', - " packageDependencies: new Map([['@tanstack/react-start', 'virtual:test#npm:1.167.52']]),", - ' }', - ' }', - " if (locator.name === '@tanstack/react-start') {", - ' return {', - ' packageLocation: reactStartRoot,', - ' packageDependencies: new Map(),', - ' }', - ' }', - ' return null', - ' },', - '}', - '', - ].join('\n'), - ) const moduleApi = requireFromTest('node:module') as { findPnpApi?: () => unknown @@ -1355,18 +1291,6 @@ describe('scanForIntents', () => { }) it('falls back to Yarn PnP when workspace discovery finds packages first', () => { - const reactStartDir = createDir( - root, - '.yarn', - '__virtual__', - '@tanstack-react-start-virtual', - '0', - 'cache', - '@tanstack-react-start-npm-1.167.52.zip', - 'node_modules', - '@tanstack', - 'react-start', - ) const appDir = createDir(root, 'packages', 'app') const workspaceSkillDir = createDir( appDir, @@ -1401,59 +1325,11 @@ describe('scanForIntents', () => { description: 'Workspace skill', }) writeFileSync(join(root, '.yarnrc.yml'), 'nodeLinker: pnp\n') - writeJson(join(reactStartDir, 'package.json'), { - name: '@tanstack/react-start', - version: '1.167.52', - intent: { - version: 1, - repo: 'TanStack/router', - docs: 'https://tanstack.com/start', - }, - repository: { - type: 'git', - url: 'git+https://github.com/TanStack/router.git', - directory: 'packages/react-start', - }, - homepage: 'https://tanstack.com/start', - }) - writeSkillMd(createDir(reactStartDir, 'skills', 'react-start'), { - name: 'react-start', - description: 'React Start skill', + const reactStartDir = writeReactStartFixture(root, { intent: true }) + writePnpStub(root, { + rootName: 'tanstack-intent-pnp-monorepo', + reactStartDir, }) - - writeFileSync( - join(root, '.pnp.cjs'), - [ - `const projectRoot = ${JSON.stringify(`${root}${sep}`)}`, - `const reactStartRoot = ${JSON.stringify(`${reactStartDir}${sep}`)}`, - "const rootLocator = { name: 'tanstack-intent-pnp-monorepo', reference: 'workspace:.' }", - "const reactStartLocator = { name: '@tanstack/react-start', reference: 'virtual:test#npm:1.167.52' }", - 'module.exports = {', - ' getDependencyTreeRoots() { return [rootLocator] },', - ' findPackageLocator(location) {', - ' if (location.startsWith(projectRoot)) return rootLocator', - ' if (location.startsWith(reactStartRoot)) return reactStartLocator', - ' return null', - ' },', - ' getPackageInformation(locator) {', - " if (locator.name === 'tanstack-intent-pnp-monorepo') {", - ' return {', - ' packageLocation: projectRoot,', - " packageDependencies: new Map([['@tanstack/react-start', 'virtual:test#npm:1.167.52']]),", - ' }', - ' }', - " if (locator.name === '@tanstack/react-start') {", - ' return {', - ' packageLocation: reactStartRoot,', - ' packageDependencies: new Map(),', - ' }', - ' }', - ' return null', - ' },', - '}', - '', - ].join('\n'), - ) createDir(root, 'node_modules') const result = scanForIntents(root) diff --git a/packages/intent/tests/setup.test.ts b/packages/intent/tests/setup.test.ts index 573ca643..f65c30a3 100644 --- a/packages/intent/tests/setup.test.ts +++ b/packages/intent/tests/setup.test.ts @@ -37,7 +37,6 @@ beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'setup-test-')) metaDir = join(root, 'meta') - // Create mock templates mkdirSync(join(metaDir, 'templates', 'workflows'), { recursive: true }) writeFileSync( @@ -107,7 +106,7 @@ describe('runEditPackageJson', () => { ) }) - it('is idempotent — re-running does not duplicate entries', () => { + it('does not duplicate entries on a second run', () => { writePkg({ name: 'test-pkg', files: ['dist'] }, 2) runEditPackageJson(root) @@ -172,7 +171,6 @@ describe('runEditPackageJson', () => { }) it('skips !skills/_artifacts in monorepo packages', () => { - // Simulate monorepo by creating a parent package.json const monoRoot = mkdtempSync(join(tmpdir(), 'mono-root-')) const pkgDir = join(monoRoot, 'packages', 'my-lib') mkdirSync(pkgDir, { recursive: true }) @@ -455,7 +453,7 @@ describe('runSetupGithubActions', () => { } }) - it('handles missing templates directory gracefully', () => { + it('returns no workflows when the templates directory is missing', () => { const emptyMeta = join(root, 'empty-meta') mkdirSync(emptyMeta) const result = runSetupGithubActions(root, emptyMeta) @@ -585,14 +583,6 @@ describe('runSetupGithubActions', () => { }) }) -// --------------------------------------------------------------------------- -// Monorepo-aware commands -// --------------------------------------------------------------------------- - -/** - * Helper: create a monorepo layout with pnpm-workspace.yaml, - * workspace packages, and optional SKILL.md files. - */ function createMonorepo(opts?: { usePackageJsonWorkspaces?: boolean packages?: Array<{ name: string; hasSkills?: boolean }> @@ -652,7 +642,6 @@ describe('runEditPackageJsonAll', () => { expect(results[0]!.package).toBe(join('packages', 'lib-a')) expect(results[0]!.result.added).toContain('files: "skills"') - // lib-b should not have been modified const libBPkg = JSON.parse( readFileSync(join(monoRoot, 'packages', 'lib-b', 'package.json'), 'utf8'), ) @@ -697,7 +686,6 @@ describe('runEditPackageJsonAll', () => { expect(Array.isArray(results)).toBe(true) expect(results).toHaveLength(0) - // Root package.json should NOT have been modified const rootPkg = JSON.parse( readFileSync(join(monoRoot, 'package.json'), 'utf8'), ) diff --git a/packages/intent/tests/stale-command.test.ts b/packages/intent/tests/stale-command.test.ts index deaa7c75..7cdde94d 100644 --- a/packages/intent/tests/stale-command.test.ts +++ b/packages/intent/tests/stale-command.test.ts @@ -7,19 +7,27 @@ import { } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { INTENT_CHECK_SKILLS_WORKFLOW_VERSION, getCheckSkillsWorkflowAdvisories, } from '../src/commands/support.js' import { runStaleCommand } from '../src/commands/stale.js' +import type { MockInstance } from 'vitest' describe('runStaleCommand', () => { - const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + const originalCwd = process.cwd() + let logSpy: MockInstance const tempDirs: Array = [] + beforeEach(() => { + logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) + }) + afterEach(() => { - logSpy.mockClear() + logSpy.mockRestore() + vi.unstubAllEnvs() + process.chdir(originalCwd) for (const dir of tempDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }) } @@ -166,55 +174,38 @@ describe('runStaleCommand', () => { it('writes GitHub review files for stale review signals', async () => { const root = mkdtempSync(join(tmpdir(), 'intent-stale-github-review-')) tempDirs.push(root) - const originalCwd = process.cwd() - const previousOutput = process.env.GITHUB_OUTPUT - const previousSummary = process.env.GITHUB_STEP_SUMMARY process.chdir(root) - process.env.GITHUB_OUTPUT = join(root, 'github-output') - process.env.GITHUB_STEP_SUMMARY = join(root, 'github-summary') - - try { - await runStaleCommand( - undefined, - { githubReview: true, packageLabel: '@tanstack/router' }, - () => - Promise.resolve({ - reports: [ - { - library: '@tanstack/router', - currentVersion: null, - skillVersion: null, - versionDrift: null, - skills: [], - signals: [ - { - type: 'missing-package-coverage', - library: '@tanstack/react-start-rsc', - packageName: '@tanstack/react-start-rsc', - reasons: ['workspace package is not represented'], - needsReview: true, - }, - ], - }, - ], - workflowAdvisories: [ - 'Intent workflow update available: run `npx @tanstack/intent@latest setup`.', - ], - }), - ) - } finally { - process.chdir(originalCwd) - if (previousOutput === undefined) { - delete process.env.GITHUB_OUTPUT - } else { - process.env.GITHUB_OUTPUT = previousOutput - } - if (previousSummary === undefined) { - delete process.env.GITHUB_STEP_SUMMARY - } else { - process.env.GITHUB_STEP_SUMMARY = previousSummary - } - } + vi.stubEnv('GITHUB_OUTPUT', join(root, 'github-output')) + vi.stubEnv('GITHUB_STEP_SUMMARY', join(root, 'github-summary')) + + await runStaleCommand( + undefined, + { githubReview: true, packageLabel: '@tanstack/router' }, + () => + Promise.resolve({ + reports: [ + { + library: '@tanstack/router', + currentVersion: null, + skillVersion: null, + versionDrift: null, + skills: [], + signals: [ + { + type: 'missing-package-coverage', + library: '@tanstack/react-start-rsc', + packageName: '@tanstack/react-start-rsc', + reasons: ['workspace package is not represented'], + needsReview: true, + }, + ], + }, + ], + workflowAdvisories: [ + 'Intent workflow update available: run `npx @tanstack/intent@latest setup`.', + ], + }), + ) expect(readFileSync(join(root, 'github-output'), 'utf8')).toContain( 'has_review=true', @@ -236,32 +227,15 @@ describe('runStaleCommand', () => { it('turns GitHub review stale check failures into review items', async () => { const root = mkdtempSync(join(tmpdir(), 'intent-stale-github-failed-')) tempDirs.push(root) - const originalCwd = process.cwd() - const previousOutput = process.env.GITHUB_OUTPUT - const previousSummary = process.env.GITHUB_STEP_SUMMARY process.chdir(root) - process.env.GITHUB_OUTPUT = join(root, 'github-output') - process.env.GITHUB_STEP_SUMMARY = join(root, 'github-summary') - - try { - await runStaleCommand( - undefined, - { githubReview: true, packageLabel: '@tanstack/router' }, - () => Promise.reject(new Error('boom')), - ) - } finally { - process.chdir(originalCwd) - if (previousOutput === undefined) { - delete process.env.GITHUB_OUTPUT - } else { - process.env.GITHUB_OUTPUT = previousOutput - } - if (previousSummary === undefined) { - delete process.env.GITHUB_STEP_SUMMARY - } else { - process.env.GITHUB_STEP_SUMMARY = previousSummary - } - } + vi.stubEnv('GITHUB_OUTPUT', join(root, 'github-output')) + vi.stubEnv('GITHUB_STEP_SUMMARY', join(root, 'github-summary')) + + await runStaleCommand( + undefined, + { githubReview: true, packageLabel: '@tanstack/router' }, + () => Promise.reject(new Error('boom')), + ) const items = JSON.parse( readFileSync(join(root, 'review-items.json'), 'utf8'), diff --git a/packages/intent/tests/staleness.test.ts b/packages/intent/tests/staleness.test.ts index 58c9332f..f3e2209e 100644 --- a/packages/intent/tests/staleness.test.ts +++ b/packages/intent/tests/staleness.test.ts @@ -1,24 +1,11 @@ -import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { checkStaleness } from '../src/staleness/index.js' -// --------------------------------------------------------------------------- -// Fixture helpers -// --------------------------------------------------------------------------- - let tmpDir: string -function setupDir(): string { - const dir = join( - tmpdir(), - `intent-stale-test-${Date.now()}-${Math.random().toString(36).slice(2)}`, - ) - mkdirSync(dir, { recursive: true }) - return dir -} - function writeSkill( dir: string, name: string, @@ -58,15 +45,10 @@ function writeArtifact( function requireFirstSkill(report: Awaited>) { const skill = report.skills[0] - expect(skill).toBeDefined() if (!skill) throw new Error('Expected at least one skill in staleness report') return skill } -// --------------------------------------------------------------------------- -// Mock fetch for npm registry -// --------------------------------------------------------------------------- - const originalFetch = globalThis.fetch function mockFetchVersion(version: string): void { @@ -81,20 +63,14 @@ function mockFetchNotOk(): void { } beforeEach(() => { - tmpDir = setupDir() + tmpDir = mkdtempSync(join(tmpdir(), 'intent-stale-test-')) }) afterEach(() => { globalThis.fetch = originalFetch - if (existsSync(tmpDir)) { - rmSync(tmpDir, { recursive: true, force: true }) - } + rmSync(tmpDir, { recursive: true, force: true }) }) -// --------------------------------------------------------------------------- -// Tests -// --------------------------------------------------------------------------- - describe('checkStaleness', () => { it('returns empty skills when no skills directory exists', async () => { const report = await checkStaleness(tmpDir, '@example/lib') @@ -242,7 +218,7 @@ describe('checkStaleness', () => { expect(requireFirstSkill(report).needsReview).toBe(false) }) - it('handles npm fetch failure gracefully', async () => { + it('returns null versions when the registry fetch rejects', async () => { writeSkill(tmpDir, 'core', { name: 'core', description: 'Core', @@ -362,7 +338,7 @@ describe('checkStaleness', () => { expect(report.versionDrift).toBe('major') }) - it('handles malformed SKILL.md without crashing', async () => { + it('treats a SKILL.md without frontmatter as one unversioned skill', async () => { const skillDir = join(tmpDir, 'skills', 'broken') mkdirSync(skillDir, { recursive: true }) writeFileSync(join(skillDir, 'SKILL.md'), 'no frontmatter here') @@ -408,11 +384,9 @@ describe('checkStaleness', () => { library_version: '2.0.0', }) - // npm returns an older published version mockFetchVersion('2.5.0') const report = await checkStaleness(tmpDir, '@example/lib') - // Local package.json should take precedence expect(report.currentVersion).toBe('3.0.0') expect(report.versionDrift).toBe('major') }) diff --git a/packages/intent/tests/support.test.ts b/packages/intent/tests/support.test.ts index f6042571..318852a8 100644 --- a/packages/intent/tests/support.test.ts +++ b/packages/intent/tests/support.test.ts @@ -35,7 +35,6 @@ describe('findMetaDir', () => { it('resolves from the flat dist/ layout used by the published package', () => { const pkgDir = join(root, 'pkg') const metaDir = seedMeta(pkgDir) - // Bundled module lives flat at /dist/support-*.mjs. const startDir = join(pkgDir, 'dist') mkdirSync(startDir, { recursive: true }) expect(findMetaDir(startDir)).toBe(metaDir) @@ -44,7 +43,6 @@ describe('findMetaDir', () => { it('resolves from the deep src/commands/ layout used in source', () => { const pkgDir = join(root, 'pkg') const metaDir = seedMeta(pkgDir) - // Source module lives at /src/commands/support.ts (two levels deep). const startDir = join(pkgDir, 'src', 'commands') mkdirSync(startDir, { recursive: true }) expect(findMetaDir(startDir)).toBe(metaDir) @@ -62,13 +60,11 @@ describe('findMetaDir', () => { const metaDir = seedMeta(pkgDir) const startDir = join(pkgDir, 'dist') mkdirSync(startDir, { recursive: true }) - // A file (not a directory) named `meta` next to startDir must not short-circuit. writeFileSync(join(startDir, 'meta'), '') expect(findMetaDir(startDir)).toBe(metaDir) }) it('resolves through a symlinked install path (pnpm-style)', () => { - // Real package lives in a pnpm-style store; the consumer reaches it via a symlink. const storePkg = join( root, 'store', From b678980f4713c8b75fef9803f03b2695885b2928 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:43:52 -0700 Subject: [PATCH 03/12] docs: shorten wording in docs and README Remove repeated caveats and filler words from the CLI reference, concept pages, and quick starts, and fix a stray list marker in the README badge row. --- README.md | 2 +- docs/cli/intent-hooks.md | 2 +- docs/cli/intent-install.md | 2 +- docs/cli/intent-list.md | 6 +----- docs/cli/intent-load.md | 2 +- docs/cli/intent-maintainer.md | 4 ++-- docs/cli/intent-repair.md | 2 +- docs/cli/intent-review.md | 6 +++--- docs/cli/intent-setup.md | 3 --- docs/cli/intent-stale.md | 2 +- docs/concepts/configuration.md | 20 ------------------- docs/concepts/trust-model.md | 13 +++--------- docs/getting-started/quick-start-consumers.md | 18 ++--------------- .../quick-start-maintainers.md | 8 ++++---- docs/overview.md | 4 ++-- docs/registry.md | 7 ++----- 16 files changed, 25 insertions(+), 76 deletions(-) diff --git a/README.md b/README.md index f62b7d98..74603e8e 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ -- + diff --git a/docs/cli/intent-hooks.md b/docs/cli/intent-hooks.md index dd62f780..2cfa7d6d 100644 --- a/docs/cli/intent-hooks.md +++ b/docs/cli/intent-hooks.md @@ -42,7 +42,7 @@ Hooks do not verify that: - The agent received the returned content. - The model applied the guidance. -Hook output is an edit gate and observation signal, not proof of activation or correct agent behavior. See [Lifecycle boundaries](../concepts/trust-model#lifecycle-boundaries). +Hook output is an edit gate and observation signal. See [Lifecycle boundaries](../concepts/trust-model#lifecycle-boundaries). ## Hook support diff --git a/docs/cli/intent-install.md b/docs/cli/intent-install.md index 398e4c22..79219210 100644 --- a/docs/cli/intent-install.md +++ b/docs/cli/intent-install.md @@ -39,7 +39,7 @@ For the full command workflow, use [`intent maintainer setup`](./intent-maintain `install --maintainer` enables initial skill batches and source-aware skill maintenance in repository agent instructions. It works without an interactive terminal or existing consumer permissions. It writes a separate `intent-maintainer` block, preserves consumer guidance, and is idempotent. `--dry-run` previews the block. -Run it from the library root. The block loads the packaged authoring procedure for substantial library work; that procedure covers the cumulative domain map, spec, and skill tree, source review, task checks, and revision-bound outcomes. It updates the file that already contains either Intent managed block, or creates `AGENTS.md` when neither exists. It cannot be combined with `--review`, `--map`, `--print-prompt`, `--global`, or `--global-only`. See [Quick Start for Maintainers](../getting-started/quick-start-maintainers). +Run it from the library root. The block loads the packaged authoring procedure for substantial library work; that procedure covers the cumulative domain map, spec, and skill tree, source review and task checks. It updates the file that already contains either Intent managed block, or creates `AGENTS.md` when neither exists. It cannot be combined with `--review`, `--map`, `--print-prompt`, `--global`, or `--global-only`. See [Quick Start for Maintainers](../getting-started/quick-start-maintainers). > [!NOTE] Maintainer installation writes guidance > It does not add Intent to `package.json`, configure consumer skill permissions, install agent hooks, or add CI. The managed block uses the detected package manager's runner with `@tanstack/intent@latest`. diff --git a/docs/cli/intent-list.md b/docs/cli/intent-list.md index 1696013b..87bcb1bc 100644 --- a/docs/cli/intent-list.md +++ b/docs/cli/intent-list.md @@ -52,10 +52,6 @@ The nearest configured `intent.skills` list applies, including inherited workspa Workspace patterns and individual skills also use the `workspace:` prefix, such as `workspace:@scope/*` and `workspace:@scope/internal#testing`. Package patterns support `*`; individual-skill entries require an exact package and skill name. Git sources are not supported. -- **No configured list:** all discovered sources appear, with a migration notice. This is the existing-project upgrade path; a future version will require explicit permissions. -- **An empty list (`[]`):** no sources are permitted, with an informational notice. -- **All sources (`["*"]`):** all discovered sources appear, with a notice that unvetted skills may enter agent guidance. - Permissions select sources and skill names. They do not freeze skill content when dependencies update. See [Configuration](../concepts/configuration) and [Trust model](../concepts/trust-model). ### Exclusions @@ -157,7 +153,7 @@ JSON includes diagnostics in the object instead of printing separate warning or - **Invalid permissions or unreadable policy files:** Intent stops and reports the problem. Fix the reported package.json or `intent.skills` entry before retrying. - **Unsupported runnable identifier:** generated commands accept only ASCII letters, numbers, `_`, `.`, `/`, `@`, `#`, and `-`. Identifiers cannot start with `#`; leading and trailing whitespace is rejected rather than trimmed. Rename the package or skill to generate runnable guidance. `--json` can still expose permitted identifiers as data. -- **Unreadable or out-of-package skill metadata:** discovery skips skill files whose real path cannot be resolved or lies outside the package root, with a warning. It checks the opened file's identity before reading and uses that descriptor for the full metadata read, including large frontmatter, so later pathname replacement cannot redirect the read. Symlinks within the resolved package root remain supported. +- **Unreadable or out-of-package skill metadata:** discovery skips skill files whose real path cannot be resolved or lies outside the package root, with a warning. Symlinks within the resolved package root remain supported. - **Deno without `node_modules`:** this discovery mode is unsupported. ## Related diff --git a/docs/cli/intent-load.md b/docs/cli/intent-load.md index 6e54ecb1..c4b509b9 100644 --- a/docs/cli/intent-load.md +++ b/docs/cli/intent-load.md @@ -42,7 +42,7 @@ id: intent-load - Prints the scanner-reported path when `--path` is passed - Prints debug details to stderr when `--debug` is passed -A successful load proves that Intent resolved the selected skill under current policy and returned its content. It does not prove that the skill was relevant to the task, reached an agent's active context, or was followed correctly. See [Lifecycle boundaries](../concepts/trust-model#lifecycle-boundaries). +A successful load proves that Intent resolved the selected skill under current policy and returned its content. See [Lifecycle boundaries](../concepts/trust-model#lifecycle-boundaries). The package can be scoped or unscoped. The skill can include slash-separated sub-skill names. diff --git a/docs/cli/intent-maintainer.md b/docs/cli/intent-maintainer.md index 44e1c3e5..c8d69590 100644 --- a/docs/cli/intent-maintainer.md +++ b/docs/cli/intent-maintainer.md @@ -123,7 +123,7 @@ Generated commands do not pin a revision or match the application's installed de Intent preserves existing plugin version fields. Claude uses an explicit plugin version to decide whether an update is available: bump the authoritative plugin version when releasing changed content. Without a version in either the plugin or its marketplace entry, Git-based Claude installs use the source commit. Updating an npm package version alone does not update plugin metadata. -Publish through the library's normal release process. Repository exports do not submit marketplace listings, publish releases, or update consumer installations. State the supported package versions in implementation skills and check them against the consumer's dependencies. Consumers manage updates and removal through their chosen installer. +Repository exports do not submit marketplace listings, publish releases, or update consumer installations. State the supported package versions in implementation skills and check them against the consumer's dependencies. Consumers manage updates and removal through their chosen installer. ## Maintain and check @@ -135,7 +135,7 @@ Publish through the library's normal release process. Repository exports do not -Status accepts `--json` and an actual Git comparison base with `--base `. Sync copies descriptions, purpose, sources, and prerequisites from the registered skills into the tree. It also adds the package discovery keyword and includes each skill directory in existing `files` allowlists. An absent allowlist stays absent, preserving npm's default contents. Sync prints each path it synchronized, or `Nothing to synchronize.` when every file is current, and labels the consumer install commands when repository distribution is selected. Inspect the actual packed archive in the library's release checks. +Status accepts `--json` and a Git comparison base with `--base `. Sync copies descriptions, purpose, sources, and prerequisites from the registered skills into the tree. It also adds the package discovery keyword and includes each skill directory in existing `files` allowlists. An absent allowlist stays absent, preserving npm's default contents. Sync prints each path it synchronized, or `Nothing to synchronize.` when every file is current, and labels the consumer install commands when repository distribution is selected. Inspect the packed archive in the library's release checks. `maintainer review --interactive` is the human path. It walks each pending item in the terminal, shows the current guidance and changed files, and records the chosen outcomes with reason and evidence. It requires a terminal outside CI. diff --git a/docs/cli/intent-repair.md b/docs/cli/intent-repair.md index 3d0e52a6..ee9adee6 100644 --- a/docs/cli/intent-repair.md +++ b/docs/cli/intent-repair.md @@ -3,7 +3,7 @@ id: intent-repair title: intent repair --- -`intent repair` handles mechanical skill maintenance before validation and source review. It does not call an agent, typecheck the library, execute examples, change version claims, or record review outcomes. +`intent repair` handles mechanical skill maintenance before validation and source review. It does not call an agent or record review outcomes. Run the CLI from your repository: diff --git a/docs/cli/intent-review.md b/docs/cli/intent-review.md index ab3db2e5..fc182ff5 100644 --- a/docs/cli/intent-review.md +++ b/docs/cli/intent-review.md @@ -33,7 +33,7 @@ A justified no-op is a completed review. Missing evidence remains pending. | Option | Behavior | | --- | --- | | `[dir]` | Locate the Git working tree. The review covers that repository, including its packages. | -| `--base ` | Compare against an available Git commit or ref, such as the actual PR base. | +| `--base ` | Compare against an available Git commit or ref, such as the PR base. | | `--json` | Print the complete structured report for an agent or script. | | `--check` | Exit nonzero when review items remain. | @@ -159,7 +159,7 @@ For a human terminal, run the interactive command from the library repository: -Inspect each item's current guidance and changed files, choose an outcome, and supply the reason and actual evidence. The changes view compares tracked files with the displayed Git base and includes untracked content. Use `--base ` for a specific comparison. Edit and test guidance before starting; changes during review invalidate the affected outcomes. +Inspect each item's current guidance and changed files, choose an outcome, and supply the reason and evidence. The changes view compares tracked files with the displayed Git base and includes untracked content. Use `--base ` for a specific comparison. Edit and test guidance before starting; changes during review invalidate the affected outcomes. Choose **Leave pending** when more work is needed. Items with unresolved source mappings or planning problems cannot be completed. The final preview lists the proposed outcomes and evidence. Confirmation records through the same fingerprint checks as `--record`; cancellation records nothing. Evidence text is stored, not executed or independently verified. @@ -233,7 +233,7 @@ For a planning item, the reason and evidence must cover all three documents. Pre ### Saved state -`--record` writes `.intent/review-state.json` containing the baseline, source/guidance hashes, reviewed revision, outcomes, reasons, and evidence, creating the directory when it is missing. It does not commit, publish, or change skill versions. `.intent/` is reserved for Intent's working files and is excluded from unmapped-change items: review state and working reports, `.intent/skill-distribution.json` written by `maintainer sync`, and the temporary `.intent/maintainer.lock` and `.intent/review-state.json.lock` that serialize writes. +`--record` writes `.intent/review-state.json` containing the baseline, source/guidance hashes, reviewed revision, outcomes, reasons, and evidence, creating the directory when it is missing. `.intent/` is reserved for Intent's working files and is excluded from unmapped-change items: review state and working reports, `.intent/skill-distribution.json` written by `maintainer sync`, and the temporary `.intent/maintainer.lock` and `.intent/review-state.json.lock` that serialize writes. Identical recorded content suppresses repeat reminders. Later edits reopen review. The saved state does not replace the planning documents, execute evidence strings, or verify the truth of a recorded conclusion. diff --git a/docs/cli/intent-setup.md b/docs/cli/intent-setup.md index 05ca474b..6b1bebd3 100644 --- a/docs/cli/intent-setup.md +++ b/docs/cli/intent-setup.md @@ -37,9 +37,6 @@ These commands configure a package for publishing skills and install the optiona - Skips files that already exist at the destination - New callers enable [repair artifacts](./intent-repair#ci-patches) for PR checks. CI applies safe mechanical repairs to its checkout and uploads patches for review; it never commits them. Existing callers can opt in with `repair: true` -> [!NOTE] -> `setup` installs the generated repository workflow, not Intent's maintainer or consumer guidance. Run `maintainer setup` to install the same CI workflow together with persistent instructions and cumulative records. - ## Security and upgrades Keep the generated full SHAs and review updates; a pin fixes a revision but does not certify its safety. Analysis has access to checked-out source even with a read-only token. Keep it on pull request, release, or manual events with no extra secrets, and keep write permissions confined to the optional publisher. Treat report and skill content as untrusted evidence, not authorization to execute commands or publish. See [GitHub's secure-use guidance](https://docs.github.com/en/actions/reference/security/secure-use). diff --git a/docs/cli/intent-stale.md b/docs/cli/intent-stale.md index 9047f847..8c4963c2 100644 --- a/docs/cli/intent-stale.md +++ b/docs/cli/intent-stale.md @@ -121,7 +121,7 @@ Reason generation: The existing `--github-review` workflow mode writes `review-items.json` and, when there are items, `pr-body.md`. Its Agent Review instructions route to `generate-skill` and its conditional review-signals reference. The command itself does not create a remote PR or edit skills; the installed GitHub workflow handles the review reminder. -Version drift and missing stored source SHAs do not prove that guidance is wrong. Review actual source changes before editing. Missing evidence stays unresolved, and an evidence-backed no-op may leave a signal flagged. Failed checks require logs; workflow advisories are separate maintenance items. Neither is a reason to rewrite skills. +Version drift and missing stored source SHAs do not prove that guidance is wrong. Review the source changes before editing. Missing evidence stays unresolved, and an evidence-backed no-op may leave a signal flagged. Failed checks require logs; workflow advisories are separate maintenance items. Neither is a reason to rewrite skills. ### `stale` and `review` serve different checks diff --git a/docs/concepts/configuration.md b/docs/concepts/configuration.md index 9717ed47..67b80086 100644 --- a/docs/concepts/configuration.md +++ b/docs/concepts/configuration.md @@ -92,26 +92,6 @@ Run `intent list` to see which packages the current policy surfaces. | Saved or inherited `intent.skills` | Updates guidance only. Keeps permissions unchanged and does not prompt. | | No effective `intent.skills` | Starts interactive permission setup. Non-TTY execution fails without writes. | -First-run setup offers **Enable all**, **Choose packages or scopes**, and **Choose individual skills**, followed by one confirmation before saving to the nearest owning `package.json` and installing guidance. - -- **Compact rules:** Enable all saves `"*"`; package choices save names such as `"@tanstack/ai"`; explicit scope choices save patterns such as `"@tanstack/*"`. These rules include future matching skills and packages. Individual choices save exact names such as `"@tanstack/ai#skill"`. -- **Optional skill review:** choose **Review individual skills** at confirmation, then pick which selected packages to inspect. Leave the list empty to keep all selected skills. Only those packages open individual skill lists; unchecking a skill covered by a broad rule adds an exclusion. Existing and inherited exclusions stay in force. -- **Changing instructions:** access choices do not record approval of specific content. Skills can change with dependency updates; update notifications are not available yet. -- **Empty selection:** explicitly confirms disabling all skills with `[]`. Empty or fully excluded discovery writes nothing, so setup can be retried. - -For example, enabling a scope and unchecking one skill saves: - -```json -{ - "intent": { - "skills": ["@tanstack/*"], - "exclude": ["@tanstack/ai#skill"] - } -} -``` - -This permits matching npm packages, including future additions, except the excluded skill. Selecting several packages individually never silently expands to a scope rule. - See [Default install](../cli/intent-install#default-install) for picker controls and cancellation behavior. ### Suppressing notices temporarily diff --git a/docs/concepts/trust-model.md b/docs/concepts/trust-model.md index 48bed8f5..2a9e94f0 100644 --- a/docs/concepts/trust-model.md +++ b/docs/concepts/trust-model.md @@ -37,16 +37,9 @@ Workspace discovery checks ancestors up to the first workspace declaration or Gi When no effective policy exists, `intent install` follows this flow: -1. **Discover:** summarize npm and workspace skill counts. Descriptions and exclusions are available through optional inspection. -2. **Choose:** enable all sources, choose packages or scopes, or select individual skills. Package and scope selections stay compact and include future matching skills. A whole scope requires an explicit selection. -3. **Confirm once:** show the current skill count, saved rules, and destination file. Optional individual review opens skill lists only for the selected packages you choose to inspect. It can add exclusions while retaining broad rules; unreviewed packages keep their selection. Only affirmative confirmation saves permissions and exclusions atomically, then installs guidance. An empty selection explicitly confirms disabling all skills. - -| Outcome | Files changed | -| --- | --- | -| No skills discovered, or all excluded | None. | -| Cancel any prompt | None. | -| Run first-time setup without a TTY | None; the command fails. | -| Save permissions, then fail to write or verify guidance | Confirmed permissions remain saved; the guidance failure is reported separately. | +1. Summarize npm and workspace skill counts. Descriptions and exclusions are available through optional inspection. +2. Enable all sources, choose packages or scopes, or select individual skills. Package and scope selections stay compact and include future matching skills. A whole scope requires an explicit selection. +3. Confirm the current skill count, saved rules, and destination file. Optional individual review opens skill lists only for the selected packages you choose to inspect. It can add exclusions while retaining broad rules; unreviewed packages keep their selection. Only affirmative confirmation saves permissions and exclusions atomically, then installs guidance. An empty selection explicitly confirms disabling all skills. The completion summary reports skills available under the saved policy. It does not prove that an agent loaded or applied them. See [Default install](../cli/intent-install#default-install) for picker controls and permission choices. diff --git a/docs/getting-started/quick-start-consumers.md b/docs/getting-started/quick-start-consumers.md index b759bfda..ab405764 100644 --- a/docs/getting-started/quick-start-consumers.md +++ b/docs/getting-started/quick-start-consumers.md @@ -13,7 +13,7 @@ Add `@tanstack/intent` as a development dependency and commit your lockfile befo -Then run setup. The command tabs use the latest published CLI, not the version in your lockfile. Generated guidance uses the detected package manager's runner; check its command if you need the installed version. The dependency pins the CLI used by CI when configured to run the installed CLI. +Then run setup. The command tabs use the latest published CLI, not the version in your lockfile. Generated guidance uses the detected package manager's runner; check its command if you need the installed version. @@ -26,14 +26,6 @@ Run this in an interactive terminal. On first use, Intent helps you choose which 1. **Choose what to enable.** Pick **Enable all**, **Choose packages or scopes**, or **Choose individual skills**. Package and skill lists support search. 2. **Confirm and finish.** Check the saved rules and destination `package.json`. Choose **Continue with all selected skills** to save, or **Review individual skills** to pick which selected packages to inspect before confirming. Intent writes permissions and guidance, verifies the guidance, and shows a command to list available skills. -**Enable all** saves `"*"`. A package choice saves `"@tanstack/ai"`; a whole scope saves `"@tanstack/*"`. These rules include future matching skills. Individual choices use `"@tanstack/ai#skill"`. Unchecking a skill during review adds an exclusion while keeping its broad rule. - -Skill instructions can change when dependencies update. Update notifications are not available yet. See **About skill access and updates** in the installer for details. - -Selecting nothing requires explicit confirmation to disable all skills. If no skills are found, or all are excluded, Intent explains the next step and leaves permissions and guidance unchanged. Install a package that ships skills or review your exclusions, then run `install` again. - -Canceling before confirmation writes neither file. `--dry-run` previews the flow without writing. First-run setup requires a terminal; noninteractive execution fails without writes when permissions have not been configured. - If an `intent-skills` block already exists, Intent updates that file in place. If no block exists, `AGENTS.md` is the default target. @@ -57,13 +49,7 @@ Project-scoped hooks are installed for Claude Code and Codex. `intent install` c Cursor and generic `AGENTS.md` agents use the guidance block only. -Hooks return the available Intent skill catalog as context for supported agent sessions and keep the edit gate active until they observe a supported `intent load` command. - -Hooks do not verify that: - -- The command succeeded. -- The skill matched the task. -- The agent applied the guidance. +Hooks return the available Intent skill catalog as context for supported agent sessions and keep the edit gate active until they observe a supported `intent load` command. See [intent hooks](../cli/intent-hooks) for what hooks do not verify. To control what appears in the session catalog, configure `intent.skills` and `intent.exclude` in `package.json`. diff --git a/docs/getting-started/quick-start-maintainers.md b/docs/getting-started/quick-start-maintainers.md index b613eaf7..94105379 100644 --- a/docs/getting-started/quick-start-maintainers.md +++ b/docs/getting-started/quick-start-maintainers.md @@ -26,7 +26,7 @@ Run `maintainer setup` from the library repository: This registers existing package-owned skills, copies the CI workflow when missing, and creates missing planning records and an `intent-maintainer` block in `AGENTS.md`, or updates the file that already contains an Intent maintainer or consumer block. It preserves surrounding instructions and a separate `intent-skills` consumer block. Review this setup diff and keep it in the repository so later agent sessions receive the same authoring and review procedure. > [!NOTE] -> Setup preserves existing records and instructions. It creates skeletons for missing records; their task knowledge still needs authoring. Registration preserves existing skill text and reports invalid or conflicting candidates. Review inferred domains and complete the records before running the maintainer check. +> Setup creates skeletons for missing records; their task knowledge still needs authoring. Registration preserves existing skill text and reports invalid or conflicting candidates. Review inferred domains and complete the records before running the maintainer check. ## Create the first useful batch @@ -102,7 +102,7 @@ Selecting skills for repository distribution requires registered, authored skill -Use the actual registered names; each must be a tree entry whose `SKILL.md` exists. When the repository, plugin name, or selection cannot be resolved, setup reports every missing input in one error. This records the selection in the skill tree. `maintainer sync` generates plugin metadata pointing to the existing package directories and prints consumer commands for `npx skills add` and `gh skill add`. Consumers can also use the native Claude or Cursor plugin flow. No second copy of the skill text is created, and later skills are not added automatically. +Use the registered names; each must be a tree entry whose `SKILL.md` exists. When the repository, plugin name, or selection cannot be resolved, setup reports every missing input in one error. This records the selection in the skill tree. `maintainer sync` generates plugin metadata pointing to the existing package directories and prints consumer commands for `npx skills add` and `gh skill add`. Consumers can also use the native Claude or Cursor plugin flow. No second copy of the skill text is created, and later skills are not added automatically. To explicitly record package-only distribution or turn off earlier repository exports: @@ -116,7 +116,7 @@ A repository discovery skill can help developers decide whether the library fits ## Keep guidance current during library work -Continue requesting library changes normally. `intent maintainer review` uses Git changes and content fingerprints to find work that has not been reviewed. Intent identifies candidates; the agent and maintainer decide whether the guidance should change. A new file does not automatically require a new skill. A justified `no-change` outcome records why accurate guidance stayed unchanged, while missing evidence remains pending. +Continue requesting library changes normally. `intent maintainer review` uses Git changes and content fingerprints to find work that has not been reviewed. Intent identifies candidates; the agent and maintainer decide whether the guidance should change. A new file does not automatically require a new skill. Before handoff, run sync so the metadata matches the final files, review the pending items in your terminal, then run the combined check: @@ -153,7 +153,7 @@ Run the same synchronization command after skill edits: `maintainer setup` already copies `check-skills.yml` to the workspace root's `.github/workflows/` directory and skips an existing destination file. The copy is a short caller for Intent's reusable workflows, pinned to the commit of the Intent release that copied it and granting each job only the permissions it needs; Dependabot or Renovate can propose pin updates for review. Setup uses the immutable SHA packaged with the installed release; it does not resolve mutable tags. CI runs the copy of `@tanstack/intent` your lockfile pins, so keep it in `devDependencies`. The workflow validates skills and recorded source reviews on pull requests. After a release or manual run, it writes a read-only review report when recorded review state or conservative staleness signals require attention. Review-reminder PRs are optional: set the repository Actions variable `INTENT_REVIEW_PULL_REQUESTS=true` to enable a separate publisher job that never executes Intent or checks out the library. See [setup commands](../cli/intent-setup). > [!NOTE] -> `intent setup` copies CI templates on its own; `intent maintainer setup` also initializes the maintainer workflow. To replace an older generated workflow, move or delete it before rerunning `setup`; Intent skips existing files. +> `intent setup` copies CI templates on its own; `intent maintainer setup` also initializes the maintainer workflow. Publish through the library's normal release process. Skills in the package's published `skills/` directory version with that library release. Consumers install the library, configure permitted skill sources with consumer [`intent install`](../cli/intent-install#default-install), discover the installed skills with [`intent list`](../cli/intent-list), and load matching guidance with `intent load`. diff --git a/docs/overview.md b/docs/overview.md index d80492c8..8edfbc7c 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -28,12 +28,12 @@ Intent provides tooling for two workflows: - Ship skills in the same release pipeline as code - Review version, source, artifact, and package coverage signals -## Keep the workflow boundaries clear +## Workflow stages | Stage | Who runs it | Result | | --- | --- | --- | | Maintainer enablement | Library maintainer | `maintainer setup` creates missing records and installs persistent authoring instructions. | -| Authoring and maintenance | Library maintainer and coding agent | `meta generate-skill` guides a focused batch; `maintainer review` records evidence-backed outcomes for later source changes. | +| Authoring and maintenance | Library maintainer and coding agent | `meta generate-skill` guides a focused batch; `maintainer review` records review outcomes. | | Package publishing | Library release process | `maintainer sync` updates package and selected repository exports; `setup` optionally adds CI. | | Consumer setup | Developer using the published library | Consumer `install` configures permitted skill sources and skill-loading guidance; `list` and `load` use skills from installed dependencies. | diff --git a/docs/registry.md b/docs/registry.md index 0a686d42..93c56463 100644 --- a/docs/registry.md +++ b/docs/registry.md @@ -50,7 +50,7 @@ This adds the `tanstack-intent` keyword and registered skill directories to exis -Save the report under `.intent/`, assess the pending items, and annotate completed outcomes with their reasons and actual evidence. Record the report with `intent maintainer review --record `, then run `intent maintainer check`. This checks skill structure, registration, generated files, and pending reviews together. See the [source-review reference](./cli/intent-review) for report fields and recording. +Save the report under `.intent/`, assess the pending items, and annotate completed outcomes with their reasons and evidence. Record the report with `intent maintainer review --record `, then run `intent maintainer check`. This checks skill structure, registration, generated files, and pending reviews together. See the [source-review reference](./cli/intent-review) for report fields and recording. ### 4. Publish @@ -72,7 +72,7 @@ Use `maintainer review` and `stale` as separate checks as the library changes. ` -Uses Git changes and recorded content fingerprints to identify skills, planning records, and unmapped source areas that need semantic review. Record completed outcomes with their evidence in `.intent/review-state.json`; missing evidence remains pending. +Uses Git changes and recorded content fingerprints to identify skills, planning records, and unmapped source areas that need semantic review. Record completed outcomes with their evidence in `.intent/review-state.json`. @@ -90,9 +90,6 @@ Reports conservative package and release signals: version drift, missing stored Copies the generated CI workflow into your repository. Pull requests validate skills and check recorded source reviews when maintainer guidance or review state exists. Release and manual runs use recorded review state when available, with conservative `stale` signals as the fallback. -> [!NOTE] -> Maintainers use `maintainer setup`, `add`, `status`, `sync`, `review`, and `check` throughout the workflow. Consumers choose their installer: Intent for installed package guidance, or the generated GitHub/plugin commands for selected repository skills. See [repository distribution](./cli/intent-maintainer#choose-repository-distribution). - ## Requesting a library If you use a library that doesn't ship skills yet, the best path is to open an issue on that library's repo pointing them here. The maintainer is the right person to author and own skills for their tool — they know the intent behind the API better than anyone. From e4f238b4ef88266ff4ea4af2b2a50498990bb106 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:43:52 -0700 Subject: [PATCH 04/12] docs: shorten wording in bundled meta skills Remove filler words and restated context from the skills that ship in meta/. Every instruction, rule, step, and table row stays. --- .../intent/meta/domain-discovery/SKILL.md | 10 +++--- packages/intent/meta/generate-skill/SKILL.md | 12 +++---- .../generate-skill/references/distribution.md | 8 ++--- .../references/maintainer-commands.md | 4 +-- .../references/planning-records.md | 4 +-- .../references/review-signals.md | 2 +- .../generate-skill/references/skill-format.md | 4 +-- .../references/source-review.md | 6 ++-- .../generate-skill/references/task-quality.md | 10 +++--- .../meta/skill-staleness-check/SKILL.md | 33 ++++++++----------- packages/intent/meta/tree-generator/SKILL.md | 6 +--- .../references/update-skills.md | 2 +- 12 files changed, 46 insertions(+), 55 deletions(-) diff --git a/packages/intent/meta/domain-discovery/SKILL.md b/packages/intent/meta/domain-discovery/SKILL.md index 8f237f5b..ff91d776 100644 --- a/packages/intent/meta/domain-discovery/SKILL.md +++ b/packages/intent/meta/domain-discovery/SKILL.md @@ -40,14 +40,14 @@ The lightweight path produces identical output artifacts (domain_map.yaml and sk These rules override any other reasoning. No exceptions. -1. **Phases 2 and 4 are interactive interviews conducted with the maintainer.** You must ask the questions specified in each sub-section and wait for the maintainer's response before continuing. Documentation, source code, and other automated analysis are NOT substitutes for the maintainer's answers. -2. **Every question in Phases 2 and 4 must be asked as an open-ended question and sent as a message to the maintainer.** You must then STOP and WAIT for their reply. Do not answer your own questions. Do not infer answers from documentation. Do not skip questions because you believe you already know the answer. -3. **Never ask factual questions you can answer by searching the codebase.** Before asking any question, determine whether the answer is a deterministic fact (how many X exist, what versions are supported, which files implement Y) or a judgment call (which ones matter, what should we prioritize, what do developers struggle with). Factual questions must be answered by searching the code — grep, glob, read files. Only ask the maintainer for priorities, opinions, trade-offs, and implicit knowledge that cannot be found in code or docs. Asking the maintainer a question whose answer is sitting in the codebase wastes their time and erodes trust in the process. +1. **Phases 2 and 4 are interactive interviews conducted with the maintainer.** You must ask the questions specified in each sub-section and wait for the maintainer's response before continuing. Documentation, source code, and other automated analysis are not substitutes for the maintainer's answers. +2. **Every question in Phases 2 and 4 must be asked as an open-ended question and sent as a message to the maintainer.** You must then stop and wait for their reply. Do not answer your own questions. Do not infer answers from documentation. Do not skip questions because you believe you already know the answer. +3. **Never ask factual questions you can answer by searching the codebase.** Before asking any question, determine whether the answer is a deterministic fact (how many X exist, what versions are supported, which files implement Y) or a judgment call (which ones matter, what should we prioritize, what do developers struggle with). Factual questions must be answered by searching the code — grep, glob, read files. Only ask the maintainer for priorities, opinions, trade-offs, and implicit knowledge that cannot be found in code or docs. 4. **Do not convert open-ended questions into multiple-choice, yes/no, or confirmation prompts.** The question templates in each sub-section are open-ended by design. Present them as open-ended questions. The maintainer's unprompted answers surface knowledge that pre-structured options suppress. 5. **Minimum question counts are enforced.** Each sub-section specifies a question count range (e.g. "2–4 questions"). You must ask at least the minimum number. Asking zero questions in any sub-section is a protocol violation. 6. **STOP gates are mandatory.** At the boundaries marked `── STOP ──` below, you must halt execution and wait for the maintainer's response or acknowledgment before proceeding. Do not continue past a STOP gate in the same message. 7. **If the maintainer asks to skip an interview phase**, explain the value of the phase and what will be lost. Proceed with skipping only if they confirm a second time. -8. **Rich documentation makes interviews MORE valuable, not less.** When docs are comprehensive, the interview surfaces what docs miss: implicit knowledge, AI-specific failure modes, undocumented tradeoffs, and the maintainer's prioritization of what matters most. Never rationalize skipping interviews because documentation is thorough. +8. **Rich documentation makes interviews more valuable, not less.** When docs are comprehensive, the interview surfaces what docs miss: implicit knowledge, AI-specific failure modes, undocumented tradeoffs, and the maintainer's prioritization of what matters most. Never rationalize skipping interviews because documentation is thorough. --- @@ -202,7 +202,7 @@ Adapt from this bank of gap-targeted question templates: ### 4c — AI-agent-specific failure modes (2–4 questions) -These target mistakes that AI coding agents make but human developers typically don't. Agent-specific failures are often the highest-value findings — in testing, maintainer answers to these questions produced the most critical failure modes. +These target mistakes that AI coding agents make but human developers typically don't. Agent-specific failures are often the highest-value findings. - "What mistakes would an AI coding agent make that a human developer wouldn't? Think about: hallucinating APIs that don't exist, defaulting to language primitives instead of library abstractions, choosing the wrong adapter or integration path." - "When an agent generates code using your library, what's the first thing you'd check? What pattern would make you immediately say 'an AI wrote this'?" diff --git a/packages/intent/meta/generate-skill/SKILL.md b/packages/intent/meta/generate-skill/SKILL.md index 8ac783d7..af4844c0 100644 --- a/packages/intent/meta/generate-skill/SKILL.md +++ b/packages/intent/meta/generate-skill/SKILL.md @@ -23,7 +23,7 @@ Check repository instructions and Git status before edits; preserve unrelated ch Before choosing or changing repository exports, follow [repository distribution](references/distribution.md). For an export-only change, complete that procedure against existing skill records; use the authoring steps below only if guidance must change. -For an initial skill set or a request spanning several developer tasks, read [initial batches](references/initial-batches.md). Reuse scope already approved in the conversation. For one concrete task, proceed directly below. During ordinary library work, keep the code change as the primary task. Read [source review](references/source-review.md) to identify affected guidance from actual changes and record completed reviews before handing off any of these workflows. +For an initial skill set or a request spanning several developer tasks, read [initial batches](references/initial-batches.md). Reuse scope already approved in the conversation. For one concrete task, proceed directly below. During ordinary library work, keep the code change as the primary task. Read [source review](references/source-review.md) to identify affected guidance from the changes and record completed reviews before handing off any of these workflows. For every authoring batch or update, read [the planning record procedure](references/planning-records.md) and create or incrementally maintain `domain_map.yaml`, `skill_spec.md`, and `skill_tree.yaml`. Read existing records first and preserve prior scope and decisions. These records grow with the batches; maintaining them does not require a full-library interview or generating every planned skill. @@ -31,7 +31,7 @@ When the input is an `intent stale` report or generated review PR, read [review- ## 2. Read the evidence and choose the owner -Read the relevant source, types, tests, docs, examples, and existing skills with their required references. Follow imports or related guidance where they affect the task. Record the source revision or package version used. For an update, inspect the supplied change and the existing skill's claims; use an actual diff or documented before/after behavior when available. A version change alone does not establish changed behavior or a baseline. +Read the relevant source, types, tests, docs, examples, and existing skills with their required references. Follow imports or related guidance where they affect the task. Record the source revision or package version used. For an update, inspect the supplied change and the existing skill's claims; use a diff or documented before/after behavior when available. A version change alone does not establish changed behavior or a baseline. Prefer updating guidance that already owns the task. Create one new skill only when developers would benefit from discovering that task independently. Clarify an ambiguous boundary with a concrete example: would a developer trying this task need the same guidance, or a different prerequisite or workflow? Keep the library's established names and terminology. @@ -49,7 +49,7 @@ No fixed interview or review-preference question is needed for one task. Apply the writing rules below to each task in the agreed batch. For a **new skill**, read [the skill format](references/skill-format.md) for frontmatter, body, and prerequisite conventions. Source documentation can establish the batch’s evidence; create or extend its required planning record alongside the skills. -For an **update**, preserve established names, layout, terminology, and scope unless the actual change requires otherwise. Edit only affected sections and references. Add a sourced old/new example when a changed pattern would otherwise mislead users. Reconcile all three planning documents with the change using the planning record procedure; update affected entries and preserve accurate, unrelated decisions. Change `metadata.library_version` only when the revised guidance is verified for that version; do not fabricate historical versions or rewrite unrelated metadata to clear a staleness signal. +For an **update**, preserve established names, layout, terminology, and scope unless the change requires otherwise. Edit only affected sections and references. Add a sourced old/new example when a changed pattern would otherwise mislead users. Reconcile all three planning documents with the change using the planning record procedure; update affected entries and preserve accurate, unrelated decisions. Change `metadata.library_version` only when the revised guidance is verified for that version; do not fabricate historical versions or rewrite unrelated metadata to clear a staleness signal. ### Writing rules @@ -72,11 +72,11 @@ For new guidance and updates that change a recommended behavior, follow [task qu For new or changed descriptions, also follow [discovery checks](references/task-quality.md#check-discovery-separately). Keep activation evidence separate from task correctness. -Run `npm exec --no -- intent validate ` with the actual owning package's skill directory (or the repository's installed `intent`). Fix errors without weakening validation. Keep every SKILL.md within the 500-line limit. Review packaging warnings separately; they do not require installing dependencies or changing publishing configuration during authoring. +Run `npm exec --no -- intent validate ` with the owning package's skill directory (or the repository's installed `intent`). Fix errors without weakening validation. Keep every SKILL.md within the 500-line limit. Review packaging warnings separately; they do not require installing dependencies or changing publishing configuration during authoring. -Check that every reference and prerequisite resolves, every changed claim matches the cited source/version, and examples use actual supported APIs. Exercise the relevant example or package check where available. Intent's structural validation does not prove semantic correctness or agent behavior. If a check cannot run, report it as not verified with the reason. +Check that every reference and prerequisite resolves, every changed claim matches the cited source/version, and examples use supported APIs. Exercise the relevant example or package check where available. Intent's structural validation does not prove semantic correctness or agent behavior. If a check cannot run, report it as not verified with the reason. -Inspect the actual `SKILL.md` output and matching tree entry before handoff: the description makes the use conditions clear, purpose explains the skill, and both stay within supported behavior. Check migrated purpose text against the pre-edit description and preserve established purpose on later updates. Do not imply stronger guarantees to attract more requests. Check that references have reading conditions and independently discoverable tasks justify any new skills. +Inspect the `SKILL.md` output and matching tree entry before handoff: the description makes the use conditions clear, purpose explains the skill, and both stay within supported behavior. Check migrated purpose text against the pre-edit description and preserve established purpose on later updates. Do not imply stronger guarantees to attract more requests. Check that references have reading conditions and independently discoverable tasks justify any new skills. Verify all three planning documents against the resulting skills and prior record, then record completed skill and planning outcomes using the [source review procedure](references/source-review.md), then inspect the final diff for unrelated edits and run `git diff --check` for touched files. Return the changed library behavior, affected skill/reference paths, all three planning document paths and their changes or justified no-op, source/version evidence, structural and task-check results, and any remaining maintainer decision. Distinguish updated guidance, verified no change, and missing evidence for each reviewed task. Report whether a fresh consumer session completed the representative task; if that check could not run, mark it unverified rather than treating the authoring session as independent evidence. The result is ready for maintainer review when the task is usable end to end and those checks pass. diff --git a/packages/intent/meta/generate-skill/references/distribution.md b/packages/intent/meta/generate-skill/references/distribution.md index d0ca8db6..b54ced4a 100644 --- a/packages/intent/meta/generate-skill/references/distribution.md +++ b/packages/intent/meta/generate-skill/references/distribution.md @@ -10,7 +10,7 @@ Package-only distribution is the default; `intent maintainer setup` mentions rep intent maintainer setup --distribution repo --skill discover-library --skill query ``` -Use the actual registered skill names. The repository is read from package metadata; supply `--repository owner/repo` when it cannot be established. `--plugin-name` chooses an initial plugin name when the default is unsuitable. To record the package-only default explicitly, so later sessions do not raise the option again, run: +Use the registered skill names. The repository is read from package metadata; supply `--repository owner/repo` when it cannot be established. `--plugin-name` chooses an initial plugin name when the default is unsuitable. To record the package-only default explicitly, so later sessions do not raise the option again, run: ```sh intent maintainer setup --distribution none @@ -31,9 +31,9 @@ Run `intent maintainer sync` after authoring. Inspect `skills` paths in `.claude - **GitHub skill installers:** use the generated `npx skills add owner/repo --full-depth --skill ` or `gh skill add owner/repo ` commands. `--full-depth` finds package skills even when root or agent-directory skills exist; `--skill` still limits the selection. Their default installation scope is the project. User scope is a separate consumer choice (`--global` for skills, `--scope user` for gh). Repository source location and installation scope are separate concepts. - **Plugins:** use the generated marketplace metadata with Claude Code or Cursor's native plugin installation. The plugin references the selected package directories; it does not require Intent to invoke those skills. -The generated selection controls Intent's exported metadata and suggested install commands. Third-party installers retain their own discovery rules; a full repository scan or explicit `--all` can expose other public skills. Use the named selection or exact paths when distributing a curated subset. Check references from the installed skill directory and test the actual consumer task separately: copying a skill does not prove that all its links or recommendations are portable. +The generated selection controls Intent's exported metadata and suggested install commands. Third-party installers retain their own discovery rules; a full repository scan or explicit `--all` can expose other public skills. Use the named selection or exact paths when distributing a curated subset. Check references from the installed skill directory and test the consumer task separately: copying a skill does not prove that all its links or recommendations are portable. -Publish through the library's normal npm/GitHub release process. `gh skill publish --dry-run` can validate a GitHub skill release without publishing it; actual releases remain a maintainer action. skills.sh indexes public GitHub skills through real installation usage; there is no submission API used by Intent. Do not simulate installations to create a listing. +Publish through the library's normal npm/GitHub release process. `gh skill publish --dry-run` can validate a GitHub skill release without publishing it; releases remain a maintainer action. skills.sh indexes public GitHub skills through real installation usage; there is no submission API used by Intent. Do not simulate installations to create a listing. ## Versions and updates @@ -48,7 +48,7 @@ Publish through the library's normal npm/GitHub release process. `gh skill publi 1. Install the selected skills in disposable consumer projects through each advertised installer and host. Check selected names and exclusion of unselected skills. For plugins, inspect all loaded components: the repository root is the plugin root, so preserved or automatically discovered commands, agents, hooks, and MCP configuration are not limited by the skill selection. 2. Resolve required references from the installed skill directory and execute bundled helpers with valid and invalid inputs. Check runtime requirements against the consumer environment. Proceed when the required files and tools work outside the source checkout. 3. Test updates and removal through the chosen installer. Use the native [Claude](https://code.claude.com/docs/en/plugin-marketplaces#validation-and-testing) or [Cursor](https://cursor.com/docs/reference/plugins) flow to check plugin activation and changed versions. Verify that source opt-out clears generated exports without removing existing consumer copies. -4. Run an actual consumer task against the supported package version using the [task quality checks](task-quality.md). File copying and valid manifests establish packaging, not task correctness. +4. Run a consumer task against the supported package version using the [task quality checks](task-quality.md). File copying and valid manifests establish packaging, not task correctness. 5. After the final sync, record supported outcomes through [source review](source-review.md) and run `intent maintainer check`. Report paths, revisions, host versions, check results, and missing evidence. The diff is ready for review when these checks pass; mark unavailable hosts or task evidence as incomplete. Publishing and commits require the maintainer's request. For changed installer syntax or host formats, verify matching versions against the [skills CLI](https://github.com/vercel-labs/skills), [GitHub skill install](https://cli.github.com/manual/gh_skill_install), [Claude plugin paths](https://code.claude.com/docs/en/plugins-reference#path-behavior-rules), and [Cursor plugins](https://cursor.com/docs/reference/plugins) before changing consumer instructions. diff --git a/packages/intent/meta/generate-skill/references/maintainer-commands.md b/packages/intent/meta/generate-skill/references/maintainer-commands.md index a494cb3e..1e7107d3 100644 --- a/packages/intent/meta/generate-skill/references/maintainer-commands.md +++ b/packages/intent/meta/generate-skill/references/maintainer-commands.md @@ -6,8 +6,8 @@ Use the repository's installed Intent command for these actions, such as `pnpm e 2. For a new task, run `intent maintainer add --domain --description --source --task `. Repeat `--source`, `--requires`, and `--task` for multiple entries; each `--task` becomes an assessed developer task in the domain map. In a monorepo, run the command from the owning package directory or pass `--package packages/` relative to the repository root. Source paths are relative to the owning package; `owner/repo:path` is relative to the repository. Use `--path /SKILL.md` for an established custom layout. To register an existing skill, supply its name, domain, package, and path; its frontmatter supplies the other fields. The command prints every file it wrote. 3. Author the skill and reconcile all three records using the procedures in this skill. The command creates a skeleton and a domain-map entry; add any tasks not supplied on the command line. Write the spec's decisions/history. Remove `` only after authoring the corresponding document. Do not remove it simply to make a check pass. To retire a registered skill, run `intent maintainer remove `; it marks the tree entry `retired` and notes it in the spec without deleting the file, and refuses while the skill is selected for distribution or required by another skill. 4. Run `intent maintainer status` to see missing work, stale metadata, and pending reviews. `--json` includes the full source-review report. For a supplied PR base, use `--base `. -5. Run `intent repair --json` when mechanical validation failures are present. Use `intent repair --write` for unambiguous frontmatter migrations; resolve conflicting values from evidence. `intent repair --patch` proposes code-preserving splits for labeled before/after examples, but inspect whether they are alternatives before applying those suggestions. The repair command does not replace validation or establish that guidance is current. Run `intent maintainer sync` after edits. It copies descriptions, purpose, sources, and prerequisites from registered skills into the tree, repairs the tree's record links, and includes the skill directories in existing package `files` allowlists. It preserves authored map/spec content and other manifest fields. It does not change version claims or run a package release. An absent `files` allowlist stays absent so npm's default contents are preserved; check the actual packed archive as part of the package's release checks. -6. Follow [source review](source-review.md) with `intent maintainer review --json`, supply justified outcomes, and record them with `intent maintainer review --record .intent/review.json`. A maintainer working in a terminal can do the same with `intent maintainer review --interactive`. The command retains the existing revision and content-fingerprint checks. Run `intent maintainer check` after recording; it exits nonzero for incomplete authoring, stale generated metadata, invalid skills, missing local prerequisites, or pending reviews. Use the same check in CI, passing the actual PR base and `--github-summary` so the reasons appear in the step summary; the workflow that `setup` copies does both. +5. Run `intent repair --json` when mechanical validation failures are present. Use `intent repair --write` for unambiguous frontmatter migrations; resolve conflicting values from evidence. `intent repair --patch` proposes code-preserving splits for labeled before/after examples, but inspect whether they are alternatives before applying those suggestions. The repair command does not replace validation or establish that guidance is current. Run `intent maintainer sync` after edits. It copies descriptions, purpose, sources, and prerequisites from registered skills into the tree, repairs the tree's record links, and includes the skill directories in existing package `files` allowlists. It preserves authored map/spec content and other manifest fields. It does not change version claims or run a package release. An absent `files` allowlist stays absent so npm's default contents are preserved; check the packed archive as part of the package's release checks. +6. Follow [source review](source-review.md) with `intent maintainer review --json`, supply justified outcomes, and record them with `intent maintainer review --record .intent/review.json`. A maintainer working in a terminal can do the same with `intent maintainer review --interactive`. The command retains the existing revision and content-fingerprint checks. Run `intent maintainer check` after recording; it exits nonzero for incomplete authoring, stale generated metadata, invalid skills, missing local prerequisites, or pending reviews. Use the same check in CI, passing the PR base and `--github-summary` so the reasons appear in the step summary; the workflow that `setup` copies does both. Keep unimplemented future skills in the tree with `status: planned` and retired entries with `status: retired`. They remain part of the cumulative record but do not count as implemented skills or enter package publishing configuration. An active entry with a missing file is an error to resolve, not an invitation to delete the entry. Local prerequisite slugs are checked against implemented tree entries; verify external package prerequisites and the developer task through the task-quality procedure. diff --git a/packages/intent/meta/generate-skill/references/planning-records.md b/packages/intent/meta/generate-skill/references/planning-records.md index 2a6f8e12..0c2b78b6 100644 --- a/packages/intent/meta/generate-skill/references/planning-records.md +++ b/packages/intent/meta/generate-skill/references/planning-records.md @@ -40,7 +40,7 @@ skills: - `domain_map.yaml` owns the domain/task relationships, supported failure modes, cross-references, tensions, and knowledge gaps. Keep task slugs and package ownership aligned with the skills. - `skill_spec.md` is the human-readable coverage and decision record. Retain the existing inventories and add a **Coverage and batch history** section recording the assessed scope, each completed batch or behavior change, its source revision/version, consequential decisions and reasons, check outcomes, and remaining work. Keep entries concise; do not store transcripts. Distinguish implemented guidance from planned work and unassessed areas. -- `skill_tree.yaml` owns skill identities, paths, prerequisites, source mappings, and package placement. Keep existing planned entries and their status or explanatory notes. Add each new skill, and update entries when their names, paths, dependencies, or sources change. Resolve `path` relative to the owning package when `package` is present; otherwise resolve it relative to the library root. Keep `generated_from` links accurate for the actual artifact location. +- `skill_tree.yaml` owns skill identities, paths, prerequisites, source mappings, and package placement. Keep existing planned entries and their status or explanatory notes. Add each new skill, and update entries when their names, paths, dependencies, or sources change. Resolve `path` relative to the owning package when `package` is present; otherwise resolve it relative to the library root. Keep `generated_from` links accurate for the artifact location. - `references` lists the `.md` files under the skill's `references/` directory. `intent validate` requires the key when the skill has reference files, and requires the list to match those files: each path has the form `references/.md`, is listed once, and exists, and no file is left out. Omit the key, or use an empty list, for a skill without reference files. `intent validate` also checks every reference file as described in [the skill format](skill-format.md). Keep each tree entry's `description` aligned with its skill's activation description and its `purpose` aligned with `metadata.purpose`. Existing map/spec task explanations retain their meaning; do not replace them with trigger text. Record a purpose migration and its preserved source text in the batch review without discarding prior decisions. @@ -60,7 +60,7 @@ Before handoff, reconcile the resulting diff with all three documents: ## Check and record completion -Check that all three files exist and contain substantive content. Parse both YAML files with the repository’s available YAML parser, then compare the map, spec, tree, and actual skill files. Verify every implemented tree path and prerequisite, the selected batch’s coverage, and preservation of prior entries. Planned future entries are not passing implementations. Run skill validation and the task-quality checks for changed guidance. +Check that all three files exist and contain substantive content. Parse both YAML files with the repository’s available YAML parser, then compare the map, spec, tree, and skill files. Verify every implemented tree path and prerequisite, the selected batch’s coverage, and preservation of prior entries. Planned future entries are not passing implementations. Run skill validation and the task-quality checks for changed guidance. Follow [source review](source-review.md) after all skill and record edits. The default installed maintainer workflow reports a planning review item whose snapshot includes the three documents and the skill/source evidence. It stays unresolved when a required file is missing, empty, ignored, or invalid; later source or skill changes reopen its review even if the documents did not change. Record an `updated` outcome after changing the record or a `no-change` outcome with evidence covering all three documents when they remain accurate. diff --git a/packages/intent/meta/generate-skill/references/review-signals.md b/packages/intent/meta/generate-skill/references/review-signals.md index af2df731..02e2b854 100644 --- a/packages/intent/meta/generate-skill/references/review-signals.md +++ b/packages/intent/meta/generate-skill/references/review-signals.md @@ -10,7 +10,7 @@ Use the report and existing conversation to locate the owning package, skill, an | Input | Evidence needed | Possible outcome | | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Stale skill or version drift | The current skill's claims and an actual source diff or documented before/after behavior for the target version. | Update affected guidance, or explain why it remains accurate. A version number alone proves neither outcome. | +| Stale skill or version drift | The current skill's claims and a source diff or documented before/after behavior for the target version. | Update affected guidance, or explain why it remains accurate. A version number alone proves neither outcome. | | Missing source SHA | The referenced source and a trustworthy revision or baseline. A missing stored SHA does not prove that the source changed. | Establish the evidence before deciding whether guidance needs an update. If unavailable, report uncertainty. | | Missing package, artifact, or generated-skill coverage | Public tasks in the package, existing skill owners, and relevant artifact entries or exclusions. | Extend an existing owner, create one independently useful task, or retain a supported out-of-scope decision. Ask only if an unresolved scope choice changes the outcome. | | Invalid or unreadable artifact | The reported parse/validation error and the relevant artifact content. | Report the affected coverage conclusion as unknown until the artifact can be read. Do not infer absent coverage from a failed read. | diff --git a/packages/intent/meta/generate-skill/references/skill-format.md b/packages/intent/meta/generate-skill/references/skill-format.md index 541828a7..685656db 100644 --- a/packages/intent/meta/generate-skill/references/skill-format.md +++ b/packages/intent/meta/generate-skill/references/skill-format.md @@ -22,13 +22,13 @@ sources: Replace template values with evidence from the library. `name` uses only lowercase letters, numbers, and hyphens, matches its parent directory, and is at most 64 characters. `description` is at most 1024 characters. Intent-specific scalars belong under `metadata`, whose values are strings. Intent supports top-level `sources` and `requires` arrays. Source entries use `Owner/repo:relative-path`; globs are supported, but select paths relevant to the task. If the repository or target version cannot be established, report that uncertainty instead of inventing provenance. -Follow [Agent Skills description guidance](https://agentskills.io/skill-creation/optimizing-descriptions). Keep library context and explicit use conditions in `description`; it must communicate the supported task without requiring custom metadata. Check actual discovery using [discovery checks](task-quality.md#check-discovery-separately). +Follow [Agent Skills description guidance](https://agentskills.io/skill-creation/optimizing-descriptions). Keep library context and explicit use conditions in `description`; it must communicate the supported task without requiring custom metadata. Check discovery using [discovery checks](task-quality.md#check-discovery-separately). ### Purpose and activation `description` is the standard agent-discovery field. Write concrete “Use when…” conditions that identify what the agent can accomplish and distinguish adjacent tasks. `metadata.purpose` is Intent's descriptive explanation of what the skill is for, stored as a string in the standard [metadata extension point](https://agentskills.io/specification#metadata-field). -For a new skill, author both fields. For an existing skill without `metadata.purpose`, read its description before editing and preserve that text unchanged as purpose, then write the activation description. Use the actual pre-edit content, not a rewritten draft or a newly invented summary. If purpose already exists, preserve it; subsequent edits to activation conditions do not replace it. If the source proves that a preserved purpose is inaccurate, report the conflict and propose the smallest correction explicitly rather than silently changing its meaning during migration. +For a new skill, author both fields. For an existing skill without `metadata.purpose`, read its description before editing and preserve that text unchanged as purpose, then write the activation description. Use the pre-edit content, not a rewritten draft or a newly invented summary. If purpose already exists, preserve it; subsequent edits to activation conditions do not replace it. If the source proves that a preserved purpose is inaccurate, report the conflict and propose the smallest correction explicitly rather than silently changing its meaning during migration. Keep purpose and activation scope aligned when maintaining the skill. Existing third-party skills without purpose remain valid; the field is an Intent authoring convention, not a universal Agent Skills requirement. Structural validation checks its string type through the metadata contract, not the quality of the prose or a literal “Use when” prefix. diff --git a/packages/intent/meta/generate-skill/references/source-review.md b/packages/intent/meta/generate-skill/references/source-review.md index b391a9ab..12572c1b 100644 --- a/packages/intent/meta/generate-skill/references/source-review.md +++ b/packages/intent/meta/generate-skill/references/source-review.md @@ -4,13 +4,13 @@ Read this before handing off an initial skill batch, an ordinary library change, ## Inspect the current changes -Run `intent maintainer review --json` using the repository's installed Intent command, or the package-manager command used to load this procedure. When the task supplies a PR base, pass `--base ` with that actual revision. Do not invent a historical baseline. Without an explicit base, Intent compares against the first recorded review's baseline, or `HEAD` when no state exists. It also compares each skill's current source and guidance content with its last recorded review. +Run `intent maintainer review --json` using the repository's installed Intent command, or the package-manager command used to load this procedure. When the task supplies a PR base, pass `--base ` with that revision. Do not invent a historical baseline. Without an explicit base, Intent compares against the first recorded review's baseline, or `HEAD` when no state exists. It also compares each skill's current source and guidance content with its last recorded review. If rewritten history makes the recorded baseline unavailable, do not guess a replacement. Fetch the missing history, or choose an available commit as a new coverage boundary from repository evidence. Generate the report with `intent maintainer review --base --json`, resolve every reported item, then record that report. A fully resolved explicit report adopts its base for later default reviews, including when the report has no items. An omitted, unresolved, or invalid item leaves the unavailable baseline unchanged. For a new batch, review the selected skills. Other items remain pending unless the maintainer has included them in the task. For ordinary code changes, inspect affected skills and unmapped changes within the agreed change. An unmapped file is an investigation input, not a demand for a new skill or full taxonomy. Decide from the source and developer task whether existing guidance needs updating, a new independently useful skill is warranted, or no guidance change is needed. -Read [the planning record procedure](planning-records.md), then review the actual diff, affected source, skill, references, relevant tests, and all three planning documents. Create missing records and reconcile changed coverage, recommendations, dependencies, and maintainer decisions before handoff. Preserve unrelated record entries and future work. An item with no recorded review compares its files with the commit that introduced its guidance, so `changedFiles` is empty for an initial review only when nothing changed since then. A recorded content snapshot detects edits even if the earlier review happened before a commit; it does not retain the earlier source text. Use an available Git diff or explain when historical text is unavailable. Missing sources, foreign repositories, conflicts, or unavailable history remain unknown until the evidence is resolved. +Read [the planning record procedure](planning-records.md), then review the diff, affected source, skill, references, relevant tests, and all three planning documents. Create missing records and reconcile changed coverage, recommendations, dependencies, and maintainer decisions before handoff. Preserve unrelated record entries and future work. An item with no recorded review compares its files with the commit that introduced its guidance, so `changedFiles` is empty for an initial review only when nothing changed since then. A recorded content snapshot detects edits even if the earlier review happened before a commit; it does not retain the earlier source text. Use an available Git diff or explain when historical text is unavailable. Missing sources, foreign repositories, conflicts, or unavailable history remain unknown until the evidence is resolved. Agent instruction files, generated plugin metadata, the generated CI workflow, `.intent/`, package manifests, and lockfiles are never reported as unmapped changes; a skill that lists one of them in `sources` still tracks it. Add repository-specific patterns under `review.ignore` in `skill_tree.yaml`. Plain `sources` paths are relative to the skill's nearest owning package, or the Git root when no package exists. `owner/repository:path` paths are relative to the Git root and must match the local repository's origin or root package repository metadata. Git glob syntax supports `*`, `?`, character classes and `**`; brace expansion and extglobs are unsupported. Keep evidence paths accurate. The command reviews Git-visible `SKILL.md` files under `skills/`, custom skill directories containing `_artifacts/`, and paths declared in an existing `skill_tree.yaml`. Previously recorded skills remain covered. Shared repository/package planning directories do not select every agent instruction in the package; list custom skill paths in the tree, using its `package` field for monorepo ownership. Installed dependencies under `node_modules` are excluded. Ignored files and external repositories still require explicit manual review. @@ -20,7 +20,7 @@ After guidance edits and task checks, regenerate the JSON report. Save it outsid - `outcome`: `updated`, `no-change`, `out-of-scope`, or `unresolved`. - `reason`: the concrete behavior comparison and why that outcome follows. -- `evidence`: source paths/revisions and actual check results. For behavior-changing guidance, include structural validation, executable task checks, and fresh-consumer evidence or its explicit limitation. +- `evidence`: source paths/revisions and check results. For behavior-changing guidance, include structural validation, executable task checks, and fresh-consumer evidence or its explicit limitation. When every pending item shares one outcome and one reason, run `intent maintainer review --unchanged ""` or `--updated ""`; the command records the reviewed revision and changed files as evidence. Otherwise preserve the report's identity, base and fingerprints and run `intent maintainer review --record .intent/review.json`. For planning items, use `updated` or an evidence-backed `no-change` covering all three documents. The command rejects a report that annotates nothing, stale fingerprints, and unresolved source mappings or planning files. It writes completed outcomes to `.intent/review-state.json`; unresolved or unannotated items stay pending. Do not invent passing checks, use a generic reason, or mark unrelated items complete just to empty the report. diff --git a/packages/intent/meta/generate-skill/references/task-quality.md b/packages/intent/meta/generate-skill/references/task-quality.md index 173a9a07..42869051 100644 --- a/packages/intent/meta/generate-skill/references/task-quality.md +++ b/packages/intent/meta/generate-skill/references/task-quality.md @@ -4,7 +4,7 @@ Read this for new skills and when a change affects the behavior a skill recommen ## Check discovery separately -For new or changed descriptions, follow [Agent Skills description evaluation](https://agentskills.io/skill-creation/optimizing-descriptions). Save realistic should-load prompts and adjacent should-not-load prompts with the task cases. Include requests that omit the library's API vocabulary. Expose the skill through normal consumer setup and inspect whether the agent actually loads its `SKILL.md`; a skill name in the answer is insufficient. +For new or changed descriptions, follow [Agent Skills description evaluation](https://agentskills.io/skill-creation/optimizing-descriptions). Save realistic should-load prompts and adjacent should-not-load prompts with the task cases. Include requests that omit the library's API vocabulary. Expose the skill through normal consumer setup and inspect whether the agent loads its `SKILL.md`; a skill name in the answer is insufficient. Repeat ambiguous results and record observed activation separately from task success. When tuning a description, keep a fixed mix of positive and negative prompts held out from revision, then check fresh phrasings. Report the prompts, attempts, and observed loads; do not claim a reliability rate from one run. If the runtime cannot expose discovery, mark it unverified rather than substituting a keyword match or structural validation. @@ -14,15 +14,15 @@ Use the library's existing examples and tests to choose a realistic developer re Put the case in the repository's existing test or eval layout. When no layout exists, use `tests/skills//` with a `task.md`, a small starting fixture, and an executable check using the package's existing test runner. The task describes what the developer needs without supplying the solution. The checks assert externally observable behavior, including the relevant error path. Keep grading tests outside the files the consumer agent is asked to edit. -Use real package APIs and the actual source version being reviewed. Execute the expected solution to validate the fixture and checker before using them to grade an agent. Apply the same behavioral assertions to a plausible incorrect solution, such as the specific mistake the skill warns about, and confirm those assertions fail. An assertion that merely says the bad solution is different does not establish that the grader rejects it. If the intended behavior is unresolved, get that decision before authoring dependent guidance or grading it. +Use real package APIs and the source version being reviewed. Execute the expected solution to validate the fixture and checker before using them to grade an agent. Apply the same behavioral assertions to a plausible incorrect solution, such as the specific mistake the skill warns about, and confirm those assertions fail. An assertion that merely says the bad solution is different does not establish that the grader rejects it. If the intended behavior is unresolved, get that decision before authoring dependent guidance or grading it. -Check precise claims in the description as well as the body and main happy path. For asynchronous APIs, distinguish synchronous throws from rejected promises, cancellation before a call from cancellation during one, and rejection from successful completion. Exercise the input and error shapes supported by the actual API before claiming errors are always preserved. A passing representative task does not validate every statement in a skill. +Check precise claims in the description as well as the body and main happy path. For asynchronous APIs, distinguish synchronous throws from rejected promises, cancellation before a call from cancellation during one, and rejection from successful completion. Exercise the input and error shapes supported by the API before claiming errors are always preserved. A passing representative task does not validate every statement in a skill. ## Exercise a fresh consumer session Use an available isolated agent session in a disposable copy of the fixture. Install or expose the candidate package and skill through the same Intent setup a consumer would use. Start from the plain developer task with no authoring conversation, personal memory, answer files, or extra hints. Keep the full authoring repository and the grader out of the consumer's context when the task does not require them. -Let the consumer attempt the task, then run the unchanged grading checks against its output. Capture the skill and package revisions, setup used, agent/model when available, final diff, check results, and which guidance actually loaded. Failed or unavailable runs are not passing quality evidence. Do not install another agent, grant broader permissions, or expose credentials just to make the evaluation run. +Let the consumer attempt the task, then run the unchanged grading checks against its output. Capture the skill and package revisions, setup used, agent/model when available, final diff, check results, and which guidance loaded. Failed or unavailable runs are not passing quality evidence. Do not install another agent, grant broader permissions, or expose credentials just to make the evaluation run. Inspect the observable tool trace as well as the result: unnecessary reference loads, repeated command reconstruction, and ignored constraints identify where to refine the procedure. Review successful runs too; a passing result can hide avoidable work. Keep useful source-backed corrections and remove instructions the task does not need. @@ -34,4 +34,4 @@ If no fresh-session capability is available, still create and run the determinis Investigate whether a failure belongs to setup/discovery, an incorrect or incomplete skill, an unsupported API, or the fixture/checker. Repair the owning defect. Preserve the check's intended behavior; do not relax an assertion to make a generated solution pass. Repeat the affected check after a repair. -When source behavior changes, update the expected outcome from the source evidence and rerun the affected case. Preserve unrelated cases. Report structural validation, executable task checks, and fresh-agent outcomes separately so the maintainer knows what was actually proved. +When source behavior changes, update the expected outcome from the source evidence and rerun the affected case. Preserve unrelated cases. Report structural validation, executable task checks, and fresh-agent outcomes separately so the maintainer knows what was proved. diff --git a/packages/intent/meta/skill-staleness-check/SKILL.md b/packages/intent/meta/skill-staleness-check/SKILL.md index 26523712..68c3820f 100644 --- a/packages/intent/meta/skill-staleness-check/SKILL.md +++ b/packages/intent/meta/skill-staleness-check/SKILL.md @@ -53,9 +53,9 @@ If no skills match, exit silently. ### Using `intent stale` -There is no separate sync script — `intent stale [dir] [--json]` is the real, -existing staleness signal (see `docs/cli/intent-stale.md`). It is **read-only**: -it reports drift, it does not write anything. For a given library: +`intent stale [dir] [--json]` is the staleness signal (see +`docs/cli/intent-stale.md`). It is **read-only**: it reports drift, it does +not write anything. For a given library: ```bash intent stale packages/query --json @@ -67,11 +67,11 @@ This reports: currently published version), classified `major`/`minor`/`patch`. - Missing source SHAs recorded in that package's `skills/sync-state.json` (a conservative signal — it flags gaps in the stored SHA record, not - actual remote content differences; see the doc's Notes section). + remote content differences; see the doc's Notes section). `intent stale` does not classify "needs regeneration" vs "version bump only" the way a dedicated sync tool might — that classification is this skill's own -job, done in Step 2 below using the actual source diff, not `intent stale`'s +job, done in Step 2 below using the source diff, not `intent stale`'s output alone. --- @@ -119,10 +119,9 @@ For skills classified as needing content updates: For version bump only: -There is no write-capable script for this. Edit `library_version` directly -in each affected skill's frontmatter, then update the recorded SHA(s) for -that library in its `skills/sync-state.json` (see Step 5) to reflect the new -synced state. +Edit `library_version` directly in each affected skill's frontmatter, then +update the recorded SHA(s) for that library in its `skills/sync-state.json` +(see Step 5) to reflect the new synced state. --- @@ -145,13 +144,10 @@ second-order dependency are not automatically re-checked. ## Step 5 — Mark skills as synced -There is no write-capable script for this either. After updating a skill, -edit that library's `skills/sync-state.json` directly: update -`library_version` and the affected skill's `skills[skillName].sources_sha` -map with the new source file SHA(s) from the commit that triggered this run. -(That is the real current shape read by `intent stale` — it has no separate -tree-generator SHA or sync-timestamp field, despite what an earlier version -of this doc implied.) +After updating a skill, edit that library's `skills/sync-state.json` +directly: update `library_version` and the affected skill's +`skills[skillName].sources_sha` map with the new source file SHA(s) from the +commit that triggered this run. --- @@ -219,9 +215,8 @@ Exit silently (no PR, no notification, no issue) when ANY of these are true: ### GitHub API usage -This skill (not a separate script) uses the `gh` CLI directly for GitHub API -access — fetching source diffs in Step 2 and opening PRs in Step 6. It -requires: +This skill uses the `gh` CLI directly for GitHub API access — fetching +source diffs in Step 2 and opening PRs in Step 6. It requires: - `gh` CLI installed and authenticated - Read access to upstream TanStack package repos (query, router, db, form, diff --git a/packages/intent/meta/tree-generator/SKILL.md b/packages/intent/meta/tree-generator/SKILL.md index c0ea1f46..3bbb21ff 100644 --- a/packages/intent/meta/tree-generator/SKILL.md +++ b/packages/intent/meta/tree-generator/SKILL.md @@ -14,7 +14,7 @@ metadata: # Skill Tree Generator -You produce and maintain a tree of SKILL.md files for a library. Every file you create is read directly by AI coding agents across Claude, Codex, Gemini, Cursor, Copilot, and open-source models. Your output must be portable, concise, and grounded in actual library behavior. +You produce and maintain a tree of SKILL.md files for a library. Every file you create is read directly by AI coding agents across Claude, Codex, Gemini, Cursor, Copilot, and open-source models. Your output must be portable, concise, and grounded in library behavior. ### Skill types @@ -114,8 +114,6 @@ If tasks stand alone, there are no framework adapter packages, and a shared over - Each skill is type `core` (not `sub-skill`) and stands alone without a parent registry - Skip Step 2 (core overview) and Step 3 (sub-skills) — go directly to writing individual skills as standalone core skills using Step 3's body format -This avoids unnecessary scaffolding for focused libraries where the overhead of a hierarchical skill tree exceeds the navigation benefit. - ### Step 1 — Plan the file tree From the domain map, each entry in the `skills` list becomes a SKILL.md file. The `type` field on each skill (`core`, `framework`, `lifecycle`, `composition`) determines where it goes. Determine the file tree: @@ -296,8 +294,6 @@ When a library version, changelog, migration guide, or accuracy report requires ## Cross-model compatibility -Output is consumed by all major AI coding agents. To ensure consistency: - - Markdown with YAML frontmatter — universally parsed - No XML tags in generated skill content - Code blocks use triple backticks with language annotation diff --git a/packages/intent/meta/tree-generator/references/update-skills.md b/packages/intent/meta/tree-generator/references/update-skills.md index 80091bcf..497bcfb6 100644 --- a/packages/intent/meta/tree-generator/references/update-skills.md +++ b/packages/intent/meta/tree-generator/references/update-skills.md @@ -2,4 +2,4 @@ For a current task, supplied diff, identified code/docs change, or accuracy report, follow [generate-skill](../../generate-skill/SKILL.md). It owns the source checks, questions, incremental edits, no-impact decision, validation, and review handoff for each affected task. -For an explicitly requested full-library audit, first identify candidate skills from the supplied changes and their documented scope. A release number is a reason to investigate, not proof of changed behavior. Use actual source diffs, changelogs, and migration guides; leave missing evidence as uncertainty. Apply the focused procedure to each candidate without redesigning the tree. Keep any requested report in the repository's existing format; no new staleness report or changelog is required merely to update a skill. +For an explicitly requested full-library audit, first identify candidate skills from the supplied changes and their documented scope. A release number is a reason to investigate, not proof of changed behavior. Use source diffs, changelogs, and migration guides; leave missing evidence as uncertainty. Apply the focused procedure to each candidate without redesigning the tree. Keep any requested report in the repository's existing format; no new staleness report or changelog is required merely to update a skill. From 73f5e1f12bbe8a6e5c72fec8e42ce2acd5b56bcd Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:43:58 -0700 Subject: [PATCH 05/12] docs: add missing opening quotes to README image attributes --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 74603e8e..1a394c3d 100644 --- a/README.md +++ b/README.md @@ -72,14 +72,14 @@ A CLI for library maintainers to generate, validate, and ship [Agent Skills](htt - CodeRabbit + CodeRabbit - + Cloudflare From fe6df0789dca0c496bd4fafe950812d1c48ab0b0 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:50:57 -0700 Subject: [PATCH 06/12] refactor: keep base behavior in four cleaned-up helpers Check tracked type entries per workspace package again in place of the batched git call, substitute template variables with the original replace chain, read _artifacts behind the existence check, and read the message of any thrown object in the install catches. Restore the JSDoc on findSkillFiles so the published types match. --- .../intent/src/commands/install/command.ts | 11 +++-- packages/intent/src/setup/project-setup.ts | 13 +++-- packages/intent/src/shared/utils.ts | 3 ++ .../intent/src/staleness/artifact-coverage.ts | 13 ++--- packages/intent/src/validate/blocks.ts | 47 +++---------------- 5 files changed, 30 insertions(+), 57 deletions(-) diff --git a/packages/intent/src/commands/install/command.ts b/packages/intent/src/commands/install/command.ts index e867eaf6..eda5f679 100644 --- a/packages/intent/src/commands/install/command.ts +++ b/packages/intent/src/commands/install/command.ts @@ -7,7 +7,6 @@ import { } from '../../shared/command-runner.js' import { coreOptionsFromGlobalFlags, - failureMessage, noticeOptionsFromGlobalFlags, printNotices, printWarnings, @@ -142,6 +141,12 @@ export interface InstallCommandRuntime { permissionPrompts?: PermissionPrompts } +function thrownMessage(error: unknown): string { + return error && typeof error === 'object' && 'message' in error + ? String(error.message) + : String(error) +} + function formatTargetPath(targetPath: string): string { return relative(process.cwd(), targetPath) || targetPath } @@ -314,7 +319,7 @@ export async function runInstallCommand( }, }) } catch (error) { - fail(`Permissions: failed: ${failureMessage(error)}`) + fail(`Permissions: failed: ${thrownMessage(error)}`) } if ( permissions.status === 'canceled' || @@ -393,7 +398,7 @@ export async function runInstallCommand( } return } catch (error) { - if (permissions) fail(`Guidance: failed: ${failureMessage(error)}`) + if (permissions) fail(`Guidance: failed: ${thrownMessage(error)}`) throw error } } diff --git a/packages/intent/src/setup/project-setup.ts b/packages/intent/src/setup/project-setup.ts index 4875c43a..d33636d9 100644 --- a/packages/intent/src/setup/project-setup.ts +++ b/packages/intent/src/setup/project-setup.ts @@ -244,9 +244,16 @@ function applyTemplate(content: string, vars: TemplateVars): string { vars.WATCH_PATHS, ) } - return content.replace(/\{\{([A-Z_]+)\}\}/g, (match, key: string) => - key in vars ? vars[key as keyof TemplateVars] : match, - ) + return content + .replace(/\{\{PACKAGE_NAME\}\}/g, vars.PACKAGE_NAME) + .replace(/\{\{PACKAGE_LABEL\}\}/g, vars.PACKAGE_LABEL) + .replace(/\{\{PAYLOAD_PACKAGE\}\}/g, vars.PAYLOAD_PACKAGE) + .replace(/\{\{REPO\}\}/g, vars.REPO) + .replace(/\{\{DOCS_PATH\}\}/g, vars.DOCS_PATH) + .replace(/\{\{SRC_PATH\}\}/g, vars.SRC_PATH) + .replace(/\{\{WATCH_PATHS\}\}/g, vars.WATCH_PATHS) + .replace(/\{\{INTENT_WORKFLOW_REF\}\}/g, vars.INTENT_WORKFLOW_REF) + .replace(/\{\{INTENT_ARTIFACTS\}\}/g, vars.INTENT_ARTIFACTS) } export function runEditPackageJson(root: string): EditPackageJsonResult { diff --git a/packages/intent/src/shared/utils.ts b/packages/intent/src/shared/utils.ts index 1c5b1c66..e9ca09bd 100644 --- a/packages/intent/src/shared/utils.ts +++ b/packages/intent/src/shared/utils.ts @@ -137,6 +137,9 @@ export function createFsIdentityCache( return getIdentity } +/** + * Recursively find all SKILL.md files under a directory. + */ export function findSkillFiles( dir: string, fs: ReadFs = nodeReadFs, diff --git a/packages/intent/src/staleness/artifact-coverage.ts b/packages/intent/src/staleness/artifact-coverage.ts index a67bec63..a7e1e9ab 100644 --- a/packages/intent/src/staleness/artifact-coverage.ts +++ b/packages/intent/src/staleness/artifact-coverage.ts @@ -1,8 +1,7 @@ -import { readFileSync, readdirSync } from 'node:fs' +import { existsSync, readFileSync, readdirSync } from 'node:fs' import { join } from 'node:path' import { parse as parseYaml } from 'yaml' import { errorMessage, isRecord, stringArray } from '../shared/utils.js' -import type { Dirent } from 'node:fs' import type { IntentArtifactCoverageIgnore, IntentArtifactFile, @@ -130,13 +129,7 @@ function parseCoverageIgnores( export function readIntentArtifacts(root: string): IntentArtifactSet | null { const artifactsDir = join(root, '_artifacts') - let entries: Array - try { - entries = readdirSync(artifactsDir, { withFileTypes: true }) - } catch (err) { - if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null - throw err - } + if (!existsSync(artifactsDir)) return null const warnings: Array = [] const skillTrees: Array = [] @@ -144,7 +137,7 @@ export function readIntentArtifacts(root: string): IntentArtifactSet | null { const skills: Array = [] const ignoredPackages: Array = [] - for (const entry of entries) { + for (const entry of readdirSync(artifactsDir, { withFileTypes: true })) { if (!entry.isFile()) continue const kind = detectArtifactKind(entry.name) diff --git a/packages/intent/src/validate/blocks.ts b/packages/intent/src/validate/blocks.ts index 10826f7f..d1b99ee5 100644 --- a/packages/intent/src/validate/blocks.ts +++ b/packages/intent/src/validate/blocks.ts @@ -561,14 +561,12 @@ function declaredEntry(manifest: Record): string | undefined { function libraryEntry( packageDir: string, manifest: Record, - tracked?: Set, ): string | null { const declared = declaredEntry(manifest) const candidates: Array = [] if (declared) { const path = resolve(packageDir, declared) - if (existsSync(path) && (tracked?.has(path) || isTracked(packageDir, path))) - return path + if (existsSync(path) && isTracked(packageDir, path)) return path const name = declared .split('/') .at(-1)! @@ -614,25 +612,14 @@ function workspacePaths(root: string): Record> { const context = resolveProjectContext({ cwd: root }) const workspaceRoot = context.workspaceRoot ?? root const paths: Record> = {} - const packages = resolveWorkspacePackages( + for (const dir of resolveWorkspacePackages( workspaceRoot, context.workspacePatterns, - ).flatMap((dir) => { + )) { const manifest = readManifest(dir) - if (!manifest || typeof manifest.name !== 'string') return [] - return [{ dir, name: manifest.name, manifest }] - }) - // One git call answers for most declared entries. A package that is its own - // repository is not listed by it, so libraryEntry asks from that package. - const tracked = trackedFiles( - workspaceRoot, - packages.flatMap(({ dir, manifest }) => { - const declared = declaredEntry(manifest) - return declared ? [resolve(dir, declared)] : [] - }), - ) - for (const { dir, name, manifest } of packages) { - const entry = libraryEntry(dir, manifest, tracked) + if (!manifest || typeof manifest.name !== 'string') continue + const { name } = manifest + const entry = libraryEntry(dir, manifest) if (!entry) continue paths[name] = [slash(entry)] paths[`${name}/*`] = [ @@ -643,28 +630,6 @@ function workspacePaths(root: string): Record> { return paths } -// The absolute paths among `paths` that Git tracks from `cwd`; none when Git -// cannot answer there. Git prints paths relative to `cwd`, so each is resolved -// back against it. -function trackedFiles(cwd: string, paths: Array): Set { - if (paths.length === 0) return new Set() - try { - const listed = execFileSync( - 'git', - ['-c', 'core.fsmonitor=false', 'ls-files', '-z', '--', ...paths], - { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }, - ) - return new Set( - listed - .split('\0') - .filter(Boolean) - .map((path) => resolve(cwd, path)), - ) - } catch { - return new Set() - } -} - function isTracked(packageDir: string, path: string): boolean { try { execFileSync( From 05c172720548b3b6e021faf488dc0dd24583f2d0 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:51:50 -0700 Subject: [PATCH 07/12] docs: restore facts that the shortened docs dropped Bring back the first-run permission rules and example, the outcome table, the setup and registry notes, the policy mode bullets, and the other statements that no longer appeared anywhere in docs/. The edits that only shorten wording stay. --- docs/cli/intent-hooks.md | 2 +- docs/cli/intent-install.md | 2 +- docs/cli/intent-list.md | 6 +++++- docs/cli/intent-load.md | 2 +- docs/cli/intent-repair.md | 2 +- docs/cli/intent-review.md | 2 +- docs/cli/intent-setup.md | 3 +++ docs/concepts/configuration.md | 20 +++++++++++++++++++ docs/concepts/trust-model.md | 7 +++++++ docs/getting-started/quick-start-consumers.md | 10 +++++++++- .../quick-start-maintainers.md | 6 +++--- docs/overview.md | 2 +- docs/registry.md | 5 ++++- 13 files changed, 57 insertions(+), 12 deletions(-) diff --git a/docs/cli/intent-hooks.md b/docs/cli/intent-hooks.md index 2cfa7d6d..dd62f780 100644 --- a/docs/cli/intent-hooks.md +++ b/docs/cli/intent-hooks.md @@ -42,7 +42,7 @@ Hooks do not verify that: - The agent received the returned content. - The model applied the guidance. -Hook output is an edit gate and observation signal. See [Lifecycle boundaries](../concepts/trust-model#lifecycle-boundaries). +Hook output is an edit gate and observation signal, not proof of activation or correct agent behavior. See [Lifecycle boundaries](../concepts/trust-model#lifecycle-boundaries). ## Hook support diff --git a/docs/cli/intent-install.md b/docs/cli/intent-install.md index 79219210..398e4c22 100644 --- a/docs/cli/intent-install.md +++ b/docs/cli/intent-install.md @@ -39,7 +39,7 @@ For the full command workflow, use [`intent maintainer setup`](./intent-maintain `install --maintainer` enables initial skill batches and source-aware skill maintenance in repository agent instructions. It works without an interactive terminal or existing consumer permissions. It writes a separate `intent-maintainer` block, preserves consumer guidance, and is idempotent. `--dry-run` previews the block. -Run it from the library root. The block loads the packaged authoring procedure for substantial library work; that procedure covers the cumulative domain map, spec, and skill tree, source review and task checks. It updates the file that already contains either Intent managed block, or creates `AGENTS.md` when neither exists. It cannot be combined with `--review`, `--map`, `--print-prompt`, `--global`, or `--global-only`. See [Quick Start for Maintainers](../getting-started/quick-start-maintainers). +Run it from the library root. The block loads the packaged authoring procedure for substantial library work; that procedure covers the cumulative domain map, spec, and skill tree, source review, task checks, and revision-bound outcomes. It updates the file that already contains either Intent managed block, or creates `AGENTS.md` when neither exists. It cannot be combined with `--review`, `--map`, `--print-prompt`, `--global`, or `--global-only`. See [Quick Start for Maintainers](../getting-started/quick-start-maintainers). > [!NOTE] Maintainer installation writes guidance > It does not add Intent to `package.json`, configure consumer skill permissions, install agent hooks, or add CI. The managed block uses the detected package manager's runner with `@tanstack/intent@latest`. diff --git a/docs/cli/intent-list.md b/docs/cli/intent-list.md index 87bcb1bc..1696013b 100644 --- a/docs/cli/intent-list.md +++ b/docs/cli/intent-list.md @@ -52,6 +52,10 @@ The nearest configured `intent.skills` list applies, including inherited workspa Workspace patterns and individual skills also use the `workspace:` prefix, such as `workspace:@scope/*` and `workspace:@scope/internal#testing`. Package patterns support `*`; individual-skill entries require an exact package and skill name. Git sources are not supported. +- **No configured list:** all discovered sources appear, with a migration notice. This is the existing-project upgrade path; a future version will require explicit permissions. +- **An empty list (`[]`):** no sources are permitted, with an informational notice. +- **All sources (`["*"]`):** all discovered sources appear, with a notice that unvetted skills may enter agent guidance. + Permissions select sources and skill names. They do not freeze skill content when dependencies update. See [Configuration](../concepts/configuration) and [Trust model](../concepts/trust-model). ### Exclusions @@ -153,7 +157,7 @@ JSON includes diagnostics in the object instead of printing separate warning or - **Invalid permissions or unreadable policy files:** Intent stops and reports the problem. Fix the reported package.json or `intent.skills` entry before retrying. - **Unsupported runnable identifier:** generated commands accept only ASCII letters, numbers, `_`, `.`, `/`, `@`, `#`, and `-`. Identifiers cannot start with `#`; leading and trailing whitespace is rejected rather than trimmed. Rename the package or skill to generate runnable guidance. `--json` can still expose permitted identifiers as data. -- **Unreadable or out-of-package skill metadata:** discovery skips skill files whose real path cannot be resolved or lies outside the package root, with a warning. Symlinks within the resolved package root remain supported. +- **Unreadable or out-of-package skill metadata:** discovery skips skill files whose real path cannot be resolved or lies outside the package root, with a warning. It checks the opened file's identity before reading and uses that descriptor for the full metadata read, including large frontmatter, so later pathname replacement cannot redirect the read. Symlinks within the resolved package root remain supported. - **Deno without `node_modules`:** this discovery mode is unsupported. ## Related diff --git a/docs/cli/intent-load.md b/docs/cli/intent-load.md index c4b509b9..6e54ecb1 100644 --- a/docs/cli/intent-load.md +++ b/docs/cli/intent-load.md @@ -42,7 +42,7 @@ id: intent-load - Prints the scanner-reported path when `--path` is passed - Prints debug details to stderr when `--debug` is passed -A successful load proves that Intent resolved the selected skill under current policy and returned its content. See [Lifecycle boundaries](../concepts/trust-model#lifecycle-boundaries). +A successful load proves that Intent resolved the selected skill under current policy and returned its content. It does not prove that the skill was relevant to the task, reached an agent's active context, or was followed correctly. See [Lifecycle boundaries](../concepts/trust-model#lifecycle-boundaries). The package can be scoped or unscoped. The skill can include slash-separated sub-skill names. diff --git a/docs/cli/intent-repair.md b/docs/cli/intent-repair.md index ee9adee6..3d0e52a6 100644 --- a/docs/cli/intent-repair.md +++ b/docs/cli/intent-repair.md @@ -3,7 +3,7 @@ id: intent-repair title: intent repair --- -`intent repair` handles mechanical skill maintenance before validation and source review. It does not call an agent or record review outcomes. +`intent repair` handles mechanical skill maintenance before validation and source review. It does not call an agent, typecheck the library, execute examples, change version claims, or record review outcomes. Run the CLI from your repository: diff --git a/docs/cli/intent-review.md b/docs/cli/intent-review.md index fc182ff5..88da317d 100644 --- a/docs/cli/intent-review.md +++ b/docs/cli/intent-review.md @@ -233,7 +233,7 @@ For a planning item, the reason and evidence must cover all three documents. Pre ### Saved state -`--record` writes `.intent/review-state.json` containing the baseline, source/guidance hashes, reviewed revision, outcomes, reasons, and evidence, creating the directory when it is missing. `.intent/` is reserved for Intent's working files and is excluded from unmapped-change items: review state and working reports, `.intent/skill-distribution.json` written by `maintainer sync`, and the temporary `.intent/maintainer.lock` and `.intent/review-state.json.lock` that serialize writes. +`--record` writes `.intent/review-state.json` containing the baseline, source/guidance hashes, reviewed revision, outcomes, reasons, and evidence, creating the directory when it is missing. It does not commit, publish, or change skill versions. `.intent/` is reserved for Intent's working files and is excluded from unmapped-change items: review state and working reports, `.intent/skill-distribution.json` written by `maintainer sync`, and the temporary `.intent/maintainer.lock` and `.intent/review-state.json.lock` that serialize writes. Identical recorded content suppresses repeat reminders. Later edits reopen review. The saved state does not replace the planning documents, execute evidence strings, or verify the truth of a recorded conclusion. diff --git a/docs/cli/intent-setup.md b/docs/cli/intent-setup.md index 6b1bebd3..05ca474b 100644 --- a/docs/cli/intent-setup.md +++ b/docs/cli/intent-setup.md @@ -37,6 +37,9 @@ These commands configure a package for publishing skills and install the optiona - Skips files that already exist at the destination - New callers enable [repair artifacts](./intent-repair#ci-patches) for PR checks. CI applies safe mechanical repairs to its checkout and uploads patches for review; it never commits them. Existing callers can opt in with `repair: true` +> [!NOTE] +> `setup` installs the generated repository workflow, not Intent's maintainer or consumer guidance. Run `maintainer setup` to install the same CI workflow together with persistent instructions and cumulative records. + ## Security and upgrades Keep the generated full SHAs and review updates; a pin fixes a revision but does not certify its safety. Analysis has access to checked-out source even with a read-only token. Keep it on pull request, release, or manual events with no extra secrets, and keep write permissions confined to the optional publisher. Treat report and skill content as untrusted evidence, not authorization to execute commands or publish. See [GitHub's secure-use guidance](https://docs.github.com/en/actions/reference/security/secure-use). diff --git a/docs/concepts/configuration.md b/docs/concepts/configuration.md index 67b80086..9717ed47 100644 --- a/docs/concepts/configuration.md +++ b/docs/concepts/configuration.md @@ -92,6 +92,26 @@ Run `intent list` to see which packages the current policy surfaces. | Saved or inherited `intent.skills` | Updates guidance only. Keeps permissions unchanged and does not prompt. | | No effective `intent.skills` | Starts interactive permission setup. Non-TTY execution fails without writes. | +First-run setup offers **Enable all**, **Choose packages or scopes**, and **Choose individual skills**, followed by one confirmation before saving to the nearest owning `package.json` and installing guidance. + +- **Compact rules:** Enable all saves `"*"`; package choices save names such as `"@tanstack/ai"`; explicit scope choices save patterns such as `"@tanstack/*"`. These rules include future matching skills and packages. Individual choices save exact names such as `"@tanstack/ai#skill"`. +- **Optional skill review:** choose **Review individual skills** at confirmation, then pick which selected packages to inspect. Leave the list empty to keep all selected skills. Only those packages open individual skill lists; unchecking a skill covered by a broad rule adds an exclusion. Existing and inherited exclusions stay in force. +- **Changing instructions:** access choices do not record approval of specific content. Skills can change with dependency updates; update notifications are not available yet. +- **Empty selection:** explicitly confirms disabling all skills with `[]`. Empty or fully excluded discovery writes nothing, so setup can be retried. + +For example, enabling a scope and unchecking one skill saves: + +```json +{ + "intent": { + "skills": ["@tanstack/*"], + "exclude": ["@tanstack/ai#skill"] + } +} +``` + +This permits matching npm packages, including future additions, except the excluded skill. Selecting several packages individually never silently expands to a scope rule. + See [Default install](../cli/intent-install#default-install) for picker controls and cancellation behavior. ### Suppressing notices temporarily diff --git a/docs/concepts/trust-model.md b/docs/concepts/trust-model.md index 2a9e94f0..b2bbe6a2 100644 --- a/docs/concepts/trust-model.md +++ b/docs/concepts/trust-model.md @@ -41,6 +41,13 @@ When no effective policy exists, `intent install` follows this flow: 2. Enable all sources, choose packages or scopes, or select individual skills. Package and scope selections stay compact and include future matching skills. A whole scope requires an explicit selection. 3. Confirm the current skill count, saved rules, and destination file. Optional individual review opens skill lists only for the selected packages you choose to inspect. It can add exclusions while retaining broad rules; unreviewed packages keep their selection. Only affirmative confirmation saves permissions and exclusions atomically, then installs guidance. An empty selection explicitly confirms disabling all skills. +| Outcome | Files changed | +| --- | --- | +| No skills discovered, or all excluded | None. | +| Cancel any prompt | None. | +| Run first-time setup without a TTY | None; the command fails. | +| Save permissions, then fail to write or verify guidance | Confirmed permissions remain saved; the guidance failure is reported separately. | + The completion summary reports skills available under the saved policy. It does not prove that an agent loaded or applied them. See [Default install](../cli/intent-install#default-install) for picker controls and permission choices. ## Revisiting permissions diff --git a/docs/getting-started/quick-start-consumers.md b/docs/getting-started/quick-start-consumers.md index ab405764..61459344 100644 --- a/docs/getting-started/quick-start-consumers.md +++ b/docs/getting-started/quick-start-consumers.md @@ -13,7 +13,7 @@ Add `@tanstack/intent` as a development dependency and commit your lockfile befo -Then run setup. The command tabs use the latest published CLI, not the version in your lockfile. Generated guidance uses the detected package manager's runner; check its command if you need the installed version. +Then run setup. The command tabs use the latest published CLI, not the version in your lockfile. Generated guidance uses the detected package manager's runner; check its command if you need the installed version. The dependency pins the CLI used by CI when configured to run the installed CLI. @@ -26,6 +26,14 @@ Run this in an interactive terminal. On first use, Intent helps you choose which 1. **Choose what to enable.** Pick **Enable all**, **Choose packages or scopes**, or **Choose individual skills**. Package and skill lists support search. 2. **Confirm and finish.** Check the saved rules and destination `package.json`. Choose **Continue with all selected skills** to save, or **Review individual skills** to pick which selected packages to inspect before confirming. Intent writes permissions and guidance, verifies the guidance, and shows a command to list available skills. +**Enable all** saves `"*"`. A package choice saves `"@tanstack/ai"`; a whole scope saves `"@tanstack/*"`. These rules include future matching skills. Individual choices use `"@tanstack/ai#skill"`. Unchecking a skill during review adds an exclusion while keeping its broad rule. + +Skill instructions can change when dependencies update. Update notifications are not available yet. See **About skill access and updates** in the installer for details. + +Selecting nothing requires explicit confirmation to disable all skills. If no skills are found, or all are excluded, Intent explains the next step and leaves permissions and guidance unchanged. Install a package that ships skills or review your exclusions, then run `install` again. + +Canceling before confirmation writes neither file. `--dry-run` previews the flow without writing. First-run setup requires a terminal; noninteractive execution fails without writes when permissions have not been configured. + If an `intent-skills` block already exists, Intent updates that file in place. If no block exists, `AGENTS.md` is the default target. diff --git a/docs/getting-started/quick-start-maintainers.md b/docs/getting-started/quick-start-maintainers.md index 94105379..25f88d96 100644 --- a/docs/getting-started/quick-start-maintainers.md +++ b/docs/getting-started/quick-start-maintainers.md @@ -26,7 +26,7 @@ Run `maintainer setup` from the library repository: This registers existing package-owned skills, copies the CI workflow when missing, and creates missing planning records and an `intent-maintainer` block in `AGENTS.md`, or updates the file that already contains an Intent maintainer or consumer block. It preserves surrounding instructions and a separate `intent-skills` consumer block. Review this setup diff and keep it in the repository so later agent sessions receive the same authoring and review procedure. > [!NOTE] -> Setup creates skeletons for missing records; their task knowledge still needs authoring. Registration preserves existing skill text and reports invalid or conflicting candidates. Review inferred domains and complete the records before running the maintainer check. +> Setup preserves existing records and instructions. It creates skeletons for missing records; their task knowledge still needs authoring. Registration preserves existing skill text and reports invalid or conflicting candidates. Review inferred domains and complete the records before running the maintainer check. ## Create the first useful batch @@ -116,7 +116,7 @@ A repository discovery skill can help developers decide whether the library fits ## Keep guidance current during library work -Continue requesting library changes normally. `intent maintainer review` uses Git changes and content fingerprints to find work that has not been reviewed. Intent identifies candidates; the agent and maintainer decide whether the guidance should change. A new file does not automatically require a new skill. +Continue requesting library changes normally. `intent maintainer review` uses Git changes and content fingerprints to find work that has not been reviewed. Intent identifies candidates; the agent and maintainer decide whether the guidance should change. A new file does not automatically require a new skill. A justified `no-change` outcome records why accurate guidance stayed unchanged, while missing evidence remains pending. Before handoff, run sync so the metadata matches the final files, review the pending items in your terminal, then run the combined check: @@ -153,7 +153,7 @@ Run the same synchronization command after skill edits: `maintainer setup` already copies `check-skills.yml` to the workspace root's `.github/workflows/` directory and skips an existing destination file. The copy is a short caller for Intent's reusable workflows, pinned to the commit of the Intent release that copied it and granting each job only the permissions it needs; Dependabot or Renovate can propose pin updates for review. Setup uses the immutable SHA packaged with the installed release; it does not resolve mutable tags. CI runs the copy of `@tanstack/intent` your lockfile pins, so keep it in `devDependencies`. The workflow validates skills and recorded source reviews on pull requests. After a release or manual run, it writes a read-only review report when recorded review state or conservative staleness signals require attention. Review-reminder PRs are optional: set the repository Actions variable `INTENT_REVIEW_PULL_REQUESTS=true` to enable a separate publisher job that never executes Intent or checks out the library. See [setup commands](../cli/intent-setup). > [!NOTE] -> `intent setup` copies CI templates on its own; `intent maintainer setup` also initializes the maintainer workflow. +> `intent setup` copies CI templates on its own; `intent maintainer setup` also initializes the maintainer workflow. To replace an older generated workflow, move or delete it before rerunning `setup`; Intent skips existing files. Publish through the library's normal release process. Skills in the package's published `skills/` directory version with that library release. Consumers install the library, configure permitted skill sources with consumer [`intent install`](../cli/intent-install#default-install), discover the installed skills with [`intent list`](../cli/intent-list), and load matching guidance with `intent load`. diff --git a/docs/overview.md b/docs/overview.md index 8edfbc7c..d6b0806d 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -33,7 +33,7 @@ Intent provides tooling for two workflows: | Stage | Who runs it | Result | | --- | --- | --- | | Maintainer enablement | Library maintainer | `maintainer setup` creates missing records and installs persistent authoring instructions. | -| Authoring and maintenance | Library maintainer and coding agent | `meta generate-skill` guides a focused batch; `maintainer review` records review outcomes. | +| Authoring and maintenance | Library maintainer and coding agent | `meta generate-skill` guides a focused batch; `maintainer review` records evidence-backed outcomes for later source changes. | | Package publishing | Library release process | `maintainer sync` updates package and selected repository exports; `setup` optionally adds CI. | | Consumer setup | Developer using the published library | Consumer `install` configures permitted skill sources and skill-loading guidance; `list` and `load` use skills from installed dependencies. | diff --git a/docs/registry.md b/docs/registry.md index 93c56463..ab76fbe9 100644 --- a/docs/registry.md +++ b/docs/registry.md @@ -72,7 +72,7 @@ Use `maintainer review` and `stale` as separate checks as the library changes. ` -Uses Git changes and recorded content fingerprints to identify skills, planning records, and unmapped source areas that need semantic review. Record completed outcomes with their evidence in `.intent/review-state.json`. +Uses Git changes and recorded content fingerprints to identify skills, planning records, and unmapped source areas that need semantic review. Record completed outcomes with their evidence in `.intent/review-state.json`; missing evidence remains pending. @@ -90,6 +90,9 @@ Reports conservative package and release signals: version drift, missing stored Copies the generated CI workflow into your repository. Pull requests validate skills and check recorded source reviews when maintainer guidance or review state exists. Release and manual runs use recorded review state when available, with conservative `stale` signals as the fallback. +> [!NOTE] +> Maintainers use `maintainer setup`, `add`, `status`, `sync`, `review`, and `check` throughout the workflow. Consumers choose their installer: Intent for installed package guidance, or the generated GitHub/plugin commands for selected repository skills. See [repository distribution](./cli/intent-maintainer#choose-repository-distribution). + ## Requesting a library If you use a library that doesn't ship skills yet, the best path is to open an issue on that library's repo pointing them here. The maintainer is the right person to author and own skills for their tool — they know the intent behind the API better than anyone. From 0fac25d8ee19b0f84cb8bd90c885b171e90c560b Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:55:30 -0700 Subject: [PATCH 08/12] refactor: remove remaining duplicate helpers and unused parameters Reuse getPackageShortName, errorMessage, and isRecord where local copies remained, and read manifests for example checks through the shared filesystem cache. Drop three pass-through exports, parameters that every caller gave one value, and a notice set that never removed a duplicate. Output does not change. --- .../intent/src/commands/install/command.ts | 12 ++---- packages/intent/src/commands/maintainer.ts | 6 +-- packages/intent/src/commands/stale.ts | 8 ++-- packages/intent/src/commands/validate.ts | 1 + packages/intent/src/core/project-context.ts | 16 ++++---- packages/intent/src/core/source-policy.ts | 19 +++------- packages/intent/src/discovery/index.ts | 2 - packages/intent/src/discovery/scanner.ts | 21 ++++------- packages/intent/src/discovery/walk.ts | 4 +- packages/intent/src/hooks/install.ts | 12 ++---- packages/intent/src/shared/cli-output.ts | 2 +- packages/intent/src/shared/command-runner.ts | 3 -- packages/intent/src/validate/blocks.ts | 37 ++++++++++--------- packages/intent/tests/source-policy.test.ts | 2 +- 14 files changed, 58 insertions(+), 87 deletions(-) delete mode 100644 packages/intent/src/discovery/index.ts diff --git a/packages/intent/src/commands/install/command.ts b/packages/intent/src/commands/install/command.ts index eda5f679..d69d0ff7 100644 --- a/packages/intent/src/commands/install/command.ts +++ b/packages/intent/src/commands/install/command.ts @@ -1,10 +1,8 @@ import { relative } from 'node:path' import { readSkillSourcesConfig } from '../../core/source-policy.js' import { fail } from '../../shared/cli-error.js' -import { - detectIntentCommandPackageManager, - formatIntentCommand, -} from '../../shared/command-runner.js' +import { detectPackageManager } from '../../discovery/package-manager.js' +import { formatIntentCommand } from '../../shared/command-runner.js' import { coreOptionsFromGlobalFlags, noticeOptionsFromGlobalFlags, @@ -231,9 +229,7 @@ export async function runInstallCommand( '--maintainer cannot be combined with --map, --review, --print-prompt, --global, or --global-only.', ) } - const generated = buildMaintainerGuidanceBlock( - detectIntentCommandPackageManager(), - ) + const generated = buildMaintainerGuidanceBlock(detectPackageManager()) const namespace = 'intent-maintainer' if (options.dryRun) { const targetPath = resolveIntentSkillsBlockTargetPath( @@ -333,7 +329,7 @@ export async function runInstallCommand( ) } - const packageManager = detectIntentCommandPackageManager() + const packageManager = detectPackageManager() const generated = buildIntentSkillGuidanceBlock(packageManager) if (options.dryRun) { diff --git a/packages/intent/src/commands/maintainer.ts b/packages/intent/src/commands/maintainer.ts index 5499b6a2..4663e1aa 100644 --- a/packages/intent/src/commands/maintainer.ts +++ b/packages/intent/src/commands/maintainer.ts @@ -21,7 +21,7 @@ import { readDistribution, } from '../maintainer/distribution.js' import { planSetupGithubActions } from '../setup/index.js' -import { detectIntentCommandPackageManager } from '../shared/command-runner.js' +import { detectPackageManager } from '../discovery/package-manager.js' import { getMetaDir } from './support.js' import { buildMaintainerGuidanceBlock, @@ -346,9 +346,7 @@ export async function runMaintainerCommand( project.artifacts, ) const guidance = planIntentSkillsBlock({ - ...buildMaintainerGuidanceBlock( - detectIntentCommandPackageManager(project.root), - ), + ...buildMaintainerGuidanceBlock(detectPackageManager(project.root)), root: project.root, namespace: 'intent-maintainer', skipWhenEmpty: false, diff --git a/packages/intent/src/commands/stale.ts b/packages/intent/src/commands/stale.ts index 986b0b7a..b23b8167 100644 --- a/packages/intent/src/commands/stale.ts +++ b/packages/intent/src/commands/stale.ts @@ -10,10 +10,8 @@ import { compileSkillSourcePolicy, readSkillSourcesConfig, } from '../core/source-policy.js' -import { - detectIntentCommandPackageManager, - formatIntentCommand, -} from '../shared/command-runner.js' +import { detectPackageManager } from '../discovery/package-manager.js' +import { formatIntentCommand } from '../shared/command-runner.js' import { failureMessage } from './support.js' import type { IntentFsCache } from '../discovery/fs-cache.js' import type { StalenessReport } from '../shared/types.js' @@ -105,7 +103,7 @@ export async function runStaleCommand( if (needsReview) { const command = formatIntentCommand( - detectIntentCommandPackageManager(targetDir), + detectPackageManager(targetDir), 'meta generate-skill', ) console.log( diff --git a/packages/intent/src/commands/validate.ts b/packages/intent/src/commands/validate.ts index 89e06085..d8e0f005 100644 --- a/packages/intent/src/commands/validate.ts +++ b/packages/intent/src/commands/validate.ts @@ -740,6 +740,7 @@ async function runValidateCommandInternal( skills, references: skills.flatMap((skill) => skill.references), cache: blockCache, + fsCache, }) if (exampleSummaries) for (const [file, summary] of summarizeSkillExamples(result, skills)) diff --git a/packages/intent/src/core/project-context.ts b/packages/intent/src/core/project-context.ts index 4e2c8651..1ae371a4 100644 --- a/packages/intent/src/core/project-context.ts +++ b/packages/intent/src/core/project-context.ts @@ -65,14 +65,14 @@ export function resolveProjectContext({ function findOwningPackageRoot( startPath: string, - fsCache?: IntentFsCache, + fsCache: IntentFsCache, ): string | null { - let cache = fsCache ? packageRootCaches.get(fsCache) : undefined - if (fsCache && !cache) { + let cache = packageRootCaches.get(fsCache) + if (!cache) { cache = new Map() packageRootCaches.set(fsCache, cache) } - const cachedStart = cache?.get(startPath) + const cachedStart = cache.get(startPath) if (cachedStart !== undefined) return cachedStart let dir = toSearchDir(startPath) @@ -80,14 +80,14 @@ function findOwningPackageRoot( const visited: Array = [startPath] while (dir !== prev) { - const cached = cache?.get(dir) + const cached = cache.get(dir) if (cached !== undefined) { - for (const visitedDir of visited) cache?.set(visitedDir, cached) + for (const visitedDir of visited) cache.set(visitedDir, cached) return cached } visited.push(dir) if (existsSync(join(dir, 'package.json'))) { - for (const visitedDir of visited) cache?.set(visitedDir, dir) + for (const visitedDir of visited) cache.set(visitedDir, dir) return dir } @@ -97,7 +97,7 @@ function findOwningPackageRoot( dir = dirname(dir) } - for (const visitedDir of visited) cache?.set(visitedDir, null) + for (const visitedDir of visited) cache.set(visitedDir, null) return null } diff --git a/packages/intent/src/core/source-policy.ts b/packages/intent/src/core/source-policy.ts index 667860e5..72a976ec 100644 --- a/packages/intent/src/core/source-policy.ts +++ b/packages/intent/src/core/source-policy.ts @@ -28,8 +28,6 @@ import type { IntentHiddenSourceSummary, } from './types.js' -export { ALLOW_ALL_NOTICE } - export const MIGRATION_NOTICE = 'intent.skills is not set — all discovered skill sources are surfaced. A future version will require an explicit intent.skills allowlist; add one to opt in to specific sources.' @@ -203,15 +201,8 @@ export function applySourcePolicy( const { config, excludeMatchers } = options const audience = options.audience ?? 'human' const sourcePolicy = compileSkillSourcePolicy(config) - const seen = new Set() const notices: Array = [] - const emit = (notice: string): void => { - if (seen.has(notice)) return - seen.add(notice) - notices.push(notice) - } - const packages: Array = [] const hiddenSources: Array = [] @@ -236,7 +227,7 @@ export function applySourcePolicy( } if (hiddenSources.length > 0) { - emit(formatUnlistedNotice(hiddenSources, audience)) + notices.push(formatUnlistedNotice(hiddenSources, audience)) } if (config.mode === 'explicit') { @@ -250,16 +241,16 @@ export function applySourcePolicy( source.skill && !pkg.skills.some((skill) => skill.name === source.skill)) ) { - emit( + notices.push( `"${source.raw}" is declared in intent.skills but was not discovered.`, ) } } } - if (config.mode === 'absent') emit(MIGRATION_NOTICE) - else if (config.mode === 'allow-all') emit(ALLOW_ALL_NOTICE) - else if (config.mode === 'empty') emit(EMPTY_NOTE) + if (config.mode === 'absent') notices.push(MIGRATION_NOTICE) + else if (config.mode === 'allow-all') notices.push(ALLOW_ALL_NOTICE) + else if (config.mode === 'empty') notices.push(EMPTY_NOTE) return { hiddenSourceCount: hiddenSources.length, diff --git a/packages/intent/src/discovery/index.ts b/packages/intent/src/discovery/index.ts deleted file mode 100644 index 0e0e22d9..00000000 --- a/packages/intent/src/discovery/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { createPackageRegistrar } from './register.js' -export { createDependencyWalker } from './walk.js' diff --git a/packages/intent/src/discovery/scanner.ts b/packages/intent/src/discovery/scanner.ts index 3aaf6926..2a5dd7da 100644 --- a/packages/intent/src/discovery/scanner.ts +++ b/packages/intent/src/discovery/scanner.ts @@ -15,6 +15,7 @@ import { } from 'node:path' import { detectGlobalNodeModules, + errorMessage, isRecord, isWithinOrEqual, parseFrontmatter, @@ -27,9 +28,11 @@ import { readWorkspacePatterns, } from '../setup/workspace-patterns.js' import { compareVersions, normalizeVersion } from '../shared/version.js' +import { getPackageShortName } from '../skills/use.js' import { createIntentFsCache } from './fs-cache.js' import { detectPackageManager } from './package-manager.js' -import { createDependencyWalker, createPackageRegistrar } from './index.js' +import { createPackageRegistrar } from './register.js' +import { createDependencyWalker } from './walk.js' import type { IntentFsCache } from './fs-cache.js' import type { ReadFs } from '../shared/utils.js' import type { @@ -169,9 +172,8 @@ function loadPnpApi(root: string): LoadedPnp | null { // Ignore and report the project PnP load error below. } - const msg = err instanceof Error ? err.message : String(err) throw new Error( - `Yarn PnP project detected, but Intent could not load Yarn's PnP API from ${pnpPath}: ${msg}`, + `Yarn PnP project detected, but Intent could not load Yarn's PnP API from ${pnpPath}: ${errorMessage(err)}`, ) } } @@ -255,7 +257,7 @@ function deriveIntentConfig( /** * Real path of the package root that owns `skillsDir`, or null when it cannot * be resolved. Computed once per package: every skill entry is checked against - * the same root, so resolving it per skill only repeated the same syscalls. + * the same root. */ function resolveRealPackageRoot( skillsDir: string, @@ -396,10 +398,6 @@ function discoverSkills( }) } -function getPackageShortName(packageName: string): string { - return packageName.split('/').pop() ?? packageName -} - function resolveSkillNameHintPath( skillsDir: string, hint: string, @@ -829,7 +827,6 @@ export interface ScanIntentPackageAtRootOptions { fsCache?: IntentFsCache includeSkillMetadata?: boolean projectRoot?: string - source?: IntentPackage['source'] skillNameHint?: string } @@ -883,11 +880,7 @@ export function scanIntentPackageAtRoot( warnings, }) - tryRegister( - packageRoot, - options.fallbackName ?? 'unknown', - options.source ?? 'local', - ) + tryRegister(packageRoot, options.fallbackName ?? 'unknown') return { package: packages[0] ?? null, diff --git a/packages/intent/src/discovery/walk.ts b/packages/intent/src/discovery/walk.ts index 626c46ea..f8282736 100644 --- a/packages/intent/src/discovery/walk.ts +++ b/packages/intent/src/discovery/walk.ts @@ -17,7 +17,7 @@ export interface CreateDependencyWalkerOptions { readPkgJson: (dirPath: string) => PackageJson | null getFsIdentity: (path: string) => string /** Marks a directory `resolveDepDir` returned as its own identity. */ - primeFsIdentity?: (realPath: string) => void + primeFsIdentity: (realPath: string) => void scanNodeModulesDir: (nodeModulesDir: string) => void tryRegister: (dirPath: string, fallbackName: string) => boolean packages: Array @@ -45,7 +45,7 @@ export function createDependencyWalker(opts: CreateDependencyWalkerOptions) { depDir = resolveDepDir(depName, fromDir, depDirResolution) byDepName.set(depName, depDir) // The result is already a real directory, so its identity is itself. - if (depDir) opts.primeFsIdentity?.(depDir) + if (depDir) opts.primeFsIdentity(depDir) } return depDir diff --git a/packages/intent/src/hooks/install.ts b/packages/intent/src/hooks/install.ts index 80665ed9..aa325e88 100644 --- a/packages/intent/src/hooks/install.ts +++ b/packages/intent/src/hooks/install.ts @@ -4,7 +4,7 @@ import { dirname, relative } from 'node:path' import { detectPackageManager } from '../discovery/package-manager.js' import { fail } from '../shared/cli-error.js' import { formatIntentCommand } from '../shared/command-runner.js' -import { errorMessage } from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/utils.js' import { ALL_HOOK_AGENTS, HOOK_AGENT_ADAPTERS } from './adapters.js' import { EDIT_TOOLS_BY_AGENT, @@ -614,10 +614,8 @@ function parseJsonObject( content: string, ): Record { try { - const parsed = JSON.parse(content) as unknown - if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { - return parsed as Record - } + const parsed: unknown = JSON.parse(content) + if (isRecord(parsed)) return parsed } catch (err) { fail(`Failed to parse ${formatPath(filePath)}: ${errorMessage(err)}`) } @@ -626,9 +624,7 @@ function parseJsonObject( } function objectValue(value: unknown): Record { - return value && typeof value === 'object' && !Array.isArray(value) - ? { ...(value as Record) } - : {} + return isRecord(value) ? { ...value } : {} } function arrayValue(value: unknown): Array { diff --git a/packages/intent/src/shared/cli-output.ts b/packages/intent/src/shared/cli-output.ts index f281d886..acdaac15 100644 --- a/packages/intent/src/shared/cli-output.ts +++ b/packages/intent/src/shared/cli-output.ts @@ -23,7 +23,7 @@ function envSuppressesNotices(): boolean { return value ? TRUE_LIKE_VALUES.has(value) : false } -function shouldSuppressNotices(options: NoticeOutputOptions = {}): boolean { +function shouldSuppressNotices(options: NoticeOutputOptions): boolean { return options.noNotices === true || envSuppressesNotices() } diff --git a/packages/intent/src/shared/command-runner.ts b/packages/intent/src/shared/command-runner.ts index 51eb4496..9efca107 100644 --- a/packages/intent/src/shared/command-runner.ts +++ b/packages/intent/src/shared/command-runner.ts @@ -1,8 +1,5 @@ -import { detectPackageManager } from '../discovery/package-manager.js' import type { PackageManager } from './types.js' -export { detectPackageManager as detectIntentCommandPackageManager } - const runnerByPackageManager: Record = { bun: 'bunx --no-install --package @tanstack/intent intent', npm: 'npm exec --no -- intent', diff --git a/packages/intent/src/validate/blocks.ts b/packages/intent/src/validate/blocks.ts index d1b99ee5..d28dd49d 100644 --- a/packages/intent/src/validate/blocks.ts +++ b/packages/intent/src/validate/blocks.ts @@ -4,6 +4,7 @@ import { createRequire } from 'node:module' import { dirname, join, relative, resolve } from 'node:path' import { pathToFileURL } from 'node:url' import { resolveProjectContext } from '../core/project-context.js' +import { createIntentFsCache } from '../discovery/fs-cache.js' import { resolveWorkspacePackages } from '../setup/workspace-patterns.js' import { errorMessage, @@ -12,6 +13,7 @@ import { readScalarField, } from '../shared/utils.js' import type TS from 'typescript' +import type { IntentFsCache } from '../discovery/fs-cache.js' import type * as NativeApi from 'typescript7/unstable/async' import type * as NativeAst from 'typescript7/unstable/ast' import type * as NativeIs from 'typescript7/unstable/ast/is' @@ -520,17 +522,6 @@ function checkSkillLinks( return findings } -function readManifest(packageDir: string): Record | null { - try { - const manifest: unknown = JSON.parse( - readFileSync(join(packageDir, 'package.json'), 'utf8'), - ) - return isRecord(manifest) ? manifest : null - } catch { - return null - } -} - // The entry the manifest declares for the library's public types. function declaredEntry(manifest: Record): string | undefined { const exportsRoot = isRecord(manifest.exports) @@ -608,7 +599,10 @@ function libraryEntry( // Every workspace package mapped to its own entry, so an example that imports // a sibling package (an adapter, a framework binding) is checked against it // instead of silently resolving to nothing. -function workspacePaths(root: string): Record> { +function workspacePaths( + root: string, + fsCache: IntentFsCache, +): Record> { const context = resolveProjectContext({ cwd: root }) const workspaceRoot = context.workspaceRoot ?? root const paths: Record> = {} @@ -616,7 +610,7 @@ function workspacePaths(root: string): Record> { workspaceRoot, context.workspacePatterns, )) { - const manifest = readManifest(dir) + const manifest = fsCache.readPackageJson(dir) if (!manifest || typeof manifest.name !== 'string') continue const { name } = manifest const entry = libraryEntry(dir, manifest) @@ -660,10 +654,17 @@ export async function checkSkillBlocks( skills: Array<{ file: string; content: string }> references?: Array<{ file: string; content: string }> cache?: SkillBlockCache + fsCache?: IntentFsCache }, ts?: typeof TS | null, ): Promise { - const { root, packageDir, library, cache = {} } = options + const { + root, + packageDir, + library, + cache = {}, + fsCache = createIntentFsCache(), + } = options const findings: Array = [] const blocks: Array = [] for (const skill of options.skills) { @@ -696,7 +697,7 @@ export async function checkSkillBlocks( return result( `TypeScript ${ts.version} has no compiler API that Intent can use; install @typescript/typescript6 beside it`, ) - const manifest = readManifest(packageDir) ?? {} + const manifest = fsCache.readPackageJson(packageDir) ?? {} const entry = libraryEntry(packageDir, manifest) const ownsLibrary = manifest.name === library if (ownsLibrary && !entry) @@ -712,7 +713,7 @@ export async function checkSkillBlocks( const compilerOptions = { ...exampleCompilerOptions, paths: { - ...(cache.workspacePaths ??= workspacePaths(root)), + ...(cache.workspacePaths ??= workspacePaths(root, fsCache)), // A skill documenting another package (metadata.library) resolves that // package through the workspace or node_modules, not this package's entry. ...(ownsLibrary @@ -978,6 +979,7 @@ export async function describeSkillExamples( root: string, files: Array, ): Promise> { + const fsCache = createIntentFsCache() const groups = new Map< string, { packageDir: string; library: string; files: Array } @@ -991,7 +993,7 @@ export async function describeSkillExamples( if (!packageRoot) continue let library = readScalarField(parseFrontmatter(absolute), 'library') if (!library) { - const name = readManifest(packageRoot)?.name + const name = fsCache.readPackageJson(packageRoot)?.name if (typeof name !== 'string') continue library = name } @@ -1017,6 +1019,7 @@ export async function describeSkillExamples( library: group.library, skills, cache, + fsCache, }) for (const [file, summary] of summarizeSkillExamples(result, skills)) summaries.set(file, summary) diff --git a/packages/intent/tests/source-policy.test.ts b/packages/intent/tests/source-policy.test.ts index 56ecc3d1..3094562c 100644 --- a/packages/intent/tests/source-policy.test.ts +++ b/packages/intent/tests/source-policy.test.ts @@ -12,8 +12,8 @@ import { compileExcludePatterns, compileWildcardPattern, } from '../src/core/excludes.js' +import { ALLOW_ALL_NOTICE } from '../src/shared/cli-output.js' import { - ALLOW_ALL_NOTICE, EMPTY_NOTE, MIGRATION_NOTICE, applySourcePolicy, From a83889705bb70b63fbac9a8c2e5e79b87b8f17fb Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 11:56:43 -0700 Subject: [PATCH 09/12] refactor: move workspace patterns from setup to core core and discovery import this module, so it belongs in the layer they share. The file moves unchanged except for its own import path. --- packages/intent/src/commands/support.ts | 2 +- packages/intent/src/commands/validate.ts | 2 +- packages/intent/src/core/load-resolution.ts | 2 +- packages/intent/src/core/project-context.ts | 2 +- packages/intent/src/{setup => core}/workspace-patterns.ts | 2 +- packages/intent/src/discovery/scanner.ts | 2 +- packages/intent/src/discovery/walk.ts | 2 +- packages/intent/src/maintainer/existing.ts | 2 +- packages/intent/src/setup/project-setup.ts | 2 +- packages/intent/src/validate/blocks.ts | 2 +- packages/intent/tests/workspace-patterns.test.ts | 2 +- 11 files changed, 11 insertions(+), 11 deletions(-) rename packages/intent/src/{setup => core}/workspace-patterns.ts (99%) diff --git a/packages/intent/src/commands/support.ts b/packages/intent/src/commands/support.ts index 8365edf7..c6d9e638 100644 --- a/packages/intent/src/commands/support.ts +++ b/packages/intent/src/commands/support.ts @@ -8,7 +8,7 @@ import { createIntentFsCache } from '../discovery/fs-cache.js' import { findWorkspacePackages, findWorkspaceRoot, -} from '../setup/workspace-patterns.js' +} from '../core/workspace-patterns.js' import type { IntentCoreOptions } from '../core/index.js' import type { IntentFsCache } from '../discovery/fs-cache.js' import type { diff --git a/packages/intent/src/commands/validate.ts b/packages/intent/src/commands/validate.ts index d8e0f005..e0c1a985 100644 --- a/packages/intent/src/commands/validate.ts +++ b/packages/intent/src/commands/validate.ts @@ -10,7 +10,7 @@ import { parseDocument, parse as parseYaml } from 'yaml' import { fail } from '../shared/cli-error.js' import { errorMessage, isRecord, readScalarField } from '../shared/utils.js' import { resolveProjectContext } from '../core/project-context.js' -import { findWorkspacePackages } from '../setup/workspace-patterns.js' +import { findWorkspacePackages } from '../core/workspace-patterns.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { checkSkillBlocks, diff --git a/packages/intent/src/core/load-resolution.ts b/packages/intent/src/core/load-resolution.ts index 84fbf854..91e7f24f 100644 --- a/packages/intent/src/core/load-resolution.ts +++ b/packages/intent/src/core/load-resolution.ts @@ -2,8 +2,8 @@ import { existsSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' import { resolveSkillEntry } from '../skills/resolver.js' import { scanIntentPackageAtRoot } from '../discovery/scanner.js' -import { findWorkspacePackages } from '../setup/workspace-patterns.js' import { getDeps } from '../shared/utils.js' +import { findWorkspacePackages } from './workspace-patterns.js' import { warningMentionsPackage } from './excludes.js' import type { ResolveSkillResult } from '../skills/resolver.js' import type { IntentFsCache } from '../discovery/fs-cache.js' diff --git a/packages/intent/src/core/project-context.ts b/packages/intent/src/core/project-context.ts index 1ae371a4..02b03218 100644 --- a/packages/intent/src/core/project-context.ts +++ b/packages/intent/src/core/project-context.ts @@ -5,7 +5,7 @@ import { createIntentFsCache } from '../discovery/fs-cache.js' import { findWorkspaceRoot, readWorkspacePatterns, -} from '../setup/workspace-patterns.js' +} from './workspace-patterns.js' import type { IntentFsCache } from '../discovery/fs-cache.js' export type ProjectContext = { diff --git a/packages/intent/src/setup/workspace-patterns.ts b/packages/intent/src/core/workspace-patterns.ts similarity index 99% rename from packages/intent/src/setup/workspace-patterns.ts rename to packages/intent/src/core/workspace-patterns.ts index 1e6ef958..a04eaf8a 100644 --- a/packages/intent/src/setup/workspace-patterns.ts +++ b/packages/intent/src/core/workspace-patterns.ts @@ -3,7 +3,7 @@ import { dirname, join } from 'node:path' import { parse as parseJsonc } from 'jsonc-parser/lib/esm/main.js' import { parse as parseYaml } from 'yaml' import { errorMessage, hasAnySkillFile, isRecord } from '../shared/utils.js' -import { readPackageJson } from '../core/package-json.js' +import { readPackageJson } from './package-json.js' import type { ParseError } from 'jsonc-parser/lib/esm/main.js' import type { IntentFsCache } from '../discovery/fs-cache.js' diff --git a/packages/intent/src/discovery/scanner.ts b/packages/intent/src/discovery/scanner.ts index 2a5dd7da..e4858931 100644 --- a/packages/intent/src/discovery/scanner.ts +++ b/packages/intent/src/discovery/scanner.ts @@ -26,7 +26,7 @@ import { findWorkspacePackages, findWorkspaceRoot, readWorkspacePatterns, -} from '../setup/workspace-patterns.js' +} from '../core/workspace-patterns.js' import { compareVersions, normalizeVersion } from '../shared/version.js' import { getPackageShortName } from '../skills/use.js' import { createIntentFsCache } from './fs-cache.js' diff --git a/packages/intent/src/discovery/walk.ts b/packages/intent/src/discovery/walk.ts index f8282736..f9dddf9e 100644 --- a/packages/intent/src/discovery/walk.ts +++ b/packages/intent/src/discovery/walk.ts @@ -5,7 +5,7 @@ import { listNestedNodeModulesPackageDirs, resolveDepDir, } from '../shared/utils.js' -import { findWorkspacePackages } from '../setup/workspace-patterns.js' +import { findWorkspacePackages } from '../core/workspace-patterns.js' import type { IntentFsCache } from './fs-cache.js' import type { IntentPackage } from '../shared/types.js' diff --git a/packages/intent/src/maintainer/existing.ts b/packages/intent/src/maintainer/existing.ts index dcdf6669..7002a19f 100644 --- a/packages/intent/src/maintainer/existing.ts +++ b/packages/intent/src/maintainer/existing.ts @@ -4,7 +4,7 @@ import { basename, dirname, relative } from 'node:path' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { reviewIgnorePatterns } from '../review/review.js' -import { resolveWorkspacePackages } from '../setup/workspace-patterns.js' +import { resolveWorkspacePackages } from '../core/workspace-patterns.js' import { errorMessage, isDefaultSkillPath, diff --git a/packages/intent/src/setup/project-setup.ts b/packages/intent/src/setup/project-setup.ts index d33636d9..b722a3ac 100644 --- a/packages/intent/src/setup/project-setup.ts +++ b/packages/intent/src/setup/project-setup.ts @@ -9,7 +9,7 @@ import { findPackagesWithSkills, findWorkspaceRoot, readWorkspacePatterns, -} from './workspace-patterns.js' +} from '../core/workspace-patterns.js' import type { FileChange } from '../maintainer/files.js' import type { IntentFsCache } from '../discovery/fs-cache.js' diff --git a/packages/intent/src/validate/blocks.ts b/packages/intent/src/validate/blocks.ts index d28dd49d..e65c41df 100644 --- a/packages/intent/src/validate/blocks.ts +++ b/packages/intent/src/validate/blocks.ts @@ -5,7 +5,7 @@ import { dirname, join, relative, resolve } from 'node:path' import { pathToFileURL } from 'node:url' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' -import { resolveWorkspacePackages } from '../setup/workspace-patterns.js' +import { resolveWorkspacePackages } from '../core/workspace-patterns.js' import { errorMessage, isRecord, diff --git a/packages/intent/tests/workspace-patterns.test.ts b/packages/intent/tests/workspace-patterns.test.ts index cc75c554..284e4216 100644 --- a/packages/intent/tests/workspace-patterns.test.ts +++ b/packages/intent/tests/workspace-patterns.test.ts @@ -14,7 +14,7 @@ import { findWorkspaceRoot, readWorkspacePatterns, resolveWorkspacePackages, -} from '../src/setup/workspace-patterns.js' +} from '../src/core/workspace-patterns.js' const roots: Array = [] const cwdStack: Array = [] From 5f38844f574bb5e8a73304c7f05706add7b1c960 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 12:00:31 -0700 Subject: [PATCH 10/12] refactor: split shared utils by job shared/utils.ts becomes guards, paths, fs-identity, skill-files, node-modules, and frontmatter. The code moves unchanged; only import paths differ. The shared exports now come first in src/index.ts so the published type declarations keep their order. --- packages/intent/src/commands/exclude.ts | 2 +- .../intent/src/commands/install/guidance.ts | 2 +- packages/intent/src/commands/maintainer.ts | 2 +- packages/intent/src/commands/meta.ts | 3 +- packages/intent/src/commands/review.ts | 2 +- packages/intent/src/commands/support.ts | 2 +- packages/intent/src/commands/validate.ts | 3 +- packages/intent/src/core/excludes.ts | 3 +- packages/intent/src/core/intent-core.ts | 5 +- packages/intent/src/core/load-resolution.ts | 2 +- packages/intent/src/core/markdown.ts | 2 +- packages/intent/src/core/package-json.ts | 2 +- packages/intent/src/core/project-context.ts | 2 +- packages/intent/src/core/source-policy.ts | 2 +- .../intent/src/core/workspace-patterns.ts | 3 +- packages/intent/src/discovery/fs-cache.ts | 11 +- packages/intent/src/discovery/register.ts | 2 +- packages/intent/src/discovery/scanner.ts | 15 +- packages/intent/src/discovery/walk.ts | 2 +- packages/intent/src/hooks/install.ts | 2 +- packages/intent/src/index.ts | 9 +- packages/intent/src/maintainer/add.ts | 3 +- .../intent/src/maintainer/distribution.ts | 3 +- packages/intent/src/maintainer/existing.ts | 9 +- packages/intent/src/maintainer/project.ts | 2 +- packages/intent/src/maintainer/sync.ts | 3 +- packages/intent/src/review/review.ts | 9 +- packages/intent/src/setup/project-setup.ts | 2 +- packages/intent/src/shared/frontmatter.ts | 91 +++ packages/intent/src/shared/fs-identity.ts | 90 +++ packages/intent/src/shared/guards.ts | 13 + packages/intent/src/shared/node-modules.ts | 271 +++++++++ packages/intent/src/shared/paths.ts | 37 ++ packages/intent/src/shared/skill-files.ts | 62 ++ packages/intent/src/shared/utils.ts | 558 ------------------ packages/intent/src/skills/paths.ts | 2 +- .../intent/src/staleness/artifact-coverage.ts | 2 +- packages/intent/src/staleness/check.ts | 7 +- packages/intent/src/validate/blocks.ts | 8 +- packages/intent/src/validate/repairs.ts | 2 +- .../intent/tests/discovery-safety.test.ts | 2 +- .../distribution-installers.test.ts | 2 +- .../intent/tests/parse-frontmatter.test.ts | 2 +- .../intent/tests/read-scalar-field.test.ts | 2 +- packages/intent/tests/repeated-work.test.ts | 2 +- packages/intent/tests/resolve-dep-dir.test.ts | 7 +- packages/intent/tests/skills.test.ts | 2 +- 47 files changed, 629 insertions(+), 642 deletions(-) create mode 100644 packages/intent/src/shared/frontmatter.ts create mode 100644 packages/intent/src/shared/fs-identity.ts create mode 100644 packages/intent/src/shared/guards.ts create mode 100644 packages/intent/src/shared/node-modules.ts create mode 100644 packages/intent/src/shared/paths.ts create mode 100644 packages/intent/src/shared/skill-files.ts delete mode 100644 packages/intent/src/shared/utils.ts diff --git a/packages/intent/src/commands/exclude.ts b/packages/intent/src/commands/exclude.ts index f7bce0ca..4c9caaf0 100644 --- a/packages/intent/src/commands/exclude.ts +++ b/packages/intent/src/commands/exclude.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { fail } from '../shared/cli-error.js' -import { errorMessage } from '../shared/utils.js' +import { errorMessage } from '../shared/guards.js' import { compileExcludePatterns } from '../core/excludes.js' export interface ExcludeCommandOptions { diff --git a/packages/intent/src/commands/install/guidance.ts b/packages/intent/src/commands/install/guidance.ts index 3a9372f7..441b015b 100644 --- a/packages/intent/src/commands/install/guidance.ts +++ b/packages/intent/src/commands/install/guidance.ts @@ -3,7 +3,7 @@ import { join } from 'node:path' import { parse as parseYaml } from 'yaml' import { formatIntentCommand } from '../../shared/command-runner.js' import { repositoryWritePath } from '../../shared/write-path.js' -import { errorMessage } from '../../shared/utils.js' +import { errorMessage } from '../../shared/guards.js' import { writeChanges } from '../../maintainer/files.js' import { parseIntentInvocation } from '../../hooks/policy.js' import { isGeneratedMappingSkill } from '../../skills/categories.js' diff --git a/packages/intent/src/commands/maintainer.ts b/packages/intent/src/commands/maintainer.ts index 4663e1aa..5b66fb20 100644 --- a/packages/intent/src/commands/maintainer.ts +++ b/packages/intent/src/commands/maintainer.ts @@ -4,7 +4,7 @@ import { isCI } from 'std-env' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { fail } from '../shared/cli-error.js' -import { errorMessage } from '../shared/utils.js' +import { errorMessage } from '../shared/guards.js' import { planSetupRecords, readRecord, diff --git a/packages/intent/src/commands/meta.ts b/packages/intent/src/commands/meta.ts index c351bab9..3a800821 100644 --- a/packages/intent/src/commands/meta.ts +++ b/packages/intent/src/commands/meta.ts @@ -1,7 +1,8 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs' import { dirname, join } from 'node:path' import { fail } from '../shared/cli-error.js' -import { errorMessage, parseFrontmatter } from '../shared/utils.js' +import { errorMessage } from '../shared/guards.js' +import { parseFrontmatter } from '../shared/frontmatter.js' import { rewriteLoadedSkillMarkdownDestinations } from '../core/markdown.js' export function runMetaCommand( diff --git a/packages/intent/src/commands/review.ts b/packages/intent/src/commands/review.ts index c7bad0e1..250b2886 100644 --- a/packages/intent/src/commands/review.ts +++ b/packages/intent/src/commands/review.ts @@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs' import { resolve } from 'node:path' import { createReview, recordReview } from '../review/review.js' import { fail, isCliFailure } from '../shared/cli-error.js' -import { errorMessage, isRecord } from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' import { writeStaleReviewWorkflowFiles } from '../staleness/workflow-review.js' export interface ReviewCommandOptions { diff --git a/packages/intent/src/commands/support.ts b/packages/intent/src/commands/support.ts index c6d9e638..ee1b42d2 100644 --- a/packages/intent/src/commands/support.ts +++ b/packages/intent/src/commands/support.ts @@ -2,7 +2,7 @@ import { existsSync, readFileSync, statSync } from 'node:fs' import { dirname, join, relative, resolve } from 'node:path' import { fileURLToPath } from 'node:url' import { fail, isCliFailure } from '../shared/cli-error.js' -import { errorMessage } from '../shared/utils.js' +import { errorMessage } from '../shared/guards.js' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { diff --git a/packages/intent/src/commands/validate.ts b/packages/intent/src/commands/validate.ts index e0c1a985..8f96818c 100644 --- a/packages/intent/src/commands/validate.ts +++ b/packages/intent/src/commands/validate.ts @@ -8,7 +8,8 @@ import { import { basename, dirname, join, relative, resolve } from 'node:path' import { parseDocument, parse as parseYaml } from 'yaml' import { fail } from '../shared/cli-error.js' -import { errorMessage, isRecord, readScalarField } from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' +import { readScalarField } from '../shared/frontmatter.js' import { resolveProjectContext } from '../core/project-context.js' import { findWorkspacePackages } from '../core/workspace-patterns.js' import { createIntentFsCache } from '../discovery/fs-cache.js' diff --git a/packages/intent/src/core/excludes.ts b/packages/intent/src/core/excludes.ts index d26db68e..e14e3ce4 100644 --- a/packages/intent/src/core/excludes.ts +++ b/packages/intent/src/core/excludes.ts @@ -1,5 +1,6 @@ import { dirname, resolve } from 'node:path' -import { isRecord, isWithinOrEqual } from '../shared/utils.js' +import { isRecord } from '../shared/guards.js' +import { isWithinOrEqual } from '../shared/paths.js' import { getPackageShortName } from '../skills/use.js' import { resolveProjectContext } from './project-context.js' import { readPackageJson } from './package-json.js' diff --git a/packages/intent/src/core/intent-core.ts b/packages/intent/src/core/intent-core.ts index 67c35876..f20684bc 100644 --- a/packages/intent/src/core/intent-core.ts +++ b/packages/intent/src/core/intent-core.ts @@ -1,6 +1,7 @@ import { resolve } from 'node:path' import { createIntentFsCache } from '../discovery/fs-cache.js' -import { errorMessage, isWithinOrEqual } from '../shared/utils.js' +import { errorMessage } from '../shared/guards.js' +import { isWithinOrEqual } from '../shared/paths.js' import { ResolveSkillUseError, resolveSkillUse } from '../skills/resolver.js' import { formatSkillUse, parseSkillUse } from '../skills/use.js' import { @@ -18,7 +19,7 @@ import { scanForPolicedIntents, } from './source-policy.js' import type { ResolveSkillResult } from '../skills/resolver.js' -import type { ReadFs } from '../shared/utils.js' +import type { ReadFs } from '../shared/fs-identity.js' import type { ScanScope } from '../shared/types.js' import type { IntentCoreErrorCode, diff --git a/packages/intent/src/core/load-resolution.ts b/packages/intent/src/core/load-resolution.ts index 91e7f24f..22c69c2a 100644 --- a/packages/intent/src/core/load-resolution.ts +++ b/packages/intent/src/core/load-resolution.ts @@ -2,7 +2,7 @@ import { existsSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' import { resolveSkillEntry } from '../skills/resolver.js' import { scanIntentPackageAtRoot } from '../discovery/scanner.js' -import { getDeps } from '../shared/utils.js' +import { getDeps } from '../shared/node-modules.js' import { findWorkspacePackages } from './workspace-patterns.js' import { warningMentionsPackage } from './excludes.js' import type { ResolveSkillResult } from '../skills/resolver.js' diff --git a/packages/intent/src/core/markdown.ts b/packages/intent/src/core/markdown.ts index 71f73a6b..29e4d3ea 100644 --- a/packages/intent/src/core/markdown.ts +++ b/packages/intent/src/core/markdown.ts @@ -1,5 +1,5 @@ import { dirname, isAbsolute, relative, resolve } from 'node:path' -import { toPosixPath } from '../shared/utils.js' +import { toPosixPath } from '../shared/paths.js' /** * A character that does not occur in `text`, taken from the Unicode private diff --git a/packages/intent/src/core/package-json.ts b/packages/intent/src/core/package-json.ts index 1b81d5a5..962438df 100644 --- a/packages/intent/src/core/package-json.ts +++ b/packages/intent/src/core/package-json.ts @@ -1,6 +1,6 @@ import { join } from 'node:path' import { createIntentFsCache } from '../discovery/fs-cache.js' -import { errorMessage } from '../shared/utils.js' +import { errorMessage } from '../shared/guards.js' /** * Reads a project policy manifest, returning null only when the file is absent. diff --git a/packages/intent/src/core/project-context.ts b/packages/intent/src/core/project-context.ts index 02b03218..70fd4e3e 100644 --- a/packages/intent/src/core/project-context.ts +++ b/packages/intent/src/core/project-context.ts @@ -1,6 +1,6 @@ import { existsSync, statSync } from 'node:fs' import { dirname, join, resolve } from 'node:path' -import { isWithinOrEqual } from '../shared/utils.js' +import { isWithinOrEqual } from '../shared/paths.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { findWorkspaceRoot, diff --git a/packages/intent/src/core/source-policy.ts b/packages/intent/src/core/source-policy.ts index 72a976ec..d65e3b2b 100644 --- a/packages/intent/src/core/source-policy.ts +++ b/packages/intent/src/core/source-policy.ts @@ -2,7 +2,7 @@ import { scanForIntents } from '../discovery/scanner.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { detectIntentAudience } from '../shared/environment.js' import { ALLOW_ALL_NOTICE } from '../shared/cli-output.js' -import { isRecord } from '../shared/utils.js' +import { isRecord } from '../shared/guards.js' import { compileExcludePatterns, compileWildcardPattern, diff --git a/packages/intent/src/core/workspace-patterns.ts b/packages/intent/src/core/workspace-patterns.ts index a04eaf8a..ebd3d725 100644 --- a/packages/intent/src/core/workspace-patterns.ts +++ b/packages/intent/src/core/workspace-patterns.ts @@ -2,7 +2,8 @@ import { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs' import { dirname, join } from 'node:path' import { parse as parseJsonc } from 'jsonc-parser/lib/esm/main.js' import { parse as parseYaml } from 'yaml' -import { errorMessage, hasAnySkillFile, isRecord } from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' +import { hasAnySkillFile } from '../shared/skill-files.js' import { readPackageJson } from './package-json.js' import type { ParseError } from 'jsonc-parser/lib/esm/main.js' import type { IntentFsCache } from '../discovery/fs-cache.js' diff --git a/packages/intent/src/discovery/fs-cache.ts b/packages/intent/src/discovery/fs-cache.ts index f47f51a2..7fed1264 100644 --- a/packages/intent/src/discovery/fs-cache.ts +++ b/packages/intent/src/discovery/fs-cache.ts @@ -1,11 +1,8 @@ import { join } from 'node:path' -import { - createFsIdentityCache, - findSkillFiles as findSkillFilesUncached, - isRecord, - nodeReadFs, -} from '../shared/utils.js' -import type { ReadFs } from '../shared/utils.js' +import { isRecord } from '../shared/guards.js' +import { createFsIdentityCache, nodeReadFs } from '../shared/fs-identity.js' +import { findSkillFiles as findSkillFilesUncached } from '../shared/skill-files.js' +import type { ReadFs } from '../shared/fs-identity.js' type PackageJsonReadResult = { packageJson: Record | null diff --git a/packages/intent/src/discovery/register.ts b/packages/intent/src/discovery/register.ts index d552d191..ed99842f 100644 --- a/packages/intent/src/discovery/register.ts +++ b/packages/intent/src/discovery/register.ts @@ -1,6 +1,6 @@ import { join, sep } from 'node:path' import { rewriteSkillLoadPaths } from '../skills/paths.js' -import { listNodeModulesPackageDirs } from '../shared/utils.js' +import { listNodeModulesPackageDirs } from '../shared/node-modules.js' import type { IntentConfig, IntentPackage, diff --git a/packages/intent/src/discovery/scanner.ts b/packages/intent/src/discovery/scanner.ts index e4858931..3f133a4b 100644 --- a/packages/intent/src/discovery/scanner.ts +++ b/packages/intent/src/discovery/scanner.ts @@ -13,15 +13,10 @@ import { resolve, sep, } from 'node:path' -import { - detectGlobalNodeModules, - errorMessage, - isRecord, - isWithinOrEqual, - parseFrontmatter, - readScalarField, - toPosixPath, -} from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' +import { isWithinOrEqual, toPosixPath } from '../shared/paths.js' +import { detectGlobalNodeModules } from '../shared/node-modules.js' +import { parseFrontmatter, readScalarField } from '../shared/frontmatter.js' import { findWorkspacePackages, findWorkspaceRoot, @@ -34,7 +29,7 @@ import { detectPackageManager } from './package-manager.js' import { createPackageRegistrar } from './register.js' import { createDependencyWalker } from './walk.js' import type { IntentFsCache } from './fs-cache.js' -import type { ReadFs } from '../shared/utils.js' +import type { ReadFs } from '../shared/fs-identity.js' import type { InstalledVariant, IntentConfig, diff --git a/packages/intent/src/discovery/walk.ts b/packages/intent/src/discovery/walk.ts index f9dddf9e..56edc76b 100644 --- a/packages/intent/src/discovery/walk.ts +++ b/packages/intent/src/discovery/walk.ts @@ -4,7 +4,7 @@ import { getDeps, listNestedNodeModulesPackageDirs, resolveDepDir, -} from '../shared/utils.js' +} from '../shared/node-modules.js' import { findWorkspacePackages } from '../core/workspace-patterns.js' import type { IntentFsCache } from './fs-cache.js' import type { IntentPackage } from '../shared/types.js' diff --git a/packages/intent/src/hooks/install.ts b/packages/intent/src/hooks/install.ts index aa325e88..bc174568 100644 --- a/packages/intent/src/hooks/install.ts +++ b/packages/intent/src/hooks/install.ts @@ -4,7 +4,7 @@ import { dirname, relative } from 'node:path' import { detectPackageManager } from '../discovery/package-manager.js' import { fail } from '../shared/cli-error.js' import { formatIntentCommand } from '../shared/command-runner.js' -import { errorMessage, isRecord } from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' import { ALL_HOOK_AGENTS, HOOK_AGENT_ADAPTERS } from './adapters.js' import { EDIT_TOOLS_BY_AGENT, diff --git a/packages/intent/src/index.ts b/packages/intent/src/index.ts index dc71567d..cac09e65 100644 --- a/packages/intent/src/index.ts +++ b/packages/intent/src/index.ts @@ -1,3 +1,6 @@ +export { findSkillFiles } from './shared/skill-files.js' +export { getDeps, resolveDepDir } from './shared/node-modules.js' +export { parseFrontmatter } from './shared/frontmatter.js' export { scanForIntents } from './discovery/scanner.js' export { checkStaleness } from './staleness/index.js' export { readIntentArtifacts } from './staleness/artifact-coverage.js' @@ -7,12 +10,6 @@ export { createFailedStaleReviewItem, type StaleReviewItem, } from './staleness/workflow-review.js' -export { - findSkillFiles, - getDeps, - parseFrontmatter, - resolveDepDir, -} from './shared/utils.js' export { formatSkillUse, isSkillUseParseError, diff --git a/packages/intent/src/maintainer/add.ts b/packages/intent/src/maintainer/add.ts index 3ef0d60b..71525533 100644 --- a/packages/intent/src/maintainer/add.ts +++ b/packages/intent/src/maintainer/add.ts @@ -3,7 +3,8 @@ import { basename, dirname, join, relative } from 'node:path' import { stringify } from 'yaml' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' -import { isRecord, parseFrontmatter } from '../shared/utils.js' +import { isRecord } from '../shared/guards.js' +import { parseFrontmatter } from '../shared/frontmatter.js' import { authoringMarker, projectPath, diff --git a/packages/intent/src/maintainer/distribution.ts b/packages/intent/src/maintainer/distribution.ts index 1778486b..905c8f87 100644 --- a/packages/intent/src/maintainer/distribution.ts +++ b/packages/intent/src/maintainer/distribution.ts @@ -1,7 +1,8 @@ import { existsSync, readFileSync } from 'node:fs' import { dirname, relative } from 'node:path' import { applyEdits, modify } from 'jsonc-parser' -import { isRecord, parseFrontmatter } from '../shared/utils.js' +import { isRecord } from '../shared/guards.js' +import { parseFrontmatter } from '../shared/frontmatter.js' import { stringList } from './add.js' import { authoringMarker, diff --git a/packages/intent/src/maintainer/existing.ts b/packages/intent/src/maintainer/existing.ts index 7002a19f..c8c14bb3 100644 --- a/packages/intent/src/maintainer/existing.ts +++ b/packages/intent/src/maintainer/existing.ts @@ -5,12 +5,9 @@ import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { reviewIgnorePatterns } from '../review/review.js' import { resolveWorkspacePackages } from '../core/workspace-patterns.js' -import { - errorMessage, - isDefaultSkillPath, - isRecord, - parseFrontmatter, -} from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' +import { isDefaultSkillPath } from '../shared/paths.js' +import { parseFrontmatter } from '../shared/frontmatter.js' import { stringList } from './add.js' import { projectPath, diff --git a/packages/intent/src/maintainer/project.ts b/packages/intent/src/maintainer/project.ts index 85155360..08749d30 100644 --- a/packages/intent/src/maintainer/project.ts +++ b/packages/intent/src/maintainer/project.ts @@ -2,7 +2,7 @@ import { execFileSync } from 'node:child_process' import { existsSync, lstatSync, readFileSync } from 'node:fs' import { basename, dirname, join, relative, resolve } from 'node:path' import { parseDocument, stringify } from 'yaml' -import { isRecord } from '../shared/utils.js' +import { isRecord } from '../shared/guards.js' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import type { IntentFsCache } from '../discovery/fs-cache.js' diff --git a/packages/intent/src/maintainer/sync.ts b/packages/intent/src/maintainer/sync.ts index 3e2236f8..1f0215b2 100644 --- a/packages/intent/src/maintainer/sync.ts +++ b/packages/intent/src/maintainer/sync.ts @@ -3,7 +3,8 @@ import { dirname, relative } from 'node:path' import { applyEdits, modify, parse } from 'jsonc-parser' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' -import { isRecord, parseFrontmatter } from '../shared/utils.js' +import { isRecord } from '../shared/guards.js' +import { parseFrontmatter } from '../shared/frontmatter.js' import { stringList } from './add.js' import { planDistribution } from './distribution.js' import { diff --git a/packages/intent/src/review/review.ts b/packages/intent/src/review/review.ts index 434c9e7b..dcce2c57 100644 --- a/packages/intent/src/review/review.ts +++ b/packages/intent/src/review/review.ts @@ -15,12 +15,9 @@ import { basename, dirname, join, relative, resolve } from 'node:path' import { parse as parseYaml } from 'yaml' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' -import { - errorMessage, - isDefaultSkillPath, - isRecord, - parseFrontmatter, -} from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' +import { isDefaultSkillPath } from '../shared/paths.js' +import { parseFrontmatter } from '../shared/frontmatter.js' type Snapshot = Record type Outcome = 'updated' | 'no-change' | 'out-of-scope' | 'unresolved' diff --git a/packages/intent/src/setup/project-setup.ts b/packages/intent/src/setup/project-setup.ts index b722a3ac..f25e75a3 100644 --- a/packages/intent/src/setup/project-setup.ts +++ b/packages/intent/src/setup/project-setup.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' import { basename, join, relative } from 'node:path' import { repositoryWritePath } from '../shared/write-path.js' -import { errorMessage, isRecord } from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' import { writeChanges } from '../maintainer/files.js' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' diff --git a/packages/intent/src/shared/frontmatter.ts b/packages/intent/src/shared/frontmatter.ts new file mode 100644 index 00000000..08db583d --- /dev/null +++ b/packages/intent/src/shared/frontmatter.ts @@ -0,0 +1,91 @@ +import { parse as parseYaml } from 'yaml' +import { nodeReadFs } from './fs-identity.js' +import type { ReadFs } from './fs-identity.js' + +/** + * Read a scalar string field from frontmatter, preferring `metadata.` over + * a top-level `` (#159 back-compat for the frontmatter migration). + */ +export function readScalarField( + fm: Record | null | undefined, + key: string, +): string | undefined { + const metadata = fm?.metadata + if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) { + const nested = (metadata as Record)[key] + if (typeof nested === 'string') return nested + } + const top = fm?.[key] + return typeof top === 'string' ? top : undefined +} + +/** + * Parse YAML frontmatter from a path or caller-owned descriptor at offset zero. + * Returns null if no frontmatter or on error; caller-owned descriptors stay open. + */ +export function parseFrontmatter( + filePath: string | number, + fs: ReadFs = nodeReadFs, +): Record | null { + const content = readFrontmatterRegion(filePath, fs) + if (content === null) return null + const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/) + if (!match?.[1]) return null + try { + return parseYaml(match[1]) as Record + } catch { + return null + } +} + +/** Max bytes read when probing a file's leading frontmatter region. */ +const FRONTMATTER_READ_LIMIT = 16 * 1024 +/** Reused across calls; safe because reads are synchronous and single-threaded. */ +const frontmatterBuffer = Buffer.allocUnsafe(FRONTMATTER_READ_LIMIT) + +/** + * Read just the leading region of a file, enough to cover its frontmatter, + * instead of its whole body. Falls back to a full read when the bounded read + * primitives are unavailable or the frontmatter exceeds the probe limit. + */ +function readFrontmatterRegion( + filePath: string | number, + fs: ReadFs, +): string | null { + if (fs.openSync && fs.readSync && fs.closeSync) { + let fd: number + try { + fd = typeof filePath === 'number' ? filePath : fs.openSync(filePath, 'r') + } catch { + return null + } + try { + const bytesRead = fs.readSync( + fd, + frontmatterBuffer, + 0, + FRONTMATTER_READ_LIMIT, + 0, + ) + const region = frontmatterBuffer.toString('utf8', 0, bytesRead) + // A full buffer means the file may extend past the probe window; only + // trust the bounded read when it captured the closing fence. + const truncated = + bytesRead === FRONTMATTER_READ_LIMIT && + !/\r?\n---/.test(region.slice(3)) + // The positional probe leaves the descriptor at offset zero. Keep the + // full-read fallback on that descriptor so replacement cannot redirect it. + return truncated ? fs.readFileSync(fd, 'utf8') : region + } catch { + return null + } finally { + if (typeof filePath !== 'number') fs.closeSync(fd) + } + } + + try { + return fs.readFileSync(filePath, 'utf8') + } catch { + return null + } +} diff --git a/packages/intent/src/shared/fs-identity.ts b/packages/intent/src/shared/fs-identity.ts new file mode 100644 index 00000000..7c9065ab --- /dev/null +++ b/packages/intent/src/shared/fs-identity.ts @@ -0,0 +1,90 @@ +import { + closeSync, + existsSync, + fstatSync, + lstatSync, + openSync, + readFileSync, + readSync, + readdirSync, + realpathSync, +} from 'node:fs' +import { resolve } from 'node:path' + +/** + * The subset of `node:fs` the scanner reads through. Under Yarn PnP this is + * swapped for Yarn's libzip-patched `fs` so reads can reach files inside + * `.yarn/cache/*.zip` (see scanner `loadPnpApi`). The static `node:fs` named + * imports cannot be used directly for that, because their bindings are captured + * before Yarn's `setup()` patches the CommonJS `fs` module. + */ +export interface ReadFs { + existsSync: typeof existsSync + lstatSync: typeof lstatSync + readFileSync: typeof readFileSync + readdirSync: typeof readdirSync + realpathSync: typeof realpathSync + /** + * Optional low-level read primitives. When present (always on `node:fs` and + * Yarn's libzip-patched module) `parseFrontmatter` reads only the leading + * region of a file instead of its whole body. + */ + openSync?: typeof openSync + readSync?: typeof readSync + closeSync?: typeof closeSync + fstatSync?: typeof fstatSync +} + +export const nodeReadFs: ReadFs = { + existsSync, + lstatSync, + readFileSync, + readdirSync, + realpathSync, + openSync, + readSync, + closeSync, + fstatSync, +} + +export interface FsIdentityResolver { + (path: string): string + /** + * Record that `realPath` is already an identity (not a symlink), so a later + * lookup returns it without an `lstat`. Callers use this for directories + * they have just resolved through `resolveDepDir`. + */ + prime: (realPath: string) => void +} + +export function createFsIdentityCache( + getFs: () => ReadFs = () => nodeReadFs, +): FsIdentityResolver { + const cache = new Map() + + const getIdentity = ((path: string): string => { + const resolved = resolve(path) + const cached = cache.get(resolved) + if (cached) return cached + + const fs = getFs() + let identity: string + try { + identity = fs.lstatSync(resolved).isSymbolicLink() + ? fs.realpathSync(resolved) + : resolved + } catch { + identity = resolved + } + + cache.set(resolved, identity) + return identity + }) as FsIdentityResolver + + getIdentity.prime = (realPath: string): void => { + const resolved = resolve(realPath) + if (!cache.has(resolved)) cache.set(resolved, resolved) + } + + return getIdentity +} diff --git a/packages/intent/src/shared/guards.ts b/packages/intent/src/shared/guards.ts new file mode 100644 index 00000000..ec6b4a3b --- /dev/null +++ b/packages/intent/src/shared/guards.ts @@ -0,0 +1,13 @@ +export function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +export function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error) +} + +export function stringArray(value: unknown): Array { + return Array.isArray(value) + ? value.filter((entry): entry is string => typeof entry === 'string') + : [] +} diff --git a/packages/intent/src/shared/node-modules.ts b/packages/intent/src/shared/node-modules.ts new file mode 100644 index 00000000..b63731f5 --- /dev/null +++ b/packages/intent/src/shared/node-modules.ts @@ -0,0 +1,271 @@ +import { execFileSync } from 'node:child_process' +import { + existsSync, + lstatSync, + readdirSync, + readlinkSync, + realpathSync, +} from 'node:fs' +import { basename, dirname, join, resolve } from 'node:path' +import { normalizeReadlinkTarget } from './paths.js' +import type { Dirent } from 'node:fs' + +/** + * Read dependencies and peerDependencies (and optionally devDependencies) from + * a parsed package.json object. + */ +export function getDeps( + pkgJson: Record, + includeDevDeps = false, +): Array { + const deps = new Set() + const fields = includeDevDeps + ? ['dependencies', 'devDependencies', 'peerDependencies'] + : ['dependencies', 'peerDependencies'] + for (const field of fields) { + const d = pkgJson[field] + if (d && typeof d === 'object') { + for (const name of Object.keys(d)) { + deps.add(name) + } + } + } + return [...deps] +} + +function readPackageEntries(dir: string): Array> { + try { + return readdirSync(dir, { withFileTypes: true, encoding: 'utf8' }).filter( + (entry) => entry.isDirectory() || entry.isSymbolicLink(), + ) + } catch { + return [] + } +} + +function forEachPackageDir( + nodeModulesDir: string, + visit: (packageDir: string) => void, +): void { + for (const entry of readPackageEntries(nodeModulesDir)) { + const dirPath = join(nodeModulesDir, entry.name) + if (entry.name.startsWith('@')) { + for (const scoped of readPackageEntries(dirPath)) { + visit(join(dirPath, scoped.name)) + } + } else if (!entry.name.startsWith('.')) { + visit(dirPath) + } + } +} + +export function listNodeModulesPackageDirs( + nodeModulesDir: string, +): Array { + const packageDirs: Array = [] + forEachPackageDir(nodeModulesDir, (dir) => packageDirs.push(dir)) + return packageDirs +} + +export function listNestedNodeModulesPackageDirs( + nodeModulesDir: string, + getFsIdentity: (path: string) => string, +): Array { + const packageDirs: Array = [] + const visitedNodeModulesDirs = new Set() + const visitedPackageDirs = new Set() + + function addPackageDir(packageDir: string): void { + const key = getFsIdentity(packageDir) + if (visitedPackageDirs.has(key)) return + visitedPackageDirs.add(key) + + if (existsSync(join(packageDir, 'package.json'))) { + packageDirs.push(packageDir) + } + + scanNodeModulesDir(join(packageDir, 'node_modules')) + } + + function scanNodeModulesDir(dir: string): void { + const key = getFsIdentity(dir) + if (visitedNodeModulesDirs.has(key)) return + visitedNodeModulesDirs.add(key) + forEachPackageDir(dir, addPackageDir) + } + + scanNodeModulesDir(nodeModulesDir) + return packageDirs +} + +const GLOBAL_NODE_MODULES_COMMAND_TIMEOUT_MS = 5_000 + +export function detectGlobalNodeModules(packageManager: string): { + path: string | null + source?: string +} { + const commands: Array<{ + command: string + args: Array + transform?: (output: string) => string + }> = [] + + if (packageManager === 'pnpm') { + commands.push({ command: 'pnpm', args: ['root', '-g'] }) + } + if (packageManager === 'yarn') { + commands.push({ + command: 'yarn', + args: ['global', 'dir'], + transform: (output) => join(output, 'node_modules'), + }) + } + commands.push({ command: 'npm', args: ['root', '-g'] }) + + for (const candidate of commands) { + try { + const output = execFileSync(candidate.command, candidate.args, { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'], + timeout: GLOBAL_NODE_MODULES_COMMAND_TIMEOUT_MS, + }).trim() + if (!output) continue + + return { + path: candidate.transform ? candidate.transform(output) : output, + source: `${candidate.command} ${candidate.args.join(' ')}`, + } + } catch { + continue + } + } + + return { path: null } +} + +/** + * Resolve the directory of a dependency by name by walking up from + * `parentDir` and checking `node_modules//package.json` at each + * ancestor, the same lookup order Node uses. A symlinked match (pnpm's + * virtual store, workspace links) is collapsed to its real directory so + * callers see one identity per installed package. + * + * This deliberately avoids `createRequire().resolve`: Node's resolver + * evaluates export maps, reads the nearest package.json, and realpaths every + * path segment on each call. In a pnpm monorepo that dominated scan time, and + * the walk below already covers every layout the resolver handled (nested, + * hoisted, and virtual-store siblings) without executing package code. + */ +export function resolveDepDir( + depName: string, + parentDir: string, + cache: DepDirCache = createDepDirCache(), +): string | null { + let dir = parentDir + let prev: string | undefined + while (dir !== prev) { + // Node skips ancestors that are themselves node_modules directories + // (`.../node_modules/node_modules/` is never a valid location). + if (basename(dir) !== 'node_modules') { + const nodeModulesDir = join(dir, 'node_modules') + if (hasNodeModulesDir(nodeModulesDir, cache)) { + const candidate = join(nodeModulesDir, depName) + let resolved = cache.candidates.get(candidate) + if (resolved === undefined) { + resolved = resolveCandidateDir(candidate, cache) + cache.candidates.set(candidate, resolved) + } + if (resolved) return resolved + } + } + prev = dir + dir = dirname(dir) + } + + return null +} + +/** + * Memo for `resolveDepDir` across one scan. A dependency graph revisits the + * same `node_modules` directories, candidate paths, and symlink targets many + * times (every package that depends on `semver` resolves it again), so the + * cache turns those repeats into map hits. It is never refreshed, so create + * one per scan rather than sharing it across runs. + */ +export interface DepDirCache { + /** `existsSync` result per `node_modules` directory. */ + nodeModulesDirs: Map + /** Resolution result per `node_modules/` candidate path. */ + candidates: Map + /** Real directory per resolved symlink target, shared by every link to it. */ + targets: Map +} + +export function createDepDirCache(): DepDirCache { + return { + nodeModulesDirs: new Map(), + candidates: new Map(), + targets: new Map(), + } +} + +function hasNodeModulesDir(dir: string, cache: DepDirCache): boolean { + let exists = cache.nodeModulesDirs.get(dir) + if (exists === undefined) { + exists = existsSync(dir) + cache.nodeModulesDirs.set(dir, exists) + } + return exists +} + +/** + * Resolve one `node_modules/` candidate to its real directory, or null + * when no package is installed there. + * + * `readlink` is the first probe because it is the cheapest call that also + * tells symlinks apart: a stat that traverses a pnpm virtual-store link costs + * several times more than reading the link. Real directories (npm and Yarn + * hoisting) make it fail with EINVAL and are then checked directly; a missing + * entry fails with ENOENT. + */ +function resolveCandidateDir( + candidate: string, + cache: DepDirCache, +): string | null { + let target: string | null + try { + target = readlinkSync(candidate) + } catch (err) { + if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null + target = null + } + + if (target === null) { + return existsSync(join(candidate, 'package.json')) ? candidate : null + } + + const resolvedTarget = resolve( + dirname(candidate), + normalizeReadlinkTarget(target), + ) + let real = cache.targets.get(resolvedTarget) + if (real === undefined) { + real = existsSync(join(resolvedTarget, 'package.json')) + ? resolveRealDir(resolvedTarget) + : null + cache.targets.set(resolvedTarget, real) + } + return real +} + +/** + * Collapse a symlinked directory to its real path with one `lstat` and, only + * when needed, one native `realpath` call. Non-links are returned as-is. + */ +function resolveRealDir(dir: string): string { + try { + return lstatSync(dir).isSymbolicLink() ? realpathSync.native(dir) : dir + } catch { + return dir + } +} diff --git a/packages/intent/src/shared/paths.ts b/packages/intent/src/shared/paths.ts new file mode 100644 index 00000000..cfd23dc6 --- /dev/null +++ b/packages/intent/src/shared/paths.ts @@ -0,0 +1,37 @@ +import { isAbsolute, relative, sep } from 'node:path' + +export function isWithinOrEqual(path: string, parentDir: string): boolean { + const rel = relative(parentDir, path) + return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)) +} + +export function toPosixPath(p: string): string { + return p.split(sep).join('/') +} + +/** + * Check whether a skill path belongs to the default skill discovery tree. + * + * Hidden directories and node_modules are excluded from default discovery, + * while explicitly declared or custom-root skills can still be handled by + * their respective discovery paths. + */ +export function isDefaultSkillPath(path: string): boolean { + return !path + .split('/') + .some((part) => part.startsWith('.') || part === 'node_modules') +} + +/** + * Strip the Windows extended-length prefix that `readlink` can report for + * junction targets. `\\?\C:\dir` becomes `C:\dir`; `\\?\UNC\server\share` + * becomes `\\server\share` so the UNC root stays absolute. Other targets, + * including relative POSIX links, are returned unchanged. + */ +export function normalizeReadlinkTarget(target: string): string { + if (target.startsWith('\\\\?\\UNC\\')) { + return `\\\\${target.slice(8)}` + } + if (target.startsWith('\\\\?\\')) return target.slice(4) + return target +} diff --git a/packages/intent/src/shared/skill-files.ts b/packages/intent/src/shared/skill-files.ts new file mode 100644 index 00000000..259f4b54 --- /dev/null +++ b/packages/intent/src/shared/skill-files.ts @@ -0,0 +1,62 @@ +import { join } from 'node:path' +import { nodeReadFs } from './fs-identity.js' +import type { Dirent } from 'node:fs' +import type { ReadFs } from './fs-identity.js' + +/** + * Recursively find all SKILL.md files under a directory. + */ +export function findSkillFiles( + dir: string, + fs: ReadFs = nodeReadFs, +): Array { + const files: Array = [] + collectSkillFiles(dir, fs, files) + return files +} + +function collectSkillFiles( + dir: string, + fs: ReadFs, + files: Array, +): void { + let entries: Array> + try { + entries = fs.readdirSync(dir, { withFileTypes: true, encoding: 'utf8' }) + } catch { + return + } + + for (const entry of entries) { + const fullPath = join(dir, entry.name) + if (entry.isDirectory()) { + collectSkillFiles(fullPath, fs, files) + } else if (entry.name === 'SKILL.md') { + files.push(fullPath) + } + } +} + +/** + * Like `findSkillFiles`, but stops at the first SKILL.md found instead of + * enumerating the whole tree. + */ +export function hasAnySkillFile(dir: string, fs: ReadFs = nodeReadFs): boolean { + let entries: Array> + try { + entries = fs.readdirSync(dir, { withFileTypes: true, encoding: 'utf8' }) + } catch { + return false + } + + for (const entry of entries) { + const fullPath = join(dir, entry.name) + if (entry.isDirectory()) { + if (hasAnySkillFile(fullPath, fs)) return true + } else if (entry.name === 'SKILL.md') { + return true + } + } + + return false +} diff --git a/packages/intent/src/shared/utils.ts b/packages/intent/src/shared/utils.ts deleted file mode 100644 index e9ca09bd..00000000 --- a/packages/intent/src/shared/utils.ts +++ /dev/null @@ -1,558 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { - closeSync, - existsSync, - fstatSync, - lstatSync, - openSync, - readFileSync, - readSync, - readdirSync, - readlinkSync, - realpathSync, -} from 'node:fs' -import { - basename, - dirname, - isAbsolute, - join, - relative, - resolve, - sep, -} from 'node:path' -import { parse as parseYaml } from 'yaml' -import type { Dirent } from 'node:fs' - -/** - * The subset of `node:fs` the scanner reads through. Under Yarn PnP this is - * swapped for Yarn's libzip-patched `fs` so reads can reach files inside - * `.yarn/cache/*.zip` (see scanner `loadPnpApi`). The static `node:fs` named - * imports cannot be used directly for that, because their bindings are captured - * before Yarn's `setup()` patches the CommonJS `fs` module. - */ -export interface ReadFs { - existsSync: typeof existsSync - lstatSync: typeof lstatSync - readFileSync: typeof readFileSync - readdirSync: typeof readdirSync - realpathSync: typeof realpathSync - /** - * Optional low-level read primitives. When present (always on `node:fs` and - * Yarn's libzip-patched module) `parseFrontmatter` reads only the leading - * region of a file instead of its whole body. - */ - openSync?: typeof openSync - readSync?: typeof readSync - closeSync?: typeof closeSync - fstatSync?: typeof fstatSync -} - -export const nodeReadFs: ReadFs = { - existsSync, - lstatSync, - readFileSync, - readdirSync, - realpathSync, - openSync, - readSync, - closeSync, - fstatSync, -} - -export function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -export function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error) -} - -export function stringArray(value: unknown): Array { - return Array.isArray(value) - ? value.filter((entry): entry is string => typeof entry === 'string') - : [] -} - -export function isWithinOrEqual(path: string, parentDir: string): boolean { - const rel = relative(parentDir, path) - return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel)) -} - -export function toPosixPath(p: string): string { - return p.split(sep).join('/') -} - -/** - * Check whether a skill path belongs to the default skill discovery tree. - * - * Hidden directories and node_modules are excluded from default discovery, - * while explicitly declared or custom-root skills can still be handled by - * their respective discovery paths. - */ -export function isDefaultSkillPath(path: string): boolean { - return !path - .split('/') - .some((part) => part.startsWith('.') || part === 'node_modules') -} - -export interface FsIdentityResolver { - (path: string): string - /** - * Record that `realPath` is already an identity (not a symlink), so a later - * lookup returns it without an `lstat`. Callers use this for directories - * they have just resolved through `resolveDepDir`. - */ - prime: (realPath: string) => void -} - -export function createFsIdentityCache( - getFs: () => ReadFs = () => nodeReadFs, -): FsIdentityResolver { - const cache = new Map() - - const getIdentity = ((path: string): string => { - const resolved = resolve(path) - const cached = cache.get(resolved) - if (cached) return cached - - const fs = getFs() - let identity: string - try { - identity = fs.lstatSync(resolved).isSymbolicLink() - ? fs.realpathSync(resolved) - : resolved - } catch { - identity = resolved - } - - cache.set(resolved, identity) - return identity - }) as FsIdentityResolver - - getIdentity.prime = (realPath: string): void => { - const resolved = resolve(realPath) - if (!cache.has(resolved)) cache.set(resolved, resolved) - } - - return getIdentity -} - -/** - * Recursively find all SKILL.md files under a directory. - */ -export function findSkillFiles( - dir: string, - fs: ReadFs = nodeReadFs, -): Array { - const files: Array = [] - collectSkillFiles(dir, fs, files) - return files -} - -function collectSkillFiles( - dir: string, - fs: ReadFs, - files: Array, -): void { - let entries: Array> - try { - entries = fs.readdirSync(dir, { withFileTypes: true, encoding: 'utf8' }) - } catch { - return - } - - for (const entry of entries) { - const fullPath = join(dir, entry.name) - if (entry.isDirectory()) { - collectSkillFiles(fullPath, fs, files) - } else if (entry.name === 'SKILL.md') { - files.push(fullPath) - } - } -} - -/** - * Like `findSkillFiles`, but stops at the first SKILL.md found instead of - * enumerating the whole tree. - */ -export function hasAnySkillFile(dir: string, fs: ReadFs = nodeReadFs): boolean { - let entries: Array> - try { - entries = fs.readdirSync(dir, { withFileTypes: true, encoding: 'utf8' }) - } catch { - return false - } - - for (const entry of entries) { - const fullPath = join(dir, entry.name) - if (entry.isDirectory()) { - if (hasAnySkillFile(fullPath, fs)) return true - } else if (entry.name === 'SKILL.md') { - return true - } - } - - return false -} - -/** - * Read dependencies and peerDependencies (and optionally devDependencies) from - * a parsed package.json object. - */ -export function getDeps( - pkgJson: Record, - includeDevDeps = false, -): Array { - const deps = new Set() - const fields = includeDevDeps - ? ['dependencies', 'devDependencies', 'peerDependencies'] - : ['dependencies', 'peerDependencies'] - for (const field of fields) { - const d = pkgJson[field] - if (d && typeof d === 'object') { - for (const name of Object.keys(d)) { - deps.add(name) - } - } - } - return [...deps] -} - -function readPackageEntries(dir: string): Array> { - try { - return readdirSync(dir, { withFileTypes: true, encoding: 'utf8' }).filter( - (entry) => entry.isDirectory() || entry.isSymbolicLink(), - ) - } catch { - return [] - } -} - -function forEachPackageDir( - nodeModulesDir: string, - visit: (packageDir: string) => void, -): void { - for (const entry of readPackageEntries(nodeModulesDir)) { - const dirPath = join(nodeModulesDir, entry.name) - if (entry.name.startsWith('@')) { - for (const scoped of readPackageEntries(dirPath)) { - visit(join(dirPath, scoped.name)) - } - } else if (!entry.name.startsWith('.')) { - visit(dirPath) - } - } -} - -export function listNodeModulesPackageDirs( - nodeModulesDir: string, -): Array { - const packageDirs: Array = [] - forEachPackageDir(nodeModulesDir, (dir) => packageDirs.push(dir)) - return packageDirs -} - -export function listNestedNodeModulesPackageDirs( - nodeModulesDir: string, - getFsIdentity: (path: string) => string, -): Array { - const packageDirs: Array = [] - const visitedNodeModulesDirs = new Set() - const visitedPackageDirs = new Set() - - function addPackageDir(packageDir: string): void { - const key = getFsIdentity(packageDir) - if (visitedPackageDirs.has(key)) return - visitedPackageDirs.add(key) - - if (existsSync(join(packageDir, 'package.json'))) { - packageDirs.push(packageDir) - } - - scanNodeModulesDir(join(packageDir, 'node_modules')) - } - - function scanNodeModulesDir(dir: string): void { - const key = getFsIdentity(dir) - if (visitedNodeModulesDirs.has(key)) return - visitedNodeModulesDirs.add(key) - forEachPackageDir(dir, addPackageDir) - } - - scanNodeModulesDir(nodeModulesDir) - return packageDirs -} - -const GLOBAL_NODE_MODULES_COMMAND_TIMEOUT_MS = 5_000 - -export function detectGlobalNodeModules(packageManager: string): { - path: string | null - source?: string -} { - const commands: Array<{ - command: string - args: Array - transform?: (output: string) => string - }> = [] - - if (packageManager === 'pnpm') { - commands.push({ command: 'pnpm', args: ['root', '-g'] }) - } - if (packageManager === 'yarn') { - commands.push({ - command: 'yarn', - args: ['global', 'dir'], - transform: (output) => join(output, 'node_modules'), - }) - } - commands.push({ command: 'npm', args: ['root', '-g'] }) - - for (const candidate of commands) { - try { - const output = execFileSync(candidate.command, candidate.args, { - encoding: 'utf8', - stdio: ['ignore', 'pipe', 'ignore'], - timeout: GLOBAL_NODE_MODULES_COMMAND_TIMEOUT_MS, - }).trim() - if (!output) continue - - return { - path: candidate.transform ? candidate.transform(output) : output, - source: `${candidate.command} ${candidate.args.join(' ')}`, - } - } catch { - continue - } - } - - return { path: null } -} - -/** - * Resolve the directory of a dependency by name by walking up from - * `parentDir` and checking `node_modules//package.json` at each - * ancestor, the same lookup order Node uses. A symlinked match (pnpm's - * virtual store, workspace links) is collapsed to its real directory so - * callers see one identity per installed package. - * - * This deliberately avoids `createRequire().resolve`: Node's resolver - * evaluates export maps, reads the nearest package.json, and realpaths every - * path segment on each call. In a pnpm monorepo that dominated scan time, and - * the walk below already covers every layout the resolver handled (nested, - * hoisted, and virtual-store siblings) without executing package code. - */ -export function resolveDepDir( - depName: string, - parentDir: string, - cache: DepDirCache = createDepDirCache(), -): string | null { - let dir = parentDir - let prev: string | undefined - while (dir !== prev) { - // Node skips ancestors that are themselves node_modules directories - // (`.../node_modules/node_modules/` is never a valid location). - if (basename(dir) !== 'node_modules') { - const nodeModulesDir = join(dir, 'node_modules') - if (hasNodeModulesDir(nodeModulesDir, cache)) { - const candidate = join(nodeModulesDir, depName) - let resolved = cache.candidates.get(candidate) - if (resolved === undefined) { - resolved = resolveCandidateDir(candidate, cache) - cache.candidates.set(candidate, resolved) - } - if (resolved) return resolved - } - } - prev = dir - dir = dirname(dir) - } - - return null -} - -/** - * Memo for `resolveDepDir` across one scan. A dependency graph revisits the - * same `node_modules` directories, candidate paths, and symlink targets many - * times (every package that depends on `semver` resolves it again), so the - * cache turns those repeats into map hits. It is never refreshed, so create - * one per scan rather than sharing it across runs. - */ -export interface DepDirCache { - /** `existsSync` result per `node_modules` directory. */ - nodeModulesDirs: Map - /** Resolution result per `node_modules/` candidate path. */ - candidates: Map - /** Real directory per resolved symlink target, shared by every link to it. */ - targets: Map -} - -export function createDepDirCache(): DepDirCache { - return { - nodeModulesDirs: new Map(), - candidates: new Map(), - targets: new Map(), - } -} - -function hasNodeModulesDir(dir: string, cache: DepDirCache): boolean { - let exists = cache.nodeModulesDirs.get(dir) - if (exists === undefined) { - exists = existsSync(dir) - cache.nodeModulesDirs.set(dir, exists) - } - return exists -} - -/** - * Resolve one `node_modules/` candidate to its real directory, or null - * when no package is installed there. - * - * `readlink` is the first probe because it is the cheapest call that also - * tells symlinks apart: a stat that traverses a pnpm virtual-store link costs - * several times more than reading the link. Real directories (npm and Yarn - * hoisting) make it fail with EINVAL and are then checked directly; a missing - * entry fails with ENOENT. - */ -function resolveCandidateDir( - candidate: string, - cache: DepDirCache, -): string | null { - let target: string | null - try { - target = readlinkSync(candidate) - } catch (err) { - if ((err as NodeJS.ErrnoException).code === 'ENOENT') return null - target = null - } - - if (target === null) { - return existsSync(join(candidate, 'package.json')) ? candidate : null - } - - const resolvedTarget = resolve( - dirname(candidate), - normalizeReadlinkTarget(target), - ) - let real = cache.targets.get(resolvedTarget) - if (real === undefined) { - real = existsSync(join(resolvedTarget, 'package.json')) - ? resolveRealDir(resolvedTarget) - : null - cache.targets.set(resolvedTarget, real) - } - return real -} - -/** - * Strip the Windows extended-length prefix that `readlink` can report for - * junction targets. `\\?\C:\dir` becomes `C:\dir`; `\\?\UNC\server\share` - * becomes `\\server\share` so the UNC root stays absolute. Other targets, - * including relative POSIX links, are returned unchanged. - */ -export function normalizeReadlinkTarget(target: string): string { - if (target.startsWith('\\\\?\\UNC\\')) { - return `\\\\${target.slice(8)}` - } - if (target.startsWith('\\\\?\\')) return target.slice(4) - return target -} - -/** - * Collapse a symlinked directory to its real path with one `lstat` and, only - * when needed, one native `realpath` call. Non-links are returned as-is. - */ -function resolveRealDir(dir: string): string { - try { - return lstatSync(dir).isSymbolicLink() ? realpathSync.native(dir) : dir - } catch { - return dir - } -} - -/** - * Read a scalar string field from frontmatter, preferring `metadata.` over - * a top-level `` (#159 back-compat for the frontmatter migration). - */ -export function readScalarField( - fm: Record | null | undefined, - key: string, -): string | undefined { - const metadata = fm?.metadata - if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) { - const nested = (metadata as Record)[key] - if (typeof nested === 'string') return nested - } - const top = fm?.[key] - return typeof top === 'string' ? top : undefined -} - -/** - * Parse YAML frontmatter from a path or caller-owned descriptor at offset zero. - * Returns null if no frontmatter or on error; caller-owned descriptors stay open. - */ -export function parseFrontmatter( - filePath: string | number, - fs: ReadFs = nodeReadFs, -): Record | null { - const content = readFrontmatterRegion(filePath, fs) - if (content === null) return null - const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/) - if (!match?.[1]) return null - try { - return parseYaml(match[1]) as Record - } catch { - return null - } -} - -/** Max bytes read when probing a file's leading frontmatter region. */ -const FRONTMATTER_READ_LIMIT = 16 * 1024 -/** Reused across calls; safe because reads are synchronous and single-threaded. */ -const frontmatterBuffer = Buffer.allocUnsafe(FRONTMATTER_READ_LIMIT) - -/** - * Read just the leading region of a file, enough to cover its frontmatter, - * instead of its whole body. Falls back to a full read when the bounded read - * primitives are unavailable or the frontmatter exceeds the probe limit. - */ -function readFrontmatterRegion( - filePath: string | number, - fs: ReadFs, -): string | null { - if (fs.openSync && fs.readSync && fs.closeSync) { - let fd: number - try { - fd = typeof filePath === 'number' ? filePath : fs.openSync(filePath, 'r') - } catch { - return null - } - try { - const bytesRead = fs.readSync( - fd, - frontmatterBuffer, - 0, - FRONTMATTER_READ_LIMIT, - 0, - ) - const region = frontmatterBuffer.toString('utf8', 0, bytesRead) - // A full buffer means the file may extend past the probe window; only - // trust the bounded read when it captured the closing fence. - const truncated = - bytesRead === FRONTMATTER_READ_LIMIT && - !/\r?\n---/.test(region.slice(3)) - // The positional probe leaves the descriptor at offset zero. Keep the - // full-read fallback on that descriptor so replacement cannot redirect it. - return truncated ? fs.readFileSync(fd, 'utf8') : region - } catch { - return null - } finally { - if (typeof filePath !== 'number') fs.closeSync(fd) - } - } - - try { - return fs.readFileSync(filePath, 'utf8') - } catch { - return null - } -} diff --git a/packages/intent/src/skills/paths.ts b/packages/intent/src/skills/paths.ts index f4a6f30a..cf79e46f 100644 --- a/packages/intent/src/skills/paths.ts +++ b/packages/intent/src/skills/paths.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs' import { join, relative } from 'node:path' -import { toPosixPath } from '../shared/utils.js' +import { toPosixPath } from '../shared/paths.js' import { formatIntentCommand } from '../shared/command-runner.js' import type { SkillUse } from './use.js' import type { SkillEntry } from '../shared/types.js' diff --git a/packages/intent/src/staleness/artifact-coverage.ts b/packages/intent/src/staleness/artifact-coverage.ts index a7e1e9ab..c61624b4 100644 --- a/packages/intent/src/staleness/artifact-coverage.ts +++ b/packages/intent/src/staleness/artifact-coverage.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs' import { join } from 'node:path' import { parse as parseYaml } from 'yaml' -import { errorMessage, isRecord, stringArray } from '../shared/utils.js' +import { errorMessage, isRecord, stringArray } from '../shared/guards.js' import type { IntentArtifactCoverageIgnore, IntentArtifactFile, diff --git a/packages/intent/src/staleness/check.ts b/packages/intent/src/staleness/check.ts index dfc8d5c1..f7bcdf44 100644 --- a/packages/intent/src/staleness/check.ts +++ b/packages/intent/src/staleness/check.ts @@ -7,11 +7,8 @@ import gt from 'semver/functions/gt.js' import parse from 'semver/functions/parse.js' import valid from 'semver/functions/valid.js' import { createIntentFsCache } from '../discovery/fs-cache.js' -import { - parseFrontmatter, - readScalarField, - toPosixPath, -} from '../shared/utils.js' +import { toPosixPath } from '../shared/paths.js' +import { parseFrontmatter, readScalarField } from '../shared/frontmatter.js' import { readIntentArtifacts } from './artifact-coverage.js' import type { IntentFsCache } from '../discovery/fs-cache.js' import type { diff --git a/packages/intent/src/validate/blocks.ts b/packages/intent/src/validate/blocks.ts index e65c41df..76790777 100644 --- a/packages/intent/src/validate/blocks.ts +++ b/packages/intent/src/validate/blocks.ts @@ -6,12 +6,8 @@ import { pathToFileURL } from 'node:url' import { resolveProjectContext } from '../core/project-context.js' import { createIntentFsCache } from '../discovery/fs-cache.js' import { resolveWorkspacePackages } from '../core/workspace-patterns.js' -import { - errorMessage, - isRecord, - parseFrontmatter, - readScalarField, -} from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' +import { parseFrontmatter, readScalarField } from '../shared/frontmatter.js' import type TS from 'typescript' import type { IntentFsCache } from '../discovery/fs-cache.js' import type * as NativeApi from 'typescript7/unstable/async' diff --git a/packages/intent/src/validate/repairs.ts b/packages/intent/src/validate/repairs.ts index fcb2268a..92dd620a 100644 --- a/packages/intent/src/validate/repairs.ts +++ b/packages/intent/src/validate/repairs.ts @@ -1,7 +1,7 @@ import { basename, dirname } from 'node:path' import { isDeepStrictEqual } from 'node:util' import { parseDocument } from 'yaml' -import { errorMessage, isRecord } from '../shared/utils.js' +import { errorMessage, isRecord } from '../shared/guards.js' import type { FileChange } from '../maintainer/files.js' export const agentSkillNamePattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/ diff --git a/packages/intent/tests/discovery-safety.test.ts b/packages/intent/tests/discovery-safety.test.ts index c197b1ee..48ca8afe 100644 --- a/packages/intent/tests/discovery-safety.test.ts +++ b/packages/intent/tests/discovery-safety.test.ts @@ -18,7 +18,7 @@ import { listIntentSkills, loadIntentSkill } from '../src/core/index.js' import { scanForIntents } from '../src/discovery/scanner.js' import { buildIntentSkillsBlock } from '../src/commands/install/guidance.js' import { formatRuntimeSkillLookupHint } from '../src/skills/paths.js' -import { nodeReadFs } from '../src/shared/utils.js' +import { nodeReadFs } from '../src/shared/fs-identity.js' import { formatIntentCommand } from '../src/shared/command-runner.js' import type { Stats } from 'node:fs' diff --git a/packages/intent/tests/integration/distribution-installers.test.ts b/packages/intent/tests/integration/distribution-installers.test.ts index e83d67e2..f241213a 100644 --- a/packages/intent/tests/integration/distribution-installers.test.ts +++ b/packages/intent/tests/integration/distribution-installers.test.ts @@ -11,7 +11,7 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' import { expect, it } from 'vitest' -import { parseFrontmatter } from '../../src/shared/utils.js' +import { parseFrontmatter } from '../../src/shared/frontmatter.js' const gh = process.env.INTENT_GH_SKILL_BIN const skills = process.env.INTENT_SKILLS_BIN diff --git a/packages/intent/tests/parse-frontmatter.test.ts b/packages/intent/tests/parse-frontmatter.test.ts index 182e2c62..07f08201 100644 --- a/packages/intent/tests/parse-frontmatter.test.ts +++ b/packages/intent/tests/parse-frontmatter.test.ts @@ -2,7 +2,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { parseFrontmatter } from '../src/shared/utils.js' +import { parseFrontmatter } from '../src/shared/frontmatter.js' let root: string diff --git a/packages/intent/tests/read-scalar-field.test.ts b/packages/intent/tests/read-scalar-field.test.ts index 461d81f1..8841b6b5 100644 --- a/packages/intent/tests/read-scalar-field.test.ts +++ b/packages/intent/tests/read-scalar-field.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { readScalarField } from '../src/shared/utils.js' +import { readScalarField } from '../src/shared/frontmatter.js' describe('readScalarField', () => { it('reads a top-level scalar (old shape)', () => { diff --git a/packages/intent/tests/repeated-work.test.ts b/packages/intent/tests/repeated-work.test.ts index d42fee1e..9c61ae65 100644 --- a/packages/intent/tests/repeated-work.test.ts +++ b/packages/intent/tests/repeated-work.test.ts @@ -23,7 +23,7 @@ import { } from '../src/core/index.js' import { rewriteLoadedSkillMarkdownDestinations } from '../src/core/markdown.js' import { checkStaleness } from '../src/staleness/check.js' -import { nodeReadFs } from '../src/shared/utils.js' +import { nodeReadFs } from '../src/shared/fs-identity.js' import type * as NodeFs from 'node:fs' import type * as NodePath from 'node:path' diff --git a/packages/intent/tests/resolve-dep-dir.test.ts b/packages/intent/tests/resolve-dep-dir.test.ts index c4feb424..ac48fc27 100644 --- a/packages/intent/tests/resolve-dep-dir.test.ts +++ b/packages/intent/tests/resolve-dep-dir.test.ts @@ -9,11 +9,8 @@ import { import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' -import { - createDepDirCache, - normalizeReadlinkTarget, - resolveDepDir, -} from '../src/shared/utils.js' +import { normalizeReadlinkTarget } from '../src/shared/paths.js' +import { createDepDirCache, resolveDepDir } from '../src/shared/node-modules.js' let root: string diff --git a/packages/intent/tests/skills.test.ts b/packages/intent/tests/skills.test.ts index 97c83e42..44231e4b 100644 --- a/packages/intent/tests/skills.test.ts +++ b/packages/intent/tests/skills.test.ts @@ -1,7 +1,7 @@ import { join, relative, sep } from 'node:path' import { describe, expect, it } from 'vitest' import { runValidateCommand } from '../src/commands/validate.js' -import { findSkillFiles } from '../src/shared/utils.js' +import { findSkillFiles } from '../src/shared/skill-files.js' const META_DIR = join(__dirname, '..', 'meta') From b9d6299e399d25503aa9deb93716ef4995e70200 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 12:03:50 -0700 Subject: [PATCH 11/12] refactor: keep the base package.json read in setup setup stopped with an error on a workspace package whose package.json is not an object. The cleanup read such a file as empty and carried on. Read it as before so setup output does not change. --- packages/intent/src/setup/project-setup.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/intent/src/setup/project-setup.ts b/packages/intent/src/setup/project-setup.ts index f25e75a3..1a5b041d 100644 --- a/packages/intent/src/setup/project-setup.ts +++ b/packages/intent/src/setup/project-setup.ts @@ -104,8 +104,7 @@ function deriveWorkspacePackageName( function readPackageJson(root: string): Record { const pkgPath = join(root, 'package.json') try { - const parsed: unknown = JSON.parse(readFileSync(pkgPath, 'utf8')) - return isRecord(parsed) ? parsed : {} + return JSON.parse(readFileSync(pkgPath, 'utf8')) as Record } catch (err: unknown) { const isNotFound = err && @@ -165,7 +164,7 @@ function buildWatchPaths(root: string, packageDirs: Array): string { paths.add(`${relDir}/src/**`) } - const { intent } = readPackageJson(packageDir) + const intent = readPackageJson(packageDir).intent const docs = isRecord(intent) && typeof intent.docs === 'string' ? intent.docs From 63fc7e4b4c4a52826e7b1c506ac13d93e38919c6 Mon Sep 17 00:00:00 2001 From: ladybluenotes Date: Sun, 22 Nov 2026 12:04:02 -0700 Subject: [PATCH 12/12] chore: add changesets for the source cleanup and meta skill wording --- .changeset/remove-unused-internal-code.md | 5 +++++ .changeset/shorten-meta-skill-wording.md | 5 +++++ 2 files changed, 10 insertions(+) create mode 100644 .changeset/remove-unused-internal-code.md create mode 100644 .changeset/shorten-meta-skill-wording.md diff --git a/.changeset/remove-unused-internal-code.md b/.changeset/remove-unused-internal-code.md new file mode 100644 index 00000000..d2fc0cc9 --- /dev/null +++ b/.changeset/remove-unused-internal-code.md @@ -0,0 +1,5 @@ +--- +'@tanstack/intent': patch +--- + +Remove unused internal helpers, duplicate path and type guards, and dead branches. Move workspace resolution into `core` and split shared utilities by job. Exports and behavior do not change. diff --git a/.changeset/shorten-meta-skill-wording.md b/.changeset/shorten-meta-skill-wording.md new file mode 100644 index 00000000..bdbe21ab --- /dev/null +++ b/.changeset/shorten-meta-skill-wording.md @@ -0,0 +1,5 @@ +--- +'@tanstack/intent': patch +--- + +Shorten the wording of the bundled `domain-discovery`, `generate-skill`, `tree-generator`, and `skill-staleness-check` skills. Instructions do not change.