mnemonica 1.1.0 → 1.2.0

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 (49) hide show
  1. package/.ai/AGENTS.md +31 -18
  2. package/.ai/DEBUG.md +7 -8
  3. package/.ai/ONBOARDING.md +23 -6
  4. package/.ai/PROTOTYPE-CHAIN.md +21 -0
  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} +66 -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/instance-methods.md → rules-instance-methods.md} +1 -1
  13. package/.ai/rules-reminders.md +19 -0
  14. package/.ai/{rules-skill/type-system.md → rules-type-system.md} +1 -1
  15. package/{docs → .ai}/theory-of-operations.md +4 -4
  16. package/AGENTS.md +62 -31
  17. package/FOR_HUMANS.md +20 -72
  18. package/README.md +23 -21
  19. package/SKILL.md +20 -20
  20. package/build/api/types/index.js +8 -3
  21. package/build/index.d.ts +9 -2
  22. package/build/index.js +17 -5
  23. package/build/types/index.d.ts +2 -0
  24. package/build/types/index.js +1 -1
  25. package/docs/ai-learning-trajectory.md +2 -3
  26. package/docs/decorate.md +123 -0
  27. package/docs/hott-primer.md +1 -1
  28. package/docs/purpose.md +3 -3
  29. package/{.ai/TACTICA-DEEP-DIVE.md → docs/tactica-deep-dive.md} +44 -1
  30. package/docs/tactica-pattern.md +1 -2
  31. package/docs/typed-lookup.md +170 -54
  32. package/package.json +1 -1
  33. package/src/api/types/index.ts +14 -4
  34. package/src/index.ts +84 -7
  35. package/src/types/index.ts +15 -0
  36. package/.ai/CODE.md +0 -111
  37. package/.ai/TACTICA-RULES.md +0 -103
  38. package/.ai/async_init.md +0 -94
  39. package/.ai/rules/REMINDERS.md +0 -63
  40. package/.ai/rules-skill/lookup-typed.md +0 -82
  41. package/.ai/rules-skill/proxy-architecture.md +0 -63
  42. package/.ai/task-templates/new-feature.md +0 -46
  43. /package/.ai/{rules-skill/code-style.md → rules-code-style.md} +0 -0
  44. /package/.ai/{rules-skill/define-patterns.md → rules-define-patterns.md} +0 -0
  45. /package/.ai/{rules-skill/ecosystem.md → rules-ecosystem.md} +0 -0
  46. /package/.ai/{rules-skill/error-system.md → rules-error-system.md} +0 -0
  47. /package/.ai/{rules-skill/hooks.md → rules-hooks.md} +0 -0
  48. /package/.ai/{rules-skill/philosophy.md → rules-philosophy.md} +0 -0
  49. /package/.ai/{rules-skill/testing.md → rules-testing.md} +0 -0
package/src/index.ts CHANGED
@@ -15,7 +15,11 @@ import type {
15
15
  TypeAbsorber,
16
16
  MnemonicaModule,
17
17
  InstanceResult,
18
- Merge
18
+ Merge,
19
+ TypeLookup,
20
+ LookupResult,
21
+ RegistryHolderBase,
22
+ StoredConstructor
19
23
  } from './types';
20
24
 
21
25
  import TypesUtils from './api/utils/index';
@@ -43,6 +47,8 @@ export type {
43
47
  TypeAbsorber,
44
48
  TypesCollection,
45
49
  TypeLookup,
50
+ LookupResult,
51
+ RegistryOf,
46
52
  MnemonicaModule,
47
53
  } from './types';
48
54
 
@@ -95,6 +101,28 @@ function checkThis(pointer: typeof mnemonica | typeof exports | unknown): boolea
95
101
 
96
102
 
97
103
  // Define function using TypeAbsorber interface with proper type casting
104
+ export function define <
105
+ Reg extends object,
106
+ Parent extends object,
107
+ Path extends string,
108
+ const Name extends string,
109
+ N extends object,
110
+ Args extends unknown[],
111
+ F extends Proto<Parent, N> = Proto<Parent, N>,
112
+ ChildPath extends string = Path extends '' ? Name : `${Path}.${Name}`
113
+ >(
114
+ // explicit-source form: define(source, name, handler, config?)
115
+ // mirrors RegistryHolderBase.define; semantics follow the source object
116
+ source: RegistryHolderBase<Reg, Parent, Path>,
117
+ TypeName: Name,
118
+ constructHandler?: IDEF<N, Args>,
119
+ config?: constructorOptions
120
+ ): IDefinitorInstance<
121
+ F,
122
+ InstanceResult<F>,
123
+ Reg & Record<ChildPath, StoredConstructor<F, ChildPath>>,
124
+ ChildPath
125
+ >;
98
126
  export function define <
99
127
  T extends object,
100
128
  P extends object = object,
@@ -107,14 +135,44 @@ export function define <
107
135
  // Allow both strict IDEF and more flexible function signatures
108
136
  constructHandler?: IDEF<T> | CallableFunction | NewableFunction | object | boolean,
109
137
  config?: constructorOptions,
138
+ ): R;
139
+ export function define <
140
+ T extends object,
141
+ P extends object = object,
142
+ N extends Proto<P, T> = Proto<P, T>,
143
+ R extends IDefinitorInstance<N> = IDefinitorInstance<N>,
144
+ >(
145
+ this: unknown,
146
+ TypeNameOrSource?: string | CallableFunction | NewableFunction | RegistryHolderBase<object, object, string>,
147
+ constructHandlerOrName?: IDEF<T> | CallableFunction | NewableFunction | object | boolean | string,
148
+ configOrHandler?: constructorOptions | IDEF<T> | CallableFunction | NewableFunction | object | boolean,
149
+ config?: constructorOptions,
110
150
  ): R {
151
+
152
+ // explicit-source form: define(source, name, handler, config?)
153
+ // the source may be a TypesCollection (object) or a TypeProxy (function),
154
+ // so detection is: has a callable .define AND the next arg is a string name
155
+ const mayBeSource = (
156
+ (typeof TypeNameOrSource === 'object' && TypeNameOrSource !== null) ||
157
+ typeof TypeNameOrSource === 'function'
158
+ ) && typeof (TypeNameOrSource as { define?: unknown }).define === 'function';
159
+ if (mayBeSource && typeof constructHandlerOrName === 'string') {
160
+ const source = TypeNameOrSource as unknown as { define: TypeAbsorber };
161
+ const sourceDefineResult = source.define(
162
+ constructHandlerOrName,
163
+ configOrHandler as IDEF<T>,
164
+ config
165
+ ) as unknown as R;
166
+ return sourceDefineResult;
167
+ }
168
+
111
169
  const types = checkThis(this) ? defaultTypes : this || defaultTypes;
112
170
  // Type assertion needed because TypesCollectionProxy is a Proxy
113
171
  const defineResult = (types as { define: TypeAbsorber })
114
172
  .define(
115
- TypeName as string,
116
- constructHandler as IDEF<T>,
117
- config
173
+ TypeNameOrSource as string,
174
+ constructHandlerOrName as IDEF<T>,
175
+ configOrHandler as constructorOptions
118
176
  ) as unknown as R;
119
177
  return defineResult;
120
178
  }
@@ -123,14 +181,33 @@ export function lookup<const K extends keyof TypeRegistry>(
123
181
  this: unknown,
124
182
  TypeNestedPath: K
125
183
  ): TypeRegistry[K];
184
+ export function lookup<Reg extends object, const K extends keyof Reg & string>(
185
+ // explicit-source form: lookup(source, path)
186
+ // resolves against the registry carried by a builder/collection value
187
+ source: { lookup: TypeLookup<Reg> },
188
+ TypeNestedPath: K
189
+ ): LookupResult<Reg, K>;
126
190
  export function lookup(this: unknown, TypeNestedPath: string): TypeClass | undefined;
127
191
  export function lookup(
128
- this: unknown,
192
+ source: { lookup: (path: string) => TypeClass | undefined },
129
193
  TypeNestedPath: string
130
- ): TypeClass | undefined {
194
+ ): TypeClass | undefined;
195
+ export function lookup(
196
+ this: unknown,
197
+ arg1: unknown,
198
+ arg2?: unknown
199
+ ): unknown {
200
+
201
+ // explicit-source form: lookup(source, path)
202
+ if (typeof arg1 !== 'string' && typeof arg2 === 'string') {
203
+ const source = arg1 as { lookup: (path: string) => TypeClass | undefined };
204
+ const sourceResult = source.lookup(arg2);
205
+ return sourceResult;
206
+ }
207
+
131
208
  const types = checkThis(this) ? defaultTypes : this || defaultTypes;
132
209
  // Type assertion needed because TypesCollectionProxy is a Proxy
133
- const lookupResult = (types as { lookup: (path: string) => TypeClass | undefined }).lookup(TypeNestedPath);
210
+ const lookupResult = (types as { lookup: (path: string) => TypeClass | undefined }).lookup(arg1 as string);
134
211
  return lookupResult;
135
212
  }
136
213
 
@@ -335,6 +335,20 @@ export interface TypeLookup<T extends object = GlobalRegistry> extends CallableF
335
335
  (this: unknown, TypeNestedPath: string): TypeClass | undefined;
336
336
  }
337
337
 
338
+ // Extracts the accumulated registry map from a builder-chain value
339
+ // (IDefinitorInstance, TypesCollection, or MnemonicaModule). Enables the
340
+ // one-line bridge that merges a builder's local registry into the global
341
+ // TypeRegistry without Tactica:
342
+ //
343
+ // declare module 'mnemonica' {
344
+ // interface TypeRegistry extends RegistryOf<typeof App> {}
345
+ // }
346
+ export type RegistryOf<T> =
347
+ T extends IDefinitorInstance<object, InstanceResult<object>, infer Registry, string> ? Registry
348
+ : T extends TypesCollection<infer Registry, object, string> ? Registry
349
+ : T extends MnemonicaModule<infer Registry> ? Registry
350
+ : never;
351
+
338
352
  // Relative keys of a registry under a given dotted path. For a root path (`''`)
339
353
  // this is all string keys; for a non-empty path it is the tail after `${Path}.`.
340
354
  export type RelativeKeys<
@@ -697,6 +711,7 @@ export type TypeDescriptorInstance = {
697
711
  lookup: TypeDescriptorLookup;
698
712
  subtypes: Map<string, object>;
699
713
  TypeName: string;
714
+ collection: CollectionDef;
700
715
  };
701
716
 
702
717
  // Constructor type for decorate function
package/.ai/CODE.md DELETED
@@ -1,111 +0,0 @@
1
- # Coding Standards — mnemonica/core
2
-
3
- > **Applies to:** All code changes. Framework-agnostic.
4
- > See also `.ai/rules/CODING.md` for extended coding rules.
5
-
6
- ---
7
-
8
- ## Build & Test Commands
9
-
10
- See [`rules-skill/testing.md`](./rules-skill/testing.md) for the full reference. Summary:
11
- ```bash
12
- npm run build # full build with linting
13
- npm run test:cov # Mocha + coverage (runs build:all internally)
14
- npm run test:jest:cov # Jest on TypeScript source
15
- npm run watch # watch mode
16
- ```
17
- **Must run `npm run test:cov` before completing any task.**
18
-
19
- ---
20
-
21
- ## Code Style Rules
22
-
23
- See [`rules-skill/code-style.md`](./rules-skill/code-style.md) for the full style guide (tabs, function spacing, aligned colons, TypeScript strictness, no `any`).
24
-
25
- The return-statement rule is design-critical and is documented in full in [`../AGENTS.md`](../AGENTS.md#return-statement-design-rule). Summary: **always use an intermediate variable before returning** so Chrome DevTools can inspect the value at a breakpoint.
26
-
27
- ---
28
-
29
- ## TypeScript Type Rules
30
-
31
- **Never use bare `Function`, `CallableFunction`, or `NewableFunction` as parameter or return types.** Define a purpose-specific interface that extends them. See [`rules-skill/code-style.md`](./rules-skill/code-style.md) for examples and allowed exceptions.
32
-
33
- ---
34
-
35
- ## Build Output Inspection
36
-
37
- 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.
38
-
39
- For test passing confirmations (e.g., `npm run test:cov`), checking the end of the output is acceptable.
40
-
41
- ---
42
-
43
- ## Type Patterns
44
-
45
- ### Proxy Handlers
46
- ```typescript
47
- type ProxyHandler<T> = {
48
- get?(target: T, prop: string, receiver: unknown): unknown;
49
- set?(target: T, prop: string, value: unknown, receiver: unknown): boolean;
50
- };
51
- ```
52
-
53
- ### Internal Instance Properties
54
- ```typescript
55
- interface MnemonicaInstance {
56
- [SymbolConstructorName]?: string;
57
- [SymbolParentType]?: object;
58
- [SymbolSubTypes]?: Map<string, object>;
59
- }
60
- ```
61
-
62
- ---
63
-
64
- ## Testing Requirements
65
-
66
- See [`rules-skill/testing.md`](./rules-skill/testing.md) for full details. 100% coverage required on both Mocha and Jest. Jest tests should mirror Mocha patterns from `test/environment.js`.
67
-
68
- ---
69
-
70
- ## Symbols Reference
71
-
72
- See [`AGENTS.md`](./AGENTS.md) for the complete symbol reference table.
73
-
74
- ---
75
-
76
- ## Adding Type Definitions
77
-
78
- ```typescript
79
- // 1. Define type in src/types/index.ts
80
- export interface NewTypeConfig {
81
- property: string;
82
- }
83
-
84
- // 2. Update existing interfaces if needed
85
- export interface MnemonicaInstance {
86
- newProperty?: NewTypeConfig;
87
- }
88
- ```
89
-
90
- ---
91
-
92
- ## Error Handling
93
-
94
- ```typescript
95
- // Use MnemonicaErrorConstructor for custom errors
96
- import { constructError } from '../api/errors/index.js';
97
-
98
- const MyError = constructError('MY_ERROR', 'Error message');
99
- throw new MyError('additional info', stack);
100
- ```
101
-
102
- ---
103
-
104
- ## Configuration Files
105
-
106
- **Disallowed without explicit approval:**
107
- - Modifying `./tsconfig.json`
108
- - Modifying `./eslint.config.js`
109
-
110
- These configuration files define the project's strict standards. Any changes
111
- require user approval first.
@@ -1,103 +0,0 @@
1
- # mnemonica + `lookup`: rules and the underlying pattern
2
-
3
- > **The real rule:** use `lookup()` plus an augmented `TypeRegistry` — never `import { X } from './collections/...'` plus `as unknown as` casts. The augmentation can be hand-written or generated by [`@mnemonica/tactica`](https://www.npmjs.com/package/@mnemonica/tactica). Tactica is the productivity tool; the **augmentation** is the requirement. For the full mechanism and a side-by-side example, see [`../docs/typed-lookup.md`](../docs/typed-lookup.md).
4
-
5
- ---
6
-
7
- ## What this file is
8
-
9
- The anti-patterns that show up when working with a mnemonica project — and what to do instead. The rules apply regardless of whether you use tactica or hand-augment `TypeRegistry`; the runtime is identical either way.
10
-
11
- ---
12
-
13
- ## Why the type-safe path matters
14
-
15
- mnemonica creates a Trie of constructors at runtime:
16
-
17
- ```
18
- RequestData
19
- └── RouteData
20
- └── PageData
21
- └── RenderData
22
- └── ResponseData
23
- ```
24
-
25
- At runtime, this works perfectly — `new requestData.RouteData({ ... })` just works.
26
-
27
- But TypeScript does not see this Trie. The `define()` function returns a constructor TypeScript understands as a single function — not as something that grows `.RouteData`, `.PageData`, etc. on each instance.
28
-
29
- The temptation is to cast around the gap:
30
-
31
- ```typescript
32
- // ❌ never
33
- const requestData = new RequestData({ ... }) as unknown as RequestDataT;
34
- ```
35
-
36
- That bypasses the type system. The right answer is to teach TypeScript what the Trie looks like — which is exactly what `lookup()` + a `TypeRegistry` augmentation does.
37
-
38
- ---
39
-
40
- ## The mechanism in one paragraph
41
-
42
- `mnemonica` exports an empty `interface TypeRegistry {}`. `lookup<const K extends keyof TypeRegistry>(path: K)` returns `TypeRegistry[K]`. So a `declare module 'mnemonica' { interface TypeRegistry { ... } }` augmentation in your project — by hand, or generated by tactica — gives `lookup('Path.To.Type')` a fully typed return value. Zero casts.
43
-
44
- After augmentation, TypeScript knows:
45
- - The constructor arguments for each type
46
- - The instance properties
47
- - The sub-constructors on each instance (`.RouteData`, `.PageData`, etc.)
48
-
49
- See [`../docs/typed-lookup.md`](../docs/typed-lookup.md) for both paths with examples.
50
-
51
- ---
52
-
53
- ## When to insist on what
54
-
55
- When asked to work with a mnemonica project:
56
-
57
- 1. **Check whether `TypeRegistry` is augmented somewhere.** This can be:
58
- - A `.tactica/` directory with `registry.ts` (tactica-generated), OR
59
- - A `.d.ts` or `.ts` file containing `declare module 'mnemonica' { interface TypeRegistry { ... } }` (hand-written)
60
-
61
- If neither exists, the project has no type-safe path. Ask the user before writing code: do they want tactica set up, or to hand-augment? Either is fine — but pick one before writing types.
62
-
63
- 2. **If `.tactica/` exists, check `tsconfig.json` includes it.** If missing, add `.tactica/**/*.ts` to `include`.
64
-
65
- 3. **Check that `lookup` is being used.** Direct imports from collection files + casts are the smell that augmentation is missing or unused.
66
-
67
- 4. **Never accept `as unknown as` as a solution.** It is a symptom of the augmentation being missing, not a fix.
68
-
69
- ---
70
-
71
- ## Quick reference
72
-
73
- | Situation | Wrong | Right |
74
- |---|---|---|
75
- | Get a constructor | `import { T } from './collections/T.js'` | `const T = lookup('T')` |
76
- | Create instance | `new T({ ... }) as unknown as TT` | `new T({ ... })` |
77
- | Chain to child | `new (instance as any).Child({ ... })` | `new instance.Child({ ... })` |
78
- | Type not found | Add `as any` | Augment `TypeRegistry` (manually or run `tactica`) |
79
-
80
- ---
81
-
82
- ## Build verification
83
-
84
- After any change:
85
-
86
- ```bash
87
- npm run tactica # only if using tactica — regenerate .tactica/
88
- npx tsc --noEmit # verify zero TS errors
89
- npx eslint src/ # verify zero lint errors
90
- npm test # verify all tests pass
91
- ```
92
-
93
- If you are not using tactica, `npm run tactica` is not required; the hand-written augmentation is the source of truth.
94
-
95
- ---
96
-
97
- ## Deeper reading
98
-
99
- - [`../docs/typed-lookup.md`](../docs/typed-lookup.md) — `lookup` with or without tactica (canonical reference, side-by-side)
100
- - [`../docs/tactica-pattern.md`](../docs/tactica-pattern.md) — human-facing explanation of declaration merging
101
- - [`./TACTICA-DEEP-DIVE.md`](./TACTICA-DEEP-DIVE.md) — comprehensive technical guide
102
-
103
- The key insight: **the runtime constructor is identical whether you import it directly or look it up. The only difference is TypeScript's compile-time knowledge.** `lookup` + augmented `TypeRegistry` teaches TypeScript what mnemonica already knows at runtime — and the augmentation can come from anywhere.
package/.ai/async_init.md DELETED
@@ -1,94 +0,0 @@
1
- # Async Class Constructor Support in Mnemonica
2
-
3
- ## Context
4
-
5
- JavaScript class constructors cannot be declared `async`. However, a constructor **can return a Promise**. When a base class constructor returns `Promise.resolve(this)`, the subclass `this` becomes the Promise object — class fields initialize on the Promise wrapper, not the real instance. This breaks field inheritance in raw JS.
6
-
7
- Mnemonica handles this correctly through its wrapper architecture. See also the [test suite](../test_async/index.js) showing the problem and wrapper fix in practice.
8
-
9
- ## How Mnemonica Preserves Class Fields
10
-
11
- In `src/api/types/compileNewModificatorFunctionBody.ts:54-66`:
12
-
13
- ```ts
14
- const getClassConstructor = (ConstructHandler, CreationHandler) => {
15
- return class extends ConstructHandler {
16
- constructor(...args) {
17
- const answer = super(...args); // user class runs, fields init on REAL this
18
- const result = CreationHandler.call(this, answer);
19
- return result;
20
- }
21
- };
22
- };
23
- ```
24
-
25
- The **wrapper class** (not the user class) is the subclass in JS's class hierarchy. When `super()` runs the user constructor, fields like `childField = 'value'` initialize on the wrapper's `this`. If the user constructor returns a Promise, `CreationHandler` processes it via `makeAwaiter`, but the fields are already on the correct object.
26
-
27
- **Key finding:** Class fields survive async initialization in mnemonica because the wrapper ensures they initialize on the real instance before the Promise is returned.
28
-
29
- ## `Symbol.hasInstance` — Nominal Typing by Name
30
-
31
- Mnemonica replaces standard JS `instanceof` with **nominal typing** checked by `getTypeChecker` (`src/api/utils/index.ts:37`):
32
-
33
- ```ts
34
- const getTypeChecker = (TypeName: string) => {
35
- return (instance: object) => {
36
- // For Promise-returning constructors, check SymbolConstructorName directly
37
- if (Reflect.getPrototypeOf(instance).constructor.name === 'Promise') {
38
- return instance[SymbolConstructorName] === TypeName;
39
- }
40
- // Normal case: walk prototype chain collecting constructor names
41
- const constructors = collectConstructors(instance);
42
- return constructors[TypeName] || false;
43
- };
44
- };
45
- ```
46
-
47
- `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`.
48
-
49
- Three places define `Symbol.hasInstance`:
50
-
51
- 1. **`TypeDescriptor.prototype`** (`src/api/types/index.ts:210`) — for `instanceof TypeName` where `TypeName` is what `define()` returned
52
- 2. **`Mnemosyne.prototype`** (`src/api/types/Mnemosyne.ts:381`) — for `instanceof` checks on the instance itself
53
- 3. **`makeSubTypeProxy`** (`src/api/types/Mnemosyne.ts:205`) — for subtype access like `parent.SubType()`
54
-
55
- ### Why This Matters for Pre-existing Class Hierarchies
56
-
57
- When passing a pre-existing class hierarchy (`class Extended extends Base`) to `define()`:
58
-
59
- - **Top-level** `define('PreExt', Extended)`: `PreExt.prototype === Extended.prototype`. The instance chain includes `Extended.prototype` and `Base.prototype`. Both `instanceof PreExt` and `instanceof Extended` work.
60
- - **Sub-type** `Root.define('Sub', Extended)`: `Sub.prototype === Extended.prototype` is still true, BUT mnemonica's subtype wiring inserts the parent type (`Root`) into the instance chain **before** `Extended.prototype`. The original class hierarchy is skipped for standard JS `instanceof`, but mnemonica's name-based `getTypeChecker` still recognizes it because `collectConstructors` sees the names in the chain.
61
-
62
- Actually — correction: in the sub-type case, standard JS `instanceof Extended` returns **false** because the prototype chain is wired to `Root`, not `Extended.prototype`. But mnemonica's `instanceof Sub` and `instanceof Root` still work because `collectConstructors` finds their names.
63
-
64
- ## Test Suite
65
-
66
- Tests live in `test_async/index.js` and run via `npm run test:async_init`.
67
-
68
- ### Acronyms Used
69
-
70
- - **WOReturn** = **W**ith**O**ut **Return** — Promise resolves to `undefined` instead of `this`
71
- - **NAR** = **N**o **A**wait **R**eturn** — `awaitReturn: false` disables the guard
72
-
73
- ### Test Coverage
74
-
75
- 1. **WOReturn guard for classes** — async class constructor returning Promise without `this` throws `WRONG_MODIFICATION_PATTERN`
76
- 2. **NAR bypass** — `awaitReturn: false` allows the same without throwing
77
- 3. **Field inheritance through mnemonica chain** — parent/child fields preserved across async constructors
78
- 4. **Pre-existing class hierarchy at top-level** — `define('Type', ExtendedClass)` preserves fields and `instanceof` against original classes
79
- 5. **Pre-existing class hierarchy as sub-type** — root type defines sub-type using `ExtendedClass`; sub instance gets root fields + class hierarchy fields, but standard JS `instanceof` against original classes is broken (mnemonica `instanceof` still works)
80
-
81
- ## Relevant Source Files
82
-
83
- - `src/api/types/compileNewModificatorFunctionBody.ts` — wrapper class creation
84
- - `src/api/utils/index.ts` — `getTypeChecker`
85
- - `src/utils/collectConstructors.ts` — prototype chain walker
86
- - `src/api/types/Mnemosyne.ts` — `Symbol.hasInstance` on instances and sub-type proxy
87
- - `src/api/types/index.ts` — `Symbol.hasInstance` on `TypeDescriptor.prototype`
88
- - `src/api/types/InstanceCreator.ts` — async routing via `makeAwaiter`
89
-
90
- ## Related
91
-
92
- - [`test_async/index.js`](../test_async/index.js) — test suite covering async initialization scenarios
93
- - [TC39 proposal-async-init issue #3](https://github.com/tc39/proposal-async-init/issues/3) — language-level discussion of the same problem
94
- - [Mnemonica README](../README.md) — project overview and API documentation
@@ -1,63 +0,0 @@
1
- # Critical Reminders for AI Agents
2
-
3
- ## Before Writing Any Code
4
-
5
- ### 1. Type vs Interface - CRITICAL
6
- **ALWAYS** check AGENTS.md section "CRITICAL: Type vs Interface vs Instance" before defining types:
7
-
8
- ```typescript
9
- // ✅ CORRECT - Instance data uses TYPE
10
- type UserData = { name: string; age: number; };
11
-
12
- // ❌ WRONG - Instance is NOT an interface!
13
- interface UserData { name: string; age: number; }
14
-
15
- // ✅ CORRECT - Constructor/Prototype contract uses INTERFACE
16
- interface MnemonicaInstance {
17
- extract(): object;
18
- parent(): object | null;
19
- }
20
- ```
21
-
22
- **Rule of thumb:**
23
- - **Interface** = Black-box contract (constructors, callables, `implements`)
24
- - **Type** = Runtime data structure/shape (instances, POJOs)
25
-
26
- ### 2. Indentation - TABS ONLY
27
- - **NEVER** use spaces for indentation
28
- - Tab width: 4
29
- - Enforced by eslint
30
-
31
- ### 3. Function Spacing
32
- ```typescript
33
- function myFunc () { } // ✅ Space before parentheses
34
- function myFunc() { } // ❌ Wrong
35
- ```
36
-
37
- ### 4. Key Spacing
38
- ```typescript
39
- { key: value } // ✅ Space after colon
40
- { key:value } // ❌ Wrong
41
- ```
42
-
43
- ### 5. Before Each Task
44
- 1. Read AGENTS.md if context seems incomplete
45
- 2. Check existing code patterns in the same directory
46
- 3. Run `npm run build` before completing (core/ directory)
47
- 4. Run `npm run test:cov` for coverage validation (core/ directory)
48
-
49
- ## Quick Reference
50
-
51
- | Decision | Check |
52
- |----------|-------|
53
- | Type vs Interface | AGENTS.md |
54
- | Build commands | AGENTS.md |
55
- | Code style | AGENTS.md |
56
- | Error handling | AGENTS.md |
57
- | Context condensing | CONTEXT-CONDENSING.md |
58
-
59
- ## File-Specific Notes
60
-
61
- - `core/src/types/index.ts` - Export types here, use `type` for instances
62
- - `core/src/api/types/*.ts` - Internal implementations, check existing patterns
63
- - Any `provider.ts` files - Check AGENTS.md for type/interface rules
@@ -1,82 +0,0 @@
1
- ---
2
- name: mnemonica-lookup-typed
3
- description: |
4
- Type-safe lookup with lookup() and TypeRegistry augmentation.
5
- Use when the user asks about lookup, TypeRegistry, tactica-generated types,
6
- declaration merging, or type-safe constructor retrieval in mnemonica.
7
- metadata:
8
- tags: [mnemonica, lookup, types, tactica, declaration-merging]
9
- ---
10
-
11
- # Type-Safe Lookup with `lookup()`
12
-
13
- ## `lookup()` with and without `TypeRegistry` augmentation
14
-
15
- ```typescript
16
- import { lookup } from 'mnemonica';
17
-
18
- // Without augmentation: returns TypeClass | undefined
19
- const SomeType = lookup('SomeType');
20
- const instance = new SomeType({ ... }); // no type safety
21
-
22
- // With augmentation: returns the typed constructor
23
- const SomeType = lookup('SomeType');
24
- const instance = new SomeType({ ... }); // TypeScript knows the signature
25
- ```
26
-
27
- ## TypeRegistry Pattern
28
-
29
- The default `TypeRegistry` is an empty interface. Application code or
30
- `@mnemonica/tactica` augments it through TypeScript declaration merging.
31
-
32
- ```typescript
33
- // In mnemonica core
34
- export interface TypeRegistry {
35
- // Intentionally empty. Augment via declaration merging.
36
- }
37
-
38
- // Generated by tactica in .tactica/registry.ts
39
- declare module 'mnemonica' {
40
- interface TypeRegistry {
41
- 'UserType': TypeConstructor<UserTypeInstance>;
42
- 'Parent.SubType': TypeConstructor<SubTypeInstance>;
43
- }
44
- }
45
- ```
46
-
47
- ## Unaugmented vs Augmented `TypeRegistry`
48
-
49
- The axis that actually matters is whether `TypeRegistry` has been augmented for your types — not whether tactica is involved. Tactica is one way to produce the augmentation; hand-writing it is another. Runtime behaviour is identical either way.
50
-
51
- | Feature | Unaugmented `TypeRegistry` | Augmented `TypeRegistry` |
52
- |---------|---------------------------|--------------------------|
53
- | Constructor retrieval | `lookup('Name')` returns `TypeClass \| undefined` | `lookup('Name')` returns typed constructor |
54
- | Type safety | Runtime only | Compile-time + runtime |
55
- | Registry default | Empty interface | Per-key constructor signatures |
56
- | Instance properties | `any` / `unknown` | Fully typed |
57
-
58
- Two ways to augment: hand-written `.d.ts` (small projects, learning) or [`@mnemonica/tactica`](https://www.npmjs.com/package/@mnemonica/tactica) (auto-generated, recommended for non-trivial projects). See [`../../docs/typed-lookup.md`](../../docs/typed-lookup.md) for both paths side by side.
59
-
60
- ## Before/After: Adding a Type to TypeRegistry
61
-
62
- **Before** (untyped lookup)
63
- ```typescript
64
- const UserType = lookup('UserType');
65
- const user = new UserType({ name: 'John' });
66
- // user is typed as object — no IntelliSense for properties
67
- ```
68
-
69
- **After** (TypeRegistry augmented — either hand-written or tactica-generated; runtime is identical)
70
- ```typescript
71
- // In a .d.ts file (hand-written) or .tactica/registry.ts (tactica-generated)
72
- declare module 'mnemonica' {
73
- interface TypeRegistry {
74
- 'UserType': new (...args: [UserData]) => UserTypeInstance;
75
- }
76
- }
77
-
78
- // In application code
79
- const UserType = lookup('UserType');
80
- const user = new UserType({ name: 'John' });
81
- // user is fully typed as UserTypeInstance
82
- ```
@@ -1,63 +0,0 @@
1
- ---
2
- name: mnemonica-proxy-architecture
3
- description: |
4
- The Proxy-based construction pipeline: TypeProxy, InstanceCreator, Mnemosyne,
5
- and createInstanceModificator. Use when the user asks about how mnemonica
6
- creates instances, the prototype chain, TypeProxy, InstanceCreator, or the
7
- internal construction mechanism.
8
- metadata:
9
- tags: [mnemonica, proxy, architecture, construction, prototype]
10
- ---
11
-
12
- # Proxy-Based Architecture
13
-
14
- ## Construction Pipeline (8 Stages)
15
-
16
- ```
17
- define(TypeName, ctor) → new TypeDescriptor() → new TypeProxy()
18
- │
19
- ▼
20
- new InstanceCreator(type, parent, args)
21
- │
22
- ▼
23
- makeInstanceModificator(self)
24
- │
25
- ▼
26
- ModificationConstructor.call(parent, ModificatorType, proto, _addProps)
27
- │
28
- ▼
29
- user constructor runs (new ModificatorType(...args))
30
- │
31
- ▼
32
- postProcessing() → invokePostHooks()
33
- ```
34
-
35
- ## Key Components
36
-
37
- ### TypeProxy
38
- Wraps type constructors. Handles property access, `.define()`, `.lookup()`,
39
- and subtype resolution.
40
-
41
- ### InstanceCreator
42
- Orchestrates the full instance construction lifecycle:
43
- 1. **Setup** — extract type, config, prepare ModificationConstructor
44
- 2. **Stack** — collect creation stack if `submitStack` or chained
45
- 3. **blockErrors** — if parent is Error, optionally block construction
46
- 4. **Pre-hooks** — invoke `preCreation` hooks on collection and type
47
- 5. **Build** — `makeInstanceModificator()` wires prototype chain
48
- 6. **Construct** — `new InstanceModificator(...args)` runs user constructor
49
- 7. **Async** — if result is Promise, attach awaiter and subtype factories
50
- 8. **Post-proc** — validate inheritance, set `__self__`, invoke `postCreation` hooks
51
-
52
- ### Mnemosyne
53
- Handles instance method access via Proxy. Provides:
54
- - `extract()` — get all enumerable properties
55
- - `pick(...keys)` — select specific properties
56
- - `parent()` — traverse prototype chain
57
- - `fork(...args)` — create new instance with same or different args
58
- - `clone` — alias for fork()
59
-
60
- ### createInstanceModificator (ModificationConstructor)
61
- The default ModificationConstructor that wires the prototype chain by creating
62
- a Mnemosyne object inheriting from the parent instance, attaching internal props,
63
- and linking `ModificatorType.prototype` to it.