@mindot/will 0.1.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 (178) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +777 -0
  3. package/dist/index.d.ts +8144 -0
  4. package/dist/index.js +26231 -0
  5. package/dist/index.js.map +1 -0
  6. package/package.json +73 -0
  7. package/src/cognition/agency/access.grants.ts +59 -0
  8. package/src/cognition/agency/competence.codec.ts +89 -0
  9. package/src/cognition/agency/engines/action.selector.ts +462 -0
  10. package/src/cognition/agency/engines/affordance.synthesizer.ts +384 -0
  11. package/src/cognition/agency/engines/deliberation.engine.ts +241 -0
  12. package/src/cognition/agency/engines/instruction.intake.ts +54 -0
  13. package/src/cognition/agency/engines/motor.schema.executor.ts +532 -0
  14. package/src/cognition/agency/engines/reafference.engine.ts +241 -0
  15. package/src/cognition/agency/execution.primitives.ts +118 -0
  16. package/src/cognition/agency/index.ts +58 -0
  17. package/src/cognition/agency/proactive.communicator.ts +274 -0
  18. package/src/cognition/agency/reconcile.learning.ts +82 -0
  19. package/src/cognition/agency/schemas/external.ts +59 -0
  20. package/src/cognition/agency/schemas/innate.ts +111 -0
  21. package/src/cognition/agency/schemas/repertoire.ts +246 -0
  22. package/src/cognition/agency/selection.scoring.ts +191 -0
  23. package/src/cognition/agency/types.ts +165 -0
  24. package/src/cognition/bus.ts +391 -0
  25. package/src/cognition/completion.inbox.ts +86 -0
  26. package/src/cognition/config.mirror.entities.ts +475 -0
  27. package/src/cognition/conversation.memory.ts +81 -0
  28. package/src/cognition/event.log.ts +116 -0
  29. package/src/cognition/event.schemas.ts +568 -0
  30. package/src/cognition/faculties/aesthetic.evaluator.ts +313 -0
  31. package/src/cognition/faculties/affective.blender.ts +562 -0
  32. package/src/cognition/faculties/attachment.evaluator.ts +432 -0
  33. package/src/cognition/faculties/attention.allocator.ts +422 -0
  34. package/src/cognition/faculties/autobiographical.narrator.ts +300 -0
  35. package/src/cognition/faculties/bias.detector.ts +363 -0
  36. package/src/cognition/faculties/circadian.oscillator.ts +294 -0
  37. package/src/cognition/faculties/confidence.calibrator.ts +324 -0
  38. package/src/cognition/faculties/dream.simulator.ts +251 -0
  39. package/src/cognition/faculties/empathy.simulator.ts +253 -0
  40. package/src/cognition/faculties/energy.regulator.ts +320 -0
  41. package/src/cognition/faculties/episodic.consolidator.ts +728 -0
  42. package/src/cognition/faculties/executive.engine/commands.ts +459 -0
  43. package/src/cognition/faculties/executive.engine/config.ts +46 -0
  44. package/src/cognition/faculties/executive.engine/context.ts +605 -0
  45. package/src/cognition/faculties/executive.engine/deferred.effects.ts +104 -0
  46. package/src/cognition/faculties/executive.engine/deliberate.reasoning.ts +60 -0
  47. package/src/cognition/faculties/executive.engine/effort.gate.ts +114 -0
  48. package/src/cognition/faculties/executive.engine/engine.ts +1028 -0
  49. package/src/cognition/faculties/executive.engine/escalation.buffer.ts +90 -0
  50. package/src/cognition/faculties/executive.engine/facet.supervisor.ts +271 -0
  51. package/src/cognition/faculties/executive.engine/facet.ts +628 -0
  52. package/src/cognition/faculties/executive.engine/gating.ts +222 -0
  53. package/src/cognition/faculties/executive.engine/index.ts +6 -0
  54. package/src/cognition/faculties/executive.engine/messages.ts +102 -0
  55. package/src/cognition/faculties/executive.engine/parser.ts +380 -0
  56. package/src/cognition/faculties/executive.engine/prompt.factory.ts +1053 -0
  57. package/src/cognition/faculties/executive.engine/types.ts +323 -0
  58. package/src/cognition/faculties/exteroception.ts +338 -0
  59. package/src/cognition/faculties/forgetting.curve.ts +202 -0
  60. package/src/cognition/faculties/frustration.evaluator.ts +280 -0
  61. package/src/cognition/faculties/goal.manager.ts +1008 -0
  62. package/src/cognition/faculties/inhibition.controller.ts +351 -0
  63. package/src/cognition/faculties/interoception.ts +417 -0
  64. package/src/cognition/faculties/introspection.engine.ts +246 -0
  65. package/src/cognition/faculties/known.entity.tracker.ts +439 -0
  66. package/src/cognition/faculties/loss.evaluator.ts +224 -0
  67. package/src/cognition/faculties/moral.evaluator.ts +437 -0
  68. package/src/cognition/faculties/novelty.detector.ts +254 -0
  69. package/src/cognition/faculties/persona.consolidator.ts +845 -0
  70. package/src/cognition/faculties/planning.engine/engine.ts +859 -0
  71. package/src/cognition/faculties/planning.engine/plan.frontier.ts +83 -0
  72. package/src/cognition/faculties/planning.engine/plan.store.ts +174 -0
  73. package/src/cognition/faculties/planning.engine/plan.supervision.ts +494 -0
  74. package/src/cognition/faculties/planning.engine/types.ts +143 -0
  75. package/src/cognition/faculties/reputation.tracker.ts +294 -0
  76. package/src/cognition/faculties/reward.evaluator.ts +304 -0
  77. package/src/cognition/faculties/self.model.updater.ts +677 -0
  78. package/src/cognition/faculties/semantic.engine/clustering.ts +673 -0
  79. package/src/cognition/faculties/semantic.engine/index.ts +6 -0
  80. package/src/cognition/faculties/semantic.engine/integrator.ts +750 -0
  81. package/src/cognition/faculties/semantic.engine/types.ts +53 -0
  82. package/src/cognition/faculties/sleep.pressure.regulator.ts +262 -0
  83. package/src/cognition/faculties/social.perception.ts +333 -0
  84. package/src/cognition/faculties/spaced.repetition.ts +605 -0
  85. package/src/cognition/faculties/stress.regulator.ts +375 -0
  86. package/src/cognition/faculties/task.switcher.ts +239 -0
  87. package/src/cognition/faculties/theory.of.mind.ts +333 -0
  88. package/src/cognition/faculties/threat.evaluator.ts +312 -0
  89. package/src/cognition/faculties/working.memory.ts +406 -0
  90. package/src/cognition/generative.model.ts +344 -0
  91. package/src/cognition/heartbeat.ts +70 -0
  92. package/src/cognition/index.ts +291 -0
  93. package/src/cognition/instruction.handler.ts +146 -0
  94. package/src/cognition/memory/index.ts +35 -0
  95. package/src/cognition/memory/vector.adapter.ts +316 -0
  96. package/src/cognition/memory/vector.content.ts +47 -0
  97. package/src/cognition/memory/vector.embedder.ts +212 -0
  98. package/src/cognition/memory/vector.index.ts +459 -0
  99. package/src/cognition/memory/vector.types.ts +65 -0
  100. package/src/cognition/orchestrator.ts +142 -0
  101. package/src/cognition/persona.prior.ts +265 -0
  102. package/src/cognition/schema.registry.ts +145 -0
  103. package/src/cognition/senses/audition.engine/engine.ts +976 -0
  104. package/src/cognition/senses/audition.engine/salience.ts +59 -0
  105. package/src/cognition/senses/base.sense.engine.ts +117 -0
  106. package/src/cognition/senses/gustation.engine.ts +24 -0
  107. package/src/cognition/senses/index.ts +172 -0
  108. package/src/cognition/senses/olfaction.engine.ts +24 -0
  109. package/src/cognition/senses/somatosensation.engine.ts +23 -0
  110. package/src/cognition/senses/vision.engine.ts +23 -0
  111. package/src/cognition/types.ts +63 -0
  112. package/src/cognition/utilities/token.tracker.ts +492 -0
  113. package/src/core/abstracts.ts +60 -0
  114. package/src/core/async.engine.ts +539 -0
  115. package/src/core/clock.ts +196 -0
  116. package/src/core/completion.recorder.ts +122 -0
  117. package/src/core/conflict.detector.ts +140 -0
  118. package/src/core/distributed.ts +626 -0
  119. package/src/core/event.bus.ts +292 -0
  120. package/src/core/inbound.recorder.ts +100 -0
  121. package/src/core/index.ts +167 -0
  122. package/src/core/logger.ts +85 -0
  123. package/src/core/metrics.ts +107 -0
  124. package/src/core/orchestrator.ts +625 -0
  125. package/src/core/replay.ts +589 -0
  126. package/src/core/scenario.ts +120 -0
  127. package/src/core/serialization.ts +448 -0
  128. package/src/core/simulation.ts +197 -0
  129. package/src/core/snapshot.manager.ts +293 -0
  130. package/src/core/state.manager.ts +283 -0
  131. package/src/core/types.ts +274 -0
  132. package/src/core/utils.ts +82 -0
  133. package/src/core/wall.clock.ts +23 -0
  134. package/src/extensions/livestream.ext.ts +570 -0
  135. package/src/extensions/time.ext.ts +339 -0
  136. package/src/index.ts +91 -0
  137. package/src/llm/gate.ts +140 -0
  138. package/src/llm/index.ts +716 -0
  139. package/src/llm/summarizer.ts +170 -0
  140. package/src/llm/wire.contracts.ts +67 -0
  141. package/src/pma/eval.ts +651 -0
  142. package/src/pma/index.ts +1082 -0
  143. package/src/profiles/built-in.ts +7 -0
  144. package/src/profiles/companion.ts +28 -0
  145. package/src/profiles/company-brain.ts +54 -0
  146. package/src/profiles/customer-service.ts +30 -0
  147. package/src/profiles/game-npc.ts +20 -0
  148. package/src/profiles/index.ts +42 -0
  149. package/src/profiles/smart-home.ts +34 -0
  150. package/src/runners/coherence.runner.ts +49 -0
  151. package/src/runners/outreach.runner.ts +158 -0
  152. package/src/runners/social.runner.ts +182 -0
  153. package/src/runners/thin-shim.runner.ts +195 -0
  154. package/src/sdk/will.ts +334 -0
  155. package/src/stem/assembly.audit.ts +88 -0
  156. package/src/stem/distribution.ts +203 -0
  157. package/src/stem/guards/identity.coherence.ts +152 -0
  158. package/src/stem/guards/identity.guard.ts +227 -0
  159. package/src/stem/index.ts +1145 -0
  160. package/src/stem/mind.ts +1090 -0
  161. package/src/stem/tracts/ack.reconciler.ts +55 -0
  162. package/src/stem/tracts/biography.writer.ts +190 -0
  163. package/src/stem/tracts/effector.controller.ts +143 -0
  164. package/src/stem/tracts/health.reporter.ts +113 -0
  165. package/src/stem/tracts/inbound.queue.ts +54 -0
  166. package/src/stem/tracts/outbox.controller.ts +167 -0
  167. package/src/stem/tracts/outbox.writer.ts +133 -0
  168. package/src/stem/tracts/pma.controller.ts +109 -0
  169. package/src/stem/tracts/replay.controller.ts +177 -0
  170. package/src/stem/tracts/sensory.controller.ts +168 -0
  171. package/src/stem/tracts/session.logger.ts +157 -0
  172. package/src/stem/tracts/transport/index.ts +38 -0
  173. package/src/stem/tracts/transport/loopback.transport.ts +86 -0
  174. package/src/stem/tracts/transport/socketio.transport.ts +200 -0
  175. package/src/stem/tracts/transport/stream.transport.ts +152 -0
  176. package/src/stem/tracts/transport/types.ts +193 -0
  177. package/src/stem/tracts/transport.controller.ts +380 -0
  178. package/src/types.ts +116 -0
@@ -0,0 +1,241 @@
1
+ // ─────────────────────────────────────────────────────────────
2
+ // src/agency/reafference.engine.ts — prediction error → competence
3
+ // ─────────────────────────────────────────────────────────────
4
+ //
5
+ // Reafference is the loop that makes the Will grow. Each tick it reads the
6
+ // `agency.outcome` records the executor wrote, folds each into its schema's
7
+ // LearnedSkill (value, habit, prediction error, param priors — see
8
+ // repertoire.ts), and mirrors the updated skills into `agency.skill` state
9
+ // entities so they snapshot, surface in telemetry, and travel in the PMA. It
10
+ // likewise mirrors learned composite *templates* into `agency.schema` entities
11
+ // so the invented multi-step programs survive a restore (the executor resolves
12
+ // the template to expand a macro); restoreComposites() rehydrates them.
13
+ //
14
+ // The behavioural payoff closes the loop with selection: a schema that succeeds
15
+ // reliably AND predictably crosses the proceduralization threshold, which both
16
+ // raises its activation (additive habit bonus) and relaxes its deliberation
17
+ // threshold — so it stops recruiting the LLM. Inference spend falls as the Will
18
+ // learns. Disuse runs the forgetting curve in the other direction.
19
+ // ─────────────────────────────────────────────────────────────
20
+
21
+ import { logger } from '#core/logger'
22
+ import type {
23
+ Duration, Tick, SimulationContext,
24
+ ReadonlySimulationState, StateCommands, EntityInput,
25
+ } from '#core/types'
26
+ import type { LearnedSkill } from '#agency/types'
27
+ import type { CognitiveBus, CognitiveEvent } from '#cognition/bus'
28
+ import type { CognitiveEngine, EngineResult } from '#cognition/types'
29
+ import type { CognitiveEventSchema } from '#cognition/schema.registry'
30
+ import type { SchemaRepertoire } from '#agency/schemas/repertoire'
31
+ import { schemaEntityId } from '#agency/schemas/repertoire'
32
+
33
+ const PROC_THRESHOLD = 0.60 // mirror of repertoire's threshold for the habitual-count metric
34
+
35
+ export class ReafferenceEngine implements CognitiveEngine {
36
+ readonly name = 'reafference'
37
+
38
+ private _repertoire: SchemaRepertoire
39
+ private _bus: CognitiveBus | null = null
40
+
41
+ constructor( repertoire: SchemaRepertoire ){ this._repertoire = repertoire }
42
+
43
+ attachBus( bus: CognitiveBus ): void { this._bus = bus }
44
+
45
+ publishes(): CognitiveEventSchema[] {
46
+ return [
47
+ { type: 'agency.skill.proceduralized', version: 1, validate: () => null },
48
+ { type: 'agency.schema.discovered', version: 1, validate: () => null },
49
+ // Async-acked outcomes (host-ack reconciliation) flow through here, not the
50
+ // executor — so for a plan-tagged reconciled outcome this engine emits the
51
+ // action.outcome the PlanningEngine advances on. (The executor is the emitter
52
+ // for sync/timeout outcomes; this is its async counterpart — one emitter each.)
53
+ { type: 'action.outcome', version: 1, validate: () => null },
54
+ ]
55
+ }
56
+ /** Creation seam: register a composite proposed by the executive/deliberation facet. */
57
+ subscribes(): string[] { return [ 'agency.composite.proposed' ] }
58
+ onCognitiveEvent( e: CognitiveEvent ): void {
59
+ if( e.type !== 'agency.composite.proposed' ) return
60
+ const p = e.payload as { id?: string; name?: string; composedOf?: unknown; tags?: unknown; cost?: number }
61
+ const id = p.id ?? p.name
62
+ const steps = Array.isArray( p.composedOf )
63
+ ? ( p.composedOf as unknown[] ).filter( ( s ): s is string => typeof s === 'string' )
64
+ : []
65
+ if( !id || steps.length < 2 ) return // a composite needs a name + ≥2 sub-schemas
66
+
67
+ this._repertoire.registerComposite({
68
+ id, kind: 'composite', source: 'repertoire', binds: 'none',
69
+ cost: typeof p.cost === 'number' ? p.cost : 0.1,
70
+ composedOf: steps,
71
+ tags: Array.isArray( p.tags ) ? ( p.tags as unknown[] ).filter( ( t ): t is string => typeof t === 'string' ) : [ 'composite' ],
72
+ })
73
+ logger.info( `[reafference] registered proposed composite "${ id }" (${ steps.join( ' → ' ) })` )
74
+ }
75
+ snapshot(): Record<string, unknown> {
76
+ return { skills: this._repertoire.skills().size }
77
+ }
78
+
79
+ async react(
80
+ _delta: Duration,
81
+ tick: Tick,
82
+ state: ReadonlySimulationState,
83
+ _context: SimulationContext,
84
+ ): Promise<EngineResult> {
85
+ const set: EntityInput[] = []
86
+ const del: string[] = []
87
+ const metrics: Array<[ string, number ]> = []
88
+
89
+ // ── 1. Fold each new outcome into its skill ──────────────────
90
+ let updates = 0
91
+ let discovered = 0
92
+ for( const [ id, e ] of state.entities ){
93
+ if( e.type !== 'agency.outcome' ) continue
94
+ const m = ( e.metadata ?? {} ) as Record<string, unknown>
95
+ const schema = str( m['schema'] )
96
+ if( !schema ){ del.push( id ); continue }
97
+
98
+ const { skill, proceduralized } = this._repertoire.recordOutcome({
99
+ schema,
100
+ success: m['success'] === true,
101
+ outcomeQuality: num( m['outcomeQuality'], 0 ),
102
+ predictedReward: num( m['predictedReward'], 0.5 ),
103
+ params: ( m['params'] as Record<string, unknown> ) ?? undefined,
104
+ tick,
105
+ })
106
+
107
+ set.push( skillEntity( skill ) )
108
+ del.push( id ) // outcome consumed
109
+ // Host-ack reconciliation: a reconciled outcome carries the awaiting intent's
110
+ // id — free it so the serial Will can act again. The executor's own sync
111
+ // outcomes already deleted their intent, so this is a harmless no-op there.
112
+ const intentId = str( m['intentId'] )
113
+ if( intentId ) del.push( intentId )
114
+ updates++
115
+
116
+ // Plan advancement for the async path: a host-acked outcome that carries plan
117
+ // provenance is the ONLY signal the PlanningEngine will get (the executor never
118
+ // saw the ack — the intent was 'awaiting'). Emit the action.outcome it advances
119
+ // on. Sync/timeout outcomes never carry planId here (the executor emitted their
120
+ // action.outcome already), so this never double-advances.
121
+ const planId = str( m['planId'] )
122
+ if( planId )
123
+ this._emitPlanOutcome( planId, str( m['stepId'] ), schema, m['success'] === true, num( m['outcomeQuality'], 0 ), num( m['surprise'], 0 ), tick )
124
+
125
+ // Discovery: the first time the Will enacts a schema, it becomes a known part
126
+ // of its repertoire (the new model's "discovered" — earned by doing, not catalogued).
127
+ if( skill.enactments === 1 ){
128
+ discovered++
129
+ this._emitDiscovered( schema, tick )
130
+ }
131
+
132
+ if( proceduralized ){
133
+ this._emitProceduralized( skill, tick )
134
+ logger.info( `[reafference] "${ schema }" proceduralized (habit ${ skill.habitStrength.toFixed( 2 ) })` )
135
+ }
136
+ }
137
+
138
+ // ── 2. Forgetting curve over the competence layer ────────────
139
+ const dropped = this._repertoire.decay( tick )
140
+ for( const id of dropped ){
141
+ del.push( `agency-skill-${ id }` )
142
+ del.push( schemaEntityId( id ) ) // composite mirror (harmless no-op for primitives)
143
+ }
144
+
145
+ // ── 3. Mirror learned composite templates ────────────────────
146
+ // Skills become `agency.skill` (above); the invented composite *definitions*
147
+ // must travel too, or a snapshot/restore brings back a skill whose schema is
148
+ // gone and the executor can't expand it. Idempotent re-write each tick, like
149
+ // GoalManager._persistGoals. Empty until a composite is actually learned.
150
+ for( const e of this._repertoire.compositeEntities() ) set.push( e )
151
+
152
+ // ── 4. Telemetry ─────────────────────────────────────────────
153
+ const skills = this._repertoire.skills()
154
+ const habitual = [ ...skills.values() ].filter( s => s.habitStrength >= PROC_THRESHOLD ).length
155
+ metrics.push(
156
+ [ 'agency.learning.updates', updates ],
157
+ [ 'agency.discovered.count', discovered ],
158
+ [ 'agency.skill.count', skills.size ],
159
+ [ 'agency.habitual.count', habitual ],
160
+ )
161
+
162
+ return { commands: { set, delete: del, metrics } }
163
+ }
164
+
165
+ private _emitProceduralized( skill: LearnedSkill, tick: Tick ): void {
166
+ if( !this._bus ) return
167
+ try {
168
+ this._bus.publish({
169
+ type: 'agency.skill.proceduralized', version: 1, sourceEngine: this.name,
170
+ salience: 0.6,
171
+ payload: { schema: skill.schema, habitStrength: skill.habitStrength, tick },
172
+ })
173
+ }
174
+ catch( err ){ logger.warn( `[reafference] publish failed: ${ err instanceof Error ? err.message : String( err ) }` ) }
175
+ }
176
+
177
+ /**
178
+ * Emit the `action.outcome{planId,stepId}` for an async (host-acked) plan-step
179
+ * enaction. Mirrors the executor's `_emitActionOutcome` payload so the
180
+ * PlanningEngine's consumer can't tell which path produced it.
181
+ */
182
+ private _emitPlanOutcome(
183
+ planId: string, stepId: string | undefined, schema: string,
184
+ success: boolean, outcomeQuality: number, surprise: number, tick: Tick,
185
+ ): void {
186
+ if( !this._bus ) return
187
+ try {
188
+ this._bus.publish({
189
+ type: 'action.outcome', version: 1, sourceEngine: this.name,
190
+ salience: Math.min( 1, outcomeQuality * 0.6 ),
191
+ payload: {
192
+ actionType: schema, domain: schema, success, outcomeQuality, surprise,
193
+ description: success ? 'The world confirmed the action.' : 'The world rejected the action.',
194
+ planId,
195
+ ...( stepId ? { stepId } : {} ),
196
+ tick,
197
+ },
198
+ })
199
+ }
200
+ catch( err ){ logger.warn( `[reafference] plan outcome publish failed: ${ err instanceof Error ? err.message : String( err ) }` ) }
201
+ }
202
+
203
+ private _emitDiscovered( schema: string, tick: Tick ): void {
204
+ if( !this._bus ) return
205
+ try {
206
+ this._bus.publish({
207
+ type: 'agency.schema.discovered', version: 1, sourceEngine: this.name,
208
+ salience: 0.5, payload: { schema, tick },
209
+ })
210
+ }
211
+ catch( err ){ logger.warn( `[reafference] discovered publish failed: ${ err instanceof Error ? err.message : String( err ) }` ) }
212
+ }
213
+ }
214
+
215
+ // ─── entity mirroring ────────────────────────────────────────────────────────
216
+
217
+ function skillEntity( s: LearnedSkill ): EntityInput {
218
+ return {
219
+ id: `agency-skill-${ s.schema }`,
220
+ type: 'agency.skill',
221
+ metadata: {
222
+ schema: s.schema,
223
+ habitStrength: s.habitStrength,
224
+ valueEstimate: s.valueEstimate,
225
+ paramPriors: s.paramPriors,
226
+ enactments: s.enactments,
227
+ successes: s.successes,
228
+ avgPredictionError: s.avgPredictionError,
229
+ lastEnactedTick: s.lastEnactedTick,
230
+ },
231
+ }
232
+ }
233
+
234
+ // ─── helpers ─────────────────────────────────────────────────────────────────
235
+
236
+ function str( v: unknown ): string | undefined {
237
+ return typeof v === 'string' ? v : undefined
238
+ }
239
+ function num( v: unknown, fallback: number ): number {
240
+ return typeof v === 'number' && Number.isFinite( v ) ? v : fallback
241
+ }
@@ -0,0 +1,118 @@
1
+ // ─────────────────────────────────────────────────────────────
2
+ // src/agency/execution.primitives.ts — the bodies of primitive schemas
3
+ // ─────────────────────────────────────────────────────────────
4
+ //
5
+ // A primitive schema's "body" is what actually happens when it is enacted.
6
+ // Three execution modes:
7
+ //
8
+ // • sync — internal stances (orient, rest, reflect, …) resolve this
9
+ // tick. Following the original "attentional directive" insight,
10
+ // these are reportorial: they yield an honest outcome grounded
11
+ // in body state and DO NOT directly mutate regulated metrics
12
+ // (energy/stress are owned by the regulators — we don't fight
13
+ // them). Wiring stance→regulator signals is a later concern.
14
+ // • communicate — an outward message; dispatched now, confirmed later (async).
15
+ // • external — a host-owned effector; emitted now, acked later (async).
16
+ //
17
+ // Composite schemas never reach here — the executor expands them into ordered
18
+ // primitive sub-intents.
19
+ // ─────────────────────────────────────────────────────────────
20
+
21
+ import type { MotorSchema } from '#agency/types'
22
+
23
+ export type EnactionMode = 'sync' | 'communicate' | 'external'
24
+
25
+ export interface Enaction {
26
+ mode: EnactionMode
27
+ success: boolean
28
+ /** 0..1 actual outcome quality (provisional for async — refined on reconciliation). */
29
+ outcomeQuality: number
30
+ /** −1..1 actual felt valence of the outcome. */
31
+ valence: number
32
+ description: string
33
+ /** Minimal, non-regulated metric nudges this stance legitimately owns. */
34
+ metricDeltas?: Array<[ string, number ]>
35
+ }
36
+
37
+ export interface EnactionContext {
38
+ schema: MotorSchema
39
+ parameters: Record<string, unknown>
40
+ targetEntityId?: string
41
+ energy: number // 0..100
42
+ stress: number // 0..100
43
+ }
44
+
45
+ const COMM_SCHEMAS = new Set([ 'reach-out', 'talk', 'text', 'broadcast', 'gesture' ])
46
+
47
+ /** Classify how a primitive schema executes. */
48
+ export function modeOf( schema: MotorSchema ): EnactionMode {
49
+ if( schema.tags?.includes( 'external' ) ) return 'external'
50
+ if( schema.tags?.includes( 'communication' ) || COMM_SCHEMAS.has( schema.id ) ) return 'communicate'
51
+ return 'sync'
52
+ }
53
+
54
+ /** Enact a primitive schema, producing a state-grounded outcome. */
55
+ export function enact( ctx: EnactionContext ): Enaction {
56
+ const mode = modeOf( ctx.schema )
57
+
58
+ if( mode === 'communicate' ){
59
+ const name = str( ctx.parameters['targetEntityName'] ) ?? ctx.targetEntityId ?? 'them'
60
+ return {
61
+ mode, success: true, outcomeQuality: 0.7, valence: 0.1,
62
+ description: `You reach toward ${ name }. The words are sent; their effect is not yet known.`,
63
+ }
64
+ }
65
+
66
+ if( mode === 'external' )
67
+ return {
68
+ mode, success: true, outcomeQuality: 0.5, valence: 0,
69
+ description: `"${ ctx.schema.id }" dispatched to the host; awaiting the world's reply.`,
70
+ }
71
+
72
+ return syncStance( ctx )
73
+ }
74
+
75
+ // ── sync stance bodies ───────────────────────────────────────────────────────
76
+
77
+ function syncStance( ctx: EnactionContext ): Enaction {
78
+ const { schema, parameters, energy, stress } = ctx
79
+ const e01 = clamp01( energy / 100 )
80
+ const s01 = clamp01( stress / 100 )
81
+
82
+ switch( schema.id ){
83
+ case 'rest':
84
+ // More restorative the more depleted you were.
85
+ return sync( 0.5 + ( 1 - e01 ) * 0.4, 0.15, 'You let yourself recover; the pressure eases a little.' )
86
+ case 'withdraw':
87
+ return sync( 0.5 + s01 * 0.3, 0.05 + s01 * 0.1, 'You pull back from the press of things; the world quietens.' )
88
+ case 'reflect':
89
+ return sync( 0.6, 0.05, 'You turn inward; patterns from recent events settle into place.' )
90
+ case 'attend':
91
+ return sync( 0.6, 0.0, 'You concentrate, mobilizing more of your attention.' )
92
+ case 'orient':
93
+ return sync( 0.5, 0.0, 'Your awareness sweeps the situation, taking its measure.' )
94
+ case 'wait':
95
+ return sync( 0.5, 0.0, 'You let time pass; regulatory processes continue their quiet work.' )
96
+ case 'express':
97
+ return sync( 0.6, 0.1, 'Your inner state becomes outwardly visible.' )
98
+ case 'inspect': {
99
+ const focus = str( parameters['focus'] ) ?? 'it'
100
+ return sync( 0.65, 0.05, `You examine ${ focus } closely; more of its detail resolves.` )
101
+ }
102
+ default:
103
+ return sync( 0.5, 0.0, `You enact ${ schema.id }.` )
104
+ }
105
+ }
106
+
107
+ function sync( outcomeQuality: number, valence: number, description: string ): Enaction {
108
+ return { mode: 'sync', success: true, outcomeQuality: clamp01( outcomeQuality ), valence, description }
109
+ }
110
+
111
+ // ── helpers ──────────────────────────────────────────────────────────────────
112
+
113
+ function str( v: unknown ): string | undefined {
114
+ return typeof v === 'string' ? v : undefined
115
+ }
116
+ function clamp01( n: number ): number {
117
+ return n < 0 ? 0 : n > 1 ? 1 : n
118
+ }
@@ -0,0 +1,58 @@
1
+ // ─────────────────────────────────────────────────────────────
2
+ // src/engines/agency/index.ts — agency pipeline barrel
3
+ // ─────────────────────────────────────────────────────────────
4
+ //
5
+ // The mind-like action layer: perception synthesizes a field of affordances, a
6
+ // biased competition selects one (recruiting the LLM only when ambiguous or
7
+ // high-stakes), the executor enacts it (running learned composites for real),
8
+ // and reafference turns outcomes into competence that proceduralizes and travels
9
+ // in the PMA. See AGENCY_PIPELINE_TODO.md.
10
+
11
+ export * from '#agency/types'
12
+
13
+ export { INNATE_SCHEMAS, INNATE_SCHEMA_BY_ID } from '#agency/schemas/innate'
14
+ export { externalSchemas } from '#agency/schemas/external'
15
+ export { SchemaRepertoire } from '#agency/schemas/repertoire'
16
+ export type { OutcomeObservation } from '#agency/schemas/repertoire'
17
+
18
+ export { AffordanceSynthesizer } from '#agency/engines/affordance.synthesizer'
19
+
20
+ export { ActionSelector } from '#agency/engines/action.selector'
21
+ export {
22
+ DeliberationEngine,
23
+ type DeliberationFacetProvider
24
+ } from '#agency/engines/deliberation.engine'
25
+ export {
26
+ scoreAffordance,
27
+ competitionEntropy,
28
+ stakes,
29
+ goalRelevance,
30
+ driveUrgency,
31
+ novelty,
32
+ risk,
33
+ DEFAULT_WEIGHTS, DEFAULT_TEMPERATURE,
34
+ type BiasContext,
35
+ type ScoreWeights,
36
+ } from '#agency/selection.scoring'
37
+
38
+ export { MotorSchemaExecutor } from '#agency/engines/motor.schema.executor'
39
+ export {
40
+ enact,
41
+ modeOf,
42
+ type Enaction,
43
+ type EnactionMode
44
+ } from '#agency/execution.primitives'
45
+
46
+ export { ReafferenceEngine } from '#agency/engines/reafference.engine'
47
+ export {
48
+ reconcileInvocation,
49
+ type HostAckResult
50
+ } from '#agency/reconcile.learning'
51
+
52
+ export { AccessGrants, EXPLICIT_EFFECTORS } from '#agency/access.grants'
53
+
54
+ export {
55
+ distillCompetence, loadCompetence, COMPETENCE_SCHEMA_VERSION,
56
+ type CompetenceSnapshot,
57
+ type DistillOptions,
58
+ } from '#agency/competence.codec'