mnemonica 1.2.3 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/FOR_HUMANS.md +160 -125
  2. package/README.md +70 -249
  3. package/build/api/types/index.js +18 -12
  4. package/build/index.js +6 -2
  5. package/docs/UTILS.md +97 -8
  6. package/docs/decorate.md +1 -1
  7. package/docs/empathy-in-ai.md +20 -10
  8. package/docs/prototype-chain.md +8 -7
  9. package/docs/typed-lookup.md +195 -5
  10. package/docs/typeomatica.md +8 -345
  11. package/package.json +6 -10
  12. package/src/api/types/index.ts +33 -20
  13. package/src/index.ts +12 -1
  14. package/.ai/AGENTS.md +0 -151
  15. package/.ai/ARCHITECT.md +0 -110
  16. package/.ai/DEBUG.md +0 -178
  17. package/.ai/ONBOARDING.md +0 -189
  18. package/.ai/PROTOTYPE-CHAIN.md +0 -155
  19. package/.ai/mode-ask.md +0 -121
  20. package/.ai/mode-orchestrator.md +0 -141
  21. package/.ai/performance-vs-security.md +0 -395
  22. package/.ai/rules-async-constructors.md +0 -352
  23. package/.ai/rules-code-style.md +0 -95
  24. package/.ai/rules-coding.md +0 -246
  25. package/.ai/rules-context-condensing.md +0 -50
  26. package/.ai/rules-contributing.md +0 -227
  27. package/.ai/rules-define-patterns.md +0 -159
  28. package/.ai/rules-ecosystem.md +0 -140
  29. package/.ai/rules-error-system.md +0 -66
  30. package/.ai/rules-hooks.md +0 -46
  31. package/.ai/rules-instance-methods.md +0 -93
  32. package/.ai/rules-philosophy.md +0 -231
  33. package/.ai/rules-reminders.md +0 -19
  34. package/.ai/rules-testing.md +0 -66
  35. package/.ai/rules-type-system.md +0 -124
  36. package/.ai/theory-of-operations.md +0 -224
  37. package/AGENTS.md +0 -345
  38. package/CONTRIBUTING.md +0 -150
  39. package/SKILL.md +0 -114
  40. package/docs/ai-learning-trajectory.md +0 -141
  41. package/docs/purpose.md +0 -707
  42. package/docs/tactica-deep-dive.md +0 -629
  43. package/docs/tactica-pattern.md +0 -146
@@ -1,224 +0,0 @@
1
- # Theory of Operations
2
-
3
- ## The Full Construction Pipeline
4
-
5
- This document traces a single `new instance.SubType(args)` call through every stage of mnemonica's internals, with references to the source files that implement each stage. It exists so that contributors (human and AI) can understand the exact data flow without reverse-engineering the code.
6
-
7
- ---
8
-
9
- ## Stage 0: Type Definition (`define()`)
10
-
11
- **File:** [`src/api/types/index.ts`](../src/api/types/index.ts)
12
-
13
- Before any instance exists, the type must be declared. `define('TypeName', ctor, config?)` performs:
14
-
15
- 1. **Resolve definition context** — determines whether this is a root type or a nested path (`Parent.SubType`)
16
- 2. **Check for duplicates** — throws `ALREADY_DECLARED` if the name exists in the target collection
17
- 3. **Compile the constructor body** — `compileNewModificatorFunctionBody.ts` wraps the user's constructor in a function that preserves `new.target` and handles both class and function constructors
18
- 4. **Create a `TypeDescriptor`** — stores: name, compiled handler, prototype, config, parent type reference
19
- 5. **Register in the `TypesCollection` Proxy** — makes the type findable via `.lookup()` and `.define()`
20
-
21
- The result is a `TypeProxy` — a constructor function with additional methods (`.define()`, `.lookup()`, `.registerHook()`).
22
-
23
- **Key invariant:** A type is immutable once defined. Its name, handler, and prototype are frozen.
24
-
25
- ---
26
-
27
- ## Stage 1: Subtype Access (`instance.SubType`)
28
-
29
- **File:** [`src/api/types/Mnemosyne.ts`](../src/api/types/Mnemosyne.ts)
30
-
31
- When code reads `instance.SubType`, the `Mnemosyne` proxy's `get` trap fires:
32
-
33
- 1. Look up `SubType` in the instance's `__subtypes__` Map (stored in the WeakMap)
34
- 2. If found, call `prepareSubtypeForConstruction(subtype, instance)`
35
- 3. This creates a **subtype proxy** — a function that closes over both the `TypeDef` and the parent `instance`
36
-
37
- The subtype proxy is what makes `new instance.SubType()` work. It is not the raw constructor; it is a wrapper that knows which parent instance to use.
38
-
39
- **Key invariant:** Every access to `instance.SubType` creates a fresh proxy (this was a deliberate design decision; caching is possible but not implemented to keep the code simple).
40
-
41
- ---
42
-
43
- ## Stage 2: Construction Invocation (`new instance.SubType(args)`)
44
-
45
- **File:** [`src/api/types/Mnemosyne.ts`](../src/api/types/Mnemosyne.ts)
46
-
47
- The subtype proxy's `construct` trap fires:
48
-
49
- 1. Call `new InstanceCreator(subtype, instance, args)`
50
- 2. The `InstanceCreator` is the orchestrator for the full lifecycle
51
-
52
- ---
53
-
54
- ## Stage 3: Instance Creator Setup
55
-
56
- **File:** [`src/api/types/InstanceCreator.ts`](../src/api/types/InstanceCreator.ts)
57
-
58
- `InstanceCreator` is a class (not a proxy) that manages the 8-stage pipeline:
59
-
60
- ### 3.1 Extract context
61
- - `type` — the `TypeDef` for `SubType`
62
- - `existentInstance` — the parent instance (`instance` in our example)
63
- - `args` — the arguments array
64
- - `config` — from the type definition
65
-
66
- ### 3.2 Resolve the `ModificatorType`
67
- - For sync constructors: compile the user handler into a new constructor function
68
- - For async constructors: wrap in an async-compatible class pattern
69
-
70
- ### 3.3 Prepare hooks
71
- - `invokePreHooks()` — calls `preCreation` hooks on the type's collection and the type itself
72
- - If any hook throws, `creationError` hooks fire and construction aborts
73
-
74
- ---
75
-
76
- ## Stage 4: Prototype Chain Assembly
77
-
78
- **File:** [`src/api/types/createInstanceModificator.ts`](../src/api/types/createInstanceModificator.ts)
79
-
80
- This is where the Trie structure is physically built:
81
-
82
- 1. **Create `Mnemosyne`** — `const Mnemosyne = {}`
83
- 2. **Link to parent** — `Reflect.setPrototypeOf(Mnemosyne, existentInstance)`
84
- - This is the critical step: the new instance's prototype chain will go through the **specific parent instance**
85
- 3. **Add internal properties** — `_addProps(Mnemosyne)` attaches getters for `__type__`, `__parent__`, `__args__`, `__timestamp__`, etc.
86
- 4. **Create `ModificatorType`** — a new constructor function with `Mnemosyne` as its prototype
87
- 5. **Copy user prototype properties** — `Object.getOwnPropertyDescriptors(ModificatorTypePrototype)` are copied onto `ModificatorType.prototype`
88
- 6. **Link ModificatorType to Mnemosyne** — `Reflect.setPrototypeOf(ModificatorType.prototype, Mnemosyne)`
89
-
90
- The resulting chain:
91
- ```
92
- newObj
93
- ↓ Object.getPrototypeOf(newObj)
94
- ModificatorType.prototype
95
- ↓ Object.getPrototypeOf(ModificatorType.prototype)
96
- Mnemosyne (has __type__, __parent__, etc.)
97
- ↓ Object.getPrototypeOf(Mnemosyne)
98
- existentInstance (the specific parent)
99
- ↓ Object.getPrototypeOf(existentInstance)
100
- ... (rest of chain to root)
101
- ```
102
-
103
- ---
104
-
105
- ## Stage 5: User Constructor Execution
106
-
107
- **File:** [`src/api/types/InstanceCreator.ts`](../src/api/types/InstanceCreator.ts)
108
-
109
- The `ModificatorType` is instantiated with `new ModificatorType(...args)`:
110
-
111
- 1. The compiled constructor body (from Stage 0) runs
112
- 2. `this` is the new object whose prototype chain was built in Stage 4
113
- 3. The user constructor assigns properties to `this`
114
- 4. If the constructor returns a non-primitive, that value is used as the instance
115
-
116
- ---
117
-
118
- ## Stage 6: Post-Processing
119
-
120
- **File:** [`src/api/types/InstanceCreator.ts`](../src/api/types/InstanceCreator.ts)
121
-
122
- After the user constructor:
123
-
124
- 1. **Set `__self__`** — `_setSelf(instance)` stores a reference to the instance itself in the props
125
- 2. **Validation** (if `strictChain: true`):
126
- - Verify the instance is actually an instance of the expected parent type
127
- - Verify the parent's constructor name matches the expected parent type name
128
- 3. **Invoke `postCreation` hooks**
129
-
130
- ---
131
-
132
- ## Stage 7: Return
133
-
134
- **File:** [`src/api/types/InstanceCreator.ts`](../src/api/types/InstanceCreator.ts)
135
-
136
- The instance is returned. It carries:
137
- - All user-assigned properties (own properties)
138
- - The prototype chain linking back to the root type
139
- - Internal construction context in the WeakMap (not enumerable, not own properties)
140
-
141
- ---
142
-
143
- ## The WeakMap Architecture
144
-
145
- **File:** [`src/api/types/Props.ts`](../src/api/types/Props.ts)
146
-
147
- Internal properties are stored in a `WeakMap` keyed by the **prototype object** (Mnemosyne), not the instance itself:
148
-
149
- ```typescript
150
- const __props__ = new WeakMap<object, PropsType>();
151
- ```
152
-
153
- Why the prototype?
154
- - Multiple instances of the same type share the same Mnemosyne prototype
155
- - Storing props on the prototype means all instances of the same construction share the same type metadata
156
- - This saves memory and keeps instance enumeration clean
157
-
158
- `getProps(instance)` walks the prototype chain to find the Mnemosyne object, then looks it up in the WeakMap.
159
-
160
- ---
161
-
162
- ## Hook Invocation Details
163
-
164
- **File:** [`src/api/hooks/invokeHook.ts`](../src/api/hooks/invokeHook.ts)
165
-
166
- Hooks are stored per-type and per-collection:
167
-
168
- ```typescript
169
- type.hooks = {
170
- preCreation: [fn1, fn2],
171
- postCreation: [fn3],
172
- creationError: [fn4]
173
- };
174
- ```
175
-
176
- When `invokeHook('preCreation', hookData)` fires:
177
- 1. Create a `HookInvocation` builder
178
- 2. For each registered hook, call it with the builder
179
- 3. Collect results in a Set
180
- 4. If any hook throws, the error propagates (aborting construction)
181
-
182
- The `flowCheckers` Map allows hooks to be conditionally enabled/disabled per invocation.
183
-
184
- ---
185
-
186
- ## Error Handling
187
-
188
- **File:** [`src/api/errors/throwModificationError.ts`](../src/api/errors/throwModificationError.ts)
189
-
190
- If any stage throws:
191
-
192
- 1. `creationError` hooks fire with the error and partial construction context
193
- 2. A `BASE_MNEMONICA_ERROR` is constructed with:
194
- - Cleaned stack trace (mnemonica internals removed)
195
- - References to the instance, type, and parent
196
- 3. The error is thrown to the caller
197
-
198
- If `config.blockErrors` is true (default for most types), errors during construction are caught and re-thrown as mnemonica errors. If false (used internally for exception construction), errors propagate raw.
199
-
200
- ---
201
-
202
- ## Summary Table
203
-
204
- | Stage | File | What Happens |
205
- |---|---|---|
206
- | 0. Type Definition | `src/api/types/index.ts` | Compile handler, create TypeDescriptor, register in collection |
207
- | 1. Subtype Access | `src/api/types/Mnemosyne.ts` | Resolve `instance.SubType` via proxy get trap |
208
- | 2. Construction Start | `src/api/types/Mnemosyne.ts` | Subtype proxy's construct trap fires |
209
- | 3. Creator Setup | `src/api/types/InstanceCreator.ts` | Extract context, resolve ModificatorType, run pre-hooks |
210
- | 4. Prototype Assembly | `src/api/types/createInstanceModificator.ts` | Build Mnemosyne → link to parent → create ModificatorType |
211
- | 5. User Constructor | `src/api/types/InstanceCreator.ts` | Run compiled handler with `this` bound to new object |
212
- | 6. Post-Processing | `src/api/types/InstanceCreator.ts` | Set __self__, validate, run post-hooks |
213
- | 7. Return | `src/api/types/InstanceCreator.ts` | Return instance with full prototype chain and WeakMap props |
214
-
215
- ---
216
-
217
- ## For Contributors
218
-
219
- When modifying any of these files, remember:
220
-
221
- - **Prototype links are load-bearing.** Changing `Reflect.setPrototypeOf` calls changes the Trie structure.
222
- - **WeakMap keys are prototype objects, not instances.** `_getProps` walks the chain; `_addProps` writes to the Mnemosyne.
223
- - **Hook order matters.** `preCreation` → construction → `postCreation`. Errors in `preCreation` abort before `Object.create`.
224
- - **The `__self__` reference is used by `utils.fork()` and `utils.clone()` to detect self-calls.**
package/AGENTS.md DELETED
@@ -1,345 +0,0 @@
1
- # AGENTS.md
2
-
3
- This file provides guidance specific to **mnemonica/core** for AI agents
4
- modifying the library itself. If you are *using* mnemonica in your own
5
- project, start with [`README.md`](./README.md).
6
-
7
- ---
8
-
9
- ## Rule #1 — Non-negotiable: PAUSE AND ASK
10
-
11
- **This is the highest-priority rule. It overrides everything else in this file.**
12
-
13
- STOP and ask the user before proceeding when ANY of these is true:
14
-
15
- 1. **An error occurred** — `Edit` failed, `Write` produced unexpected
16
- results, or any tool returned an error. A successful retry does NOT
17
- cancel this rule: report the error AND how you recovered.
18
- 2. **You are uncertain** — about what change to make, how a function works,
19
- or what the user intended.
20
- 3. **You are filling gaps with assumption** — "probably", "likely",
21
- "I think", "it should work" are signals to stop.
22
- 4. **A tool or environment constraint conflicts with the user's stated
23
- preference** — surface the conflict verbatim; never silently satisfy
24
- the tool at the user's expense.
25
- 5. **You are about to create or duplicate a file the user did not
26
- explicitly request** — ask first. Never copy content when `mv`,
27
- rename, or a reference suffices.
28
-
29
- When in doubt: STOP, ask one clear specific question, WAIT for the answer.
30
- Do not invent workarounds (no `sed`, no `python -c`, no console hacks,
31
- no rewriting files to bypass a tool restriction).
32
- **Silent recovery is a violation, even when the outcome looks fine.**
33
-
34
- The reason this rule exists: wrong assumptions waste both your time and the
35
- user's. The library encodes non-obvious design intent (data-flow vs control-flow,
36
- `define()` semantics, the proxy architecture, the return-via-variable rule).
37
- Confident guesses produce code that compiles but corrupts the design.
38
-
39
- ---
40
-
41
- > **Note:** Framework-agnostic rules are also available in `.ai/`:
42
- > [`AGENTS.md`](./.ai/AGENTS.md),
43
- > [`ARCHITECT.md`](./.ai/ARCHITECT.md), [`DEBUG.md`](./.ai/DEBUG.md).
44
- > These rules apply to all agent frameworks.
45
-
46
- > **Document locations:** this repository is agent-tools-agnostic. Documents
47
- > about *contributing to the core* live in [`.ai/`](./.ai/); documents about
48
- > *using the library* (for humans and agents alike) live in
49
- > [`docs/`](./docs/). Tool-specific directories (`.kilo/`, `.kilocode/`,
50
- > `.opencode/`, etc.) are for tool configuration only — never put project
51
- > documents (plans, rules, guides) there.
52
-
53
- ## What and why
54
-
55
- For the library's thesis, the four data mistakes it eliminates, the Trie observation, the pipeline pattern, and the HoTT framing, read [`README.md`](./README.md). This file assumes you have.
56
-
57
- The short version for editors: mnemonica is an instance inheritance system; `define()` declares types; subtypes are constructed from parent *instances* via `new instance.SubType(args)`; the prototype chain back to root IS the identity; construction context is stored in a WeakMap and exposed via `getProps()`.
58
-
59
- ## Agent Reading Guide
60
-
61
- Load the docs that match your change type. The wrong context produces broken code; the right context is a short read.
62
-
63
- | Change type | Read before starting |
64
- |---|---|
65
- | Any `src/` change | This file + [`.ai/ONBOARDING.md`](./.ai/ONBOARDING.md) |
66
- | Involves `define()` / type graph | + [`.ai/rules-define-patterns.md`](./.ai/rules-define-patterns.md) |
67
- | Involves hooks | + [`.ai/rules-hooks.md`](./.ai/rules-hooks.md) |
68
- | Involves async constructors | + [`.ai/rules-async-constructors.md`](./.ai/rules-async-constructors.md) |
69
- | Involves TypeScript types | + [`.ai/rules-type-system.md`](./.ai/rules-type-system.md) |
70
- | Involves proxy internals | + [`.ai/PROTOTYPE-CHAIN.md`](./.ai/PROTOTYPE-CHAIN.md) |
71
- | Uses tactica / `lookup` | + [`docs/tactica-deep-dive.md`](./docs/tactica-deep-dive.md) |
72
- | Docs-only change | README section you're touching only |
73
-
74
- **This file + `.ai/ONBOARDING.md` are the always-required baseline for any `src/` edit.**
75
-
76
- ### Framework-specific rules
77
-
78
- Mode-specific files in `.ai/`:
79
- - [`.ai/rules-coding.md`](./.ai/rules-coding.md) — universal coding rules
80
- - [`.ai/rules-reminders.md`](./.ai/rules-reminders.md) — type vs interface, spacing reminders
81
- - [`.ai/rules-context-condensing.md`](./.ai/rules-context-condensing.md) — context recovery protocol
82
-
83
- ## Build/Test Commands
84
-
85
- See [`.ai/rules-testing.md`](./.ai/rules-testing.md) for the full command reference, dual-framework details, and coverage requirements. Summary:
86
-
87
- ```bash
88
- npm run build # full build with linting
89
- npm run test:cov # Mocha + coverage (runs build:all internally)
90
- npm run test:jest:cov # Jest on TypeScript source
91
- npm run watch # watch mode
92
- ```
93
-
94
- **Must run `npm run test:cov` before completing any task.**
95
-
96
- **Documentation changes:** When modifying any `.md` file, `npm run lint:md` is mandatory. It checks for broken links and anchors. Run it and fix any reported issues before finishing.
97
-
98
- ## Code Style (Project-Specific)
99
-
100
- See [`.ai/rules-code-style.md`](./.ai/rules-code-style.md) for the full style reference. Key rules: tabs only, space before function parens, colons aligned in object literals, `strict: true`, **no `any`** (`no-explicit-any: error`).
101
-
102
- ## Architecture Patterns
103
-
104
- ### The `define()` Function
105
- The core API is `define(TypeName, constructHandler, config?)` in `src/index.ts`. It returns a constructor with additional methods:
106
- - `.define()` - define subtypes
107
- - `.lookup()` - find types by path
108
- - `.registerHook()` - register lifecycle hooks
109
-
110
- ### The `lookup()` Function
111
-
112
- For user-facing semantics, see [`README.md`](./README.md) and [`docs/tactica-deep-dive.md`](./docs/tactica-deep-dive.md). The contributor-relevant detail is the implementation pattern: `TypeRegistry` starts empty, and `lookup()` uses overloads so augmented keys return the typed constructor while unaugmented keys fall back to `TypeClass | undefined`.
113
-
114
- ```typescript
115
- // In mnemonica core (src/index.ts)
116
- export interface TypeRegistry {
117
- // Intentionally empty. Augment via declaration merging.
118
- }
119
-
120
- export function lookup<const K extends keyof TypeRegistry>(
121
- this: unknown,
122
- TypeNestedPath: K
123
- ): TypeRegistry[K];
124
- export function lookup(
125
- this: unknown,
126
- TypeNestedPath: string
127
- ): TypeClass | undefined {
128
- // Runtime delegates to types.lookup(); type safety is compile-time only.
129
- const types = checkThis(this) ? defaultTypes : this || defaultTypes;
130
- return types.lookup(TypeNestedPath);
131
- }
132
- ```
133
-
134
- Tactica generates the augmentation:
135
-
136
- ```typescript
137
- // In .tactica/registry.ts (generated)
138
- declare module 'mnemonica' {
139
- interface TypeRegistry {
140
- 'UserType': TypeConstructor<UserTypeInstance>;
141
- 'Parent.SubType': TypeConstructor<SubTypeInstance>;
142
- }
143
- }
144
- ```
145
-
146
- Runtime behavior is identical whether `TypeRegistry` is augmented or not; the only difference is the compile-time return type.
147
-
148
- > **Roadmap.** Nested `lookup()` (a type-safe `.lookup()` method
149
- > on constructors that preserves the prototype chain) is designed but not
150
- > yet shipped.
151
-
152
- ### Typed registry builders
153
-
154
- Mnemonica has three compile-time paths for the same runtime API:
155
-
156
- - **Builder mode** (default) — chain `.define()` on the exported `mnemonica` object or on
157
- a `createTypesCollection()` result. No `TypeRegistry` augmentation, no Tactica.
158
- - **Registry bridge** — one hand-written line merges a builder's local registry
159
- into the global `TypeRegistry`:
160
- `interface TypeRegistry extends RegistryOf<typeof App> {}`
161
- (inside `declare module 'mnemonica'`, in a dedicated `registry.ts`).
162
- - **Augmented mode** — use free `define()`/`lookup()` or `@decorate()`, and let
163
- Tactica (or a hand-written file) populate the global `TypeRegistry`. Required
164
- for `@decorate()`: TypeScript never applies a class decorator's return type
165
- to the class binding, so no local-registry mechanism can type decorators.
166
-
167
- Public types involved:
168
-
169
- - `TypesCollection<T, Parent, Path>` — type of `createTypesCollection()`.
170
- - `MnemonicaModule<Registry>` — type of the exported `mnemonica` object.
171
- - `IDefinitorInstance<N, R, Registry, Path>` — type of constructors returned by
172
- `.define()`.
173
- - `RegistryOf<T>` — extracts the accumulated `Registry` from any of the above,
174
- for the bridge.
175
-
176
- Quick builder example:
177
-
178
- ```typescript
179
- import { mnemonica } from 'mnemonica';
180
-
181
- const App = mnemonica
182
- .define('User', function (this: User, data: { name: string }) {
183
- this.name = data.name;
184
- })
185
- .define('Admin', function (this: Admin, data: { role: string }) {
186
- this.role = data.role;
187
- });
188
-
189
- const User = App.lookup('User');
190
- const user = new User({ name: 'Ada' });
191
- const admin = new user.Admin({ role: 'root' });
192
- ```
193
-
194
- Constructor `.lookup()` resolves **relative first, then root fallback**: the
195
- type's own subtypes are searched first, then the same string is resolved as an
196
- absolute path from the collection root. Exported builder values carry the
197
- registry across files (registry threading).
198
-
199
- The free `define()`/`lookup()` exports resolve against the global
200
- `TypeRegistry` (augmentation or bridge). When you hold a builder value, prefer
201
- the explicit-source forms — `lookup(source, path)` and
202
- `define(source, name, handler)` — which infer the registry from the source
203
- instead of falling back to the global interface.
204
-
205
- For the full guide — multi-file threading, the bridge, two-arg overloads,
206
- `strictChain` notes, and `@decorate` limitations — see
207
- [`docs/typed-lookup.md`](./docs/typed-lookup.md).
208
-
209
- ### Type System Structure
210
- ```
211
- src/
212
- ├── index.ts # Main exports: define, lookup, apply, call, bind
213
- ├── types/index.ts # TypeScript type definitions
214
- ├── constants/ # Symbols and default options
215
- ├── descriptors/ # Type collection and error definitions
216
- ├── api/ # Core implementation
217
- │ ├── types/ # Type creation (TypeProxy, InstanceCreator, Mnemosyne)
218
- │ ├── errors/ # Error handling and stack traces
219
- │ ├── hooks/ # Lifecycle hooks (preCreation, postCreation, creationError)
220
- │ └── utils/ # Utilities (getTypeChecker, CreationHandler)
221
- └── utils/ # Public utilities (extract, parse, merge, etc.)
222
- ```
223
-
224
- ### Proxy-Based Architecture
225
- The library makes heavy use of JavaScript Proxies:
226
- - **TypeProxy** (`src/api/types/TypeProxy.ts`): Wraps type constructors
227
- - **Mnemosyne** (`src/api/types/Mnemosyne.ts`): Handles instance method access
228
- - **TypesCollection Proxy** (`src/descriptors/types/index.ts`): Dynamic type lookup
229
-
230
- ### Internal Instance Properties
231
-
232
- Stored in a `WeakMap` keyed by the instance's **Mnemosyne memory layer** — the prototype object created per construction in `createInstanceModificator` — not as own properties on the instance itself. `_getProps` reaches it by walking the prototype chain from the instance. Access via `getProps(instance)`. For the full property list (9 entries, with meanings) see the **Internal instance properties** table in [`README.md`](./README.md) — that table is the canonical reference.
233
-
234
- `setProps(instance, values)` is the mutating counterpart; rarely needed and considered advanced.
235
-
236
- ## Build Requirements
237
-
238
- ### No Warnings Policy
239
- The build **must have zero warnings**. Running `npm run build` should produce **no ESLint warnings** in the `./src` directory. If there are warnings:
240
- 1. Fix the source code causing the warning
241
- 2. Do not modify `./tsconfig.json` or `./eslint.config.js` to suppress warnings
242
-
243
- ### Build Output Inspection
244
- When running `npm run build` or `npm run build:all`, **check the beginning of the output** for errors and warnings. Build failures (TypeScript compilation errors, ESLint issues, etc.) often appear at the start of the output. Do not rely only on the end of the output or `tail` for build status.
245
-
246
- For test passing confirmations (e.g., `npm run test:cov`), checking the end of the output is acceptable.
247
-
248
- ### Configuration Files
249
- **Disallowed without explicit approval:**
250
- - Modifying `./tsconfig.json`
251
- - Modifying `./eslint.config.js`
252
-
253
- These configuration files define the project's strict standards. Any changes require user approval first.
254
-
255
- ## Return Statement Design Rule (Non-negotiable)
256
-
257
- **Every return expression must go through an intermediate variable/constant.** No exceptions. This is critical for debuggability with `npm run debug` and Chrome Dev Tools — when execution pauses on `return result`, you can hover your mouse over `result` and inspect the value. With `return SomeFn(arg)`, the value is gone before the debugger can show it.
258
-
259
- **This rule is enforced. If you write `return new Foo()` or `return fn()`, the PR will be rejected.**
260
-
261
- ### Prohibited patterns:
262
- ```typescript
263
- // BAD — cannot inspect the returned value in debugger
264
- return { target, name };
265
- return SomeFnInvocation(arg);
266
- return new TypeDescriptor(...);
267
- ```
268
-
269
- ### Required pattern:
270
- ```typescript
271
- // GOOD — can set breakpoint on return and inspect result
272
- const result = {
273
- target : subtypes,
274
- name : head,
275
- };
276
- return result;
277
-
278
- const result = SomeFnInvocation(arg);
279
- return result;
280
-
281
- const result = new TypeDescriptor(
282
- origin, target, name, handler, proto, config
283
- );
284
- return result;
285
- ```
286
-
287
- This applies to **all** `return` statements where the expression is anything other than a bare variable or literal. The rule exists because Chrome Dev Tools' debugger cannot show the evaluated result of a complex expression on the `return` line — you must step past it, at which point the frame has already exited.
288
-
289
- ## TypeScript Type Rules
290
-
291
- **Never use bare `Function`, `CallableFunction`, or `NewableFunction` as types** — always define a purpose-specific interface that extends them. See [`.ai/rules-code-style.md`](./.ai/rules-code-style.md) for examples and allowed exceptions.
292
-
293
- ## Preserving Design Comments and Memory Notes
294
-
295
- When refactoring or reformatting code, **preserve all comments that carry design intent, architectural rationale, or developer memory**. This includes:
296
-
297
- - Inline comments explaining *why* a non-obvious approach was chosen (e.g. `// "this" argument may be passed for tracking why something happened`)
298
- - Comments marking intentional workarounds for JS/Node version differences (e.g. `// starting from Node.js v22 we should define this property through odp`)
299
- - Comments describing what a code section is *about* (e.g. `// this is a direct Sub-Type invocation`)
300
- - TODOs and commented-out code that documents explored but rejected alternatives
301
- - Debugger statements left as breadcrumbs for future investigation
302
-
303
- **Do NOT remove comments because they seem like "clutter" or because the code is now typed.** TypeScript types answer "what" — comments answer "why". Both are necessary.
304
-
305
- If a comment becomes technically inaccurate after a change, update it rather than deleting it.
306
-
307
- ## Testing Requirements
308
-
309
- See [`.ai/rules-testing.md`](./.ai/rules-testing.md) for full coverage requirements and patterns. 100% required on both Mocha and Jest. Must run `npm run test:cov` before completing any task.
310
-
311
- ## Before Saying a Task Is Done
312
-
313
- When a task uses a TODO list, the list is part of the deliverable:
314
-
315
- 1. **Before reporting completion, update the TODO list** so every item is
316
- marked done (struck through). A stale `in_progress` item reads as
317
- unfinished work even when the work itself is complete.
318
- 2. **Only mark items done that are verified** — tests green, coverage at
319
- 100% on both suites, `lint:md` clean where docs changed. Never mark an
320
- item done just to tidy the list.
321
- 3. **When the task concludes, wipe the TODO list.** A concluded task leaves
322
- no list behind; the next task starts fresh.
323
-
324
- ## Common Patterns
325
-
326
- ### Adding Types
327
- ```typescript
328
- const MyType = define('MyType', function (this: MyType, data: Data) {
329
- Object.assign(this, data);
330
- });
331
-
332
- const SubType = MyType.define('SubType', function (this: SubType, extra: string) {
333
- this.extra = extra;
334
- });
335
- ```
336
-
337
- ### Error Handling
338
- All errors extend `BASE_MNEMONICA_ERROR` in `src/api/errors/index.ts`. Custom errors are dynamically generated in `src/descriptors/errors/index.ts`.
339
-
340
- ### Symbol Usage
341
- Key symbols defined in `src/constants/index.ts`:
342
- - `SymbolConstructorName` - stores type name on constructors
343
- - `SymbolParentType` - links to parent type
344
- - `SymbolDefaultTypesCollection` - default collection identifier
345
- - `SymbolConfig` - type configuration storage