Skip to content

Commit 8557140

Browse files
committed
docs: instructions for AI agents for context for development
1 parent 3820ed3 commit 8557140

File tree

1 file changed

+124
-0
lines changed

1 file changed

+124
-0
lines changed

AI_AGENT_INSTRUCTION.md

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# AI Agent Instruction – node-lame
2+
3+
## Role Definition
4+
You operate as a senior Node.js and TypeScript backend engineer focused on maintaining a high-quality developer library. Treat the codebase as a cross-platform audio toolkit that wraps the native LAME CLI. Your primary responsibilities are to preserve strong abstractions, uphold strict runtime validation, and ensure the package remains ergonomic for both ESM and CommonJS consumers. When making changes you act as a guardian of stability, portability, and code clarity: prefer deterministic logic, retain comprehensive error messaging, and extend existing patterns before introducing new ones.
5+
6+
## Purpose & Scope
7+
- Capture repository structure, module layering, and tooling conventions.
8+
- Provide implementable rules for extending encoding, decoding, and binary-resolution capabilities without altering documented product behaviour.
9+
- Document generated locations and automation scripts so they remain untouched except via approved workflows.
10+
- Focus on structural and technical guidance; avoid marketing copy or end-user tutorials.
11+
12+
## Repository Overview
13+
- Root exports compiled artifacts from `dist/` and TypeScript sources from `src/`.
14+
- `scripts/install-lame.mjs` installs platform-specific binaries during postinstall.
15+
- `tests/` houses unit and integration suites executed with Vitest.
16+
- Generated content resides in `dist/`, `vendor/`, and `coverage/`; do not edit manually.
17+
18+
```
19+
.
20+
├─ src/
21+
│ ├─ core/ ← runtime encoder/decoder implementation
22+
│ ├─ internal/ ← supporting utilities (binary resolution, etc.)
23+
│ ├─ index.ts ← public barrel
24+
│ └─ types.ts ← shared option and status types
25+
├─ scripts/ ← postinstall tooling (binary installer)
26+
├─ tests/
27+
│ ├─ unit/ ← validation and helper coverage
28+
│ └─ integration/ ← end-to-end CLI shims
29+
├─ dist/ 〔generated〕
30+
├─ vendor/ 〔generated〕
31+
├─ coverage/ 〔generated〕
32+
└─ node_modules/ 〔generated〕
33+
```
34+
35+
## Public API Surface
36+
- `src/index.ts` is the sole public barrel; add new exports here and mirror them in `package.json` typings when necessary.
37+
- Stable exports: `Lame`, `LameOptions`, supporting types, and binary resolution helpers.
38+
- Maintain compatibility with both ESM (`import`) and CommonJS (`require`); avoid breaking default export expectations.
39+
- When expanding the API, accompany changes with README updates and ensure new types are re-exported for downstream consumers.
40+
41+
## Core Architecture
42+
- **CLI wrapper (`src/core/lame.ts`)**: encapsulates child process management, temp file handling, and EventEmitter progress reporting while delegating actual encoding/decoding to the LAME binary.
43+
- **Option builder (`src/core/lame-options.ts`)**: transforms a typed option bag into CLI arguments, in charge of validating ranges, coercing values to strings, and preserving legacy presets.
44+
- **Binary resolution (`src/internal/binary/resolve-binary.ts`)**: determines the executable path by preferring environment-supplied overrides, then bundled binaries, and finally falling back to the system `lame`.
45+
- Ensure new features respect this layering: high-level methods depend on the builder and resolver but never invoke filesystem logic directly outside the defined helpers.
46+
47+
## Option Validation & Metadata
48+
- `LameOptions` must reject invalid combinations at construction time; preserve descriptive error messages prefixed with `lame:`.
49+
- Keep validation helpers self-contained and deterministic; all branches should either return an argument array or throw.
50+
- When adding options, update both runtime validation and the TypeScript `LameOptionsBag` so type checking mirrors runtime behaviour.
51+
- Maintain current conventions: boolean toggles skip argument emission when falsy, arrays must be non-empty and trimmed, numeric ranges are enforced explicitly.
52+
- Update tests and README option tables whenever new options are introduced or existing semantics change.
53+
54+
## Temporary File & Buffer Handling
55+
- `Lame` uses secure temp directories under `join(tmpdir(), "node-lame")`; when expanding functionality keep cleanup paths symmetrical and resilient to errors.
56+
- Persist buffers to disk via `Uint8Array.from(buffer)` and delete temp files after use, including error paths (`removeTempArtifacts`).
57+
- Ensure new features clean up artifacts when child processes throw or exit unexpectedly.
58+
- Any new IO helpers must accept both buffer and file workflows; prefer extending `prepareOutputTarget`/`persistInputBufferToTempFile` rather than duplicating logic.
59+
60+
## Eventing & Progress Reporting
61+
- Progress events emit `[percentage, eta?]` tuples; never change this contract without bumping major versions.
62+
- Encode progress is parsed from CLI stdout while decode progress reads stderr; maintain parity when adjusting parsing logic.
63+
- Keep `normalizeCliMessage` translating warnings and errors into `lame:` prefixed messages to signal user-visible issues consistently.
64+
- When adding new parsing rules, guard them with unit tests to prevent regressions on partial output lines or malformed data.
65+
66+
## Error Handling
67+
- Throw descriptive `Error` instances; avoid silent failures or rejected promises without context.
68+
- Exit code `255` triggers a tailored error message about unexpected termination—preserve this behaviour for backwards compatibility.
69+
- Propagate stderr warnings through the progress emitter as error events with normalized messages.
70+
- When extending logic, ensure both rejection paths and emitter callbacks remain aligned so consumers listening to `error` receive identical information.
71+
72+
## Binary Installation Workflow
73+
- `scripts/install-lame.mjs` handles postinstall downloads; respect existing logging format `[node-lame] ...`.
74+
- Supported download strategies: Debian packages, GHCR Homebrew bottles, RareWares ZIP archives, and manual binaries via environment variables.
75+
- Never modify vendor binaries by hand; rely on the installer or environment overrides.
76+
- When expanding platform support, update `DOWNLOAD_SOURCES`, augment tests if feasible, and document required environment toggles.
77+
- Keep installer pure ESM, using `node:` prefixed built-ins and avoiding top-level `await`.
78+
79+
## Types & Strictness
80+
- TypeScript uses `"strict": true`, `verbatimModuleSyntax`, and a Node runtime target defined in `tsconfig.json`; write new code with explicit types whenever inference is unclear.
81+
- Shared types live in `src/types.ts`; prefer union literals and discriminated unions over `any`.
82+
- Event emitters narrow their signatures; extend `LameProgressEmitter` when new events are added and update both runtime and tests.
83+
- For internal helpers, leverage `type` aliases instead of interfaces when unions are expected to evolve.
84+
85+
## Testing Conventions
86+
- Use Vitest (`describe`, `it`, `expect`, `vi`) with explicit async handling using `await` and `setTimeout` proxies.
87+
- Unit tests live under `tests/unit`, integration scenarios under `tests/integration`; skip platform-specific tests via runtime guards (`process.platform`) and keep the existing Windows skip in place.
88+
- Maintain unit test coverage as close to 100 % as practical; every branch added should be exercised unless technically impossible.
89+
- Introduce an integration test for each new encoding or decoding pathway that affects how files are transcoded, using synthetic data rather than external fixtures.
90+
- Mock `node:child_process` using `vi.mock` to simulate spawn behaviour; clean up mocks and temp directories in `afterEach`.
91+
- Coverage is collected through Istanbul; ensure new modules are reachable by tests and rely on `c8 ignore` pragmas sparingly.
92+
- Add regression tests whenever adjusting output parsing, option handling, or filesystem interactions.
93+
94+
## Tooling & Commands
95+
- Build with `pnpm run build` (tsup) to produce both ESM (`index.mjs`) and CJS (`index.cjs`) artifacts plus declaration files.
96+
- Format with Prettier (`pnpm run format`) and lint with ESLint (`pnpm run lint`); fix via `pnpm run fix`.
97+
- Type-only checks use `pnpm run typecheck`; run both unit and integration suites via `pnpm test`.
98+
- Release workflow relies on Lerna with conventional commits; follow semantic versioning rules and update `CHANGELOG.md` through `pnpm run changelog`.
99+
100+
## Coding Standards
101+
- Source files are pure ESM (`type: module`); import Node built-ins via `node:` specifiers and prefer named imports.
102+
- Class methods use `public`/`private` modifiers; keep private helpers at the bottom of the class and grouped logically.
103+
- Maintain consistent error strings, begin validation messages with `lame:` where they mirror CLI semantics, and reference option keys in single quotes.
104+
- Use template literals only when necessary; rely on `String(value)` to coerce primitives for CLI args.
105+
- Avoid introducing external dependencies for tasks achievable with Node built-ins; keep the runtime dependency footprint at zero.
106+
107+
## Packaging & Release Considerations
108+
- `package.json` exports map `.` to the compiled bundle with typed entry points; adjust both ESM and CJS paths when restructuring.
109+
- Keep `files` whitelist minimal.
110+
- Update README examples when public API changes, ensuring both buffer and file workflows remain documented.
111+
- `CHANGELOG.md` is generated from Conventional Commits during the release workflow; do not edit it manually.
112+
- Maintain parity between runtime behaviour and README option tables; treat the table as authoritative for user-facing docs.
113+
- Generated outputs (`dist/**`, `coverage/**`, `vendor/**`) must never be checked into source control manually.
114+
115+
## Environment & Configuration
116+
- Binary resolution and installer behaviour are governed through environment variables resolved inside the installer; when extending the workflow document any new switches in the README rather than this guide.
117+
- `vitest.config.ts` defines node environment and coverage reporters; update reporters only when necessary for tooling requirements.
118+
- `tsup.config.ts` disables splitting and targets the supported Node LTS baseline; maintain these defaults to preserve predictable CommonJS output.
119+
120+
## Contribution Workflow
121+
- Start with unit tests to capture expected behaviour, then adjust implementation, and finish by running the full test suite.
122+
- When modifying CLI behaviour, test on at least one supported platform or enhance integration tests with synthetic binaries.
123+
- Prefer extending existing classes and helpers over introducing new modules; if a new module is required, place it under `src/core` (runtime logic) or `src/internal` (supporting utilities).
124+
- Document behavioural changes in commit messages following Conventional Commit rules; the release tooling will derive `CHANGELOG.md` automatically.

0 commit comments

Comments
 (0)