@@ -85,7 +85,13 @@ import type { AgentOSUsageAggregate, AgentOSUsageLedgerOptions } from './runtime
8585import { exportAgentConfig , exportAgentConfigJSON } from './agentExportCore.js' ;
8686import { getDeferredCapabilities , isMeaningfullyConfigured } from './runtime/lightweightAgentDiagnostics.js' ;
8787import { resolveTurnMode } from '../cognition/learning/config.js' ;
88- import { adoptLearningMemory , createLearningLayer , releaseLearningMemory , releaseLearningStore } from '../cognition/learning/LearningLayer.js' ;
88+ import {
89+ adoptLearningMemory ,
90+ createLearningLayer ,
91+ learningAgentHasLearners ,
92+ releaseLearningMemory ,
93+ releaseLearningStore ,
94+ } from '../cognition/learning/LearningLayer.js' ;
8995import { deferLearnerSession } from '../cognition/learning/LearnerSession.js' ;
9096import { InMemoryLearningStore } from '../cognition/learning/store/InMemoryLearningStore.js' ;
9197import type { LearningStore } from '../cognition/learning/store/LearningStore.js' ;
@@ -460,35 +466,42 @@ function hostLoopsOf(cognition: ResolvedCognition): Partial<Record<HostLoopName,
460466 * agent with none, everything its layer serves, since such an agent has no durable store and its store is its own.
461467 * Each member is `async`, so a key it lacks rejects the call rather than throwing at it.
462468 *
469+ * @param agent - The agent's key, resolved at each call as the agent's sessions resolve their learners' key, and its
470+ * namespace.
463471 * @param beforeForget - Runs before `forgetUser`: with `memory.store`, it hands the layer the agent's memory.
464472 * @param running - Holds each call until it settles: `agent.close()` lets the calls already running finish before it
465473 * closes the memory and the Brain they run on.
466474 */
467475function learningHostCalls (
468476 layer : LearningLayerHandle ,
469- agent : { agentKey : string | undefined ; namespace : string } ,
477+ agent : { agentKey : ( ) => Promise < string | undefined > ; namespace : string } ,
470478 beforeForget ?: ( ) => Promise < void > ,
471479 running ?: Set < Promise < unknown > > ,
472480) : AgentLearning {
473- const learnerOf = ( userId : string , call : string ) : LearnerKey => {
474- if ( ! agent . agentKey ) {
481+ const learnerOf = async ( userId : string , call : string ) : Promise < LearnerKey > => {
482+ const agentKey = await agent . agentKey ( ) ;
483+ if ( ! agentKey ) {
475484 throw new Error ( `gmi(): agent.learning.${ call } names a learner, and this agent has no stable key: set learning.agentKey or give the agent a name.` ) ;
476485 }
477- return { namespace : agent . namespace , agentKey : agent . agentKey , userId } ;
486+ return { namespace : agent . namespace , agentKey, userId } ;
487+ } ;
488+ const scopeOf = async ( target : { userId ?: string } | undefined , call : string ) : Promise < FreezeScope > => {
489+ if ( target ?. userId !== undefined ) return { learner : await learnerOf ( target . userId , call ) } ;
490+ const agentKey = await agent . agentKey ( ) ;
491+ return agentKey ? { agentKey } : { scope : 'all' } ;
478492 } ;
479- const scopeOf = ( target : { userId ?: string } | undefined , call : string ) : FreezeScope =>
480- target ?. userId !== undefined ? { learner : learnerOf ( target . userId , call ) } : agent . agentKey ? { agentKey : agent . agentKey } : { scope : 'all' } ;
481493 const calls : AgentLearning = {
482494 manifest : ( ) => layer . manifest ( ) ,
483- freeze : async ( target , by ) => layer . freeze ( scopeOf ( target , 'freeze' ) , by ) ,
484- unfreeze : async ( target ) => layer . unfreeze ( scopeOf ( target , 'unfreeze' ) ) ,
485- suspend : async ( target , by ) => layer . suspend ( scopeOf ( target , 'suspend' ) , by ) ,
486- unsuspend : async ( target ) => layer . unsuspend ( scopeOf ( target , 'unsuspend' ) ) ,
495+ freeze : async ( target , by ) => layer . freeze ( await scopeOf ( target , 'freeze' ) , by ) ,
496+ unfreeze : async ( target ) => layer . unfreeze ( await scopeOf ( target , 'unfreeze' ) ) ,
497+ suspend : async ( target , by ) => layer . suspend ( await scopeOf ( target , 'suspend' ) , by ) ,
498+ unsuspend : async ( target ) => layer . unsuspend ( await scopeOf ( target , 'unsuspend' ) ) ,
487499 operatorSet : async ( { userId, traits, by, note } ) =>
488- layer . operatorSet ( { learner : learnerOf ( userId , 'operatorSet' ) , traits, by, ...( note !== undefined ? { note } : { } ) } ) ,
500+ layer . operatorSet ( { learner : await learnerOf ( userId , 'operatorSet' ) , traits, by, ...( note !== undefined ? { note } : { } ) } ) ,
489501 revert : async ( ledgerId , by ) => layer . revert ( ledgerId , by ) ,
490- exportLearnedState : async ( userId ) => layer . exportLearnedState ( learnerOf ( userId , 'exportLearnedState' ) ) ,
491- importLearnedState : async ( doc , target ) => layer . importLearnedState ( doc , target ? learnerOf ( target . userId , 'importLearnedState' ) : undefined ) ,
502+ exportLearnedState : async ( userId ) => layer . exportLearnedState ( await learnerOf ( userId , 'exportLearnedState' ) ) ,
503+ importLearnedState : async ( doc , target ) =>
504+ layer . importLearnedState ( doc , target ? await learnerOf ( target . userId , 'importLearnedState' ) : undefined ) ,
492505 forgetUser : async ( userId ) => {
493506 await beforeForget ?.( ) ;
494507 return layer . forgetUser ( userId , { namespace : agent . namespace } ) ;
@@ -555,8 +568,6 @@ export function gmi(opts: GmiOptions): GmiHandle {
555568 const soulId = soul ? soulAgentIdOf ( soul . frontmatter , opts . name ) : undefined ;
556569 /** The key of the brain behind memory.store: `learning.agentKey`, else the soul's id. */
557570 const brainKey = learningConfig ?. agentKey ?. trim ( ) || soulId ;
558- /** The agent's key: `learning.agentKey`, else the soul's id, else a named agent's persona id; none for an unnamed agent with neither. */
559- const agentKey = brainKey || stablePersonaIdOf ( opts ) ;
560571 const memoryStore = cognition . memory ? cognition . memory . store : undefined ;
561572 // A durable store needs the learning flag and a key that names its brain: learning.agentKey, or the soul's id.
562573 if ( memoryStore !== undefined ) assertMemoryStore ( memoryStore , cognition . learning !== undefined , brainKey , soul !== null ) ;
@@ -598,6 +609,27 @@ export function gmi(opts: GmiOptions): GmiHandle {
598609 : { } ) ,
599610 } )
600611 : undefined ;
612+ /**
613+ * The key the agent's learners are filed under when `learning.agentKey` is unset (the layer lets that one win):
614+ * `learning.learnerKey`; else the soul's id, unless the learning store holds learner rows under the slug of the
615+ * agent's name and none under the soul's id, which keeps the slug and says so once; else the slug of the name, or
616+ * none for an agent with no name. Resolved at first use, since the store opens then.
617+ */
618+ const learnersKey = retryingOnce < string > ( async ( ) => {
619+ const chosen = learningConfig ?. learnerKey ?. trim ( ) ;
620+ if ( chosen ) return chosen ;
621+ const oldSlug = stablePersonaIdOf ( opts ) ;
622+ if ( ! soulId ) return oldSlug ?? '' ;
623+ if ( ! layer || ! oldSlug || oldSlug === soulId ) return soulId ;
624+ const namespace = learningConfig ?. namespace ?? '' ;
625+ const [ underSlug , underSoulId ] = await Promise . all ( [
626+ learningAgentHasLearners ( layer , namespace , oldSlug ) ,
627+ learningAgentHasLearners ( layer , namespace , soulId ) ,
628+ ] ) ;
629+ if ( ! underSlug || underSoulId ) return soulId ;
630+ soulLog . warn ( 'soul.id_fallback' , { reason : 'old_slug_learner' } ) ;
631+ return oldSlug ;
632+ } ) ;
601633 /** The traits the agent was given, by option or by its soul, as the layer and a GMI's own render read them. */
602634 const authoredTraits = normalizeHexacoTraits ( opts . personality ?? soul ?. frontmatter . hexaco ) ;
603635 const hasTraits = Object . keys ( authoredTraits ) . length > 0 ;
@@ -740,9 +772,12 @@ export function gmi(opts: GmiOptions): GmiHandle {
740772 ...( noLearner ? { noLearnerReason : 'workflow_seat' as const } : { } ) ,
741773 ...( manager ? { memory : manager } : { } ) ,
742774 } ;
743- // A named agent's persona id is stable; an agent without a name is named by `learning.agentKey` alone.
744- const learnerKey = userId === undefined || noLearner ? null : { namespace : '' , agentKey : opts . name ?. trim ( ) ? personaId : '' , userId } ;
745- const open = ( ) : Promise < ILearnerSession > => active . forLearner ( learnerKey , context ) ;
775+ // The learners' key: see `learnersKey`. It is read inside the open, so a store that cannot answer yet fails the open
776+ // as any other open fails, and the turn asks again.
777+ const open = async ( ) : Promise < ILearnerSession > => {
778+ const learnerKey = userId === undefined || noLearner ? null : { namespace : '' , agentKey : await learnersKey . get ( ) , userId } ;
779+ return active . forLearner ( learnerKey , context ) ;
780+ } ;
746781 try {
747782 return await open ( ) ;
748783 } catch ( error ) {
@@ -1390,7 +1425,12 @@ export function gmi(opts: GmiOptions): GmiHandle {
13901425 // With learning on: the layer as the agent's host reads it and the operator's calls, with the agent's key and
13911426 // namespace filled in. agent.close() ends every session's learner session as it closes the session, without ending
13921427 // the session id's memory, and leaves the layer open, because the agent serves sessions opened after close().
1393- ...( layer ? { learning : learningHostCalls ( layer , { agentKey, namespace : learningConfig ?. namespace ?? '' } , memoryForForget , runningHostCalls ) } : { } ) ,
1428+ ...( layer ? { learning : learningHostCalls (
1429+ layer ,
1430+ { agentKey : async ( ) => learningConfig ?. agentKey ?. trim ( ) || ( await learnersKey . get ( ) ) || undefined , namespace : learningConfig ?. namespace ?? '' } ,
1431+ memoryForForget ,
1432+ runningHostCalls ,
1433+ ) } : { } ) ,
13941434 } ;
13951435 Object . defineProperty ( handle , '__config' , { value : opts , enumerable : false , configurable : true } ) ;
13961436 // The mark sessionSeat() and agencies.members read: this handle is a gmi() agent.
0 commit comments