maestrokit 0.0.0-stage → 0.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +107 -2
  3. package/THIRD_PARTY.md +13 -0
  4. package/agents/tester/mk-tester.md +20 -0
  5. package/agents/tester/skills/mk-test/SKILL.md +32 -0
  6. package/commands/mk-feat-notest.md +23 -0
  7. package/commands/mk-feat.md +57 -0
  8. package/dist/cli.js +47 -0
  9. package/dist/main.js +2549 -0
  10. package/package.json +77 -4
  11. package/shared/mk-clarify/SKILL.md +43 -0
  12. package/shared/mk-implement/SKILL.md +31 -0
  13. package/shared/mk-knowledge/SKILL.md +46 -0
  14. package/shared/mk-plan/SKILL.md +53 -0
  15. package/shared/mk-plan/references/structure-expo.md +21 -0
  16. package/shared/mk-plan/references/structure-flutter.md +22 -0
  17. package/shared/mk-plan/references/structure-rn-bare.md +22 -0
  18. package/shared/mk-rules/SKILL.md +20 -0
  19. package/tech/frameworks/flutter/flutter-core/SKILL.md +61 -0
  20. package/tech/frameworks/flutter/flutter-testing/SKILL.md +45 -0
  21. package/tech/frameworks/flutter/stack.yaml +40 -0
  22. package/tech/frameworks/react-native/expo/eas/SKILL.md +27 -0
  23. package/tech/frameworks/react-native/expo/expo-core/SKILL.md +33 -0
  24. package/tech/frameworks/react-native/expo/expo-upgrade/SKILL.md +27 -0
  25. package/tech/frameworks/react-native/rn-core/SKILL.md +60 -0
  26. package/tech/frameworks/react-native/rn-core/references/performance.md +32 -0
  27. package/tech/frameworks/react-native/rn-core/references/platform-security-a11y.md +21 -0
  28. package/tech/frameworks/react-native/rn-testing/SKILL.md +44 -0
  29. package/tech/frameworks/react-native/rn-testing/references/examples.md +49 -0
  30. package/tech/frameworks/react-native/stack.yaml +57 -0
  31. package/tech/languages/dart/dart-core/SKILL.md +49 -0
  32. package/tech/languages/dart/stack.yaml +34 -0
  33. package/tech/languages/typescript/ts-core/SKILL.md +35 -0
  34. package/tech/languages/typescript/ts-core/references/patterns.md +40 -0
@@ -0,0 +1,60 @@
1
+ ---
2
+ name: rn-core
3
+ description: Core React Native rules (components, lists, effects, platforms, theming, screen states, security, accessibility, startup). Project conventions win; these are defaults.
4
+ kind: core
5
+ tier: 2
6
+ version: 1.1.0
7
+ frameworks: [react-native]
8
+ libraries: [react-native]
9
+ inspired_by: [callstackincubator/agent-skills react-native-best-practices (MIT), expo/skills native-ui + data-fetching (MIT)]
10
+ ---
11
+
12
+ # rn-core
13
+
14
+ **Project first.** `.maestrokit/knowledge/structure.md`, the design system and the existing code patterns win. Expo-only rules (`expo/fetch`, Expo Router, `EXPO_PUBLIC_*`) live in the `expo` skill, not here.
15
+
16
+ ## Rules
17
+ - **RN-01 Components.** Use function components and hooks. All text goes inside `<Text>`.
18
+ - **RN-02 Long lists are virtualized.** For long or unknown-length data use `FlatList` / `FlashList` (whatever the project uses), never `ScrollView` + `map`. Give items stable keys.
19
+ - **RN-03 Measure before optimizing.** Do not add `useMemo`, `useCallback`, `React.memo` or state restructuring without a measured render or FPS problem. Correctness first.
20
+ - **RN-04 Clean up effects.** Every `useEffect` that subscribes, sets timers or listeners, or starts a request must clean up: unsubscribe, clear, and cancel (e.g. `AbortController`). This prevents leaks and state updates after unmount.
21
+ - **RN-05 Platforms.**
22
+ - Handle iOS/Android differences with `Platform.select` or `.ios.tsx` / `.android.tsx` files.
23
+ - Always respect the safe area and the keyboard (`KeyboardAvoidingView` or the project's helper).
24
+ - **RN-06 Theme only.** Colors, spacing, radii and font sizes come from the theme or design-system tokens. No hard-coded values.
25
+ - **RN-07 Screen states.**
26
+ - Loading ≠ empty ≠ error.
27
+ - When a refresh fails, keep the old data and show a non-blocking error with retry.
28
+ - While submitting, disable the action and keep the user's input if it fails.
29
+ - **RN-08 (safety) Security.**
30
+ - Tokens and secrets go only in secure storage (Keychain / SecureStore, as the project uses). Never put them in AsyncStorage, plain MMKV, logs or analytics.
31
+ - No secrets in env values bundled into the app.
32
+ - **RN-09 Accessibility.**
33
+ - Touchable elements have `accessibilityRole` and an accessible label.
34
+ - Touch targets are large enough.
35
+ - State is exposed (`accessibilityState`) where it changes (disabled, selected).
36
+ - **RN-10 Startup.** Import from the module directly; avoid barrel `index.ts` re-exports on startup paths.
37
+ - **RN-11 (safety) Native changes need approval.** Do not add native libraries or edit `ios/` / `android/` config unless the approved task says so; these need pod install and a rebuild (R-SAFE-03).
38
+
39
+ ## Common choices
40
+ Used by `mk-plan` §Library choices: an installed library for the problem always wins; otherwise offer the recommendation at gate ②.
41
+ | Problem | Recommended when none installed | No library is fine when |
42
+ |---|---|---|
43
+ | Forms + validation | `react-hook-form` + `zod` | 1–2 fields, no validation rules |
44
+ | Server data / API calls | `@tanstack/react-query` + `fetch` (`axios` if installed) | one request, no cache or refetch |
45
+ | Global client state | `zustand` (`redux` / RTK if installed) | 1–2 values → React context |
46
+ | Local storage (not secret) | `@react-native-async-storage/async-storage` (`react-native-mmkv` with dev builds, when speed matters) | — |
47
+ | Secrets, tokens | Expo `expo-secure-store` · bare `react-native-keychain` | never (RN-08) |
48
+ | Navigation | Expo `expo-router` · bare `@react-navigation/native` | usually already installed |
49
+
50
+ ## Quick checks before handoff
51
+ - [ ] No `ScrollView` + `map` over long data
52
+ - [ ] Every effect with a subscription, timer or request cleans up
53
+ - [ ] No hard-coded colors or sizes; tokens only
54
+ - [ ] Loading, empty and error states handled where data loads
55
+ - [ ] No token or secret outside secure storage; nothing sensitive logged
56
+ - [ ] Interactive elements have role + label
57
+
58
+ ## References (open only when needed)
59
+ - `references/performance.md`: lists, re-renders, startup, memory (from Callstack priorities).
60
+ - `references/platform-security-a11y.md`: platform differences, secure storage, accessibility details.
@@ -0,0 +1,32 @@
1
+ # rn-core — performance reference
2
+
3
+ Source: callstackincubator/agent-skills `react-native-best-practices` (MIT), read 2026-11-25. Its priority order: FPS & re-renders (CRITICAL) · bundle size (CRITICAL) · time-to-interactive (HIGH) · native performance (HIGH) · memory (MEDIUM-HIGH) · animations (MEDIUM).
4
+
5
+ ## Workflow
6
+ Measure → optimize → re-measure → validate. If the metric did not improve, revert and try the next fix. Never optimize speculatively (RN-03).
7
+
8
+ ## Lists
9
+ - Long or unknown-length lists: `FlatList` / `FlashList` / Legend List instead of `ScrollView`.
10
+ - FlashList v2 no longer needs `estimatedItemSize`. Do not flag it as missing.
11
+ - Keep `renderItem` light and move heavy work out of it.
12
+
13
+ ## Re-renders
14
+ - Profile first (React DevTools; Metro `j` opens it).
15
+ - Cascading re-renders shown by profiling: consider the React Compiler or memoization.
16
+ - Broad store or context updates shown by profiling: use narrower subscriptions (selectors / atomic state).
17
+ - For expensive derived values that block input, use `useDeferredValue`.
18
+
19
+ ## Startup / bundle
20
+ - Import directly from source; avoid barrel imports.
21
+ - Measure the release bundle: `npx react-native bundle --dev false --minify true …` plus `source-map-explorer`.
22
+ - Measure cold starts only.
23
+ - Use native navigation primitives (react-native-screens).
24
+
25
+ ## Memory
26
+ - Clean up subscriptions, timers and listeners (RN-04).
27
+ - Cancel in-flight requests on unmount.
28
+ - Watch for closures that capture large objects in long-lived listeners.
29
+
30
+ ## Native
31
+ - Prefer async over sync native (Turbo Module) methods on hot paths.
32
+ - Run heavy native work on background threads.
@@ -0,0 +1,21 @@
1
+ # rn-core — platform, security, accessibility reference
2
+
3
+ ## Platform differences (RN-05)
4
+ - Small differences: `Platform.select({ ios: …, android: … })`, or `Platform.OS` checks.
5
+ - Large differences: separate `Component.ios.tsx` / `Component.android.tsx` with the same props type.
6
+ - Safe area: use the project's safe-area provider/hook (commonly `react-native-safe-area-context`).
7
+ - Keyboard: forms must stay visible when the keyboard opens (`KeyboardAvoidingView` with a per-platform `behavior`, or the project's helper).
8
+ - Android back button: screens with unsaved input should confirm before leaving (follow `ux-patterns.md`).
9
+
10
+ ## Security (RN-08)
11
+ - Tokens and refresh tokens: secure storage only (Keychain on iOS / Keystore-backed on Android, via the project's library, e.g. react-native-keychain or expo-secure-store).
12
+ - Plain key-value storage (AsyncStorage, MMKV without encryption) is for non-sensitive data. MMKV supports optional encryption, but keys stored in code are not secrets.
13
+ - Never log tokens, passwords, or personal data, and never put them in crash reports or analytics.
14
+ - Env values bundled into the app are public. Never put API secrets there.
15
+
16
+ ## Accessibility (RN-09)
17
+ - Buttons/links: `accessibilityRole="button" | "link"` and an `accessibilityLabel` when the visible text is not enough (icon buttons).
18
+ - Expose state: `accessibilityState={{ disabled, selected, checked }}`.
19
+ - Images that carry meaning: `accessibilityLabel`; decorative images: hidden from accessibility.
20
+ - Touch target ≥ 44×44 pt (iOS guideline) / 48×48 dp (Android); use `hitSlop` when the visual is smaller.
21
+ - These props also make components testable by role (`rn-testing` RT-02).
@@ -0,0 +1,44 @@
1
+ ---
2
+ name: rn-testing
3
+ description: How to write React Native tests with Jest + React Native Testing Library (queries, user events, async, mocks, traceability). Used by mk-tester to write and check tests; the main agent reads it to understand them.
4
+ kind: core
5
+ tier: 2
6
+ version: 1.0.0
7
+ frameworks: [react-native]
8
+ libraries: ["@testing-library/react-native", jest]
9
+ inspired_by: [React Native Testing Library docs 14.x (MIT)]
10
+ ---
11
+
12
+ # rn-testing
13
+
14
+ **Project first.** Use the project's test setup, helpers (custom `render`, providers) and mocking style. The commands come from the stack profile and `package.json` scripts.
15
+
16
+ ## Rules
17
+ - **RT-01 Test behavior, not internals.** Assert what the user sees and does. Do not assert on state variables, hook internals or private function names.
18
+ - **RT-02 Query priority.**
19
+ 1. `getByRole(role, { name })`;
20
+ 2. label / placeholder / display value;
21
+ 3. `getByText`;
22
+ 4. `getByTestId`, only when nothing else works.
23
+
24
+ Use `getBy` for one match, `getAllBy` for lists, `findBy` for async results, and `queryBy` only to assert absence.
25
+ - **RT-03 User events.** Prefer `userEvent` over `fireEvent`: `const user = userEvent.setup(); await user.press(button); await user.type(input, 'abc');`. `type` appends to existing text; call `clear` first to replace it.
26
+ - **RT-04 Async.** Use `await screen.findBy…`, not `waitFor` + `getBy…`. A `waitFor` callback holds one assertion and no side effects.
27
+ - **RT-05 No manual wrapping.** Do not wrap `render`, `fireEvent` or `userEvent` in `act`. Do not call `cleanup()`. Query through `screen`.
28
+ - **RT-06 RNTL matchers.** Use matchers like `toBeOnTheScreen()`, `toBeDisabled()`, `toHaveTextContent()`. Do not inspect props directly.
29
+ - **RT-07 Mock at boundaries.**
30
+ - Mock the network or API layer and native modules the way the project already does.
31
+ - Never mock the unit under test.
32
+ - Reset mocks between tests.
33
+ - **RT-08 Traceable names.** Each test name starts with its AC or TC ID: `it('AC2: shows email error and does not call API', …)`.
34
+ - **RT-09 Tests belong to mk-tester.** The main agent never edits, skips or weakens them (mk-rules R4). A test that looks wrong → `TEST-DISPUTE` in `status.md`.
35
+ - **RT-10 Expo projects** use the `jest-expo` preset (per platform projects if the app targets web); Expo Router screens are tested with `expo-router/testing-library` `renderRouter`; native-only Expo modules are mocked at the project's wrapper module.
36
+
37
+ ## Quick checks before handoff
38
+ - [ ] No `getByTestId` where a role or text query works
39
+ - [ ] No `act(...)` around render or events; no manual `cleanup()`
40
+ - [ ] Every test name carries an AC/TC ID
41
+ - [ ] Related tests pass: `test_related` from the stack profile
42
+
43
+ ## References (open only when needed)
44
+ - `references/examples.md`: a login form test, mocking an API hook, testing a custom hook.
@@ -0,0 +1,49 @@
1
+ # rn-testing examples
2
+
3
+ ## Form behavior (RT-02, RT-03, RT-06, RT-08)
4
+ ```tsx
5
+ import { render, screen, userEvent } from '@testing-library/react-native';
6
+ import { LoginScreen } from '../screens/LoginScreen';
7
+ import { login } from '@/api/auth';
8
+
9
+ jest.mock('@/api/auth'); // boundary mock (RT-07)
10
+
11
+ describe('LoginScreen', () => {
12
+ beforeEach(() => jest.resetAllMocks());
13
+
14
+ it('AC2: shows email error and does not call API', async () => {
15
+ const user = userEvent.setup();
16
+ render(<LoginScreen />); // use the project's custom render if it wraps providers
17
+ await user.type(screen.getByLabelText('Email'), 'not-an-email');
18
+ await user.press(screen.getByRole('button', { name: 'Log in' }));
19
+ expect(await screen.findByText('Invalid email')).toBeOnTheScreen();
20
+ expect(login).not.toHaveBeenCalled();
21
+ });
22
+
23
+ it('AC8: disables the button while the request is pending', async () => {
24
+ jest.mocked(login).mockReturnValue(new Promise(() => {})); // never resolves
25
+ const user = userEvent.setup();
26
+ render(<LoginScreen />);
27
+ await user.type(screen.getByLabelText('Email'), 'a@b.co');
28
+ await user.type(screen.getByLabelText('Password'), 'abcdefg1');
29
+ await user.press(screen.getByRole('button', { name: 'Log in' }));
30
+ expect(screen.getByRole('button', { name: 'Log in' })).toBeDisabled();
31
+ });
32
+ });
33
+ ```
34
+
35
+ ## Custom hook
36
+ ```tsx
37
+ import { renderHook, act } from '@testing-library/react-native';
38
+ // act is fine here: it wraps a direct state update outside render/events
39
+ it('TC5: toggles remember me', () => {
40
+ const { result } = renderHook(() => useRememberMe());
41
+ act(() => result.current.toggle());
42
+ expect(result.current.value).toBe(true);
43
+ });
44
+ ```
45
+
46
+ ## Absence
47
+ ```tsx
48
+ expect(screen.queryByText('Wrong email or password')).not.toBeOnTheScreen();
49
+ ```
@@ -0,0 +1,57 @@
1
+ # Stack profile — React Native (D179, D180)
2
+ # Agents and scripts read stack-specific facts from here; process skills stay stack-neutral.
3
+ # Lives in the tool repo at tech/frameworks/react-native/; `init` copies the matching profile to .maestrokit/stack.yaml.
4
+ # Generated-file rule (D167): no timestamps or random values in this file.
5
+
6
+ id: react-native
7
+ detect: # all must match
8
+ manifest: package.json
9
+ dependency: react-native
10
+ variants: # refined after detection; first match wins (D201)
11
+ expo:
12
+ detect: { dependency: expo }
13
+ workflow: # EX-02
14
+ cng: "no committed ios/ and android/ folders (native projects generated by prebuild)"
15
+ prebuild: "ios/ and android/ committed, expo present"
16
+ extra_core_skills: [expo-core] # tech/frameworks/react-native/expo/
17
+ task_skills: [eas, expo-upgrade] # loaded only when the task touches EAS or an SDK upgrade (D229)
18
+ commands:
19
+ start: "npx expo start"
20
+ install: "npx expo install {pkg}" # only after approval (R-SAFE-03)
21
+ lint: "npx expo lint {files}" # when configured; else the eslint fallback
22
+ doctor: "npx expo-doctor"
23
+ allow_commands: ["npx expo lint"] # init → .claude/settings.local.json (read-only checks only)
24
+ test_preset: jest-expo
25
+ new_project: "npx create-expo-app@latest {dir}"
26
+ navigation: expo-router # default for new Expo apps
27
+ bare:
28
+ detect: { otherwise: true } # React Native without expo; Android-only apps count too (D211)
29
+ navigation: react-navigation
30
+ language: typescript # javascript allowed; ts-core still applies to .ts/.tsx
31
+ manifest: package.json
32
+ lockfiles: [package-lock.json, yarn.lock, pnpm-lock.yaml, bun.lockb]
33
+ source_globs: ["src/**/*.{ts,tsx,js,jsx}", "app/**/*.{ts,tsx}"]
34
+ library_api_source: "node_modules/<lib>/**/*.d.ts"
35
+
36
+ commands: # detected from package.json scripts first; these are fallbacks
37
+ test_related: "npx jest --findRelatedTests {files}"
38
+ test_all: "npx jest"
39
+ lint: "npx eslint {files}"
40
+ typecheck: "npx tsc --noEmit"
41
+ test_detect: # mk-plan test-setup check (D224)
42
+ any_of: [jest.config.js, jest.config.ts, "package.json#jest"]
43
+ test_conventions: ["**/__tests__/**/*.{ts,tsx}", "**/*.test.{ts,tsx}"]
44
+
45
+ analyzer: ts-morph # planned (D227)
46
+ navigation_generator: # planned (D227)
47
+ react-navigation: "createNativeStackNavigator|createBottomTabNavigator|createDrawerNavigator"
48
+ expo-router: "app/ file routes + _layout.tsx"
49
+ ui_hardcoded_patterns: # mk-test review: hard-coded UI
50
+ - "color literals in style objects (#hex, rgb(), named colors)"
51
+ - "numeric margin/padding/fontSize not from theme tokens"
52
+ platforms: [ios, android]
53
+ build_types: [debug, release]
54
+
55
+ allow_commands: ["npx tsc", "npx jest", "npx eslint", "npm test", "npm run test", "npm run typecheck", "npm run lint"] # init → .claude/settings.local.json; never install/build/publish
56
+ core_skills: [ts-core, rn-core, rn-testing] # ts-core from tech/languages/typescript; + variant extra_core_skills
57
+ library_ecosystem: npm # tier 3 skills from tech/libraries/npm/ (installed when the manifest has the library)
@@ -0,0 +1,49 @@
1
+ ---
2
+ name: dart-core
3
+ description: Core Dart 3 rules for Flutter app code (null safety, types, async, immutability, naming, imports, errors, analyzer). Project conventions win; these are defaults.
4
+ kind: core
5
+ tier: 2
6
+ version: 1.0.0
7
+ language: dart
8
+ inspired_by: ["Effective Dart (dart.dev, CC BY 4.0)", "Dart language docs (dart.dev, CC BY 4.0)"]
9
+ ---
10
+
11
+ # dart-core
12
+
13
+ **Project first.** `analysis_options.yaml`, `.maestrokit/knowledge/structure.md` and the existing code patterns win. These rules fill the gaps.
14
+
15
+ ## Rules
16
+ - **DC-01 Sound null safety.**
17
+ - No `!` unless the value was checked just before or the API guarantees it; prefer `?.`, `??`, early return, or a local `final` that Dart can promote.
18
+ - Never use `late` only to silence the analyzer; `late` is for values set before first use (e.g. `initState`).
19
+ - **DC-02 Types at boundaries.**
20
+ - Public functions, fields and return types have explicit types.
21
+ - No `dynamic` except for decoded JSON, which is turned into a typed model at once (`fromJson`).
22
+ - Prefer `final` locals; use `var` only when the type is obvious from the right side.
23
+ - **DC-03 Async.**
24
+ - Every `Future` is awaited or passed to `unawaited(...)` on purpose; no fire-and-forget by accident.
25
+ - After an `await` in a widget, check `if (!context.mounted) return;` (or `mounted` in a `State`) before using `BuildContext`.
26
+ - Streams opened by a class are cancelled by that class.
27
+ - **DC-04 Immutability.**
28
+ - Models are immutable: `final` fields, `const` constructors where possible, changes through `copyWith`.
29
+ - Never mutate a list or map that another widget or provider also holds; build a new one.
30
+ - Value equality: use the project's approach (`==`/`hashCode`, `equatable`, `freezed`) — do not mix.
31
+ - **DC-05 Naming (Effective Dart).** `UpperCamelCase` types and extensions, `lowerCamelCase` members and constants, `snake_case` files and folders, `_` prefix = library-private. Booleans read as questions (`isLoading`, `hasError`).
32
+ - **DC-06 Imports.**
33
+ - Follow the project's style and lints (`prefer_relative_imports` or `always_use_package_imports`); without one, Effective Dart's default: relative imports inside `lib/`, `package:<app>/…` from `test/`.
34
+ - Never a relative import that climbs out of `lib/`; never mix both styles for the same file.
35
+ - Do not import another feature's private files; go through what it exposes.
36
+ - Remove unused imports.
37
+ - **DC-07 Errors.**
38
+ - Throw `Exception` subclasses for expected failures and catch them where the UI can show them; never catch `Error` (bugs) to hide it.
39
+ - No empty `catch`; log or rethrow. `on SomeException catch (e)` over a bare `catch`.
40
+ - **DC-08 Patterns and records (Dart 3).** Use `switch` expressions and sealed classes for closed sets of states, so the analyzer checks every case. Records for small multi-value returns inside a feature, not as public API.
41
+ - **DC-09 Analyzer clean.** `flutter analyze` reports nothing new. Never add `// ignore:` or relax `analysis_options.yaml` to pass.
42
+ - **DC-10 (safety) No secrets in code.** No API keys or tokens in Dart source, `--dart-define` defaults or logs.
43
+
44
+ ## Quick checks before handoff
45
+ - [ ] No unchecked `!`, no `late` used to silence the analyzer
46
+ - [ ] No `dynamic` beyond JSON decoding
47
+ - [ ] Every `Future` awaited or `unawaited`; `context.mounted` checked after `await`
48
+ - [ ] Models immutable, `copyWith` for changes
49
+ - [ ] `flutter analyze` clean for the changed files, no new `// ignore:`
@@ -0,0 +1,34 @@
1
+ # Stack profile — pure Dart package (D243: basic support)
2
+ # Agents and scripts read stack-specific facts from here; process skills stay stack-neutral.
3
+ # Lives in the tool repo at tech/languages/dart/; `init` copies it to .maestrokit/stack.yaml.
4
+ # Generated-file rule (D167): no timestamps or random values in this file.
5
+ # Detected when pubspec.yaml has no Flutter SDK dependency (Flutter apps and plugins use tech/frameworks/flutter/).
6
+
7
+ id: dart
8
+ detect:
9
+ manifest: pubspec.yaml
10
+ sdk: dart
11
+ variants:
12
+ package:
13
+ detect: { otherwise: true }
14
+ language: dart
15
+ manifest: pubspec.yaml
16
+ lockfiles: [pubspec.lock]
17
+ source_globs: ["lib/**/*.dart", "test/**/*.dart", "bin/**/*.dart"]
18
+ library_api_source: "the package's public API in the pub cache (source under lib/) or pub.dev docs for the locked version"
19
+
20
+ commands:
21
+ lint: "dart analyze" # analyzer: type errors and lints in one step
22
+ typecheck_covered_by: lint # verify prints "– typecheck covered by lint"
23
+ test_all: "dart test"
24
+ test_related: "dart test {files}"
25
+ format: "dart format {files}"
26
+ install: "dart pub add {pkg}" # only after approval at gate ②
27
+ get: "dart pub get"
28
+ test_detect: # mk-plan test-setup check (D224)
29
+ any_of: ["pubspec.yaml#dev_dependencies.test"]
30
+ test_conventions: ["test/**/*_test.dart"]
31
+
32
+ allow_commands: ["dart analyze", "dart test", "dart format"] # init → .claude/settings.local.json; never publish
33
+ core_skills: [dart-core]
34
+ library_ecosystem: pub
@@ -0,0 +1,35 @@
1
+ ---
2
+ name: ts-core
3
+ description: Core TypeScript rules for any .ts/.tsx file (types, narrowing, assertions, imports, errors). Project conventions win; these are defaults.
4
+ kind: core
5
+ tier: 2
6
+ version: 1.0.0
7
+ language: typescript # any framework using TypeScript
8
+ libraries: [typescript]
9
+ inspired_by: [Google TypeScript Style Guide (CC-BY 3.0), wshobson/agents typescript-pro (MIT)]
10
+ ---
11
+
12
+ # ts-core
13
+
14
+ **Project first.** Follow `tsconfig.json`, the lint config and `.maestrokit/knowledge/structure.md`. These rules apply only where the project says nothing.
15
+
16
+ ## Rules
17
+ - **TS-01 Keep strict.** Never relax `strict` or other compiler flags. No `// @ts-ignore`. If a suppression is truly needed, use `// @ts-expect-error <reason>`.
18
+ - **TS-02 No `any`.** For data of unknown shape use `unknown`, then narrow it with a type guard, `in`, `typeof` or a schema.
19
+ - **TS-03 Assertions are a last resort.**
20
+ - Use `as` and the non-null `!` only with an obvious reason, stated in a short comment.
21
+ - Prefer annotations (`const x: Foo = …`) over `as Foo` on object literals.
22
+ - For a double cast, go through `unknown`, never `any`.
23
+ - **TS-04 Model states as unions.** For values with several shapes, use a discriminated union (`{ status: 'loading' } | { status: 'error'; error: ApiError } | { status: 'ready'; data: T }`). Handle every case; end the `switch` with an exhaustive `never` check.
24
+ - **TS-05 Type-only imports.** Use `import type { Foo }` (or `import { type Foo, bar }`) for symbols used only as types.
25
+ - **TS-06 Errors.** Throw `Error` or a subclass, never strings or plain objects. Wrap with `{ cause }` when rethrowing. An empty `catch` needs a comment saying why.
26
+ - **TS-07 Validate at boundaries.** Check data from outside (API responses, storage, deep links, params) at the boundary, with the project's schema tool if it has one (e.g. zod). Inside the app, trust the types.
27
+ - **TS-08 Exports.** Follow the project. If it has no convention, use named exports and export only what other modules use.
28
+
29
+ ## Quick checks before handoff
30
+ - [ ] No new `any`, `@ts-ignore`, or unexplained `as` / `!`
31
+ - [ ] `tsc --noEmit` shows no new errors in changed files
32
+ - [ ] Every union `switch` is exhaustive
33
+
34
+ ## References (open only when needed)
35
+ - `references/patterns.md`: discriminated union + exhaustive switch, type guards, `satisfies` for config objects.
@@ -0,0 +1,40 @@
1
+ # ts-core patterns
2
+
3
+ ## Discriminated union + exhaustive switch (TS-04)
4
+ ```ts
5
+ type LoadState<T> =
6
+ | { status: 'loading' }
7
+ | { status: 'error'; error: ApiError }
8
+ | { status: 'ready'; data: T };
9
+
10
+ function render<T>(s: LoadState<T>) {
11
+ switch (s.status) {
12
+ case 'loading': return 'spinner';
13
+ case 'error': return s.error.message;
14
+ case 'ready': return s.data;
15
+ default: {
16
+ const unreachable: never = s; // compile error if a case is added and not handled
17
+ throw new Error(`Unhandled state: ${JSON.stringify(unreachable)}`);
18
+ }
19
+ }
20
+ }
21
+ ```
22
+
23
+ ## Narrowing `unknown` (TS-02)
24
+ ```ts
25
+ function isUser(v: unknown): v is User {
26
+ return typeof v === 'object' && v !== null && 'id' in v && typeof (v as { id: unknown }).id === 'string';
27
+ }
28
+ ```
29
+ If the project uses zod: `const user = UserSchema.parse(json)` at the boundary (TS-07).
30
+
31
+ ## `satisfies` for config objects
32
+ Use it to check a literal against a type while keeping its narrow inferred type:
33
+ ```ts
34
+ const routes = { home: '/', profile: '/profile' } satisfies Record<string, string>;
35
+ ```
36
+
37
+ ## Rethrow with cause (TS-06)
38
+ ```ts
39
+ try { await save(); } catch (e) { throw new Error('Saving profile failed', { cause: e }); }
40
+ ```