mnemonica 1.2.1 → 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 (53) hide show
  1. package/FOR_HUMANS.md +186 -138
  2. package/README.md +70 -249
  3. package/build/api/errors/exceptionConstructor.js +20 -47
  4. package/build/api/errors/throwModificationError.js +26 -61
  5. package/build/api/types/InstanceCreator.js +5 -1
  6. package/build/api/types/Props.js +24 -10
  7. package/build/api/types/index.js +18 -12
  8. package/build/types/index.d.ts +9 -4
  9. package/build/types/index.js +1 -1
  10. package/docs/UTILS.md +97 -8
  11. package/docs/async-constructors.md +2 -0
  12. package/docs/decorate.md +1 -1
  13. package/docs/empathy-in-ai.md +20 -10
  14. package/docs/prototype-chain.md +8 -7
  15. package/docs/typed-lookup.md +195 -5
  16. package/docs/typeomatica.md +8 -345
  17. package/package.json +6 -10
  18. package/src/api/errors/exceptionConstructor.ts +40 -83
  19. package/src/api/errors/throwModificationError.ts +64 -104
  20. package/src/api/types/InstanceCreator.ts +14 -0
  21. package/src/api/types/Props.ts +53 -18
  22. package/src/api/types/index.ts +33 -20
  23. package/src/types/index.ts +15 -5
  24. package/.ai/AGENTS.md +0 -151
  25. package/.ai/ARCHITECT.md +0 -110
  26. package/.ai/DEBUG.md +0 -178
  27. package/.ai/ONBOARDING.md +0 -189
  28. package/.ai/PROTOTYPE-CHAIN.md +0 -153
  29. package/.ai/mode-ask.md +0 -121
  30. package/.ai/mode-orchestrator.md +0 -141
  31. package/.ai/performance-vs-security.md +0 -395
  32. package/.ai/rules-async-constructors.md +0 -352
  33. package/.ai/rules-code-style.md +0 -95
  34. package/.ai/rules-coding.md +0 -246
  35. package/.ai/rules-context-condensing.md +0 -50
  36. package/.ai/rules-contributing.md +0 -227
  37. package/.ai/rules-define-patterns.md +0 -159
  38. package/.ai/rules-ecosystem.md +0 -140
  39. package/.ai/rules-error-system.md +0 -56
  40. package/.ai/rules-hooks.md +0 -46
  41. package/.ai/rules-instance-methods.md +0 -93
  42. package/.ai/rules-philosophy.md +0 -231
  43. package/.ai/rules-reminders.md +0 -19
  44. package/.ai/rules-testing.md +0 -66
  45. package/.ai/rules-type-system.md +0 -124
  46. package/.ai/theory-of-operations.md +0 -224
  47. package/AGENTS.md +0 -345
  48. package/CONTRIBUTING.md +0 -150
  49. package/SKILL.md +0 -114
  50. package/docs/ai-learning-trajectory.md +0 -141
  51. package/docs/purpose.md +0 -707
  52. package/docs/tactica-deep-dive.md +0 -629
  53. package/docs/tactica-pattern.md +0 -146
@@ -1,153 +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)` walks the prototype chain from the instance until it finds the first object with a `WeakMap` entry. 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. The memory layer is the only props key; `setProps` additions are keyed by the props object itself.
96
-
97
- **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.
98
-
99
- ## `_setSelf` and async construction
100
-
101
- `_setSelf(instance)` is called at the end of successful construction. It adds one more getter to the props object:
102
-
103
- ```js
104
- __self__: () => instance
105
- ```
106
-
107
- 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.
108
-
109
- When a constructor returns a Promise, the initial value of `new Constructor()` is that Promise. `makeAwaiter` waits for resolution, then checks:
110
-
111
- ```js
112
- if (props.__self__ !== self.inheritedInstance) {
113
- self.postProcessing(type);
114
- }
115
- ```
116
-
117
- 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.
118
-
119
- ## Subtype lookup
120
-
121
- Only the root has a Proxy. When you access `admin.SomeSubType`, the property lookup walks:
122
-
123
- ```
124
- admin → AdminType.prototype → AdminMemory → user → UserType.prototype → UserMemory → root Mnemosyne Proxy
125
- ```
126
-
127
- 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.
128
-
129
- This means the root Proxy serves the entire branch below it.
130
-
131
- ## Why the root Proxy is kept
132
-
133
- The root Proxy exists so that **subtypes defined after an instance is created are still visible on that instance**.
134
-
135
- 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.
136
-
137
- 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.
138
-
139
- ## Classes vs functions
140
-
141
- The final chain shape is identical for class and function definitions. The difference is only in how `ModificatorType` runs the user constructor:
142
-
143
- - **Function:** the wrapper temporarily swaps `ConstructHandler.prototype`, calls `new ConstructHandler(...)`, then restores it.
144
- - **Class:** the generated class `extends ConstructHandler`, calls `super(...)`, then runs the post-construction handler.
145
-
146
- In both cases the resulting prototype chain is rewired to `instance → ModificatorType.prototype → memoryLayer → parent`.
147
-
148
- ## Common mistakes
149
-
150
- - **Assuming internal props are own properties of the instance.** They are stored in a `WeakMap` keyed by the memory layer.
151
- - **Assuming `instance.constructor` is the user’s original function.** It points to the per-construction `ModificatorType`, which delegates behavior to the user handler.
152
- - **Thinking the `Mnemosyne` constructor is used for every instance.** It is used once for the root; subtype memory layers are plain objects.
153
- - **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`.
package/.ai/mode-ask.md DELETED
@@ -1,121 +0,0 @@
1
- # Ask Mode Guidelines — mnemonica/core
2
-
3
- > **Applies to:** Explaining concepts, analyzing code, answering questions.
4
- > Framework-agnostic.
5
-
6
- ---
7
-
8
- ## Role
9
-
10
- You are in **Ask** mode. Your task is to explain concepts, analyze code, and
11
- answer questions about the mnemonica codebase.
12
-
13
- ## Key Concepts
14
-
15
- ### 1. Instance Inheritance
16
-
17
- ```typescript
18
- // Define a type
19
- const User = define('User', function (name: string) {
20
- this.name = name;
21
- });
22
-
23
- // Create instance
24
- const user = new User('John');
25
-
26
- // Create child instance (inherits from user)
27
- const admin = user.Admin('privileges');
28
- ```
29
-
30
- ### 2. The `define()` Function
31
-
32
- Creates type constructors with special inheritance capabilities:
33
- - Wraps constructors in TypeProxy
34
- - Registers type in TypesCollection
35
- - Enables `.subtypes` collection
36
-
37
- ### 3. Proxy Architecture
38
-
39
- - **TypeProxy** — Wraps type constructors, handles `.call`, `.apply`
40
- - **Mnemosyne** — Manages instance prototype chain
41
- - **TypesCollectionProxy** — Manages type registry, handles type lookup
42
-
43
- ### 4. Symbol System
44
-
45
- See [`AGENTS.md`](./AGENTS.md) for the complete symbol reference table.
46
-
47
- ## Code Analysis Guidelines
48
-
49
- When explaining code:
50
- 1. Reference specific files: `src/api/types/Mnemosyne.ts`
51
- 2. Include line numbers for key concepts
52
- 3. Explain the "why" behind design decisions
53
- 4. Connect to the broader architecture
54
-
55
- ## Explaining Proxy Handlers
56
-
57
- ```typescript
58
- // TypeProxy pattern
59
- const TypeProxy = new Proxy(Constructor, {
60
- // Intercepts Constructor() calls
61
- apply(target, thisArg, args) {
62
- return createInstance(target, args);
63
- },
64
- // Intercepts new Constructor() calls
65
- construct(target, args) {
66
- return createInstance(target, args);
67
- }
68
- });
69
- ```
70
-
71
- ## Explaining Instance Introspection
72
-
73
- Starting from v1.0.6 the legacy instance methods are no longer auto-injected.
74
- Use the standalone `utils` export:
75
-
76
- | Utility | Purpose | Defined In |
77
- |---------|---------|------------|
78
- | `utils.fork(instance)` | Create a fork constructor | fork.ts |
79
- | `utils.parent(instance)` | Access parent instance | parent.ts |
80
- | `utils.pick(instance, ...keys)` | Extract specific properties | pick.ts |
81
- | `utils.extract(instance)` | Get all inherited properties | extract.ts |
82
- | `utils.parse(instance)` | Parse instance structure | parse.ts |
83
-
84
- To restore the old `instance.fork()` / `instance.extract()` style, attach the
85
- methods to the constructor's prototype before calling `define()`.
86
-
87
- ## Test Framework Differences
88
-
89
- | Aspect | Mocha | Jest |
90
- |--------|-------|------|
91
- | Source | `build/` (transpiled) | `src/` (TypeScript) |
92
- | Config | package.json scripts | jest.config.js |
93
- | Coverage | nyc | built-in |
94
- | Purpose | Integration | Unit/Types |
95
-
96
- ## Common Questions
97
-
98
- ### Why strict TypeScript?
99
- The project enforces 100% code coverage and strict type checking to ensure
100
- reliability in the complex proxy-based architecture.
101
-
102
- ### Why two test frameworks?
103
- Mocha tests the transpiled output (integration), Jest tests TypeScript source
104
- directly (types and units).
105
-
106
- ### Why tabs for indentation?
107
- Project standard — configured in `.editorconfig` and `eslint.config.js`.
108
-
109
- ### How do async constructors work?
110
- mnemonica supports async constructors natively. `await new AsyncType()` returns
111
- the resolved instance (with `awaitReturn: true`, the default). Async subtypes
112
- must be invoked as methods on the parent instance: `await parent.AsyncChild()`.
113
- See `docs/async-constructors.md` for the `super()` return-value pattern and
114
- native async class wrapping.
115
-
116
- ## Documentation References
117
-
118
- - Main README: `core/README.md`
119
- - Type definitions: `src/types/index.ts`
120
- - Constants: `src/constants/index.ts`
121
- - Test examples: `test-jest/types.ts`
@@ -1,141 +0,0 @@
1
- # Orchestrator Mode Guidelines — mnemonica/core
2
-
3
- > **Applies to:** Coordinating complex, multi-step projects across domains.
4
- > Framework-agnostic.
5
-
6
- ---
7
-
8
- ## Role
9
-
10
- You are in **Orchestrator** mode. Your task is to coordinate complex, multi-step
11
- projects that require work across different domains and specialties.
12
-
13
- ## Project Structure
14
-
15
- See [`ONBOARDING.md`](./ONBOARDING.md#architecture) for the source directory tree.
16
-
17
- ## Workflow Coordination
18
-
19
- ### For Type System Changes
20
- 1. **Architect** — Design type interfaces
21
- 2. **Code** — Implement type definitions in `src/types/index.ts`
22
- 3. **Code** — Update files using the types
23
- 4. **Debug** — Verify build and tests pass
24
- 5. **Code** — Update tests if needed
25
-
26
- ### For New Features
27
- 1. **Architect** — Design feature specification
28
- 2. **Code** — Implement core logic
29
- 3. **Code** — Add type definitions
30
- 4. **Debug** — Test and fix issues
31
- 5. **Code** — Add test coverage
32
-
33
- ### For Bug Fixes
34
- 1. **Debug** — Identify root cause
35
- 2. **Code** — Implement fix
36
- 3. **Debug** — Verify fix works
37
- 4. **Code** — Add regression test
38
- 5. **Code** — Update related documentation
39
-
40
- ## Task Delegation Patterns
41
-
42
- ```
43
- User Request
44
- │
45
- ▼
46
- Orchestrator (Analyze)
47
- │
48
- ├──► Architect (Design) ──┐
49
- │ │
50
- ├──► Code (Implement) ◄────┘
51
- │ │
52
- ├──► Debug (Verify) ◄──────┘
53
- │ │
54
- └──► Code (Test) ◄─────────┘
55
- │
56
- Orchestrator (Complete)
57
- ```
58
-
59
- ## Mode-Specific File Patterns
60
-
61
- | Mode | Can Edit | Cannot Edit |
62
- |------|----------|-------------|
63
- | architect | `*.md` | `*.ts`, `*.js` |
64
- | code | `*.ts`, `*.js` | — |
65
- | debug | read-only analysis | modifications |
66
- | ask | read-only explanation | modifications |
67
- | orchestrator | task delegation | implementation |
68
-
69
- ## Quality Gates
70
-
71
- Before completing any orchestrated task:
72
- 1. [ ] `npm run build` — TypeScript compiles
73
- 2. [ ] `npm run test:cov` — 100% coverage maintained
74
- 3. [ ] `npm run test:jest:cov` — Jest tests pass
75
- 4. [ ] No `any` or `unknown` types introduced
76
- 5. [ ] Follow code style rules (see [`rules-code-style.md`](./rules-code-style.md))
77
-
78
- ## Multi-Step Task Example
79
-
80
- **Task**: Add new instance method `.toYAML()`
81
-
82
- ```
83
- Step 1: Architect
84
- - Design API: instance.toYAML(): string
85
- - Add to Mnemosyne.ts or separate utility
86
- - Document in AGENTS.md
87
-
88
- Step 2: Code (types)
89
- - Add to src/types/index.ts interface
90
- - Update MnemonicaInstance definition
91
-
92
- Step 3: Code (implementation)
93
- - Add to Mnemosyne.ts or src/utils/toYAML.ts
94
- - Export from src/utils/index.ts
95
- - Update src/index.ts exports
96
-
97
- Step 4: Code (tests)
98
- - Add test-jest/toYAML.ts
99
- - Add test-ts/test-toYAML.ts
100
-
101
- Step 5: Debug
102
- - Run all test suites
103
- - Verify 100% coverage
104
- - Fix any issues
105
- ```
106
-
107
- ## Communication Templates
108
-
109
- ### Delegating to Code Mode
110
- ```
111
- Implement [feature] in [file]:
112
- 1. Add [specific function/method]
113
- 2. Follow [existing pattern from reference]
114
- 3. Ensure [specific requirement]
115
- 4. Run tests to verify
116
- ```
117
-
118
- ### Delegating to Debug Mode
119
- ```
120
- Investigate [issue]:
121
- 1. Check [specific area]
122
- 2. Identify root cause
123
- 3. Report findings with file paths and line numbers
124
- ```
125
-
126
- ### Delegating to Architect Mode
127
- ```
128
- Design [feature]:
129
- 1. Create specification in [file.md]
130
- 2. Define interfaces and types
131
- 3. Document integration points
132
- ```
133
-
134
- ## Important Constraints
135
-
136
- - Never skip test verification
137
- - Maintain 100% code coverage
138
- - Respect the dual test framework
139
- - Follow strict TypeScript rules
140
- - Use tabs for indentation
141
- - **No `any`** (`@typescript-eslint/no-explicit-any: error`) — define proper types