mnemonica 1.1.0 → 1.2.1

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 (78) hide show
  1. package/.ai/AGENTS.md +31 -18
  2. package/.ai/DEBUG.md +7 -8
  3. package/.ai/ONBOARDING.md +24 -7
  4. package/.ai/PROTOTYPE-CHAIN.md +33 -2
  5. package/.ai/{ask/AGENTS.md → mode-ask.md} +1 -1
  6. package/.ai/{orchestrator/AGENTS.md → mode-orchestrator.md} +2 -19
  7. package/{docs → .ai}/performance-vs-security.md +1 -1
  8. package/.ai/{rules-skill/async-constructors.md → rules-async-constructors.md} +146 -0
  9. package/.ai/{rules/CODING.md → rules-coding.md} +19 -2
  10. package/.ai/{rules/CONTEXT-CONDENSING.md → rules-context-condensing.md} +2 -2
  11. package/.ai/{rules-skill/contributing.md → rules-contributing.md} +35 -0
  12. package/.ai/{rules-skill/define-patterns.md → rules-define-patterns.md} +39 -0
  13. package/.ai/{rules-skill/instance-methods.md → rules-instance-methods.md} +1 -1
  14. package/.ai/rules-reminders.md +19 -0
  15. package/.ai/{rules-skill/type-system.md → rules-type-system.md} +1 -1
  16. package/{docs → .ai}/theory-of-operations.md +4 -4
  17. package/AGENTS.md +76 -32
  18. package/CONTRIBUTING.md +4 -18
  19. package/FOR_HUMANS.md +123 -83
  20. package/README.md +65 -28
  21. package/SKILL.md +27 -22
  22. package/build/api/errors/index.js +7 -5
  23. package/build/api/index.d.ts +1 -0
  24. package/build/api/index.js +2 -1
  25. package/build/api/types/InstanceCreator.js +16 -5
  26. package/build/api/types/Mnemosyne.d.ts +3 -14
  27. package/build/api/types/Mnemosyne.js +21 -8
  28. package/build/api/types/Props.js +1 -2
  29. package/build/api/types/TypeProxy.d.ts +1 -1
  30. package/build/api/types/TypeProxy.js +9 -9
  31. package/build/api/types/compileNewModificatorFunctionBody.js +3 -5
  32. package/build/api/types/index.d.ts +5 -0
  33. package/build/api/types/index.js +77 -33
  34. package/build/api/utils/index.d.ts +1 -0
  35. package/build/api/utils/index.js +13 -3
  36. package/build/descriptors/types/index.js +46 -2
  37. package/build/index.d.ts +14 -3
  38. package/build/index.js +34 -7
  39. package/build/types/index.d.ts +24 -4
  40. package/build/types/index.js +1 -1
  41. package/build/utils/parent.js +35 -5
  42. package/docs/ai-learning-trajectory.md +2 -3
  43. package/docs/async-constructors.md +1 -1
  44. package/docs/decorate.md +123 -0
  45. package/docs/empathy-in-ai.md +2 -3
  46. package/docs/hott-primer.md +1 -1
  47. package/docs/prototype-chain.md +4 -0
  48. package/docs/purpose.md +3 -3
  49. package/{.ai/TACTICA-DEEP-DIVE.md → docs/tactica-deep-dive.md} +44 -1
  50. package/docs/tactica-pattern.md +1 -2
  51. package/docs/typed-lookup.md +183 -50
  52. package/package.json +8 -8
  53. package/src/api/errors/index.ts +10 -4
  54. package/src/api/index.ts +2 -8
  55. package/src/api/types/InstanceCreator.ts +28 -6
  56. package/src/api/types/Mnemosyne.ts +34 -15
  57. package/src/api/types/Props.ts +4 -4
  58. package/src/api/types/TypeProxy.ts +10 -9
  59. package/src/api/types/compileNewModificatorFunctionBody.ts +12 -4
  60. package/src/api/types/index.ts +136 -69
  61. package/src/api/utils/index.ts +27 -9
  62. package/src/descriptors/types/index.ts +81 -3
  63. package/src/index.ts +150 -7
  64. package/src/types/index.ts +120 -10
  65. package/src/utils/parent.ts +48 -4
  66. package/.ai/CODE.md +0 -111
  67. package/.ai/TACTICA-RULES.md +0 -103
  68. package/.ai/async_init.md +0 -94
  69. package/.ai/rules/REMINDERS.md +0 -63
  70. package/.ai/rules-skill/lookup-typed.md +0 -82
  71. package/.ai/rules-skill/proxy-architecture.md +0 -63
  72. package/.ai/task-templates/new-feature.md +0 -46
  73. /package/.ai/{rules-skill/code-style.md → rules-code-style.md} +0 -0
  74. /package/.ai/{rules-skill/ecosystem.md → rules-ecosystem.md} +0 -0
  75. /package/.ai/{rules-skill/error-system.md → rules-error-system.md} +0 -0
  76. /package/.ai/{rules-skill/hooks.md → rules-hooks.md} +0 -0
  77. /package/.ai/{rules-skill/philosophy.md → rules-philosophy.md} +0 -0
  78. /package/.ai/{rules-skill/testing.md → rules-testing.md} +0 -0
package/.ai/AGENTS.md CHANGED
@@ -1,7 +1,8 @@
1
1
  # AI Agent Guidelines — mnemonica/core
2
2
 
3
- > **Framework-agnostic entry point for all AI agents.**
4
- > This directory is the authoritative source.
3
+ > **Entry point for AI agents contributing to mnemonica core.**
4
+ > This directory is for *editing the library*. Documentation for *using* the
5
+ > library (humans and agents alike) lives in [`docs/`](../docs/).
5
6
 
6
7
  ---
7
8
 
@@ -23,16 +24,28 @@ inheritance graphs, making certain classes of bugs impossible by design.
23
24
  | File | Purpose |
24
25
  |------|---------|
25
26
  | [`AGENTS.md`](./AGENTS.md) | This file — main entry point and overview |
26
- | [`CODE.md`](./CODE.md) | Coding standards: style, TypeScript rules, testing |
27
+ | [`ONBOARDING.md`](./ONBOARDING.md) | Five-minute editor quickstart |
27
28
  | [`ARCHITECT.md`](./ARCHITECT.md) | Design guidelines: patterns, planning, constraints |
28
29
  | [`DEBUG.md`](./DEBUG.md) | Debugging guidelines: commands, common issues, logging |
29
- | [`async_init.md`](./async_init.md) | Async class constructor support: wrapper pattern, `Symbol.hasInstance`, tests |
30
- | [`ask/AGENTS.md`](./ask/AGENTS.md) | Ask mode: explaining concepts, analyzing code |
31
- | [`orchestrator/AGENTS.md`](./orchestrator/AGENTS.md) | Orchestrator mode: multi-step task coordination |
32
- | [`rules/CODING.md`](./rules/CODING.md) | Extended coding rules: models vs controllers, raw* prefix, full file reading |
33
- | [`rules/REMINDERS.md`](./rules/REMINDERS.md) | Quick reference: type vs interface, spacing, before-task checklist |
34
- | [`rules/CONTEXT-CONDENSING.md`](./rules/CONTEXT-CONDENSING.md) | Recovery protocol when context condenses |
35
- | [`task-templates/`](./task-templates/) | Reusable task templates |
30
+ | [`PROTOTYPE-CHAIN.md`](./PROTOTYPE-CHAIN.md) | The exact shape of the prototype chain, layer by layer |
31
+ | [`theory-of-operations.md`](./theory-of-operations.md) | Full construction pipeline, stage by stage |
32
+ | [`performance-vs-security.md`](./performance-vs-security.md) | Performance/security trade-off analysis |
33
+ | [`mode-ask.md`](./mode-ask.md) | Ask mode: explaining concepts, analyzing code |
34
+ | [`mode-orchestrator.md`](./mode-orchestrator.md) | Orchestrator mode: multi-step task coordination |
35
+ | [`rules-coding.md`](./rules-coding.md) | Extended coding rules: models vs controllers, raw* prefix, full file reading |
36
+ | [`rules-reminders.md`](./rules-reminders.md) | Quick reference pointers to canonical sources |
37
+ | [`rules-context-condensing.md`](./rules-context-condensing.md) | Recovery protocol when context condenses |
38
+ | [`rules-contributing.md`](./rules-contributing.md) | Behavioral guidelines + new feature checklist |
39
+ | [`rules-type-system.md`](./rules-type-system.md) | `Proto<P,T>`, `TypeConstructor`, type vs interface |
40
+ | [`rules-define-patterns.md`](./rules-define-patterns.md) | `define()` usage, subtypes, config options |
41
+ | [`rules-async-constructors.md`](./rules-async-constructors.md) | Async constructors, `awaitReturn`, chaining |
42
+ | [`rules-hooks.md`](./rules-hooks.md) | `preCreation`, `postCreation`, `creationError` |
43
+ | [`rules-instance-methods.md`](./rules-instance-methods.md) | `extract()`, `fork()`, `parent()`, internal props |
44
+ | [`rules-code-style.md`](./rules-code-style.md) | Tabs, spacing, type vs interface |
45
+ | [`rules-testing.md`](./rules-testing.md) | 100% coverage, Mocha + Jest, error path patterns |
46
+ | [`rules-error-system.md`](./rules-error-system.md) | `BASE_MNEMONICA_ERROR`, `constructError`, stack cleaning |
47
+ | [`rules-philosophy.md`](./rules-philosophy.md) | HoTT concepts applied to mnemonica's self-reflection model |
48
+ | [`rules-ecosystem.md`](./rules-ecosystem.md) | PACT framework: personas, collaboration modes, integration points |
36
49
 
37
50
  ---
38
51
 
@@ -44,10 +57,10 @@ Read [`ONBOARDING.md`](./ONBOARDING.md) — a single-file quickstart covering ev
44
57
 
45
58
  ### Before You Write Any Code
46
59
 
47
- 1. Read [`CODE.md`](./CODE.md) — style rules, TypeScript rules, testing requirements.
60
+ 1. Read [`ONBOARDING.md`](./ONBOARDING.md) — style rules, TypeScript rules, testing requirements.
48
61
  2. Read [`ARCHITECT.md`](./ARCHITECT.md) — design patterns and constraints.
49
62
  3. If debugging: read [`DEBUG.md`](./DEBUG.md).
50
- 4. If working with async constructors: read [`../docs/async-constructors.md`](../docs/async-constructors.md) — the `super()` return-value pattern and native async class wrapping.
63
+ 4. If working with async constructors: read [`rules-async-constructors.md`](./rules-async-constructors.md) — the `super()` return-value pattern and native async class wrapping.
51
64
 
52
65
  ### Build & Test Commands
53
66
 
@@ -117,9 +130,9 @@ Based on observed agent behavior:
117
130
  | Read source code third | Infers architecture from implementation |
118
131
  | Skip `AGENTS.md` unless told | Often misses build rules, style constraints |
119
132
 
120
- **If you are an agent reading this:** You likely arrived via `README.md` → `AGENTS.md` → `.ai/AGENTS.md`. Good path. Now read `ONBOARDING.md` for the condensed version, or `CODE.md` + `ARCHITECT.md` for full detail.
133
+ **If you are an agent reading this:** You likely arrived via `README.md` → `AGENTS.md` → `.ai/AGENTS.md`. Good path. Now read `ONBOARDING.md` for the condensed version, or `ARCHITECT.md` + `DEBUG.md` for full detail.
121
134
 
122
- **If you are a human:** These docs are for AI agents. The human-facing docs live in `docs/`.
135
+ **If you are a human:** This directory documents *contributing to the core*. For *using* the library, see [`docs/`](../docs/).
123
136
 
124
137
  ---
125
138
 
@@ -129,10 +142,10 @@ Based on observed agent behavior:
129
142
  |------|---------|
130
143
  | [`../SKILL.md`](../SKILL.md) | Condensed skill reference for framework injection |
131
144
  | [`../AGENTS.md`](../AGENTS.md) | Root agent guidelines |
132
- | [`rules-skill/philosophy.md`](./rules-skill/philosophy.md) | HoTT concepts applied to mnemonica's self-reflection model |
133
- | [`rules-skill/ecosystem.md`](./rules-skill/ecosystem.md) | PACT framework: personas, collaboration modes, integration points |
134
- | [`rules-skill/contributing.md`](./rules-skill/contributing.md) | Behavioral guidelines for AI contributors |
135
- | [`TACTICA-DEEP-DIVE.md`](./TACTICA-DEEP-DIVE.md) | Comprehensive tactica + lookup technical guide |
145
+ | [`rules-philosophy.md`](./rules-philosophy.md) | HoTT concepts applied to mnemonica's self-reflection model |
146
+ | [`rules-ecosystem.md`](./rules-ecosystem.md) | PACT framework: personas, collaboration modes, integration points |
147
+ | [`rules-contributing.md`](./rules-contributing.md) | Behavioral guidelines for AI contributors |
148
+ | [`../docs/tactica-deep-dive.md`](../docs/tactica-deep-dive.md) | Comprehensive tactica + lookup technical guide |
136
149
  | [`../docs/async-constructors.md`](../docs/async-constructors.md) | Async constructors: super() return values, native class mixing, chains |
137
150
 
138
151
  - Main README: [`../README.md`](../README.md)
package/.ai/DEBUG.md CHANGED
@@ -158,14 +158,13 @@ npx jest test-jest/types.ts --verbose --no-coverage
158
158
 
159
159
  1. [ ] Check TypeScript compilation: `npm run build`
160
160
  2. [ ] Check build output **at the beginning** for errors/warnings (not just tail)
161
- 3. [ ] Run Mocha tests: `npm run test:mocha`
162
- 4. [ ] Run Jest tests: `npm run test:jest`
163
- 5. [ ] Check test coverage: `npm run test:cov`
164
- 6. [ ] Verify indentation (tabs not spaces)
165
- 7. [ ] Check for bare `Function` / `CallableFunction` / `NewableFunction` types
166
- 8. [ ] Verify symbol usage is correct
167
- 9. [ ] Check proxy handler return types
168
- 10. [ ] Verify return statements use intermediate variables
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
169
168
 
170
169
  ---
171
170
 
package/.ai/ONBOARDING.md CHANGED
@@ -82,13 +82,31 @@ return { target, name };
82
82
  - **No `any`** (`@typescript-eslint/no-explicit-any: error`) — use purpose-specific interfaces
83
83
  - **Never** use bare `Function`, `CallableFunction`, or `NewableFunction` — define purpose-specific interfaces
84
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
+
85
103
  ---
86
104
 
87
105
  ## Architecture
88
106
 
89
107
  ```
90
108
  src/
91
- ├── index.ts # Main exports: define, lookup, apply, call, bind
109
+ ├── index.ts # Main exports: define, lazy, lookup, apply, call, bind
92
110
  ├── types/index.ts # TypeScript type definitions
93
111
  ├── constants/ # Symbols and default options
94
112
  ├── descriptors/ # Type collection and error definitions
@@ -157,15 +175,14 @@ Read [`../docs/async-constructors.md`](../docs/async-constructors.md) for the `s
157
175
 
158
176
  | Need | Read |
159
177
  |------|------|
160
- | Coding standards, type rules | [`CODE.md`](./CODE.md) |
161
178
  | Design patterns, constraints | [`ARCHITECT.md`](./ARCHITECT.md) |
162
179
  | Prototype chain internals | [`PROTOTYPE-CHAIN.md`](./PROTOTYPE-CHAIN.md) |
163
180
  | Debugging commands, issues | [`DEBUG.md`](./DEBUG.md) |
164
- | Async constructor deep dive | [`../docs/async-constructors.md`](../docs/async-constructors.md) |
165
- | tactica type-safe lookup | [`TACTICA-RULES.md`](./TACTICA-RULES.md) |
166
- | Behavioral guidelines | [`rules-skill/contributing.md`](./rules-skill/contributing.md) |
167
- | Explaining code (ask mode) | [`ask/AGENTS.md`](./ask/AGENTS.md) |
168
- | Multi-step coordination | [`orchestrator/AGENTS.md`](./orchestrator/AGENTS.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) |
169
186
 
170
187
  ---
171
188
 
@@ -21,7 +21,7 @@ superadmin
21
21
  └── root Mnemosyne Proxy
22
22
  └── Mnemonica instance
23
23
  └── Mnemonica.prototype
24
- └── uranus
24
+ └── ancestor
25
25
  ```
26
26
 
27
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.
@@ -34,6 +34,27 @@ Every mnemonica type adds three levels to the chain:
34
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
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
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
+
37
58
  ## Files and functions involved
38
59
 
39
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.
@@ -65,6 +86,16 @@ This is why the same constructor function can be reused across multiple type def
65
86
 
66
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`.
67
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
+
68
99
  ## `_setSelf` and async construction
69
100
 
70
101
  `_setSelf(instance)` is called at the end of successful construction. It adds one more getter to the props object:
@@ -73,7 +104,7 @@ This is why the same constructor function can be reused across multiple type def
73
104
  __self__: () => instance
74
105
  ```
75
106
 
76
- Then it stores the props object in the `WeakMap` keyed by the instance itself. This solves the async-constructor problem.
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.
77
108
 
78
109
  When a constructor returns a Promise, the initial value of `new Constructor()` is that Promise. `makeAwaiter` waits for resolution, then checks:
79
110
 
@@ -42,7 +42,7 @@ Creates type constructors with special inheritance capabilities:
42
42
 
43
43
  ### 4. Symbol System
44
44
 
45
- See [`../AGENTS.md`](../AGENTS.md) for the complete symbol reference table.
45
+ See [`AGENTS.md`](./AGENTS.md) for the complete symbol reference table.
46
46
 
47
47
  ## Code Analysis Guidelines
48
48
 
@@ -12,23 +12,7 @@ projects that require work across different domains and specialties.
12
12
 
13
13
  ## Project Structure
14
14
 
15
- ```
16
- core/
17
- ├── src/ # Source TypeScript
18
- │ ├── index.ts # Main exports
19
- │ ├── api/ # Public API
20
- │ │ ├── types/ # TypeProxy, Mnemosyne, InstanceCreator
21
- │ │ ├── errors/ # Error constructors
22
- │ │ ├── hooks/ # Hook system
23
- │ │ └── utils/ # Utility functions
24
- │ ├── descriptors/ # Type descriptors
25
- │ ├── constants/ # Symbols and constants
26
- │ └── utils/ # extract, parse, merge, etc.
27
- ├── build/ # Transpiled output
28
- ├── test-jest/ # Jest tests (TypeScript)
29
- ├── test-ts/ # Mocha tests (TypeScript)
30
- └── module/ # Module-specific config
31
- ```
15
+ See [`ONBOARDING.md`](./ONBOARDING.md#architecture) for the source directory tree.
32
16
 
33
17
  ## Workflow Coordination
34
18
 
@@ -89,8 +73,7 @@ Before completing any orchestrated task:
89
73
  2. [ ] `npm run test:cov` — 100% coverage maintained
90
74
  3. [ ] `npm run test:jest:cov` — Jest tests pass
91
75
  4. [ ] No `any` or `unknown` types introduced
92
- 5. [ ] Tabs used for indentation
93
- 6. [ ] Space-before-function-paren style
76
+ 5. [ ] Follow code style rules (see [`rules-code-style.md`](./rules-code-style.md))
94
77
 
95
78
  ## Multi-Step Task Example
96
79
 
@@ -153,7 +153,7 @@ const props = getProps(instance);
153
153
 
154
154
  **The vulnerability:** Attacker pollutes `Object.prototype` or `Function.prototype`, affecting all objects in the process.
155
155
 
156
- **mnemonica's defense:** Instances are created via `Object.create(null)` roots or mnemonica's own proto chains, not `Object.prototype`. `Object.prototype.isPrototypeOf(instance)` returns `false`. `__proto__` injection does not affect mnemonica instances.
156
+ **mnemonica's defense:** Instances are created via `Object.create(null)` roots or mnemonica's own proto chains, not `Object.prototype`. `Object.prototype.isPrototypeOf(instance)` returns `false`. Injection via the legacy `__proto__` accessor does not affect mnemonica instances.
157
157
 
158
158
  **Honesty check:** The library *manipulates* prototypes heavily internally. It replaces `ConstructHandler.prototype` temporarily during construction (`compileNewModificatorFunctionBody.ts:96`). This is controlled, not user-accessible, but it means mnemonica's internal attack surface is non-zero.
159
159
 
@@ -204,3 +204,149 @@ try {
204
204
  | `await new AsyncSubType()` | ❌ | Fails `strictChain` — no parent instance |
205
205
  | Native `instanceof` through chain | ⚠️ | Follows mnemonica's graph, not native class hierarchy |
206
206
  | `super()` returning Promise | ✅ | Standard JS; mnemonica's wrapper preserves it |
207
+
208
+ ---
209
+
210
+ ## Symbol.hasInstance — Nominal Typing by Name
211
+
212
+ Mnemonica replaces standard JS `instanceof` with **nominal typing** checked by `getTypeChecker` (`src/api/utils/index.ts:37`):
213
+
214
+ ```ts
215
+ const getTypeChecker = (TypeName: string) => {
216
+ return (instance: object) => {
217
+ if (Reflect.getPrototypeOf(instance).constructor.name === 'Promise') {
218
+ return instance[SymbolConstructorName] === TypeName;
219
+ }
220
+ const constructors = collectConstructors(instance);
221
+ return constructors[TypeName] || false;
222
+ };
223
+ };
224
+ ```
225
+
226
+ `collectConstructors` (`src/utils/collectConstructors.ts`) walks the prototype chain upward, collecting `constructor.name` values into a lookup object like `{ AsyncInitParent: true, AsyncInitChild: true, Mnemonica: true, Object: true }`. It stops at `Mnemonica`.
227
+
228
+ Three places define `Symbol.hasInstance`:
229
+
230
+ 1. **`TypeDescriptor.prototype`** (`src/api/types/index.ts:210`) — for `instanceof TypeName` where `TypeName` is what `define()` returned
231
+ 2. **`Mnemosyne.prototype`** (`src/api/types/Mnemosyne.ts:381`) — for `instanceof` checks on the instance itself
232
+ 3. **`makeSubTypeProxy`** (`src/api/types/Mnemosyne.ts:205`) — for subtype access like `parent.SubType()`
233
+
234
+ ### Impact on Pre-existing Class Hierarchies
235
+
236
+ When passing a pre-existing class hierarchy (`class Extended extends Base`) to `define()`:
237
+
238
+ - **Top-level** `define('PreExt', Extended)`: `PreExt.prototype === Extended.prototype`. Both `instanceof PreExt` and `instanceof Extended` work.
239
+ - **Sub-type** `Root.define('Sub', Extended)`: mnemonica's subtype wiring inserts the parent type (`Root`) into the instance chain **before** `Extended.prototype`. Standard JS `instanceof Extended` returns **false**, but mnemonica's `instanceof Sub` and `instanceof Root` still work because `collectConstructors` finds their names.
240
+
241
+ ---
242
+
243
+ ## Test Suite
244
+
245
+ Tests live in `test_async/index.js` and run via `npm run test:async_init`.
246
+
247
+ ### Acronyms
248
+
249
+ - **WOReturn** = **W**ith**O**ut **Return** — Promise resolves to `undefined` instead of `this`
250
+ - **NAR** = **N**o **A**wait **R**eturn** — `awaitReturn: false` disables the guard
251
+
252
+ ### Coverage Items
253
+
254
+ 1. **WOReturn guard for classes** — async class constructor returning Promise without `this` throws `WRONG_MODIFICATION_PATTERN`
255
+ 2. **NAR bypass** — `awaitReturn: false` allows the same without throwing
256
+ 3. **Field inheritance through mnemonica chain** — parent/child fields preserved across async constructors
257
+ 4. **Pre-existing class hierarchy at top-level** — `define('Type', ExtendedClass)` preserves fields and `instanceof` against original classes
258
+ 5. **Pre-existing class hierarchy as sub-type** — sub instance gets root fields + class hierarchy fields, but standard JS `instanceof` against original classes is broken (mnemonica `instanceof` still works)
259
+
260
+ ### Relevant Source Files
261
+
262
+ - `src/api/types/compileNewModificatorFunctionBody.ts` — wrapper class creation
263
+ - `src/api/utils/index.ts` — `getTypeChecker`
264
+ - `src/utils/collectConstructors.ts` — prototype chain walker
265
+ - `src/api/types/Mnemosyne.ts` — `Symbol.hasInstance` on instances and sub-type proxy
266
+ - `src/api/types/index.ts` — `Symbol.hasInstance` on `TypeDescriptor.prototype`
267
+ - `src/api/types/InstanceCreator.ts` — async routing via `makeAwaiter`
268
+
269
+ ### Historical examples (from the unshipped `test_async` suite)
270
+
271
+ `test_async/index.js` is a historical record and is **not part of the
272
+ published package**. The scenarios it covered are preserved here.
273
+
274
+ Async class constructors that resolve `this` keep fields and chain identity:
275
+
276
+ ```js
277
+ const AsyncInitParent = define('AsyncInitParent', class {
278
+ parentField = 'parent-field';
279
+ constructor () {
280
+ return new Promise((resolve) => {
281
+ setTimeout(() => resolve(this), 10);
282
+ });
283
+ }
284
+ });
285
+
286
+ const AsyncInitChild = AsyncInitParent.define('AsyncInitChild', class {
287
+ childField = 'child-field';
288
+ constructor () {
289
+ return new Promise((resolve) => {
290
+ setTimeout(() => resolve(this), 10);
291
+ });
292
+ }
293
+ });
294
+
295
+ const parent = await new AsyncInitParent();
296
+ const child = await parent.AsyncInitChild();
297
+ child.parentField; // 'parent-field' — inherited through the async chain
298
+ child.childField; // 'child-field'
299
+ ```
300
+
301
+ An async constructor that resolves `undefined` throws by default;
302
+ `awaitReturn: false` disables the guard:
303
+
304
+ ```js
305
+ const AsyncInitWOReturn = define('AsyncInitWOReturn', class {
306
+ constructor () {
307
+ return new Promise((resolve) => {
308
+ setTimeout(() => resolve(), 10); // resolves undefined → throws
309
+ });
310
+ }
311
+ });
312
+
313
+ define('AsyncInitWOReturnNAR', class {
314
+ constructor () {
315
+ return new Promise((resolve) => {
316
+ setTimeout(() => resolve(), 10);
317
+ });
318
+ }
319
+ }, { awaitReturn: false }); // resolves undefined → no throw
320
+ ```
321
+
322
+ A pre-existing class hierarchy can serve as the construct handler, at the
323
+ top level or as a subtype:
324
+
325
+ ```js
326
+ class AsyncInitBaseClass {
327
+ baseField = 'base-field';
328
+ }
329
+
330
+ class AsyncInitExtendedClass extends AsyncInitBaseClass {
331
+ extField = 'ext-field';
332
+ constructor () {
333
+ super();
334
+ return new Promise((resolve) => {
335
+ setTimeout(() => resolve(this), 10);
336
+ });
337
+ }
338
+ }
339
+
340
+ // top level: instanceof works against BOTH the mnemonica type
341
+ // and the original classes
342
+ const AsyncInitPreExtended = define('AsyncInitPreExtended', AsyncInitExtendedClass);
343
+
344
+ // as a subtype of a root type (AsyncInitRooted, defined as above):
345
+ // fields are inherited and mnemonica instanceof works, but plain JS
346
+ // instanceof against the original classes is broken
347
+ const AsyncInitRootedSub = AsyncInitRooted.define('AsyncInitRootedSub', AsyncInitExtendedClass);
348
+ ```
349
+
350
+ ### Related
351
+
352
+ - [TC39 proposal-async-init issue #3](https://github.com/tc39/proposal-async-init/issues/3) — language-level discussion of the same problem
@@ -6,17 +6,20 @@
6
6
 
7
7
  You MUST pause BEFORE proceeding and ask the user for clarification if ANY of the following is true:
8
8
 
9
- 1. **Editing errors** — `apply_diff` fails, `write_to_file` produces unexpected results, or any tool returns an error.
9
+ 1. **Errors** — `apply_diff` fails, `write_to_file` produces unexpected results, or any tool returns an error. A successful retry does NOT cancel this rule: report the error AND how you recovered.
10
10
  2. **Uncertainty** — you are not 100% certain about what change to make, how a function works, or what the user intended.
11
11
  3. **Assumptions** — you find yourself filling in gaps with "probably", "likely", "I think", or "it should work".
12
+ 4. **Conflicting constraints** — a tool or environment constraint conflicts with the user's stated preference. Surface the conflict verbatim; never silently satisfy the tool at the user's expense.
13
+ 5. **Unrequested file creation or duplication** — you are about to create or duplicate a file the user did not explicitly request. Ask first. Never copy content when `mv`, rename, or a reference suffices.
12
14
 
13
15
  ## What To Do
14
16
 
15
17
  - STOP immediately.
16
- - Do NOT proceed with workarounds (no `sed`, no `python -c`, no console hacks).
18
+ - Do NOT proceed with workarounds (no `sed`, no `python -c`, no console hacks, no rewriting files to bypass a tool restriction).
17
19
  - Do NOT make assumptions.
18
20
  - ASK the user a clear, specific question.
19
21
  - WAIT for their answer before continuing.
22
+ - **Silent recovery is a violation, even when the outcome looks fine.**
20
23
 
21
24
  ## Why This Matters
22
25
 
@@ -24,6 +27,20 @@ You work with a Computer Science Enthusiast. You are their clever and knowledgea
24
27
 
25
28
  ---
26
29
 
30
+ # Files: Move, Don't Rewrite
31
+
32
+ Never create a file whose content substantially duplicates an existing file.
33
+ Two copies of the same document will drift apart.
34
+
35
+ - To relocate a file: use `mv` (or rename) — never rewrite the full content
36
+ into a new path and leave the original behind.
37
+ - To share content: reference or link to the canonical file.
38
+ - If a tool rejects the original path (permission error, workspace boundary):
39
+ STOP and ask the user (Rule #1, clause 4). Do not work around the tool
40
+ by duplicating the file elsewhere.
41
+
42
+ ---
43
+
27
44
  # Extended Coding Rules
28
45
 
29
46
  ## CRITICAL: Full File Reading Required
@@ -16,11 +16,11 @@ Context condenses when:
16
16
  1. **STOP** - Do not continue implementing
17
17
  2. **Re-read AGENTS.md files:**
18
18
  - `AGENTS.md` in workspace root (if exists)
19
- - `.ai/rules/CODING.md`
19
+ - `.ai/rules-coding.md`
20
20
  3. **Check specific sections:**
21
21
  - "CRITICAL: Type vs Interface vs Instance" (lines 244-279)
22
22
  - "Lessons Learned from Recent Refactoring" (lines 99-191)
23
- 4. **Re-read REMINDERS.md** in `.ai/rules/`
23
+ 4. **Re-read** `.ai/rules-reminders.md`
24
24
  5. **Review recent code** - Look at the last few files you edited to confirm patterns
25
25
  6. **Resume** only after context is refreshed
26
26
 
@@ -190,3 +190,38 @@ These guidelines are working if you see:
190
190
  - **Clarifying questions come before implementation** — Not after mistakes
191
191
  - **Clean, minimal PRs** — No drive-by refactoring or "improvements"
192
192
  - **100% coverage maintained** — Tests verify every change
193
+
194
+ ---
195
+
196
+ ## New Feature Checklist
197
+
198
+ Folded in from the former `.ai/task-templates/new-feature.md`.
199
+
200
+ ### Pre-Flight
201
+
202
+ - [ ] Read `AGENTS.md` (root) sections on type vs interface vs instance and build/test commands
203
+ - [ ] Check existing code patterns in the target directory
204
+ - [ ] Run `npm run build` to ensure a clean baseline
205
+
206
+ ### Implementation
207
+
208
+ 1. **Design**
209
+ - [ ] Define types (use `type` for instances, `interface` for constructors/contracts)
210
+ - [ ] Check `.ai/rules-reminders.md`
211
+ 2. **Coding**
212
+ - [ ] Indentation: TABS ONLY (width 4)
213
+ - [ ] Function spacing: `function myFunc () { }`
214
+ - [ ] Key spacing: `{ key : value }` (colons aligned)
215
+ 3. **Testing**
216
+ - [ ] Run `npm run test:cov` (validates build + 100% coverage)
217
+ - [ ] Verify no ESLint warnings
218
+ - [ ] Re-read the full content of each edited file as if it were a code review
219
+ 4. **Completion**
220
+ - [ ] Update the TODO list
221
+ - [ ] Run the final build
222
+
223
+ ### Context Condensing
224
+
225
+ **CRITICAL:** If you notice yourself forgetting established patterns:
226
+
227
+ → **READ** `.ai/rules-context-condensing.md` immediately
@@ -63,6 +63,45 @@ define('Parent.Child', function (this: Child, data: Data) {
63
63
  });
64
64
  ```
65
65
 
66
+ ## Lazy definitions
67
+
68
+ Use `.lazy()` when the constructor must be resolved through a getter — for
69
+ example, to break a circular dependency or to defer constructor selection until
70
+ definition time. `.define()` no longer accepts an anonymous function as its
71
+ first argument; that form has moved to `.lazy()`.
72
+
73
+ ### Unnamed (name from returned constructor)
74
+ ```typescript
75
+ const LazyType = define('RootType', function () {})
76
+ .lazy(() => function LazySubType(this: LazySubType, data: LazyData) {
77
+ Object.assign(this, data);
78
+ });
79
+ ```
80
+
81
+ ### Named (explicit type name)
82
+ ```typescript
83
+ const NamedLazy = RootType.lazy('NamedLazy', () => function (data: NamedData) {
84
+ Object.assign(this, data);
85
+ });
86
+ ```
87
+
88
+ ### Free-function form
89
+ ```typescript
90
+ import { lazy } from 'mnemonica';
91
+
92
+ const LazyRoot = lazy('LazyRoot', () => class LazyRoot {
93
+ field: string;
94
+ constructor(field: string) {
95
+ this.field = field;
96
+ }
97
+ });
98
+ ```
99
+
100
+ The getter is called once at definition time. The returned constructor is
101
+ registered exactly like a constructor passed directly to `define()`, and the
102
+ resulting type supports `.define()`, `.lazy()`, `.lookup()`, and subtype
103
+ chaining.
104
+
66
105
  ## Export root constructors only when needed; never export subtypes
67
106
 
68
107
  Subtypes live on the parent constructor and on parent instances. Exporting a subtype splits the Trie and usually loses the parent part of the chain.
@@ -14,7 +14,7 @@ metadata:
14
14
 
15
15
  For the type-level details of the corresponding standalone utilities
16
16
  (`utils.extract`, `utils.pick`, `utils.parent`, `utils.fork`, `utils.clone`,
17
- `utils.sibling`, `utils.exception`), see [`docs/UTILS.md`](../../docs/UTILS.md).
17
+ `utils.sibling`, `utils.exception`), see [`docs/UTILS.md`](../docs/UTILS.md).
18
18
 
19
19
  ## Standalone Utilities (Default)
20
20
 
@@ -0,0 +1,19 @@
1
+ # Quick Check Before Coding
2
+
3
+ ## Type vs Interface
4
+ See [rules-type-system.md](./rules-type-system.md#type-vs-interface-rule).
5
+
6
+ ## Indentation
7
+ Tabs only. Width 4. See [rules-code-style.md](./rules-code-style.md).
8
+
9
+ ## Function Spacing
10
+ Space before paren: `function myFunc ()`. See [rules-code-style.md](./rules-code-style.md).
11
+
12
+ ## Key Spacing
13
+ Space after colon: `{ key : value }`. See [rules-code-style.md](./rules-code-style.md).
14
+
15
+ ## Before Each Task
16
+ 1. Read AGENTS.md if context seems incomplete
17
+ 2. Check existing code patterns in the same directory
18
+ 3. Run `npm run build` before completing
19
+ 4. Run `npm run test:cov` for coverage validation
@@ -121,4 +121,4 @@ argument. Callers should never need an explicit `<T>` cast for ordinary operatio
121
121
 
122
122
  The full reference — helper types (`Extracted`, `Merge`, `InstanceResult`,
123
123
  `Parsed`, `SiblingAccessor`), every utility signature, and the type-level
124
- explanation of `utils.merge` — lives in [`docs/UTILS.md`](../../docs/UTILS.md).
124
+ explanation of `utils.merge` — lives in [`docs/UTILS.md`](../docs/UTILS.md).
@@ -90,13 +90,13 @@ This is where the Trie structure is physically built:
90
90
  The resulting chain:
91
91
  ```
92
92
  newObj
93
- ↓ __proto__
93
+ ↓ Object.getPrototypeOf(newObj)
94
94
  ModificatorType.prototype
95
- ↓ __proto__
95
+ ↓ Object.getPrototypeOf(ModificatorType.prototype)
96
96
  Mnemosyne (has __type__, __parent__, etc.)
97
- ↓ __proto__
97
+ ↓ Object.getPrototypeOf(Mnemosyne)
98
98
  existentInstance (the specific parent)
99
- ↓ __proto__
99
+ ↓ Object.getPrototypeOf(existentInstance)
100
100
  ... (rest of chain to root)
101
101
  ```
102
102