mnemonica 1.2.3 → 1.2.5

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 (41) 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/docs/UTILS.md +97 -8
  5. package/docs/decorate.md +1 -1
  6. package/docs/empathy-in-ai.md +20 -10
  7. package/docs/prototype-chain.md +8 -7
  8. package/docs/typed-lookup.md +195 -5
  9. package/docs/typeomatica.md +8 -345
  10. package/package.json +6 -10
  11. package/src/api/types/index.ts +33 -20
  12. package/.ai/AGENTS.md +0 -151
  13. package/.ai/ARCHITECT.md +0 -110
  14. package/.ai/DEBUG.md +0 -178
  15. package/.ai/ONBOARDING.md +0 -189
  16. package/.ai/PROTOTYPE-CHAIN.md +0 -155
  17. package/.ai/mode-ask.md +0 -121
  18. package/.ai/mode-orchestrator.md +0 -141
  19. package/.ai/performance-vs-security.md +0 -395
  20. package/.ai/rules-async-constructors.md +0 -352
  21. package/.ai/rules-code-style.md +0 -95
  22. package/.ai/rules-coding.md +0 -246
  23. package/.ai/rules-context-condensing.md +0 -50
  24. package/.ai/rules-contributing.md +0 -227
  25. package/.ai/rules-define-patterns.md +0 -159
  26. package/.ai/rules-ecosystem.md +0 -140
  27. package/.ai/rules-error-system.md +0 -66
  28. package/.ai/rules-hooks.md +0 -46
  29. package/.ai/rules-instance-methods.md +0 -93
  30. package/.ai/rules-philosophy.md +0 -231
  31. package/.ai/rules-reminders.md +0 -19
  32. package/.ai/rules-testing.md +0 -66
  33. package/.ai/rules-type-system.md +0 -124
  34. package/.ai/theory-of-operations.md +0 -224
  35. package/AGENTS.md +0 -345
  36. package/CONTRIBUTING.md +0 -150
  37. package/SKILL.md +0 -114
  38. package/docs/ai-learning-trajectory.md +0 -141
  39. package/docs/purpose.md +0 -707
  40. package/docs/tactica-deep-dive.md +0 -629
  41. package/docs/tactica-pattern.md +0 -146
package/.ai/ARCHITECT.md DELETED
@@ -1,110 +0,0 @@
1
- # Design Guidelines — mnemonica/core
2
-
3
- > **Applies to:** Planning, designing, and strategizing changes without modifying
4
- > implementation files. Framework-agnostic.
5
-
6
- ---
7
-
8
- ## Role
9
-
10
- You are in **Architect** mode. Your task is to plan, design, and strategize
11
- changes to the mnemonica codebase without modifying implementation files.
12
-
13
- ---
14
-
15
- ## Project Overview
16
-
17
- Mnemonica is an **instance inheritance system** using JavaScript prototype
18
- chains. It allows creating type hierarchies where instances can spawn child
19
- instances that inherit from parent instances.
20
-
21
- ### Core Concept
22
-
23
- ```typescript
24
- // Define types
25
- const User = define('User', function (name: string) {
26
- this.name = name;
27
- });
28
-
29
- // Create parent instance
30
- const user = new User('John');
31
-
32
- // Create child instance inheriting from parent
33
- const admin = user.Admin('admin privileges');
34
- // admin inherits all User properties + new Admin properties
35
- ```
36
-
37
- ---
38
-
39
- ## Architecture Patterns
40
-
41
- ### Proxy-Based Design
42
-
43
- ```
44
- TypeProxy → wraps constructor functions
45
- Mnemosyne → handles instance prototype chain
46
- TypesCollection → manages type registry
47
- ```
48
-
49
- ### Internal Instance Properties
50
-
51
- ```typescript
52
- interface InstanceInternalProps {
53
- [SymbolConstructorName]: string; // Type name
54
- [SymbolParentType]: object; // Parent instance
55
- [SymbolSubTypes]: Map<string, object>; // Child types
56
- }
57
- ```
58
-
59
- ### Symbol System
60
-
61
- See [`AGENTS.md`](./AGENTS.md) for the complete symbol reference table.
62
-
63
- ---
64
-
65
- ## Design Principles
66
-
67
- ### Type Safety
68
- - Strict TypeScript with `strict: true`
69
- - All functions must have explicit return types
70
- - Types must be complete and reusable
71
- - **No `any`** (`@typescript-eslint/no-explicit-any: error`) — define proper types
72
- - Never use bare `Function`, `CallableFunction`, or `NewableFunction` — define purpose-specific interfaces
73
-
74
- ### Proxy Handler Design
75
-
76
- ```typescript
77
- // Pattern for proxy handlers
78
- type ProxyHandler<T> = {
79
- get?(target: T, prop: string, receiver: unknown): unknown;
80
- set?(target: T, prop: string, value: unknown, receiver: unknown): boolean;
81
- apply?(target: T, thisArg: unknown, args: unknown[]): unknown;
82
- };
83
- ```
84
-
85
- ### Extension Points
86
-
87
- 1. **Types** — Create via `define()` function
88
- 2. **Hooks** — Register with `registerHook()`
89
- 3. **Flow Checkers** — Add validation with `registerFlowChecker()`
90
- 4. **Subtypes** — Extend types with `type.define()`
91
-
92
- ---
93
-
94
- ## Documentation Format
95
-
96
- When creating design documents:
97
- 1. Use `.md` extension only
98
- 2. Include code examples in TypeScript
99
- 3. Reference existing patterns from `src/types/index.ts`
100
- 4. Document symbol usage and meanings
101
-
102
- ---
103
-
104
- ## Constraints
105
-
106
- - **Do not** write implementation code (`*.ts` files)
107
- - **Do not** modify existing source files
108
- - Focus on `.md` documentation and planning
109
- - Consider 100% test coverage requirement
110
- - Respect the dual test framework (Mocha + Jest)
package/.ai/DEBUG.md DELETED
@@ -1,178 +0,0 @@
1
- # Debugging Guidelines — mnemonica/core
2
-
3
- > **Applies to:** Investigating issues, diagnosing problems, identifying root
4
- > causes. Framework-agnostic.
5
-
6
- ---
7
-
8
- ## Role
9
-
10
- You are in **Debug** mode. Your task is to investigate issues, diagnose problems,
11
- and identify root causes in the mnemonica codebase.
12
-
13
- ---
14
-
15
- ## Debug Commands
16
-
17
- ```bash
18
- # Run tests with coverage to identify untested paths
19
- npm run test:cov
20
-
21
- # Run Jest with verbose output
22
- npm run test:jest -- --verbose
23
-
24
- # Run specific test file
25
- npx jest test-jest/types.ts --verbose
26
-
27
- # Run Mocha with debug output
28
- DEBUG=* npm test
29
-
30
- # Build and check for TypeScript errors
31
- npm run build
32
- ```
33
-
34
- ### Build Output Inspection
35
-
36
- When running `npm run build` or `npm run build:all`, **check the beginning of the
37
- output** for errors and warnings. Build failures (TypeScript compilation errors,
38
- ESLint issues, etc.) often appear at the start of the output. Do not rely only on
39
- the end of the output or `tail` for build status.
40
-
41
- For test passing confirmations (e.g., `npm run test:cov`), checking the end of
42
- the output is acceptable.
43
-
44
- ---
45
-
46
- ## Common Issue Patterns
47
-
48
- ### Proxy Handler Issues
49
-
50
- ```typescript
51
- // If traps are not working, check:
52
- // 1. Handler methods return correct types
53
- // 2. `get` trap returns `unknown`, not implicit `any`
54
- // 3. `set` trap returns boolean, not void
55
-
56
- // Debug proxy behavior
57
- const debugProxy = new Proxy(target, {
58
- get(target, prop, receiver) {
59
- console.log('Getting:', prop);
60
- return Reflect.get(target, prop, receiver);
61
- }
62
- });
63
- ```
64
-
65
- ### Type Errors
66
-
67
- ```typescript
68
- // Common: 'any' type assignment
69
- // Fix: Add proper type annotation
70
- const value: SpecificType = unknownValue as SpecificType;
71
-
72
- // Common: missing 'this' type
73
- // Fix: Add explicit this parameter
74
- function method(this: SpecificType) { }
75
- ```
76
-
77
- ### Instance Chain Issues
78
-
79
- ```typescript
80
- // Check instance properties
81
- console.log(instance[SymbolConstructorName]);
82
- console.log(instance[SymbolParentType]);
83
- console.log(instance[SymbolSubTypes]);
84
-
85
- // Verify prototype chain
86
- console.log(Object.getPrototypeOf(instance));
87
- ```
88
-
89
- ---
90
-
91
- ## Logging Strategy
92
-
93
- ### Add Temporary Logging
94
-
95
- ```typescript
96
- // In proxy handlers
97
- get(target, prop, receiver) {
98
- console.log(`[Proxy.get] prop: ${String(prop)}`);
99
- // ... existing code
100
- }
101
-
102
- // In error constructors
103
- constructor(message, additionalStack) {
104
- console.log('[Error]', message, additionalStack);
105
- // ... existing code
106
- }
107
- ```
108
-
109
- ### Stack Trace Analysis
110
-
111
- ```typescript
112
- // Use error stack cleaners
113
- import { cleanupStack } from '../api/errors/index.js';
114
-
115
- const cleaned = cleanupStack(stack.split('\n'));
116
- console.log('Cleaned stack:', cleaned);
117
- ```
118
-
119
- ---
120
-
121
- ## Symbol Debugging
122
-
123
- ```typescript
124
- // Inspect instance symbols
125
- const symbols = Object.getOwnPropertySymbols(instance);
126
- symbols.forEach(sym => {
127
- console.log(sym.toString(), ':', (instance as Record<symbol, unknown>)[sym]);
128
- });
129
- ```
130
-
131
- ---
132
-
133
- ## Test Debugging
134
-
135
- ### Mocha Tests
136
-
137
- ```bash
138
- # Run single test suite
139
- npx mocha build/test-ts/test-example.js
140
-
141
- # With debug output
142
- DEBUG=mnemonica npx mocha build/test-ts/test-example.js
143
- ```
144
-
145
- ### Jest Tests
146
-
147
- ```bash
148
- # Run with debugger
149
- node --inspect-brk node_modules/.bin/jest --runInBand test-jest/types.ts
150
-
151
- # With console output
152
- npx jest test-jest/types.ts --verbose --no-coverage
153
- ```
154
-
155
- ---
156
-
157
- ## Issue Checklist
158
-
159
- 1. [ ] Check TypeScript compilation: `npm run build`
160
- 2. [ ] Check build output **at the beginning** for errors/warnings (not just tail)
161
- 3. [ ] Run Mocha tests: `npm run test:cov`
162
- 4. [ ] Run Jest tests: `npm run test:jest:cov`
163
- 5. [ ] Verify code style (see [`rules-code-style.md`](./rules-code-style.md))
164
- 6. [ ] Check for bare `Function` / `CallableFunction` / `NewableFunction` types
165
- 7. [ ] Verify symbol usage is correct
166
- 8. [ ] Check proxy handler return types
167
- 9. [ ] Verify return statements use intermediate variables
168
-
169
- ---
170
-
171
- ## Reporting Issues
172
-
173
- When reporting findings:
174
- 1. Include file paths and line numbers
175
- 2. Show relevant code snippets
176
- 3. Provide error messages in full
177
- 4. Suggest root cause, not just symptoms
178
- 5. Reference related test files
package/.ai/ONBOARDING.md DELETED
@@ -1,189 +0,0 @@
1
- # Onboarding — New Agent Quickstart
2
-
3
- > **Read this first.** One file. Five minutes. Everything you need to contribute to mnemonica without reading 8+ files.
4
-
5
- ---
6
-
7
- ## What Is mnemonica?
8
-
9
- An **instance inheritance system** for JavaScript/TypeScript. You define types with `define()` and create instances that inherit through prototype chains — not just classes, but between instances.
10
-
11
- ```typescript
12
- const User = define('User', function (this: UserData, data: UserData) {
13
- Object.assign(this, data);
14
- });
15
-
16
- const user = new User({ name: 'John' });
17
- const admin = new user.Admin({ role: 'admin' }); // inherits from user instance
18
- ```
19
-
20
- **Scope:** mnemonica types the data flow, not the control flow. It gives data memory of its own creation (type, parent, arguments, timestamp) but does not dictate how services, algorithms, or control flow work. Keep behavior code intact; mnemonica only replaces plain data objects with typed instances.
21
-
22
- **The greater view.** mnemonica does not add a new abstraction on top of JavaScript — it makes an existing one explicit. The prototype chain is already a Trie; every `new` already extends a node. `new user.Admin()` is not a library call — it is JavaScript's prototype mechanism used deliberately. mnemonica names each node, stores the construction arguments at each step, and makes the chain queryable. The thing you have been building with manually all along, made first-class.
23
-
24
- **Why not class hierarchies?** Class inheritance shares `Admin.prototype` across all instances. Two concurrent requests both creating `Admin` instances share the same prototype. `new user.Admin()` creates a chain where `user` IS the prototype — each pipeline run is isolated structurally, not by convention.
25
-
26
- **Why not TypeScript interfaces alone?** TypeScript is structural at compile time: a `Payment` and an `Invoice` with identical fields are interchangeable to the type checker. At runtime, `processPayment(invoice)` silently succeeds and produces wrong results. mnemonica's runtime types are nominal — the type IS its name, established at `define()` time and stable thereafter.
27
-
28
- **Why not Object.assign / spread?** `{...raw, ...apiResult}` is one flat object with no lineage. You cannot answer "which step set `amount`?" without reading the source. mnemonica's prototype chain preserves every ancestor; `utils.parent(enriched, 'ApiResult')` returns the exact API response object.
29
-
30
- ---
31
-
32
- ## Build & Test
33
-
34
- ```bash
35
- # Install dependencies
36
- npm ci
37
-
38
- # Build TypeScript
39
- npm run build
40
-
41
- # Run Mocha tests with coverage (runs build:all internally)
42
- npm run test:cov
43
-
44
- # Run Jest tests with coverage (TypeScript source, faster)
45
- npm run test:jest:cov
46
-
47
- # Watch mode
48
- npm run watch
49
- ```
50
-
51
- **Rule:** `npm run test:cov` before completing any task. It validates the build and ensures 100% coverage.
52
-
53
- **Build tip:** Check the **beginning** of build output for errors. For tests, the end is fine.
54
-
55
- ---
56
-
57
- ## Code Style (Non-Negotiable)
58
-
59
- ### Indentation
60
- - **TABS ONLY** — never spaces. Tab width: 4.
61
-
62
- ### Function Spacing
63
- ```typescript
64
- function myFunc () { } // ✓ space before paren
65
- function myFunc() { } // ✗ wrong
66
- ```
67
-
68
- ### Return Statements
69
- **Always use an intermediate variable before returning.**
70
-
71
- ```typescript
72
- // ✓ GOOD — inspectable in debugger
73
- const result = { target, name };
74
- return result;
75
-
76
- // ✗ BAD — can't inspect
77
- return { target, name };
78
- ```
79
-
80
- ### TypeScript Types
81
- - `strict: true`, `noUnusedLocals: true`, `noUnusedParameters: true`
82
- - **No `any`** (`@typescript-eslint/no-explicit-any: error`) — use purpose-specific interfaces
83
- - **Never** use bare `Function`, `CallableFunction`, or `NewableFunction` — define purpose-specific interfaces
84
-
85
- ### Error Handling
86
-
87
- ```typescript
88
- import { constructError } from '../api/errors/index.js';
89
-
90
- const MyError = constructError('MY_ERROR', 'Error message');
91
- throw new MyError('additional info', stack);
92
- ```
93
-
94
- ### Configuration Files
95
-
96
- **Disallowed without explicit approval:**
97
- - Modifying `./tsconfig.json`
98
- - Modifying `./eslint.config.js`
99
-
100
- These configuration files define the project's strict standards. Any changes
101
- require user approval first.
102
-
103
- ---
104
-
105
- ## Architecture
106
-
107
- ```
108
- src/
109
- ├── index.ts # Main exports: define, lazy, lookup, apply, call, bind
110
- ├── types/index.ts # TypeScript type definitions
111
- ├── constants/ # Symbols and default options
112
- ├── descriptors/ # Type collection and error definitions
113
- ├── api/ # Core implementation
114
- │ ├── types/ # TypeProxy, InstanceCreator, Mnemosyne
115
- │ ├── errors/ # Error handling and stack traces
116
- │ ├── hooks/ # Lifecycle hooks
117
- │ └── utils/ # Utilities
118
- └── utils/ # Public utilities (extract, parse, merge, etc.)
119
- ```
120
-
121
- Key components:
122
- - **TypeProxy** — wraps type constructors
123
- - **InstanceCreator** — orchestrates construction lifecycle
124
- - **Mnemosyne** — root memory proxy; stores construction context and resolves subtype lookups
125
-
126
- ---
127
-
128
- ## Testing Rules
129
-
130
- - **Dual framework:** Mocha (transpiled `build/`), Jest (TypeScript `src/`)
131
- - **100% coverage** required for both
132
- - Jest tests should mirror Mocha patterns from `test/environment.js`
133
- - Tests must pass with `--allow-uncaught` (mocha)
134
-
135
- ---
136
-
137
- ## Async Constructors
138
-
139
- mnemonica supports async constructors natively:
140
-
141
- ```typescript
142
- const AsyncType = define('AsyncType', async function () {
143
- await sleep(100);
144
- this.done = true;
145
- return this; // MUST return with awaitReturn: true (default)
146
- });
147
-
148
- const instance = await new AsyncType();
149
- ```
150
-
151
- **Critical:** Async subtypes are invoked as methods on the parent instance:
152
-
153
- ```typescript
154
- const parent = await new AsyncParent();
155
- const child = await parent.AsyncChild(); // ✓ correct
156
-
157
- const wrong = await new AsyncChild(); // ✗ fails strictChain
158
- ```
159
-
160
- Read [`../docs/async-constructors.md`](../docs/async-constructors.md) for the `super()` return-value trap and native async class wrapping.
161
-
162
- ---
163
-
164
- ## Common Pitfalls
165
-
166
- 1. **`await new AsyncSubType()`** — wrong. Use `await parent.AsyncSubType()`.
167
- 2. **`return { a, b }`** — wrong. Use `const result = { a, b }; return result;`.
168
- 3. **Modifying `tsconfig.json` or `eslint.config.js`** — forbidden without explicit approval.
169
- 4. **Forgetting `npm run test:cov`** — always run before finishing.
170
- 5. **Using `Function` as a type** — define `interface MyHandler extends CallableFunction { ... }`.
171
-
172
- ---
173
-
174
- ## Where to Go Next
175
-
176
- | Need | Read |
177
- |------|------|
178
- | Design patterns, constraints | [`ARCHITECT.md`](./ARCHITECT.md) |
179
- | Prototype chain internals | [`PROTOTYPE-CHAIN.md`](./PROTOTYPE-CHAIN.md) |
180
- | Debugging commands, issues | [`DEBUG.md`](./DEBUG.md) |
181
- | Async constructor deep dive | [`rules-async-constructors.md`](./rules-async-constructors.md) |
182
- | tactica type-safe lookup | [`tactica-deep-dive.md`](../docs/tactica-deep-dive.md) |
183
- | Behavioral guidelines | [`rules-contributing.md`](./rules-contributing.md) |
184
- | Explaining code (ask mode) | [`mode-ask.md`](./mode-ask.md) |
185
- | Multi-step coordination | [`mode-orchestrator.md`](./mode-orchestrator.md) |
186
-
187
- ---
188
-
189
- > **This file is a summary.** For authoritative rules, read the linked files. For the full type system, read `src/types/index.ts`.
@@ -1,155 +0,0 @@
1
- # Prototype Chain Architecture
2
-
3
- ## Why this document exists
4
-
5
- mnemonica instances do not have a normal JavaScript prototype chain. Between every parent instance and child instance there are two intermediate objects. If you are changing construction, props storage, `instanceof`, or subtype lookup, you need to know what those objects are and why they exist.
6
-
7
- ## High-level shape
8
-
9
- For a chain `user → admin → superadmin` the instance-level chain is:
10
-
11
- ```
12
- superadmin
13
- └── SuperAdminType.prototype
14
- └── SuperAdminMemory
15
- └── admin
16
- └── AdminType.prototype
17
- └── AdminMemory
18
- └── user
19
- └── UserType.prototype
20
- └── UserMemory
21
- └── root Mnemosyne Proxy
22
- └── Mnemonica instance
23
- └── Mnemonica.prototype
24
- └── ancestor
25
- ```
26
-
27
- `SuperAdminMemory`, `AdminMemory`, and `UserMemory` are the **memory layers**. Only `UserMemory`’s parent is the real `Mnemosyne` constructor result wrapped in a Proxy. The deeper memory layers are plain objects that play the same role.
28
-
29
- ## The three levels contributed by each type
30
-
31
- Every mnemonica type adds three levels to the chain:
32
-
33
- 1. **Instance object** — the object returned by `new parent.ChildType(...)`. Holds only the own properties assigned by the user constructor.
34
- 2. **`ModificatorType.prototype`** — the user-prototype layer. Holds methods and getters captured at `define()` time. It gets a fresh `constructor` property pointing to the per-construction `ModificatorType` function.
35
- 3. **Memory layer** — a plain object whose `[[Prototype]]` is the parent instance. It is the `WeakMap` key for internal props and has a `constructor` getter returning `ModificatorType`.
36
-
37
- ## Construction Pipeline (8 Stages)
38
-
39
- ```
40
- define(TypeName, ctor) → new TypeDescriptor() → new TypeProxy()
41
- │
42
- ▼
43
- new InstanceCreator(type, parent, args)
44
- │
45
- ▼
46
- makeInstanceModificator(self)
47
- │
48
- ▼
49
- ModificationConstructor.call(parent, ModificatorType, proto, _addProps)
50
- │
51
- ▼
52
- user constructor runs (new ModificatorType(...args))
53
- │
54
- ▼
55
- postProcessing() → invokePostHooks()
56
- ```
57
-
58
- ## Files and functions involved
59
-
60
- - `src/api/types/compileNewModificatorFunctionBody.ts` builds the `ModificatorType`, the actual function or class used for `new`. For function constructors it preserves `new.target`; for class constructors it generates a class that extends the user class so `super(...)` works.
61
- - `src/api/types/createInstanceModificator.ts` is the default `ModificationConstructor`. It creates the memory layer, wires `_addProps`, copies the captured user prototype onto `ModificatorType.prototype`, and rewires `ModificatorType.prototype` to inherit from the memory layer.
62
- - `src/api/types/Props.ts` implements `_addProps` and `getProps`. Internal props are stored in a module-level `WeakMap` keyed by the memory-layer object.
63
- - `src/api/types/Mnemosyne.ts` builds the root memory proxy. Only the root type goes through `createMnemosyne`; all deeper memory layers are plain objects produced by `createInstanceModificator`.
64
- - `src/api/types/InstanceCreator.ts` orchestrates the pipeline and passes `existentInstance` (the parent instance) into the `ModificationConstructor`.
65
- - `src/api/types/TypeProxy.ts` is the constructor-like object returned by `define()`. Its `construct` trap creates the root Mnemosyne proxy and then invokes `InstanceCreator`.
66
-
67
- ## Capturing the user prototype
68
-
69
- At `define()` time the `TypeDescriptor` stores `proto` — a snapshot of the user constructor’s `.prototype`. During construction that snapshot is copied onto the fresh `ModificatorType.prototype`. The user constructor’s original `.prototype` is restored after construction, so it is never part of the instance chain.
70
-
71
- This is why the same constructor function can be reused across multiple type definitions without bleeding prototype state.
72
-
73
- ## Internal props storage
74
-
75
- `_addProps` receives the memory-layer object and stores a `value` object in the module `WeakMap` keyed by that object. The stored object contains getters for:
76
-
77
- - `__type__`
78
- - `__parent__`
79
- - `__args__`
80
- - `__timestamp__`
81
- - `__creator__`
82
- - `__collection__`
83
- - `__subtypes__`
84
- - `__proto_proto__`
85
- - `__stack__`
86
-
87
- `getProps(instance)` first checks for a record keyed by the object itself (see the error-props note below), then walks the prototype chain from the instance until it finds the first object with a `WeakMap` entry. For instances that is always the instance's own memory layer. `parent(instance)` reads `__parent__` from that props object; it is the `existentInstance` passed to `InstanceCreator`.
88
-
89
- ## Why the memory layer is the `WeakMap` key
90
-
91
- **Why not key props on `ModificatorType.prototype`?** It would save one hop in the walk, but that object is user-facing: it receives the captured user-prototype descriptors during construction and is reachable via `instance.constructor.prototype`. The memory layer is created fresh per construction, is never handed out as a value, and its only own property (`constructor`) is a non-configurable getter. Keying the props by an object identity that userland cannot forge or pollute keeps the metadata lookup deterministic no matter what user code does to instances or prototypes.
92
-
93
- **This is not a security boundary.** JavaScript within a realm offers none: a determined user with `Reflect` can reach the memory layer (`Reflect.getPrototypeOf(instance.constructor.prototype)`) and even change its prototype. The design goal is determinism under *accidental* interference — the `WeakMap` entry is keyed by identity rather than by any name or property another library could collide with, and the `constructor` getter cannot be redefined. (This was historically nicknamed "MITM resistance": forgery and pollution of the metadata lookup are structurally deflected; deliberate reflection is not. Security tooling would rightly not count this as a defense.)
94
-
95
- **Do not re-add keying by instance or creator.** Props were historically keyed by the `InstanceCreator` context, then by the instance itself. Both writes were proven unread (sentinel experiment: both suites green with garbage stored in the entry) and removed. For instances the memory layer is the only props key; `setProps` additions are keyed by the props object itself.
96
-
97
- **Error props use a second key-space.** Error instances carry their data (`args`, `originalError`, `instance`, `exceptionReason`, `reasons`, `surplus`) in a record keyed by the error object itself, stored in a *separate* `WeakMap` (`__object_props__` in `Props.ts`) that `_getProps` consults before the chain walk. The two key-spaces must never share one map: memory layer objects are themselves keys in `__props__`, so a shared map would make `_getProps(memoryLayer)` return the layer's own record when the caller meant to reach the parent layer's one (this exact regression once silently bypassed the `prepareSubtypeForConstruction` early-exit and cost a coverage branch). `setProps` on an object with no chain record (plain objects, `Error` objects) creates such an object-keyed record on demand; on primitives it returns `false`.
98
-
99
- **The `_getProps` guard.** The chain walk stops with `undefined` as soon as the next level’s `constructor` differs from the original object’s; the memory layer’s own getter keeps constructors aligned across its level, so the walk survives it. Consequence: `getProps(Object.create(instance))` resolves to the parent instance’s props — derived objects share the nearest ancestor’s memory layer.
100
-
101
- ## `_setSelf` and async construction
102
-
103
- `_setSelf(instance)` is called at the end of successful construction. It adds one more getter to the props object:
104
-
105
- ```js
106
- __self__: () => instance
107
- ```
108
-
109
- This is what solves the async-constructor problem: the props object is already reachable from the instance through the prototype-chain walk, so the `__self__` getter can serve as a completion marker.
110
-
111
- When a constructor returns a Promise, the initial value of `new Constructor()` is that Promise. `makeAwaiter` waits for resolution, then checks:
112
-
113
- ```js
114
- if (props.__self__ !== self.inheritedInstance) {
115
- self.postProcessing(type);
116
- }
117
- ```
118
-
119
- If `__self__` is missing or does not match the resolved instance, post-processing has not run yet, so it runs validation and hooks. If it matches, post-processing has already happened and is skipped. The constructor can therefore return a Promise, and mnemonica finalizes the instance only after the Promise resolves — without double-initializing or losing the construction context.
120
-
121
- ## Subtype lookup
122
-
123
- Only the root has a Proxy. When you access `admin.SomeSubType`, the property lookup walks:
124
-
125
- ```
126
- admin → AdminType.prototype → AdminMemory → user → UserType.prototype → UserMemory → root Mnemosyne Proxy
127
- ```
128
-
129
- The Proxy’s `get` trap calls `prepareSubtypeForConstruction(prop, receiver)`. It uses `_getProps` to find the memory layer of `receiver` by walking from `Reflect.getPrototypeOf(receiver)`, reads `__subtypes__`, and returns a `SubTypeProxy` that closes over the subtype `TypeDef` and the parent instance.
130
-
131
- This means the root Proxy serves the entire branch below it.
132
-
133
- ## Why the root Proxy is kept
134
-
135
- The root Proxy exists so that **subtypes defined after an instance is created are still visible on that instance**.
136
-
137
- If subtype constructors were attached to the memory layer at construction time, an instance would only know about the subtypes that existed when it was built. Any `ParentType.define('NewSubType', ...)` call afterward would not appear on existing instances.
138
-
139
- The Proxy avoids that by doing a live lookup in the type’s `__subtypes__` Map on every property access. Instances do not carry a snapshot of the Trie; they delegate to the current type graph. That decouples instance lifetime from type-graph evolution and is the main reason a Proxy is necessary. The other Proxy-based mechanisms in the codebase could be replaced with simpler constructs, but this live lookup is hard to achieve without a Proxy.
140
-
141
- ## Classes vs functions
142
-
143
- The final chain shape is identical for class and function definitions. The difference is only in how `ModificatorType` runs the user constructor:
144
-
145
- - **Function:** the wrapper temporarily swaps `ConstructHandler.prototype`, calls `new ConstructHandler(...)`, then restores it.
146
- - **Class:** the generated class `extends ConstructHandler`, calls `super(...)`, then runs the post-construction handler.
147
-
148
- In both cases the resulting prototype chain is rewired to `instance → ModificatorType.prototype → memoryLayer → parent`.
149
-
150
- ## Common mistakes
151
-
152
- - **Assuming internal props are own properties of the instance.** They are stored in a `WeakMap` keyed by the memory layer.
153
- - **Assuming `instance.constructor` is the user’s original function.** It points to the per-construction `ModificatorType`, which delegates behavior to the user handler.
154
- - **Thinking the `Mnemosyne` constructor is used for every instance.** It is used once for the root; subtype memory layers are plain objects.
155
- - **Expecting the user constructor’s `.prototype` to be in the chain.** It is snapshotted and restored; only copies of its descriptors end up on `ModificatorType.prototype`.