From 750b2c667bac53dd0b0221ad332318df5bea4d04 Mon Sep 17 00:00:00 2001 From: Bartosz Hanc Date: Mon, 2 Nov 2026 16:06:39 +0100 Subject: [PATCH 1/2] docs: improve contributor agent guidance and validation --- .agents/scripts/check-guidance.mjs | 134 +++++++++ .agents/skills/README.md | 5 + .agents/skills/add-api-tests/SKILL.md | 42 +-- .agents/skills/add-native-extension/SKILL.md | 30 +- .agents/skills/add-task-pipeline/SKILL.md | 142 ++++++---- .agents/skills/core-guidelines/SKILL.md | 143 ++++------ .agents/skills/error-handling/SKILL.md | 2 +- .../skills/model-schema-validation/SKILL.md | 14 +- .agents/skills/skills-maintenance/SKILL.md | 30 +- .agents/skills/verify-and-build/SKILL.md | 259 +++++++----------- .github/workflows/check-guidance.yml | 28 ++ .github/workflows/ci.yml | 6 +- .gitignore | 1 + AGENTS.md | 61 +++++ CONTRIBUTING.md | 5 + package.json | 4 +- yarn.lock | 1 + 17 files changed, 556 insertions(+), 351 deletions(-) create mode 100644 .agents/scripts/check-guidance.mjs create mode 100644 .github/workflows/check-guidance.yml create mode 100644 AGENTS.md diff --git a/.agents/scripts/check-guidance.mjs b/.agents/scripts/check-guidance.mjs new file mode 100644 index 0000000000..c2be82b20c --- /dev/null +++ b/.agents/scripts/check-guidance.mjs @@ -0,0 +1,134 @@ +import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'; +import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseDocument } from 'yaml'; + +// An optional root lets validation be exercised on isolated fixtures. +const root = resolve(process.argv[2] ?? fileURLToPath(new URL('../../', import.meta.url))); +const skillsDir = resolve(root, '.agents/skills'); +const errors = []; +const fail = (file, message) => errors.push(`${relative(root, file)}: ${message}`); + +function markdownFiles(directory) { + return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const path = resolve(directory, entry.name); + return entry.isDirectory() ? markdownFiles(path) : entry.name.endsWith('.md') ? [path] : []; + }); +} + +// Ignore code examples, including indented fences inside Markdown lists. +function prose(content) { + let fence; + return content + .split('\n') + .filter((line) => { + const marker = line.match(/^\s*(`{3,}|~{3,})(.*)$/); + if (!fence && marker) { + fence = marker[1]; + return false; + } + if (fence) { + if ( + marker && + marker[1][0] === fence[0] && + marker[1].length >= fence.length && + !marker[2].trim() + ) { + fence = undefined; + } + return false; + } + return true; + }) + .join('\n'); +} + +const files = markdownFiles(skillsDir); +files.push(resolve(root, 'AGENTS.md')); +const names = new Set(); +let skills = 0; + +for (const file of files) { + if (!existsSync(file)) { + fail(file, 'file is missing'); + continue; + } + let content = readFileSync(file, 'utf8'); + if (basename(file) === 'SKILL.md') { + skills++; + const header = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/); + if (!header) { + fail(file, 'missing YAML frontmatter'); + } else { + const document = parseDocument(header[1]); + for (const error of document.errors) fail(file, `invalid YAML: ${error.message}`); + if (!document.errors.length) { + const data = document.toJS(); + if (!data || typeof data !== 'object' || Array.isArray(data)) { + fail(file, 'frontmatter must be a mapping'); + } else { + const { name, description, metadata } = data; + if ( + typeof name !== 'string' || + name.length > 64 || + !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || + name !== relative(skillsDir, dirname(file)) + ) { + fail( + file, + 'name must match its skill directory and use lowercase letters/digits/hyphens' + ); + } + if (names.has(name)) fail(file, `duplicate skill name: ${name}`); + names.add(name); + if (typeof description !== 'string' || !description.trim() || description.length > 1024) { + fail(file, 'description must be a nonempty string of at most 1024 characters'); + } + if ( + metadata !== undefined && + (!metadata || + typeof metadata !== 'object' || + Array.isArray(metadata) || + Object.values(metadata).some((value) => typeof value !== 'string')) + ) { + fail(file, 'metadata must be a mapping of string values'); + } + } + } + content = content.slice(header[0].length); + } + } + + // Repository guidance uses inline Markdown links with simple local paths. External URLs and + // anchors are not fetched. Code spans are left intact so links with code-formatted labels work. + for (const match of prose(content).matchAll(/\[[^\]\n]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g)) { + const target = match[1].replace(/^<|>$/g, ''); + if (/^(?:[a-z][a-z\d+.-]*:|#)/i.test(target)) continue; + const path = target.split(/[?#]/)[0]; + if (!path) continue; + let decoded; + try { + decoded = decodeURIComponent(path); + } catch { + fail(file, `invalid URL encoding: ${target}`); + continue; + } + const destination = resolve(dirname(file), decoded); + const fromRoot = relative(root, destination); + if (isAbsolute(decoded) || fromRoot === '..' || fromRoot.startsWith(`..${sep}`)) { + fail(file, `local link must stay within the repository: ${target}`); + } else if (!existsSync(destination) || !statSync(destination).isFile()) { + fail(file, `missing local file: ${target}`); + } + } +} + +if (!skills) fail(skillsDir, 'no skills found'); +if (errors.length) { + console.error(errors.join('\n')); + process.exitCode = 1; +} else { + console.log( + `Validated ${skills} contributor skills and local links in ${files.length} Markdown files.` + ); +} diff --git a/.agents/skills/README.md b/.agents/skills/README.md index 486abd3ff8..22e9973386 100644 --- a/.agents/skills/README.md +++ b/.agents/skills/README.md @@ -2,6 +2,11 @@ This directory contains specialized skills (recipes) to guide contributors and AI coding assistants in extending the codebase cleanly and consistently. +Start with [the repository contributor entry point](../../AGENTS.md) for setup and task routing. +Load only the relevant skills. Package-relative `src/` and `cpp/` paths refer to +`packages/react-native-executorch/`; metadata scopes describe relevance and do not automatically load +instructions. Run `yarn check:guidance` from the repository root after edits. + ## Available Skills - [Core Guidelines](./core-guidelines/SKILL.md) — Symmetrical architecture, conventions, and model rules. diff --git a/.agents/skills/add-api-tests/SKILL.md b/.agents/skills/add-api-tests/SKILL.md index 7f9801b680..57cffd9276 100644 --- a/.agents/skills/add-api-tests/SKILL.md +++ b/.agents/skills/add-api-tests/SKILL.md @@ -8,10 +8,12 @@ metadata: # Skill: Add TypeScript API Tests -Every change under `src/` belongs in the Jest suites at +Behavior changes under `src/` should be covered by the Jest suites at [`packages/react-native-executorch/__tests__/`](../../../packages/react-native-executorch/__tests__/README.md). They run on a laptop or a CI runner — no simulator, no device, no `.pte` — and -finish in a few seconds. +finish in a few seconds. Reuse existing coverage for comments or changes with no observable behavior; +do not add tests that merely restate the implementation. Fake-runtime tests exercise TypeScript logic, +not production C++ or actual delegated model inference. ```bash yarn workspace react-native-executorch test @@ -19,7 +21,9 @@ yarn workspace react-native-executorch test __tests__/tasks # one directory yarn workspace react-native-executorch test -u # update snapshots ``` -Types come along for free: `yarn typecheck` already covers `__tests__/`. +From the repository root, `yarn workspace react-native-executorch typecheck` includes `__tests__/`. +Root `yarn typecheck` also builds and checks other workspaces; see the +[verification matrix](../verify-and-build/SKILL.md#verification-matrix). --- @@ -49,19 +53,19 @@ expect(await runner.runTask(imageBuffer(8, 8))).toEqual(/* ... */); Key helpers: -| Helper | Use | -| :--- | :--- | -| `fakeJsi.registerModel(path, program)` | Make `loadModel(path)` succeed with a given schema and `execute` | -| `fakeJsi.registerTokenizer(path, vocabulary)` | Same for `loadTokenizer` | -| `fakeJsi.registerLLMRunner(path, program)` | Same for `createLLMRunner`: a context window and the responses to generate, one per `generate` call | -| `fakePhonemizer.serve(text, phonemes)` | Script the native grapheme-to-phoneme converter | -| `fakeFs.write(path, contents)` | Put a file where a pipeline will read it (a charset, a `tokenizer_config.json`, a voice matrix) | -| `exported(spec)` | Reinterpret a spec built with `method`/`f32`/`i64` as an *exported* one (it verifies no symbolic dims are left) | -| `writesOutputs(...)`, `copiesInputToOutput()` | Ready-made `execute` implementations | -| `tracked(pipeline)` | Auto-dispose at the end of the test | -| `imageBuffer(w, h, format)` | A deterministic input image | -| `cachePathFor(url)` | Where the fetcher will download a URL, so a hook test can register its model up front | -| `fakeNet.serve(url, route)` | Script the server: status, body, `Range` support, and a `gate` to hold a download open | +| Helper | Use | +| :-------------------------------------------- | :-------------------------------------------------------------------------------------------------------------- | +| `fakeJsi.registerModel(path, program)` | Make `loadModel(path)` succeed with a given schema and `execute` | +| `fakeJsi.registerTokenizer(path, vocabulary)` | Same for `loadTokenizer` | +| `fakeJsi.registerLLMRunner(path, program)` | Same for `createLLMRunner`: a context window and the responses to generate, one per `generate` call | +| `fakePhonemizer.serve(text, phonemes)` | Script the native grapheme-to-phoneme converter | +| `fakeFs.write(path, contents)` | Put a file where a pipeline will read it (a charset, a `tokenizer_config.json`, a voice matrix) | +| `exported(spec)` | Reinterpret a spec built with `method`/`f32`/`i64` as an _exported_ one (it verifies no symbolic dims are left) | +| `writesOutputs(...)`, `copiesInputToOutput()` | Ready-made `execute` implementations | +| `tracked(pipeline)` | Auto-dispose at the end of the test | +| `imageBuffer(w, h, format)` | A deterministic input image | +| `cachePathFor(url)` | Where the fetcher will download a URL, so a hook test can register its model up front | +| `fakeNet.serve(url, route)` | Script the server: status, body, `Range` support, and a `gate` to hold a download open | --- @@ -70,7 +74,7 @@ Key helpers: 1. **Schema acceptance** — one test per variant the pipeline declares (`batched`, `unbatched`, ...), asserting the factory resolves. 2. **Schema rejection** — a model that matches no variant, asserting the error - names the mismatch (`Rank mismatch`, `inconsistent bindings`, ...). A caller + has code `SCHEMA_MISMATCH` and describes the mismatch (`Rank mismatch`, `inconsistent bindings`, ...). A caller should learn what is wrong from the message. 3. **Configuration mismatch** — e.g. a `labels` array that disagrees with the model's output dimension. @@ -80,14 +84,14 @@ Key helpers: 5. **Options** — every default in `modelOpts`, and every per-call override. 6. **Disposal** — `dispose()` leaves `fakeJsi.liveTensors()` at 0 and `fakeJsi.liveModels()` empty, and repeated calls do not accumulate scratch - tensors. The same has to hold when construction *fails*: allocate through a + tensors. The same has to hold when construction _fails_: allocate through a `createResourceScope()` and wrap the factory body in `try`/`catch` so a schema mismatch releases the model instead of stranding it. Add the factory to `__tests__/tasks/constructionFailure.test.ts`, which drives every one of them. 7. **Sync/async parity** — `runTaskWorklet(x)` equals `await runTask(x)`. -Only the *weights* are out of scope, not the pipeline that runs on them. Before +Only the _weights_ are out of scope, not the pipeline that runs on them. Before settling for schema-acceptance-and-disposal, check what is actually TypeScript: a decode loop, a sliding window, a chunker, an argument check, a streaming generator and a disposal path all run fine over a scripted `execute`. Reach for diff --git a/.agents/skills/add-native-extension/SKILL.md b/.agents/skills/add-native-extension/SKILL.md index 5534575959..208394a544 100644 --- a/.agents/skills/add-native-extension/SKILL.md +++ b/.agents/skills/add-native-extension/SKILL.md @@ -1,9 +1,9 @@ --- name: add-native-extension -description: Use when adding a C++ extension, writing native JSI host functions, registering functions in C++ install maps, or compiling native code. +description: Use when implementing native C++ operations, exposing them through JSI, or updating domain installation and TypeScript wrappers. For build/debug workflows use verify-and-build. metadata: id: add_native_extension - scope: cpp/extensions/*, src/extensions/* + scope: packages/react-native-executorch/cpp/extensions/*, packages/react-native-executorch/src/extensions/* --- # Skill: Add a Native C++ Extension & JSI Bindings @@ -17,7 +17,9 @@ Use this guide to add custom, performance-critical native operations in C++ and Before writing any C++ code, ensure you adhere to the following principles: 1. **Amdahl's Law & Premature Optimization**: - - Evaluate what percentage of total inference/pipeline time the processing step occupies. If the preprocessing/postprocessing step takes `< 5%` of the total inference budget, write it in **pure TypeScript** to reduce codebase complexity and maintenance overhead. + - Prefer existing operations and TypeScript orchestration. Add native code when a missing platform + capability, memory/threading requirement or measured bottleneck justifies it. Record relevant + measurements when performance is the reason; there is no universal percentage cutoff. 2. **Destination Tensors & Local Memory**: - **Local Memory is Allowed**: You can allocate temporary native C++ memory (such as stack variables, `std::vector`s, or dynamic memory cleaned up before the function exits) for intermediate calculations. @@ -129,7 +131,7 @@ namespace rnexecutorch::extensions:: --- -### Step 2: Register in Extension and Core JSI Installs +### Step 2: Register the Operation and, If New, Its Domain 1. **Extension Register** (`cpp/extensions//install.cpp`): @@ -148,7 +150,7 @@ namespace rnexecutorch::extensions:: } ``` -2. **Core Register** ([cpp/RnExecutorch.cpp](../../../packages/react-native-executorch/cpp/RnExecutorch.cpp)): +2. **New domain only** ([cpp/RnExecutorch.cpp](../../../packages/react-native-executorch/cpp/RnExecutorch.cpp)): ```cpp #include "extensions//install.h" // ... inside rnexecutorch::install ... @@ -161,7 +163,9 @@ namespace rnexecutorch::extensions:: **Where the wrapper file goes — general vs. model-specific ops:** -- **Domain-general ops** (reusable across every task in the domain, e.g. `image_ops`, `box_ops`) go in the domain's shared op files (`src/extensions//ops.ts`), re-exported from `src/extensions//index.ts`. +- **Domain-general ops** go in the domain's existing shared op layout, re-exported from its `index.ts`. + For example, CV uses `src/extensions/cv/ops/image.ts` and `ops/box.ts`; inspect the domain before + creating a new `ops.ts`. - **Model- or task-specific ops** (only meaningful to one model/pipeline, e.g. FSMN-VAD framing) **must** go under `src/extensions//utils/.ts` — one file per model/task, named for it (e.g. `vadUtils.ts`, `supertonicUtils.ts`). Keep them out of the shared `ops.ts` so it stays a home for genuinely reusable ops, and group each model's helpers together under `utils/`. Re-export them from the domain `index.ts` too so power users can reach them. Then, in that wrapper file: @@ -172,8 +176,9 @@ Then, in that wrapper file: - Mark wrapper functions with the `"worklet";` directive. ```typescript -import { rnexecutorchJsi } from '../native/bridge'; -import { type Tensor } from '../core/tensor'; +// For src/extensions//ops.ts; adjust depth for nested ops/.ts. +import { rnexecutorchJsi } from '../../native/bridge'; +import { type Tensor } from '../../core/tensor'; /** * Applies a custom operation scaling the src tensor by factor. @@ -193,7 +198,7 @@ export function customOp(src: Tensor, dst: Tensor, factor: number = 1.0): Tensor When adding a native extension, verify that: -- [ ] You only implemented in C++ if the operation takes `> 5%` of the total inference budget. +- [ ] A native capability or measured performance/memory/threading need justifies the C++ implementation. - [ ] No JSI Tensors are implicitly allocated and returned in the C++ code. - [ ] Input and output tensors are extracted and validated using `tensor::fromJs` with strict expected `DType` and shape constraints where possible. - [ ] Primitive arguments are extracted and converted using `conversions::asType`. @@ -203,7 +208,10 @@ When adding a native extension, verify that: - [ ] Every failure is raised through a factory, `error::X(message)`; no raw `jsi::JSError` / `std::runtime_error` / `std::invalid_argument` was introduced. - [ ] The host function is registered through `error::guarded(fnBody)`, not a bare `fnBody`. - [ ] `#include "core/error.h"` and the `namespace error = ...` alias sit at file scope, outside any `#if defined(__ANDROID__)` / `#elif defined(__APPLE__)` branch. -- [ ] The custom operation install function is registered in both the domain `install` function and core [cpp/RnExecutorch.cpp](../../../packages/react-native-executorch/cpp/RnExecutorch.cpp). -- [ ] The TypeScript wrapper lives in the right place: domain-general ops in the shared `ops.ts`, model-/task-specific ops under `src/extensions//utils/.ts`. +- [ ] The operation is registered in the domain install; a new domain is registered in [cpp/RnExecutorch.cpp](../../../packages/react-native-executorch/cpp/RnExecutorch.cpp). +- [ ] The TypeScript wrapper follows the domain's existing shared op or task utility layout. - [ ] The TypeScript wrapper imports and uses `rnexecutorchJsi` instead of the global `__rnexecutorch_jsi__`. - [ ] The TypeScript wrapper is marked with the `"worklet";` directive and defines all default parameter values. + +Use [error handling](../error-handling/SKILL.md) for error-code/guard conventions and +[verify and build](../verify-and-build/SKILL.md#verification-matrix) for static, host and device checks. diff --git a/.agents/skills/add-task-pipeline/SKILL.md b/.agents/skills/add-task-pipeline/SKILL.md index 35c372f7af..dd5a3d4a50 100644 --- a/.agents/skills/add-task-pipeline/SKILL.md +++ b/.agents/skills/add-task-pipeline/SKILL.md @@ -3,7 +3,7 @@ name: add-task-pipeline description: Use when creating a TypeScript task pipeline, implementing image preprocessing/postprocessing, loading models, or wrapping pipelines in React hooks. metadata: id: add_task_pipeline - scope: src/extensions/*/tasks/*, src/hooks/* + scope: packages/react-native-executorch/src/extensions/*/tasks/*, packages/react-native-executorch/src/hooks/* --- # Skill: Add a High-Level Task Pipeline (TypeScript) @@ -20,7 +20,10 @@ When implementing task constructors like `create` (e.g. `createClassifier` - Statically sized scratch/output tensors required for inference should be pre-allocated inside the constructor body. - Allocate them using: ```typescript - const tensors = [tensor('float32', shapeA), tensor('float32', shapeB)] as const; + const tensors = [ + scope.track(tensor('float32', shapeA)), + scope.track(tensor('float32', shapeB)), + ] as const; ``` - **Destructuring & Naming**: Destructure and name the individual tensors immediately after allocation. Always prefix tensor variables with a lowercase `t` (e.g. `tReshape`, `tUint8`, `tInput`) to easily distinguish them from raw data buffers. ```typescript @@ -29,6 +32,7 @@ When implementing task constructors like `create` (e.g. `createClassifier` 2. **Allocate Through a Resource Scope**: - Open a `createResourceScope()` as the first statement of the constructor, take its `dispose` as the pipeline's, and wrap the whole body in `try`/`catch`. `track` every native resource as it is created: + ```typescript const scope = createResourceScope(); const dispose = scope.dispose; @@ -37,8 +41,7 @@ When implementing task constructors like `create` (e.g. `createClassifier` const model = scope.track(await wrapAsync(loadModel, runtime)(modelPath)); const { dims } = validateSpec(model.schema, { ... }); // may throw - const tensors = [tensor('float32', shapeA), tensor('float32', shapeB)] as const; - tensors.forEach(scope.track); + const tensors = [scope.track(tensor('float32', shapeA)), scope.track(tensor('float32', shapeB))] as const; const preprocessor = scope.track(createImagePreprocessor(modelOpts, inpShape)); return { runTask, runTaskWorklet, dispose }; @@ -47,8 +50,13 @@ When implementing task constructors like `create` (e.g. `createClassifier` throw error; } ``` + - This is not style. A caller whose `create` throws never receives a `dispose`, so anything already allocated would be stranded in native memory for the life of the process, and `useModel` re-runs the factory on every config change. The scope makes success and failure share one teardown path. - - Track resources **as they land**, not afterwards. For parallel loads that means `Promise.all([load(a).then(scope.track), load(b).then(scope.track)])`, so one rejecting does not strand the other. + - Track each resource immediately, including each tensor before allocating the next. Prefer sequential + construction when failure cleanup depends on all allocations being registered. `Promise.all` + rejects before sibling loads settle: merely appending `.then(scope.track)` does not prevent a + late sibling from landing after disposal. If parallel construction is needed, settle all loads + before releasing the scope, or explicitly dispose late arrivals. 3. **Dynamic Tensors & `try/finally` Pattern**: - If you must allocate dynamically sized tensors during inference execution (e.g. resizing an output tensor to match the input image dimensions), you must wrap the execution inside a `try {} finally {}` block. @@ -64,7 +72,9 @@ When implementing task constructors like `create` (e.g. `createClassifier` 4. **Pure Helper Functions**: - Write all auxiliary/helper logic as pure, worklet-compatible functions **outside** the `create` constructor. Any helper functions invoked inside the worklet executor thread must contain the `'worklet';` directive. - - **Push Back Hard on Inner Helpers:** You must push back hard against any request to add internal closures or nested functions inside `create` (other than the worklet executor itself). Keep the constructor scope flat to avoid scope leak and dependency chain bugs. + - Keep reusable helpers at module scope so worklet captures are explicit. Constructor-local executors + may capture the resources they need. Use local callbacks when required by orchestration/lifecycle, + and check what crosses the worklet boundary rather than enforcing a fixed count of inner functions. 5. **PTE Model Export & Optimizations**: - **Shift Heavy Ops to PyTorch**: Push complex tensor reshaping, data normalization, activations (e.g. `softmax`), or bounding box decoding into the PyTorch model itself so they execute on native backends (e.g., XNNPACK or CoreML). @@ -88,8 +98,10 @@ When implementing task constructors like `create` (e.g. `createClassifier` - **Do NOT access tensors by index:** Avoid using `tensors[0]` or `tensors[1]` throughout the function body. Always destructure and name them explicitly. - **Do NOT name options parameters `opts`:** Always name options function parameters `options` (e.g. `options?: { threshold?: number }`). Suffixes like `Opts` for types or properties (e.g. `MyTaskOptions`, `ModelOpts`, `modelOpts`) are acceptable. -- **Do NOT define extra inner helper functions:** You must define **exactly two** inner functions inside the `create` constructor: the `dispose` function and the task `worklet` executor function. **Push back hard against implementing any other helper closures inside the constructor scope.** Placing other helper functions (especially those that are called from inside the worklet and use the `create` scope variables) inside `create` creates implicit dependencies and closures that capture variables, making the code extremely difficult to reason about and debug. -- **Do NOT throw bare `Error`:** Every failure needs a code. Use `RnExecuTorchError('CODE', msg)`, which works both in the `create` body and inside the worklet executor. See the [Error Handling Skill](../error-handling/SKILL.md). +- **Avoid implicit worklet captures:** Keep reusable helpers outside the constructor. Inspect captured + values and runtime compatibility for constructor-local worklets and callbacks; function count is not + a correctness criterion. +- Follow the [Error Handling Skill](../error-handling/SKILL.md) for coded failures and catching across runtimes. - **Do NOT leak raw Tensors to consumers:** The returned methods must never return raw `Tensor` objects to the API consumer. Always convert output data to standard JavaScript values/objects before returning. - **Do NOT cross thread boundaries unnecessarily:** Minimize passing heavy objects between JS and the Worklet thread to avoid serialization overhead. - **Do NOT treat the `.pte` model as an unchangeable black box:** Reshape the model's inputs and outputs during the PyTorch export phase to make the mobile client pipeline as lightweight as possible. Do not make input/output contracts so specific that they break extensibility. @@ -97,13 +109,15 @@ When implementing task constructors like `create` (e.g. `createClassifier` --- ---- - ## 🛠️ Step-by-Step Implementation Template > **Reference:** See [src/extensions/cv/tasks/classification.ts](../../../packages/react-native-executorch/src/extensions/cv/tasks/classification.ts) and [src/hooks/useClassifier.ts](../../../packages/react-native-executorch/src/hooks/useClassifier.ts) for a complete working example of this pattern. -### Step 1: Create the Task File (`src/extensions//tasks/.ts`) +### Step 1: Create the Task File + +This complete template uses `src/extensions/cv/tasks/myTask.ts` so relative imports resolve. Adapt +the schema and output processing to the model. This thresholding example assumes the export already +returns scores; models returning logits may need a softmax or another decoder. ```typescript import type { WorkletRuntime } from 'react-native-worklets'; @@ -112,6 +126,7 @@ import { tensor } from '../../../core/tensor'; import { loadModel } from '../../../core/model'; import { validateSpec, method, f32 } from '../../../core/schema'; import { wrapAsync } from '../../../core/runtime'; +import { createResourceScope } from '../../../core/lifetime'; import { type ImageBuffer } from '../image'; import { createImagePreprocessor, type ImagePreprocessorOptions } from '../utils/imagePreprocessor'; @@ -121,7 +136,7 @@ export type MyTaskOptions = ImagePreprocessorOptions & { export type MyTaskModel = { readonly modelPath: string; - readonly taskOpts: MyTaskOptions; + readonly modelOpts: MyTaskOptions; }; export type MyTaskResult = { @@ -149,51 +164,55 @@ export async function createMyTask( runTask: (input: ImageBuffer, options?: { threshold?: number }) => Promise; runTaskWorklet: (input: ImageBuffer, options?: { threshold?: number }) => MyTaskResult[]; }> { - const { modelPath, taskOpts } = config; - const model = await wrapAsync(loadModel, runtime)(modelPath); - - // Validate model spec - const { variant, dims } = validateSpec(model.schema, { - batched: method('forward', [f32(1, 3, 'H', 'W')], [f32(1, 10)]), - unbatched: method('forward', [f32(3, 'H', 'W')], [f32(10)]), - }); - - const [H, W] = dims.constant('H', 'W'); - const inpShape = { batched: [1, 3, H, W], unbatched: [3, H, W] }[variant]; - const outShape = { batched: [1, 10], unbatched: [10] }[variant]; - - // 2. Pre-allocate static tensors - const tensors = [tensor('float32', outShape)] as const; - - // Idiomatic destructuring and naming with "t" prefix - const [tOutput] = tensors; - const preprocessor = createImagePreprocessor(taskOpts, inpShape); - - // 3. Define dispose() immediately after allocation - const dispose = () => { - preprocessor.dispose(); - tensors.forEach((t) => t.dispose()); - model.dispose(); - }; - - // 4. Define exactly two inner functions (dispose & runTaskWorklet) - const runTaskWorklet = (input: ImageBuffer, options?: { threshold?: number }): MyTaskResult[] => { - 'worklet'; - - // Process input buffer to input tensor - const tInput = preprocessor.process(input); - model.execute('forward', [tInput], [tOutput]); - - const data = tOutput.getData(new Float32Array(tOutput.numel)); - const threshold = options?.threshold ?? taskOpts.defaultThreshold; - - // 5. Return standard JS object, never raw Tensor - return postprocessOutput(data, threshold); - }; - - const runTask = wrapAsync(runTaskWorklet, runtime); - - return { runTask, runTaskWorklet, dispose }; + const scope = createResourceScope(); + const dispose = scope.dispose; + + try { + const { modelPath, modelOpts } = config; + const model = scope.track(await wrapAsync(loadModel, runtime)(modelPath)); + + // Validate model spec + const { variant, dims } = validateSpec(model.schema, { + batched: method('forward', [f32(1, 3, 'H', 'W')], [f32(1, 10)]), + unbatched: method('forward', [f32(3, 'H', 'W')], [f32(10)]), + }); + + const [H, W] = dims.constant('H', 'W'); + const inpShape = { batched: [1, 3, H, W], unbatched: [3, H, W] }[variant]; + const outShape = { batched: [1, 10], unbatched: [10] }[variant]; + + // 2. Pre-allocate static tensors + const tensors = [scope.track(tensor('float32', outShape))] as const; + + // Idiomatic destructuring and naming with "t" prefix + const [tOutput] = tensors; + const preprocessor = scope.track(createImagePreprocessor(modelOpts, inpShape)); + + // Capture the resources needed by this task's executor. + const runTaskWorklet = ( + input: ImageBuffer, + options?: { threshold?: number } + ): MyTaskResult[] => { + 'worklet'; + + // Process input buffer to input tensor + const tInput = preprocessor.process(input); + model.execute('forward', [tInput], [tOutput]); + + const data = tOutput.getData(new Float32Array(tOutput.numel)); + const threshold = options?.threshold ?? modelOpts.defaultThreshold; + + // 5. Return standard JS object, never raw Tensor + return postprocessOutput(data, threshold); + }; + + const runTask = wrapAsync(runTaskWorklet, runtime); + + return { runTask, runTaskWorklet, dispose }; + } catch (error) { + dispose(); + throw error; + } } ``` @@ -204,7 +223,7 @@ Wrap the task pipeline in a custom React Hook using the core hooks `useResourceD ```typescript import { useModel } from './useModel'; import { useResourceDownload, type ResourceOptions } from './useResourceDownload'; -import { createMyTask, type MyTaskModel } from '../extensions//tasks/'; +import { createMyTask, type MyTaskModel } from '../extensions/cv/tasks/myTask'; export function useMyTask(config: MyTaskModel, options?: ResourceOptions) { // 1. Resolve remote or local asset model path and download progress @@ -232,9 +251,9 @@ When adding a task pipeline or React hook, verify that: - [ ] Scratch/output tensors are pre-allocated using `tensor() as const` and prefixed with lowercase `t` (e.g. `tInput`). - [ ] Static tensors are destructured and named (no index-based access in the body). -- [ ] The `dispose` function is defined immediately after static allocations. +- [ ] Each native resource is tracked immediately by the construction scope; failure and success share `scope.dispose`. - [ ] Any dynamically allocated tensors are wrapped in `try/finally` and disposed of inside `finally`. -- [ ] The constructor contains exactly two inner functions (the `dispose` function and the worklet executor). +- [ ] Parallel loads, if present, cannot register resources after failure cleanup has finished. - [ ] Auxiliary helpers are defined outside the constructor and marked with the `'worklet';` directive if run on the worklet runtime. - [ ] Raw `Tensor` objects are never returned to the consumer. - [ ] Every throw uses `RnExecuTorchError('CODE', message)`. @@ -242,3 +261,6 @@ When adding a task pipeline or React hook, verify that: - [ ] Every parameter is bucketed per Principle 6: varies across variants → option; fixed by the export → `const` in the task file; per-call choice → executor argument. - [ ] No exposed option has exactly one valid value, and no two `models.ts` variants pass an identical options object. - [ ] The React Hook utilizes `useModel` and properly returns progress, ready state, errors, and task execution bindings. + +Cover success and construction failure using [API tests](../add-api-tests/SKILL.md), and choose checks +from [verify and build](../verify-and-build/SKILL.md#verification-matrix). diff --git a/.agents/skills/core-guidelines/SKILL.md b/.agents/skills/core-guidelines/SKILL.md index 45d8bc0b31..fa0e5a06ac 100644 --- a/.agents/skills/core-guidelines/SKILL.md +++ b/.agents/skills/core-guidelines/SKILL.md @@ -1,116 +1,69 @@ --- name: core-guidelines -description: Use when learning the codebase architecture, design patterns, core/extension symmetry, file structure, or general coding standards. +description: Use when learning or changing the library architecture, package boundaries, public exports, model registry, or shared coding conventions. metadata: id: core_guidelines - scope: general + scope: packages/react-native-executorch/src, packages/react-native-executorch/cpp --- -# React Native ExecuTorch Architecture Guide +# Library architecture and conventions -Welcome! This directory contains specialized "skills" (recipes) designed to help you extend this codebase in an idiomatic, clean, and consistent manner. +Paths below are relative to `packages/react-native-executorch/`. Use the repository +[AGENTS.md](../../../AGENTS.md) to select task-specific skills and verification. -Before implementing any feature or modifying code, please find the corresponding skill folder in `.agents/skills/` and review its `SKILL.md` to ensure you follow the correct patterns. +## Core and extensions ---- - -## 🎯 Design Philosophy - -The library is designed around the separation of responsibilities into two distinct layers: - -1. **Lower-Level API (Flexible & Domain-Agnostic)**: Exposes raw bindings to native ExecuTorch capabilities (tensors, models, runtime execution, and basic math/CV operations) in C++ without task-specific code. This layer is designed to be highly flexible, allowing developer customization directly in TypeScript. -2. **Higher-Level API (Transparent & Orchestrated)**: Built as orchestration layers **entirely in TypeScript** on top of the lower-level native bindings. Preprocessing, running model inference, and output postprocessing are composed dynamically in TS. - -- **Why this matters**: In contrast to opaque native pipelines, implementing pipelines in TypeScript makes them transparent, easy to debug, highly customizable, and easy to extend without writing complex native C++ code. +The library has two layers: ---- +- `cpp/core/` and `src/core/` implement domain-agnostic tensors, models, schemas, runtime execution and + resource ownership. Extend core when a foundational capability is needed; keep task-specific behavior + out of it and verify affected callers. +- `cpp/extensions//` implements native domain operations. `src/extensions//` contains + wrappers, utilities and TypeScript task pipelines; `src/hooks/` manages React loading and lifecycle. -## 🏛️ Symmetrical Architecture (Core vs. Extensions) - -This library is strictly structured using a symmetrical layout between the native C++ layer (`cpp/`) and the TypeScript layer (`src/`). When adding a new capability, you will typically need to modify or add files in both layers under their respective subfolders: - -```text -cpp/ │ src/ -├── core/ │ ├── core/ -│ ├── install.h │ │ ├── model.ts -│ ├── tensor.h │ │ ├── tensor.ts -│ └── ... │ │ └── ... -└── extensions/ │ ├── extensions/ - ├── math/ │ │ ├── math.ts - │ ├── install.h │ │ └── cv/ - │ └── operations.h │ │ ├── image.ts - └── cv/ │ │ └── tasks/ - ├── install.h │ │ └── classification.ts - └── image_ops.h │ └── hooks/ - │ └── useClassifier.ts -``` - -### 1. Core (`cpp/core/` and `src/core/`) - -- **Purpose**: Implements the absolute bare minimum required for the lower-level API. -- **Responsibilities**: Primitives for `Tensor` and `Model` management, JSI bindings, and the ExecuTorch runtime execution logic. -- **Rule**: Core is domain-agnostic. **Do not** add task-specific or domain-specific code (like computer vision ops, tokenizers, or speech preprocessing) here. - -### 2. Extensions (`cpp/extensions/` and `src/extensions/`) - -- **Purpose**: Contains all domain-specific logic, organized by domain (e.g., `cv`, `math`, `llm`, `speech`). -- **Symmetry Rules**: - - **Native operations** (e.g. image transformations, box math) go under `cpp/extensions//`. - - **JSI Installation** is registered via `cpp/extensions//install.cpp` and exposed on the global JSI object under `__rnexecutorch_jsi__.`. - - **TypeScript wrappers** for these native operations go in `src/extensions/.ts` or `src/extensions//`. - - **Higher-level task pipelines** (orchestration of model loading, input pre-processing, running inference, and output post-processing) are written entirely in TypeScript under `src/extensions//tasks/`. - - **React Hooks** (lightweight state/lifecycle wrappers around task pipelines) go in `src/hooks/`. +Native and TypeScript domains mirror each other where bindings are needed. A task built from existing +operations can be entirely TypeScript. Add C++ when the operation needs a new native capability or +measurements justify it; see [native extension guidance](../add-native-extension/SKILL.md). ---- +Task orchestration, preprocessing and postprocessing normally live in TypeScript so they can be +inspected and customized. Model export can perform expensive transformations when that improves +execution without hiding necessary configuration; see [task pipelines](../add-task-pipeline/SKILL.md). -## 📂 Skills Index +## Sources of truth -Use the following index to locate the specific procedural guides for your task: +| Concern | Source | +| ------------------------------------------ | -------------------------------------------------------------------------------------- | +| Root exports | [src/index.ts](../../../packages/react-native-executorch/src/index.ts) | +| Public subpaths and published files | [package.json](../../../packages/react-native-executorch/package.json) | +| Model configurations and hosted asset URLs | [src/models.ts](../../../packages/react-native-executorch/src/models.ts) | +| Shared labels and constants | [src/constants.ts](../../../packages/react-native-executorch/src/constants.ts) | +| Native domain installation | [cpp/RnExecutorch.cpp](../../../packages/react-native-executorch/cpp/RnExecutorch.cpp) | +| JSI access from TypeScript | [src/native/bridge.ts](../../../packages/react-native-executorch/src/native/bridge.ts) | -| I want to... | Use this Skill File | Description | -| :------------------------------------------- | :---------------------------------------------- | :------------------------------------------------------------------------------------------------------------- | -| **Add a new native operator or C++ binding** | [SKILL.md](../add-native-extension/SKILL.md) | Procedural guide to implementing C++ functions, exposing them via JSI, and writing TypeScript bridge wrappers. | -| **Create a task pipeline or hook** | [SKILL.md](../add-task-pipeline/SKILL.md) | Guide to building end-to-end TS pipelines (e.g. object detection) and exposing them via React hooks. | -| **Verify, rebuild, or troubleshoot changes** | [SKILL.md](../verify-and-build/SKILL.md) | Workflows for rebuilding TS/C++ and resolving common JSI runtime errors. | -| **Test TypeScript changes** | [SKILL.md](../add-api-tests/SKILL.md) | Covering `src/` with the Jest API suites and their fake native runtime. | -| **Validate model constraints & schemas** | [SKILL.md](../model-schema-validation/SKILL.md) | Guide on specifying model specs, dynamic shapes, and runtime constraints for model validation. | -| **Throw, catch, or classify an error** | [SKILL.md](../error-handling/SKILL.md) | The error code set, `RnExecuTorchError`, C++ `RnExecuTorchException`/`guarded`, and adding a code. | -| **Maintain or refactor codebase patterns** | [SKILL.md](../skills-maintenance/SKILL.md) | Guide to keeping workspace skills in sync with codebase state to prevent documentation decay. | +Export new public tasks/hooks through the root entry point and domain utilities through the appropriate +domain entry point. Inspect `package.json` exports before adding a subpath. Avoid exposing internal +helpers accidentally; export changes are checked by the API surface tests. ---- +`models.ts` exports the single `models` registry. Keep individual configurations private and register +them under the appropriate task/model/variant. Reuse task types and `constants.ts` for shared labels. +Export-pinned shapes or scalar values belong beside task code; model-varying configuration belongs in +registry options. The [task skill](../add-task-pipeline/SKILL.md) owns that distinction. -## 💡 Key Coding Conventions +## Shared conventions -- **Worklets**: Ensure all TypeScript functions directly wrapping native JSI calls start with the `"worklet";` directive so they are compatible with worklet-based libraries (e.g., React Native Reanimated). -- **Options Parameter Naming**: Always name function and method options parameters `options` (not `opts`, `optsObj`, `taskOpts`, or `chunkOpts`). Using `Opts` as a type or property suffix (e.g. `ModelOpts`, `TaskOpts`, `modelOpts`) is acceptable. -- **Errors**: Every failure the library raises carries a string `code`. Use `RnExecuTorchError('CODE', msg)` in TypeScript (a function, not a class, so it survives worklet boundaries) and `error::InvalidArgument(msg)` + `error::guarded(...)` in C++. Never branch on message text. See the [Error Handling Skill](../error-handling/SKILL.md). -- **Memory Management**: When writing native C++ code with JSI, pay close attention to JSI reference management and handle ExecuTorch lifecycle states safely. -- **Keep Core Clean**: Always build on top of core primitives. Do not modify files in `cpp/core/` or `src/core/` unless you are fixing a bug in the foundational runtime. - ---- +- Name options parameters `options`. Existing suffixes such as `ModelOpts` or `modelOpts` are allowed. +- Native JSI wrappers use `rnexecutorchJsi` from the bridge and start with `'worklet';`. Helpers called + from worklets must also be compatible with that runtime. See the native extension skill for bindings. +- The [error skill](../error-handling/SKILL.md) owns coded factories, catch behavior and C++ guards. +- The [task skill](../add-task-pipeline/SKILL.md) owns construction failure cleanup and resource scopes. +- The [schema skill](../model-schema-validation/SKILL.md) owns load-time shape/domain validation. -## 📢 Package Registration & Exports - -Whenever you add a new extension, task pipeline, or hook, you **must** register and export them at the package level to make them accessible to users: - -1. **TypeScript Exports** ([src/index.ts](../../../packages/react-native-executorch/src/index.ts)): Export the new task pipelines (e.g. `export * from './extensions/cv/tasks/myTask'`) and hooks (e.g. `export * from './hooks/useMyTask'`). -2. **Model Configurations** ([src/models.ts](../../../packages/react-native-executorch/src/models.ts)) & **Constants** ([src/constants.ts](../../../packages/react-native-executorch/src/constants.ts)): - - These **two files are the sole source of truth** for defining pre-exported models, their options, and their label structures. Do not define models or options ad-hoc anywhere else. - - **Model Registry Rule**: You must **only export the single `models` object registry** from `models.ts`. Do not export individual model configuration constants. Define them as internal (private) `const` variables inside `models.ts` and register them under the appropriate category nested inside the exported `models` registry object. - - If you are introducing a standard pre-configured model, add its metadata config and HuggingFace/local URI endpoint mapping here. - ---- - -## 🔍 Model Inspection & Testing via Example Apps - -The workspace uses a monorepo structure with domain-specific example apps under `apps/` (e.g., `apps/computer-vision`, `apps/nlp`). These are the primary playgrounds for inspecting models and testing your pipelines on-device: - -1. **Inspect Screen** (e.g., `apps/computer-vision/app/inspect/index.tsx`): Paste any arbitrary `.pte` model URL to load and print its metadata, inputs, and outputs dynamically. -2. **Interactive Testing Screens** (e.g., `apps/nlp/app/tokenizer/index.tsx`): Test task pipelines interactively. When adding a new task, you should add a corresponding interactive testing card/flow in the appropriate domain's app. -3. **Camera Screen** (e.g., `apps/computer-vision/app/camera/index.tsx`): Run real-time camera-based inferences using the task pipelines. - ---- +## Inspecting and verifying behavior -## 🛠️ Verification & Rebuilding +Use the domain apps under `apps/` for model inspection and device inference. Inspect their current +screens before choosing an example to extend. For a new task, add an appropriate demonstration when +needed to exercise inputs, outputs or device-only behavior. Do not commit downloaded model binaries. -Please refer to the [Verify & Build Skill](../verify-and-build/SKILL.md) for the complete checklist on compiling TS/C++, rebuilding iOS pods, and troubleshooting native changes. +Use [API tests](../add-api-tests/SKILL.md) for TypeScript behavior and +[verify and build](../verify-and-build/SKILL.md) to select host/native/device checks. When conventions +change, update affected guidance following [skills maintenance](../skills-maintenance/SKILL.md). diff --git a/.agents/skills/error-handling/SKILL.md b/.agents/skills/error-handling/SKILL.md index 154c72bdcd..ea49777d2f 100644 --- a/.agents/skills/error-handling/SKILL.md +++ b/.agents/skills/error-handling/SKILL.md @@ -3,7 +3,7 @@ name: error-handling description: Use when throwing, catching, or classifying errors anywhere in the library (TypeScript, worklets, C++/JSI), or when adding a new error code. metadata: id: error_handling - scope: src/core/error.ts, cpp/core/error.* + scope: packages/react-native-executorch/src/core/error.ts, packages/react-native-executorch/cpp/core/error.* --- # Skill: Error Handling diff --git a/.agents/skills/model-schema-validation/SKILL.md b/.agents/skills/model-schema-validation/SKILL.md index 9b39dd6106..ebbea32cbd 100644 --- a/.agents/skills/model-schema-validation/SKILL.md +++ b/.agents/skills/model-schema-validation/SKILL.md @@ -3,7 +3,7 @@ name: model-schema-validation description: Use when defining model spec constraints, validating ExecuTorch model shapes, checking method signatures, or resolving dimension symbols. metadata: id: model_schema_validation - scope: src/core/schema.ts, src/extensions/*/tasks/* + scope: packages/react-native-executorch/src/core/schema.ts, packages/react-native-executorch/src/extensions/*/tasks/* --- # Skill: Model Schema Validation Guide @@ -179,7 +179,7 @@ const { dims } = validateSpec(model.schema, { const [H, W] = dims.constant('H', 'W'); ``` -### 3. Object Detection (Dynamic Box Count) +### 3. Object Detection (Export-Specific Static Box Count) Accepts an image tensor, and outputs boxes, scores, and class labels for `N` detections: @@ -191,6 +191,10 @@ const { dims } = validateSpec(model.schema, { const [N, H, W] = dims.constant('N', 'H', 'W'); ``` +Here `'N'` binds an unknown-at-authoring-time **constant** from the exported schema. For an export +whose box count varies at runtime, use `DynamicDim('N')`, inspect `dims.range`/`dims.enum`, and design +allocation and output decoding around that domain rather than treating it as a constant. + ### 4. Single-Model Pipeline (Fully Static Export) Assert exact shape constants from the task file: @@ -214,7 +218,9 @@ const { dims } = validateSpec(model.schema, { ## 🚫 Avoid / Anti-Patterns - **Do NOT write manual imperative shape/type checks:** Always use declarative `validateSpec` variants which report unified, readable mismatch errors. -- **Do NOT use hardcoded integers for dynamic dimensions:** Use string symbols (like `'H'`, `'W'`, `'N'`) for dynamic dimensions. Conversely, fixed export dimensions should be integers. +- Use integers for exact static requirements, strings such as `'H'` for static wildcard dimensions, + and `DynamicDim('S')` for runtime-varying domains. Repeated dynamic symbols match domains, not runtime + equality; declare runtime constraints when equality is required. - **Do NOT skip validation at startup:** Validate `model.schema` before allocating static tensors. - **Do NOT skip validation for single-model pipelines:** Single-model pipelines should still validate against task shape constants. @@ -234,7 +240,7 @@ raises `INVALID_ARGUMENT`, not `SCHEMA_MISMATCH`: the model is fine, the call is When specifying model schema validations, verify that: - [ ] Schema validation is performed immediately after model loading and before tensor initialization using `validateSpec(model.schema, { ... })`. -- [ ] Dynamic dimensions are defined as string symbols, while fixed dimensions are plain integers. +- [ ] Static wildcard symbols and runtime-dynamic domains are distinguished; exact fixed requirements use integers. - [ ] Symbol values are extracted using `dims.constant(...)`, `dims.range(...)`, or `dims.enum(...)`. - [ ] Multiple shape variants (e.g. `batched` vs `unbatched`) are provided when supported. - [ ] Input and output constraints map accurately to model specifications. diff --git a/.agents/skills/skills-maintenance/SKILL.md b/.agents/skills/skills-maintenance/SKILL.md index 09a18cf2dc..ee4fc96a6e 100644 --- a/.agents/skills/skills-maintenance/SKILL.md +++ b/.agents/skills/skills-maintenance/SKILL.md @@ -1,9 +1,9 @@ --- name: skills-maintenance -description: Use when introducing new patterns, refactoring core primitives, adding helper utilities, or changing standard idioms to ensure the workspace skills remain up-to-date. +description: Use when APIs, build/test commands, shared helpers, architecture or contributor instructions change and affected skills need review or updates. metadata: id: skills_maintenance - scope: general development + scope: AGENTS.md, .agents, packages/react-native-executorch --- # Skill: Skills Maintenance & Documentation Integrity @@ -32,8 +32,27 @@ Use this guide when you introduce, modify, or deprecate core codebase patterns, - Ensure all code blocks and examples in updated skills compile/work and match actual usage in the repository. - Do not leave references to deprecated fields, functions, or old workflows. -4. **Update the Checklist**: - - If a new verification rule is introduced (e.g., "must use helper X instead of manual code Y"), update the **Verification Checklist** section at the bottom of the relevant skill's `SKILL.md`. +4. **Keep Each Rule in One Place**: + - Architecture and exports belong in [core guidelines](../core-guidelines/SKILL.md), resource + ownership in [task pipelines](../add-task-pipeline/SKILL.md), coded errors in + [error handling](../error-handling/SKILL.md), and check selection in + [verify and build](../verify-and-build/SKILL.md). Link to the owning skill from related procedures. + - Keep [AGENTS.md](../../../AGENTS.md) as the short contributor entry point. Add routing when a task + needs different guidance; do not copy every skill into the root file. + - Retain concrete invariants and their reasons. Remove outdated examples or conflicting checklists; + avoid turning a single failure into an unrelated universal restriction. + +5. **Validate the Changed Guidance**: + - Run `yarn check:guidance` from the repository root. It checks YAML, required names/descriptions, + directory/name agreement, metadata value types and local file links in `AGENTS.md` and skill + Markdown. It ignores fenced examples and does not fetch external URLs or validate anchors. + - Format changed files with the repository's Prettier. Typecheck complete TypeScript templates + against their intended package paths; distinguish those from schematic snippets containing + placeholders. Review shell commands and source references against current scripts. + - The validator cannot establish semantic correctness or agent behavior. For substantial workflow + changes, try representative contributor requests (a TS-only task, a native op, and a prose-only + edit) and inspect whether routing and verification choices are appropriate. Keep these checks + scoped to available prerequisites; do not provision a device merely to validate prose. --- @@ -45,3 +64,6 @@ When introducing or refactoring a pattern, verify that: - [ ] You updated all examples and templates to reflect the new, correct APIs and idioms. - [ ] You updated the corresponding checklists to enforce the new conventions. - [ ] The updated skill files are valid markdown and keep lines reasonably short. +- [ ] Root routing still reaches the relevant skills without loading unrelated procedures. +- [ ] `yarn check:guidance` passes, and changed complete examples were checked against actual APIs. +- [ ] The PR identifies verification performed and any remaining limitations. diff --git a/.agents/skills/verify-and-build/SKILL.md b/.agents/skills/verify-and-build/SKILL.md index 814af7ec00..47ac9f323b 100644 --- a/.agents/skills/verify-and-build/SKILL.md +++ b/.agents/skills/verify-and-build/SKILL.md @@ -1,206 +1,159 @@ --- name: verify-and-build -description: Use when compiling TS/C++, rebuilding iOS pods, troubleshooting JSI runtime errors, debugging native crashes, or sync'ing Android Gradle. +description: Use when selecting verification for library changes, building TypeScript or C++, rebuilding native apps, or troubleshooting JSI and device runtime failures. metadata: id: verify_and_build - scope: general development, apps/ + scope: packages/react-native-executorch, apps, docs --- -# Skill: Verification, Compilation & Troubleshooting +# Verification, builds and runtime debugging -Use this guide to compile, test, verify, and troubleshoot your modifications to the library (both JS/TS and native C++). +Run root commands from the repository root and package commands from +`packages/react-native-executorch/`. Select checks for the behavior changed; do not run native builds +for prose edits. Report missing prerequisites and skipped suites separately from passed checks. ---- +## Verification matrix -## 🛠️ Verification & Compilation Workflows +| Change | Checks | Limits and additional verification | +| -------------------------------------- | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| Contributor guidance or skills | `yarn check:guidance`; Prettier on changed Markdown; inspect examples against source | Typecheck complete changed TS examples; review schematic snippets against source | +| Library TypeScript behavior | Package typecheck, relevant Jest suites and package build; lint changed code | Broaden tests for shared APIs; fake JSI does not verify production C++ or model output | +| Public exports or model registry | Package typecheck/build, API surface or model registry suites | Inspect export snapshot diffs; verify new models/backends on the relevant device | +| C++/JSI | Native static checks and relevant host C++ suites; API tests for changed TS contracts | Rebuild affected platforms; host tests do not execute delegated inference | +| Native build/configuration | Affected platform build; installation/artifact checks where applicable | Pods/Gradle and binary provisioning depend on what changed | +| Docs pages, generators or API comments | `yarn build` from `docs/`; inspect relevant generated output | Site checks do not prove code samples run on-device | -### 1. Build and Typecheck TypeScript +For cross-workspace changes, use root `yarn typecheck` and relevant app checks. Repeat or broaden checks +when additional changes, failures or remaining uncertainty justify it. -To check types and compile the TypeScript source code: +## TypeScript checks -- **Verify Types (Fast)**: - ```bash - yarn typecheck - ``` -- **Run the TypeScript API Tests**: - ```bash - yarn workspace react-native-executorch test - ``` - _Jest suites over the public `src/` surface — hooks, task pipelines, core - primitives, the fetcher and the model registry — running against a fake - native runtime, so they need no simulator, device or `.pte` file. See the - [Add API Tests skill](../add-api-tests/SKILL.md)._ -- **Build Bundles**: - ```bash - yarn prepare - ``` - _This cleans target directories and builds modules into the `lib/` directory using `react-native-builder-bob`._ -- **When**: After adding/updating TypeScript files under `src/`. -- **Verification**: Ensure no compiler or type-checking errors are raised. +From the repository root: -### 2. Native Rebuilding +```bash +yarn workspace react-native-executorch typecheck +yarn workspace react-native-executorch test +yarn workspace react-native-executorch prepare +``` -#### iOS Development +The package typecheck includes `__tests__/`. Target suites by path for focused iteration, for example +`yarn workspace react-native-executorch test __tests__/tasks`. See +[API tests](../add-api-tests/SKILL.md) for fixtures, lifecycle and construction-failure assertions. -Whenever you modify native files under `cpp/` or update `.podspec`: +`prepare` runs `react-native-builder-bob` to produce JS and declaration outputs. Root `yarn prepare` +runs workspace preparation; root `yarn typecheck` runs preparation first and then checks workspace types. +Avoid running the same build again solely because it has a different entry command. -```bash -pushd apps//ios && pod install && popd -``` +Root `yarn lint` runs workspace lint scripts; some app scripts use `--fix`, so inspect resulting changes. +For focused library linting, run ESLint on changed files from the package directory. + +## C++ static checks -- **Rebuilding**: Re-run the app from within the appropriate app folder: - ```bash - cd apps/ - yarn run ios - ``` -- **Clean Build**: If files aren't being picked up: - - In Xcode: `Product` > `Clean Build Folder` (Cmd + Shift + K). +Run both checks for C++ changes when prerequisites are available. The warning checker may exit 0 after +skipping work: read its output rather than reporting that as a successful compilation. -#### Android Development +### clang-tidy -Android compiles C++ source files on-demand during application builds: +From the repository root on macOS with Homebrew LLVM: ```bash -cd apps/ -yarn run android +CLANG_TIDY=$(brew --prefix llvm)/bin/clang-tidy yarn workspace react-native-executorch lint:cpp ``` -- **Clean Build**: If caching issues occur: - ```bash - pushd apps//android && ./gradlew clean && popd - ``` +On other hosts, use `yarn workspace react-native-executorch lint:cpp` with compatible `clang-tidy` on +PATH, or set `CLANG_TIDY` to its executable. The Xcode toolchain does not supply the required checker. +Requires JSI and provisioned third-party headers. See +[third-party setup](../../../packages/react-native-executorch/third-party/README.md). ---- +Local LLVM can report findings absent from CI. Compare a finding against unchanged base code before +expanding scope. Keep platform-independent includes and namespace aliases outside platform branches; +a macOS check cannot validate Android-only compilation. -## 🧹 C++ Static Analysis +### Compiler warnings -Two complementary checks gate C++ quality. Always run both before committing. - -### 1. `lint:cpp` — clang-tidy - -Runs the project's `.clang-tidy` ruleset (bugprone / performance / clang-analyzer / llvm-include-order) over all `cpp/` sources. +From the package directory, pass changed files explicitly, for example: ```bash -# clang-tidy must be installed from Homebrew LLVM — the Xcode bundled version is too old: -CLANG_TIDY=$(brew --prefix llvm)/bin/clang-tidy yarn workspace react-native-executorch lint:cpp +./scripts/check-cpp-warnings.sh cpp/core/tensor.cpp ``` -- Requires ExecuTorch headers provisioned under `third-party/include` and `yarn install` (for JSI headers). -- Any finding fails the run (`--warnings-as-errors`). Suppress a deliberate, reviewed finding with `// NOLINTNEXTLINE(check-name)` rather than relaxing the shared config. -- **Homebrew LLVM is newer than CI's clang-tidy and reports checks CI does not have.** Before "fixing" a local finding, copy the unmodified base-branch version of the file in under a temp name and lint that too. A finding that also fires there is pre-existing and is not yours to fix in your PR. -- **A local macOS-only syntax check cannot see platform-conditional code.** Anything inside `#if defined(__ANDROID__)` / `#elif defined(__APPLE__)` compiles locally and can still fail CI on another target. Check by eye that new includes and `using` declarations sit at file scope, outside every preprocessor branch. - -### 2. `check-cpp-warnings.sh` — clangd warning set - -Compiles staged (or explicitly passed) `cpp/` sources with the same flags clangd uses in the editor (from `compile_flags.txt` + `-W` flags in `.clangd`), so the editor and CI stay in sync. Run from the package root (`packages/react-native-executorch/`): +For all production sources: ```bash -# The script takes file paths as positional arguments and exits 0 immediately -# with none — it has no built-in file discovery. Pass files explicitly: find cpp/ -path cpp/tests -prune -o \( -name '*.cpp' -o -name '*.h' \) -print | \ xargs ./scripts/check-cpp-warnings.sh ``` -The script skips gracefully (exit 0) when no compiler, `compile_flags.txt`, `.clangd`, or provisioned headers are found — it never blocks contributors who don't build the native code. - ---- - -## 🔍 Debugging & Log Access - -### 1. TypeScript & Worklet Logging - -Logging inside worklets (functions annotated with `'worklet';`) behaves slightly differently as they run on a separate runtime thread. - -- Use standard `console.log(...)` inside worklets. -- **Caution**: Worklet logs are piped back to the JS console, but passing complex circular objects to `console.log` from a worklet can fail or freeze. Stringify or log specific primitive properties instead. +The script has no file discovery and does nothing with no arguments. It skips when the compiler, +configuration or headers are missing. It uses `compile_flags.txt` and `.clangd`, not the mobile app's +entire platform build configuration. -### 2. Native C++ Debugging +## Host C++ tests -Native JSI crashes, standard outputs, or ExecuTorch errors can be caught in the native log streams: +The [C++ test README](../../../packages/react-native-executorch/cpp/tests/README.md) owns dependency, +submodule and fixture provisioning. From the package directory after provisioning: -- **iOS**: Watch outputs directly inside the Xcode Console while running the app target. -- **Android**: Use Android Studio's logcat or run: - ```bash - adb logcat *:S ReactNative:V ReactNativeJS:V rnexecutorch:V - ``` - ---- +```bash +scripts/run-native-tests.sh +scripts/run-native-tests.sh -R MathOpsTest +``` -## 🚦 Common JSI Troubleshooting +These suites use Hermes and an ExecuTorch host build to test real JSI contracts. They require CMake, +Ninja, headers and pinned native dependencies. Optional OpenCV/phonemis support and downloaded fixtures +affect which suites run. Inspect CMake/CTest output and report disabled or omitted coverage. Provisioning +can take several minutes; do not repeatedly rebuild unchanged dependencies. -### Symptom: `Error: JSI global object '__rnexecutorch_jsi__' is not registered.` +Host tests do not establish model execution with mobile delegates, LLM generation quality, or actual +phoneme output. Use device/emulator integration for those behaviors. -- **Cause 1**: The native code wasn't linked or JSI installation failed during loading. - - _Fix_: Verify that you have registered your new extension/module in [cpp/RnExecutorch.cpp](../../../packages/react-native-executorch/cpp/RnExecutorch.cpp). - - _Fix_: Re-run `pod install` (for iOS) or perform a Gradle sync/clean (for Android) to ensure your C++ changes compiled. -- **Cause 2**: The bridge did not invoke the native installation. - - _Fix_: Ensure the JS entrypoint triggers the load (see [src/native/bridge.ts](../../../packages/react-native-executorch/src/native/bridge.ts)). +## Native app verification -### Symptom: `TypeError: Cannot read property '' of undefined` +Choose the relevant app (`computer-vision`, `nlp` or `speech`) and inspect its current native setup. +Provision matching native libraries before rebuilding. If iOS native projects already exist, run +`pod install` in the app's `ios/` directory when dependencies, podspec files or source discovery change. +C++ source edits require recompilation, not necessarily pod reinstallation. Do not assume generated +`ios/` or `android/` directories exist in a fresh Expo checkout. -- **Cause**: You added an extension in C++ but forgot to register it in your TypeScript bridge bindings. - - _Fix_: Check that `module.setProperty(rt, "", subModule)` is called in your native `install.cpp` and that your TS wrapper exports and references it under `rnexecutorchJsi.`. +From the selected app directory: ---- +```bash +yarn ios +# or +yarn android +``` -## 📂 Model Hosting & Download Caching - -This project does **not** bundle local `.pte` model files inside the React Native application package. Instead, the standard workflow is: - -1. **Upload to Hugging Face**: - - Upload compiled/exported `.pte` models directly to our Hugging Face repository bucket. - - **Naming Convention**: All `.pte` files must follow the strict name contract: - `modelname_optionalsize_backend_precision.pte` - - _Example_: `efficientnet_v2_s_xnnpack_int8.pte` - - _Example_: `style_transfer_candy_xnnpack_fp32.pte` - -2. **Define in Models Manifest** ([src/models.ts](../../../packages/react-native-executorch/src/models.ts)): - - **Single Export Registry Rule**: Define the new model configuration as an internal (private) `const` inside `models.ts`. **Do not** export individual model configuration constants. Instead, expose them solely by registering them under the appropriate category nested inside the main `models` registry object, which is the only exported symbol from `models.ts`. - - _Example_: - - ```typescript - // Defined internally (private) - const MY_MODEL_XNNPACK_FP32: MyTaskModel = { ... }; - - // Registered in the exported models object - export const models = { - ... - myTask: { - MY_MODEL: { - XNNPACK_FP32: MY_MODEL_XNNPACK_FP32, - } - } - }; - ``` - -3. **Runtime Downloading & Caching**: - - The custom hook `useResourceDownload(config.modelPath)` handles checks automatically: - - If the model file is not already in the device cache directory, it downloads it from the Hugging Face URL to `RNFS.CachesDirectoryPath`. - - If the model file exists in the cache, it bypasses the download and returns the cached local path immediately to load the model. +The app scripts use Expo native build commands. iOS needs macOS/Xcode and CocoaPods; Android needs its +SDK/NDK and a suitable device/emulator. Clear build caches only when stale output explains a failure. +For changes shared by both platforms, verify both or record which remains unverified. ---- +## JSI and worklet troubleshooting -## 🚫 Avoid / Anti-Patterns +- **JSI global not registered:** inspect + [the bridge](../../../packages/react-native-executorch/src/native/bridge.ts) and native linkage; + confirm the rebuilt app includes the module. Native installation is wired in + [RnExecutorch.cpp](../../../packages/react-native-executorch/cpp/RnExecutorch.cpp). +- **Missing domain/operator:** compare the domain `install.cpp`, bridge wrapper and TypeScript exports. + Adding an operator to an existing domain usually needs no new top-level domain registration. +- **Native crash or execution error:** collect Xcode console or Android logcat output and the model, + platform, backend and input schema. Use coded failures as described in + [error handling](../error-handling/SKILL.md). +- **Worklet logging:** log primitives or selected properties. Passing circular/native resource objects + to the logger can freeze or fail across runtimes. -- **Do NOT run code without verification:** Do not test TypeScript changes in the app without first running `yarn typecheck` (verify types), `yarn workspace react-native-executorch test` (API suites) and `yarn prepare` (build target bundles). -- **Do NOT skip native rebuilds after C++ edits:** If any C++ files or config bindings are added/modified, do not attempt to run the app without executing `pod install` (for iOS) or letting Gradle sync (for Android). -- **Do NOT run `lint:cpp` with the system `clang-tidy`**: Use the Homebrew LLVM binary: `CLANG_TIDY=$(brew --prefix llvm)/bin/clang-tidy yarn workspace react-native-executorch lint:cpp`. -- **Do NOT trust a green macOS-only syntax check for platform-conditional C++:** see the clang-tidy notes above. -- **Do NOT log complex objects inside worklets:** Avoid passing complex circular objects directly to `console.log()` inside functions annotated with `'worklet';` as it can hang or crash the worklet runtime thread. -- **Do NOT bundle local `.pte` files in the repository:** Do not commit heavy model binaries to the git repository. Always host them on Hugging Face and register their metadata in `src/models.ts`. +For Android logs: ---- +```bash +adb logcat '*:S' ReactNative:V ReactNativeJS:V rnexecutorch:V +``` -## 📋 Verification Checklist +## Model downloads and registry changes -When verifying or compiling your modifications, check that: +Inspect [the fetcher](../../../packages/react-native-executorch/src/fetcher/fetcher.ts) and +[useResourceDownload](../../../packages/react-native-executorch/src/hooks/useResourceDownload.ts) +before debugging downloads. The hook resolves URLs throughout a nested config, delegates to `download`, +and reports progress from 0 to 100. Storage uses `react-native-blob-util`: persistent document storage +on iOS and the configured Android storage path, not `RNFS.CachesDirectoryPath`. -- [ ] TypeScript typechecking passes without errors (`yarn typecheck`). -- [ ] The TypeScript API tests pass (`yarn workspace react-native-executorch test`), and any new `src/` behavior is covered by them. -- [ ] Bundles compile successfully (`yarn prepare`). -- [ ] `pod install` has been run inside `apps//ios/` after any native C++ edits. -- [ ] `lint:cpp` passes cleanly: `CLANG_TIDY=$(brew --prefix llvm)/bin/clang-tidy yarn workspace react-native-executorch lint:cpp`. -- [ ] `check-cpp-warnings.sh` passes cleanly (run via `find cpp/ -name '*.cpp' -o -name '*.h' | xargs ./scripts/check-cpp-warnings.sh` from the package root). -- [ ] No `.pte` files are staged or added to git history. -- [ ] Model configurations are registered inside the single `models` object registry in `src/models.ts`. -- [ ] Native runtime issues have been investigated using Xcode Console or `adb logcat`. +Registry URL/revision/filename/default invariants are checked by the model registry API tests. Use +[core guidelines](../core-guidelines/SKILL.md) for registry ownership. Do not commit downloaded `.pte` +binaries; use pinned hosted assets or the existing checksum-verified test fixture mechanism. diff --git a/.github/workflows/check-guidance.yml b/.github/workflows/check-guidance.yml new file mode 100644 index 0000000000..77036722db --- /dev/null +++ b/.github/workflows/check-guidance.yml @@ -0,0 +1,28 @@ +name: Check contributor guidance + +on: + pull_request: + paths: + - 'AGENTS.md' + - '.agents/**' + - 'package.json' + - 'yarn.lock' + - '.github/actions/setup/**' + - '.github/workflows/check-guidance.yml' + # Renaming source files can break links from otherwise unchanged skills. + - 'packages/react-native-executorch/**' + - 'docs/README.md' + push: + branches: [main] + merge_group: + types: [checks_requested] + workflow_dispatch: + +jobs: + check: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v6 + - uses: ./.github/actions/setup + - run: yarn check:guidance diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7b46ab8cf9..463f9299d6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -68,9 +68,9 @@ jobs: # set this job provably cannot be affected by", so a path nobody # thought of runs the job instead of silently skipping it. - # eslint, tsc and jest read none of the C++ trees, and none of the - # documentation. - ts_irrelevant='^(docs/|[^/]+\.md$|packages/react-native-executorch/cpp/)' + # eslint, tsc and jest read none of the C++ trees or contributor/docs + # Markdown. Contributor guidance has its own validation workflow. + ts_irrelevant='^(docs/|\.agents/|[^/]+\.md$|packages/react-native-executorch/cpp/)' if echo "$files" | grep -qvE "$ts_irrelevant"; then ts=true; else ts=false; fi # The C++ suite compiles cpp/ only (cpp/tests/CMakeLists.txt globs diff --git a/.gitignore b/.gitignore index 384eb8ba29..6dee0b4545 100644 --- a/.gitignore +++ b/.gitignore @@ -104,6 +104,7 @@ Makefile .agents/* !.agents/skills/ +!.agents/scripts/ .claude skills-lock.json diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000000..d3d1b89d7e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,61 @@ +# Contributing with an agent + +This repository develops React Native ExecuTorch. These instructions cover library contributions; +application integration guidance lives in the documentation. + +## Workspace and setup + +- `packages/react-native-executorch/`: published library; TypeScript in `src/`, native code in `cpp/`, + API tests in `__tests__/`, host C++ tests in `cpp/tests/`. +- `apps/computer-vision/`, `apps/nlp/`, `apps/speech/`: Expo development apps for device verification. +- `docs/`: Docusaurus site with its own package and build scripts. +- `.agents/skills/`: contributor procedures. Paths starting with `src/` or `cpp/` inside skills are + relative to `packages/react-native-executorch/` unless stated otherwise. `metadata.scope` describes + relevant paths; it is not an automatic instruction-loading mechanism. + +Use the Node version in `.nvmrc` and Yarn version in root `package.json`. Run `yarn install --immutable` +from the repository root. The install normally provisions native binaries; for TypeScript-only work, +`RNET_SKIP_DOWNLOAD=1 yarn install --immutable` skips that download. Native builds need matching +headers/binaries and platform toolchains; see the verification skill before provisioning them. + +## Load guidance for the task + +Read only relevant skills. Start with core guidelines when learning the architecture. + +| Task | Skill | +| ------------------------------------------------------------ | -------------------------------------------------------------------------- | +| Architecture, package boundaries, exports and model registry | [Core guidelines](.agents/skills/core-guidelines/SKILL.md) | +| TypeScript task pipeline or React hook | [Add task pipeline](.agents/skills/add-task-pipeline/SKILL.md) | +| C++ operation, JSI host function or native registration | [Add native extension](.agents/skills/add-native-extension/SKILL.md) | +| Model schemas, method signatures and dimension constraints | [Model schema validation](.agents/skills/model-schema-validation/SKILL.md) | +| Throwing, catching or adding error codes | [Error handling](.agents/skills/error-handling/SKILL.md) | +| TypeScript behavior and fake-runtime tests | [Add API tests](.agents/skills/add-api-tests/SKILL.md) | +| Selecting checks, native builds or runtime debugging | [Verify and build](.agents/skills/verify-and-build/SKILL.md) | +| Changing established APIs, helpers, conventions or skills | [Skills maintenance](.agents/skills/skills-maintenance/SKILL.md) | +| Documentation source, generation or versioning | [Documentation README](docs/README.md) | + +## Working rules + +- Match existing code before inventing a new pattern. Core stays domain-agnostic; task orchestration + belongs in TypeScript extensions. TypeScript-only changes do not require a C++ counterpart. +- Update public exports deliberately. Model configurations come from `src/models.ts`; shared labels + and constants come from `src/constants.ts`. +- Follow the task skill for native resource ownership and the error skill for coded failures across + JSI/worklet boundaries. +- Update affected skills alongside API or convention changes. Link to the owning skill instead of + copying its rules into other files. + +## Verification + +Choose checks using the [verification matrix](.agents/skills/verify-and-build/SKILL.md#verification-matrix). +Commands below run from the repository root unless stated otherwise: + +- `yarn check:guidance`: contributor metadata and local link validation. +- `yarn workspace react-native-executorch typecheck`: package types, including API tests. +- `yarn workspace react-native-executorch test`: TypeScript API tests against a fake native runtime. +- `yarn workspace react-native-executorch prepare`: build published JS and declaration outputs. +- `yarn typecheck`: broader workspace verification; runs `yarn prepare` first. +- `yarn build` from `docs/`: generated documentation and site validation. + +Report checks actually run and missing prerequisites or skipped suites. Fake-runtime tests and host C++ +tests do not prove device inference works. Documentation/skill-only changes need no native rebuild. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 097a37aa8a..9f1b7c156d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,10 @@ Thank you for your interest in contributing to react-native-executorch! +For repository layout, task-specific contributor skills and verification commands, see +[AGENTS.md](./AGENTS.md). When changing an API, build command or established pattern, update affected +guidance alongside the code. Run `yarn check:guidance` after editing contributor instructions or skills; +it validates metadata and local file links, not the behavior of code examples. + # Ways to contribute There are several ways you can contribute to react-native-executorch: diff --git a/package.json b/package.json index 41f61bca8b..06e7a895c8 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ ] }, "scripts": { + "check:guidance": "node .agents/scripts/check-guidance.mjs", "prepare": "yarn workspaces foreach --all --topological-dev run prepare", "lint": "yarn workspaces foreach --all --parallel run lint", "typecheck": "yarn prepare && yarn workspaces foreach --all --parallel run typecheck" @@ -31,7 +32,8 @@ "prettier": "^3.3.3", "prettier-plugin-jsdoc": "^1.3.0", "react-native-worklets": "0.13.0", - "typescript": "~5.9.2" + "typescript": "~5.9.2", + "yaml": "^2.7.1" }, "resolutions": { "react-native-worklets": "0.13.0" diff --git a/yarn.lock b/yarn.lock index 1166ea8d67..9ec2ffc33f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -12976,6 +12976,7 @@ __metadata: prettier-plugin-jsdoc: "npm:^1.3.0" react-native-worklets: "npm:0.13.0" typescript: "npm:~5.9.2" + yaml: "npm:^2.7.1" languageName: unknown linkType: soft From 847db3a30be26905adb16c51b781bcfc9aa56c34 Mon Sep 17 00:00:00 2001 From: Bartosz Hanc Date: Mon, 2 Nov 2026 18:05:18 +0100 Subject: [PATCH 2/2] docs: simplify contributor skills README --- .agents/skills/README.md | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/.agents/skills/README.md b/.agents/skills/README.md index 22e9973386..d581f43082 100644 --- a/.agents/skills/README.md +++ b/.agents/skills/README.md @@ -1,19 +1,5 @@ -# Development Skills Directory +# Contributor skills -This directory contains specialized skills (recipes) to guide contributors and AI coding assistants in extending the codebase cleanly and consistently. +Task-specific procedures for contributing to React Native ExecuTorch live in each skill's `SKILL.md`. -Start with [the repository contributor entry point](../../AGENTS.md) for setup and task routing. -Load only the relevant skills. Package-relative `src/` and `cpp/` paths refer to -`packages/react-native-executorch/`; metadata scopes describe relevance and do not automatically load -instructions. Run `yarn check:guidance` from the repository root after edits. - -## Available Skills - -- [Core Guidelines](./core-guidelines/SKILL.md) — Symmetrical architecture, conventions, and model rules. -- [Add Native Extension](./add-native-extension/SKILL.md) — C++ operations and JSI bindings. -- [Add Task Pipeline](./add-task-pipeline/SKILL.md) — TypeScript task pipelines and React hooks. -- [Model Schema Validation](./model-schema-validation/SKILL.md) — Model specs, dynamic shapes, and schema validation. -- [Error Handling](./error-handling/SKILL.md) — Error codes, throwing across worklet and JSI boundaries, and catching. -- [Add API Tests](./add-api-tests/SKILL.md) — TypeScript API test suites and the fake native runtime. -- [Verify and Build](./verify-and-build/SKILL.md) — TypeScript typechecking, native rebuilding, and troubleshooting. -- [Skills Maintenance](./skills-maintenance/SKILL.md) — Keeping skills synchronized with core primitives. +Start with the root [AGENTS.md](../../AGENTS.md) for setup, task routing, and verification commands.