Skip to content

feat(@angular-devkit/schematics): add schematics to generate ai context files. #30763

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion goldens/public-api/angular_devkit/schematics/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -637,7 +637,10 @@ export enum MergeStrategy {
export function mergeWith(source: Source, strategy?: MergeStrategy): Rule;

// @public (undocumented)
export function move(from: string, to?: string): Rule;
export function move(from: string, to: string): Rule;

// @public (undocumented)
export function move(to: string): Rule;

// @public (undocumented)
export function noop(): Rule;
Expand Down
2 changes: 2 additions & 0 deletions packages/angular_devkit/schematics/src/rules/move.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import { join, normalize } from '@angular-devkit/core';
import { Rule } from '../engine/interface';
import { noop } from './base';

export function move(from: string, to: string): Rule;
export function move(to: string): Rule;
export function move(from: string, to?: string): Rule {
if (to === undefined) {
to = from;
Expand Down
54 changes: 54 additions & 0 deletions packages/schematics/angular/config/files/__rulesName__.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<% if (frontmatter) { %><%= frontmatter %>

<% } %>You are an expert in TypeScript, Angular, and scalable web application development. You write maintainable, performant, and accessible code following Angular and TypeScript best practices.

## TypeScript Best Practices

- Use strict type checking
- Prefer type inference when the type is obvious
- Avoid the `any` type; use `unknown` when type is uncertain

## Angular Best Practices

- Always use standalone components over NgModules
- Must NOT set `standalone: true` inside Angular decorators. It's the default.
- Use signals for state management
- Implement lazy loading for feature routes
- Do NOT use the `@HostBinding` and `@HostListener` decorators. Put host bindings inside the `host` object of the `@Component` or `@Directive` decorator instead
- Use `NgOptimizedImage` for all static images.
- `NgOptimizedImage` does not work for inline base64 images.

## Components

- Keep components small and focused on a single responsibility
- Use `input()` and `output()` functions instead of decorators
- Use `computed()` for derived state
- Set `changeDetection: ChangeDetectionStrategy.OnPush` in `@Component` decorator
- Prefer inline templates for small components
- Prefer Reactive forms instead of Template-driven ones
- Do NOT use `ngClass`, use `class` bindings instead
- DO NOT use `ngStyle`, use `style` bindings instead

## State Management

- Use signals for local component state
- Use `computed()` for derived state
- Keep state transformations pure and predictable
- Do NOT use `mutate` on signals, use `update` or `set` instead

## Templates

- Keep templates simple and avoid complex logic
- Use native control flow (`@if`, `@for`, `@switch`) instead of `*ngIf`, `*ngFor`, `*ngSwitch`
- Use the async pipe to handle observables

## Services

- Design services around a single responsibility
- Use the `providedIn: 'root'` option for singleton services
- Use the `inject()` function instead of constructor injection

## Common pitfalls

- Control flow (`@if`):
- You cannot use `as` expressions in `@else if (...)`. E.g. invalid code: `@else if (bla(); as x)`.
66 changes: 66 additions & 0 deletions packages/schematics/angular/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
SchematicsException,
apply,
applyTemplates,
chain,
filter,
mergeWith,
move,
Expand All @@ -24,12 +25,40 @@ import { getWorkspace as readWorkspace, updateWorkspace } from '../utility/works
import { Builders as AngularBuilder } from '../utility/workspace-models';
import { Schema as ConfigOptions, Type as ConfigType } from './schema';

const geminiFile: ContextFileInfo = { rulesName: 'GEMINI.md', directory: '.gemini' };
const copilotFile: ContextFileInfo = {
rulesName: 'copilot-instructions.md',
directory: '.github',
};
const claudeFile: ContextFileInfo = { rulesName: 'CLAUDE.md', directory: '.claude' };
const windsurfFile: ContextFileInfo = {
rulesName: 'guidelines.md',
directory: path.join('.windsurf', 'rules'),
};

// Cursor file is a bit different, it has a front matter section.
const cursorFile: ContextFileInfo = {
rulesName: 'cursor.mdc',
directory: path.join('.cursor', 'rules'),
frontmatter: `---\ncontext: true\npriority: high\nscope: project\n---`,
};

const AI_TOOLS = {
'gemini': geminiFile,
'claude': claudeFile,
'copilot': copilotFile,
'cursor': cursorFile,
'windsurf': windsurfFile,
};

export default function (options: ConfigOptions): Rule {
switch (options.type) {
case ConfigType.Karma:
return addKarmaConfig(options);
case ConfigType.Browserslist:
return addBrowserslistConfig(options);
case ConfigType.Ai:
return addAiContextFile(options);
default:
throw new SchematicsException(`"${options.type}" is an unknown configuration file type.`);
}
Expand Down Expand Up @@ -103,3 +132,40 @@ function addKarmaConfig(options: ConfigOptions): Rule {
);
});
}

interface ContextFileInfo {
rulesName: string;
directory: string;
frontmatter?: string;
}

function addAiContextFile(options: ConfigOptions): Rule {
const selectedTool = options.tool as keyof typeof AI_TOOLS;
const files: ContextFileInfo[] =
options.tool === 'all' ? Object.values(AI_TOOLS) : [AI_TOOLS[selectedTool]];

return async (host) => {
const workspace = await readWorkspace(host);
const project = workspace.projects.get(options.project);
if (!project) {
throw new SchematicsException(`Project name "${options.project}" doesn't not exist.`);
}

const rules = files.map(({ rulesName, directory, frontmatter }) =>
mergeWith(
apply(url('./files'), [
// Keep only the single source template
filter((p) => p.endsWith('__rulesName__.template')),
applyTemplates({
...strings,
rulesName,
frontmatter: frontmatter ?? '',
}),
move(directory),
]),
),
);

return chain(rules);
};
}
41 changes: 39 additions & 2 deletions packages/schematics/angular/config/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import { SchematicTestRunner, UnitTestTree } from '@angular-devkit/schematics/testing';
import { Schema as ApplicationOptions } from '../application/schema';
import { Schema as WorkspaceOptions } from '../workspace/schema';
import { Schema as ConfigOptions, Type as ConfigType } from './schema';
import { Schema as ConfigOptions, Tool as ConfigTool, Type as ConfigType } from './schema';

describe('Config Schematic', () => {
const schematicRunner = new SchematicTestRunner(
Expand All @@ -32,12 +32,15 @@ describe('Config Schematic', () => {
};

let applicationTree: UnitTestTree;
function runConfigSchematic(type: ConfigType): Promise<UnitTestTree> {
function runConfigSchematic(type: ConfigType, tool?: ConfigTool): Promise<UnitTestTree>;
function runConfigSchematic(type: ConfigType.Ai, tool: ConfigTool): Promise<UnitTestTree>;
function runConfigSchematic(type: ConfigType, tool?: ConfigTool): Promise<UnitTestTree> {
return schematicRunner.runSchematic<ConfigOptions>(
'config',
{
project: 'foo',
type,
tool,
},
applicationTree,
);
Expand Down Expand Up @@ -97,4 +100,38 @@ describe('Config Schematic', () => {
expect(tree.readContent('projects/foo/.browserslistrc')).toContain('Chrome >=');
});
});

describe(`when 'type' is 'ai'`, () => {
it('should create a GEMINI.MD file', async () => {
const tree = await runConfigSchematic(ConfigType.Ai, ConfigTool.Gemini);
expect(tree.readContent('.gemini/GEMINI.md')).toMatch(/^You are an expert in TypeScript/);
});

it('should create a copilot-instructions.md file', async () => {
const tree = await runConfigSchematic(ConfigType.Ai, ConfigTool.Copilot);
expect(tree.readContent('.github/copilot-instructions.md')).toContain(
'You are an expert in TypeScript',
);
});

it('should create a cursor file', async () => {
const tree = await runConfigSchematic(ConfigType.Ai, ConfigTool.Cursor);
const cursorFile = tree.readContent('.cursor/rules/cursor.mdc');
expect(cursorFile).toContain('You are an expert in TypeScript');
expect(cursorFile).toContain('context: true');
expect(cursorFile).toContain('---\n\nYou are an expert in TypeScript');
});

it('should create a windsurf file', async () => {
const tree = await runConfigSchematic(ConfigType.Ai, ConfigTool.Windsurf);
expect(tree.readContent('.windsurf/rules/guidelines.md')).toContain(
'You are an expert in TypeScript',
);
});

it('should create a claude file', async () => {
const tree = await runConfigSchematic(ConfigType.Ai, ConfigTool.Claude);
expect(tree.readContent('.claude/CLAUDE.md')).toContain('You are an expert in TypeScript');
});
});
});
27 changes: 25 additions & 2 deletions packages/schematics/angular/config/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,36 @@
"type": {
"type": "string",
"description": "Specifies the type of configuration file to generate.",
"enum": ["karma", "browserslist"],
"enum": ["karma", "browserslist", "ai"],
"x-prompt": "Which type of configuration file would you like to create?",
"$default": {
"$source": "argv",
"index": 0
}
},
"tool": {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be a multi-select prompt?
We could still default to having them all selected. Would need to change the type to a string array though. But it's probably unlikely that everyone would want all available tools when not specifying the option. Especially since the option may not be known to even exist.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As mentionned by @alan-agius4 here, the prompt would show for the others options. Or do you have an alternative in mind ?

"type": "string",
"description": "Specifies the AI tool to configure when type is 'ai'.",
"enum": ["gemini", "copilot", "claude", "cursor", "windsurf", "all", "none"]
}
},
"required": ["project", "type"]
"required": ["project", "type"],
"allOf": [
{
"if": {
"properties": {
"type": {
"not": {
"const": "ai"
}
}
}
},
"then": {
"not": {
"required": ["tool"]
}
}
}
]
}
8 changes: 8 additions & 0 deletions packages/schematics/angular/ng-new/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
RepositoryInitializerTask,
} from '@angular-devkit/schematics/tasks';
import { Schema as ApplicationOptions } from '../application/schema';
import { Tool as AiTool, Schema as ConfigOptions, Type as ConfigType } from '../config/schema';
import { Schema as WorkspaceOptions } from '../workspace/schema';
import { Schema as NgNewOptions } from './schema';

Expand Down Expand Up @@ -60,11 +61,18 @@ export default function (options: NgNewOptions): Rule {
zoneless: options.zoneless,
};

const configOptions: ConfigOptions = {
project: options.name,
type: ConfigType.Ai,
tool: options.aiConfig as unknown as AiTool,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure why I couldn't get the enums to match. It works fine for the packageManager above for example. (Yes I also tried with removing "none" from the enum here in ng-new).

};

return chain([
mergeWith(
apply(empty(), [
schematic('workspace', workspaceOptions),
options.createApplication ? schematic('application', applicationOptions) : noop,
options.aiConfig !== "none" ? schematic('config', configOptions) : noop,
move(options.directory),
]),
),
Expand Down
9 changes: 9 additions & 0 deletions packages/schematics/angular/ng-new/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,13 @@ describe('Ng New Schematic', () => {
const { cli } = JSON.parse(tree.readContent('/bar/angular.json'));
expect(cli.packageManager).toBe('npm');
});

it('should add ai config file when aiConfig is set', async () => {
const options = { ...defaultOptions, aiConfig: 'gemini' };

const tree = await schematicRunner.runSchematic('ng-new', options);
const files = tree.files;
expect(files).toContain('/bar/.gemini/GEMINI.md');
expect(tree.readContent('/bar/.gemini/GEMINI.md')).toMatch(/^You are an expert in TypeScript/);
Comment on lines +112 to +113
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dgp1130 Is this the location we would want or the workspace root ?

});
});
6 changes: 6 additions & 0 deletions packages/schematics/angular/ng-new/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,12 @@
"x-prompt": "Do you want to create a 'zoneless' application without zone.js (Developer Preview)?",
"type": "boolean",
"default": false
},
"aiConfig": {
"description": "Create an AI configuration file for the project. This file is used to improve the outputs of AI tools by following the best practices.",
"default": "none",
"type": "string",
"enum": ["gemini", "copilot", "claude", "cursor", "windsurf", "all", "none"]
}
},
"required": ["name", "version"]
Expand Down
Loading