@@ -63,6 +63,7 @@ import {
6363import { ensureMemoryDir , withoutMigratedEndMarker } from '../memory/wiki/migrateMemoryMd.js' ;
6464import type { IPersonaDefinition } from './IPersonaDefinition.js' ;
6565import { normalizeHexacoTraits } from './hexaco.js' ;
66+ import { stableIdOfName } from './stableId.js' ;
6667
6768/**
6869 * Result of loading a soul workspace. The `personaDefinition` is suitable for
@@ -129,6 +130,71 @@ export interface SoulFrontmatter {
129130 reasoningTrace ?: { maxEntries ?: number ; maxMessageLength ?: number } ;
130131}
131132
133+ /** Thrown when a soul cannot be loaded: its file is missing or was not read, or its front matter has a field of the wrong type. */
134+ export class SoulLoadError extends Error {
135+ readonly code = 'SOUL_LOAD_FAILED' as const ;
136+ /** What names the soul: its path as given, or `inline soul` for inline content. */
137+ readonly source : string ;
138+ /** The error this one wraps, when the failure came from another error. */
139+ readonly cause ?: unknown ;
140+
141+ /**
142+ * @param source - What names the soul: its path as given, or `inline soul`.
143+ * @param reason - Why it failed; the message ends with it.
144+ * @param options - `cause`: the error this one wraps.
145+ */
146+ constructor ( source : string , reason : string , options ?: { cause ?: unknown } ) {
147+ super ( `The soul failed to load (${ source } ): ${ reason } ` ) ;
148+ this . name = 'SoulLoadError' ;
149+ this . source = source ;
150+ if ( options ?. cause !== undefined ) this . cause = options . cause ;
151+ }
152+ }
153+
154+ const STRING_FIELDS = [ 'name' , 'agentId' , 'role' , 'defaultMood' ] as const ;
155+ const STRING_LIST_FIELDS = [ 'allowedMoods' , 'hardLimits' ] as const ;
156+ const OBJECT_FIELDS = [ 'voice' , 'avatar' , 'reasoningTrace' , 'metadata' ] as const ;
157+ const DECLARED_FIELDS : readonly string [ ] = [ ...STRING_FIELDS , ...STRING_LIST_FIELDS , ...OBJECT_FIELDS , 'hexaco' ] ;
158+
159+ /** True for a value YAML reads as a mapping: an object that is not a list and not a date. */
160+ function isMapping ( value : unknown ) : value is Record < string , unknown > {
161+ return typeof value === 'object' && value !== null && ! Array . isArray ( value ) && ! ( value instanceof Date ) ;
162+ }
163+
164+ /**
165+ * Checks the declared fields of a soul's front matter and returns it. A declared field set to `null` (an empty YAML
166+ * value) counts as not set and is left out; keys the loader does not declare are kept as they are.
167+ *
168+ * @param data - The front matter as parsed.
169+ * @param source - What names the soul in the error: its path, or `inline soul`.
170+ * @throws {SoulLoadError } Naming the field, when a declared field has a value of the wrong type.
171+ */
172+ export function validateSoulFrontmatter ( data : Record < string , unknown > , source = 'inline soul' ) : SoulFrontmatter {
173+ const out : Record < string , unknown > = { ...data } ;
174+ for ( const field of DECLARED_FIELDS ) if ( out [ field ] === null ) delete out [ field ] ;
175+ const refuse = ( field : string , expected : string ) : never => {
176+ throw new SoulLoadError ( source , `front matter field '${ field } ' must be ${ expected } ` ) ;
177+ } ;
178+ for ( const field of STRING_FIELDS ) {
179+ if ( out [ field ] !== undefined && typeof out [ field ] !== 'string' ) refuse ( field , 'a string' ) ;
180+ }
181+ for ( const field of STRING_LIST_FIELDS ) {
182+ const value = out [ field ] ;
183+ if ( value !== undefined && ! ( Array . isArray ( value ) && value . every ( ( entry ) => typeof entry === 'string' ) ) ) refuse ( field , 'a list of strings' ) ;
184+ }
185+ for ( const field of OBJECT_FIELDS ) {
186+ if ( out [ field ] !== undefined && ! isMapping ( out [ field ] ) ) refuse ( field , 'an object' ) ;
187+ }
188+ const hexaco = out . hexaco ;
189+ if ( hexaco !== undefined ) {
190+ const scores = isMapping ( hexaco ) ? Object . values ( hexaco ) : undefined ;
191+ if ( ! scores || scores . some ( ( score ) => typeof score !== 'number' || ! Number . isFinite ( score ) || score < 0 || score > 1 ) ) {
192+ refuse ( 'hexaco' , 'an object of numbers between 0 and 1' ) ;
193+ }
194+ }
195+ return out as SoulFrontmatter ;
196+ }
197+
132198/**
133199 * HEXACO personality model scores. All values 0.0-1.0.
134200 * See {@link https://hexaco.org/} for the trait reference.
@@ -232,7 +298,7 @@ export async function loadSoul(options: SoulLoaderOptions): Promise<LoadedSoul>
232298
233299 // Parse frontmatter + body. The frontmatter is read as data, never evaluated.
234300 const parsed = soulRaw ? readFrontMatter ( soulRaw ) : { data : { } , content : '' } ;
235- const frontmatter = parsed . data as SoulFrontmatter ;
301+ const frontmatter = validateSoulFrontmatter ( parsed . data as Record < string , unknown > , options . source ) ;
236302 const soulContent = parsed . content . trim ( ) ;
237303
238304 // Read optional companion files
@@ -295,7 +361,7 @@ export function loadSoulSync(options: SoulLoaderOptions): LoadedSoul {
295361 const soulRaw = soulText ( soulPath , readSoulFileSync ( folder , path . basename ( soulPath ) ) , requireSoul ) ;
296362
297363 const parsed = soulRaw ? readFrontMatter ( soulRaw ) : { data : { } , content : '' } ;
298- const frontmatter = parsed . data as SoulFrontmatter ;
364+ const frontmatter = validateSoulFrontmatter ( parsed . data as Record < string , unknown > , options . source ) ;
299365 const soulContent = parsed . content . trim ( ) ;
300366
301367 const styleContent = trimmedText ( readSoulFileSync ( folder , 'STYLE.md' ) ) ;
@@ -332,7 +398,7 @@ export function loadSoulSync(options: SoulLoaderOptions): LoadedSoul {
332398 */
333399export function parseSoul ( soulMarkdown : string ) : LoadedSoul {
334400 const parsed = readFrontMatter ( soulMarkdown ) ;
335- const frontmatter = parsed . data as SoulFrontmatter ;
401+ const frontmatter = validateSoulFrontmatter ( parsed . data as Record < string , unknown > ) ;
336402 const soulContent = parsed . content . trim ( ) ;
337403 return {
338404 personaDefinition : frontmatterToPersona ( frontmatter , soulContent ) ,
@@ -342,34 +408,22 @@ export function parseSoul(soulMarkdown: string): LoadedSoul {
342408 } ;
343409}
344410
345- /**
346- * Convert SoulFrontmatter + markdown body into an IPersonaDefinition that
347- * the existing PersonaOverlayManager and persona overlays can consume.
348- */
349- export function frontmatterToPersona (
350- frontmatter : SoulFrontmatter ,
351- soulBody : string ,
352- styleBody ?: string ,
353- ) : IPersonaDefinition {
354- const baseSystemPrompt = [ soulBody , styleBody && `## Style\n\n${ styleBody } ` ]
355- . filter ( Boolean )
356- . join ( '\n\n' )
357- . trim ( ) ;
411+ /** The persona fields a soul's front matter sets, with no prompt: the one mapping every path consumes. */
412+ export type SoulPersonaFields = Pick <
413+ IPersonaDefinition ,
414+ 'id' | 'name' | 'description' | 'personalityTraits' | 'reasoningTraceConfig' | 'moodAdaptation' | 'voiceConfig' | 'avatarConfig' | 'hardLimits'
415+ > & { metadata ?: Record < string , unknown > } ;
358416
359- const definition : IPersonaDefinition = {
417+ /** The persona fields of a soul's front matter: id, name, role, traits, reasoning-trace limits, mood, voice, avatar, hard limits and metadata. */
418+ export function personaFieldsOf ( frontmatter : SoulFrontmatter ) : SoulPersonaFields {
419+ return {
360420 id : frontmatter . agentId ?? slugify ( frontmatter . name ?? 'unnamed-agent' ) ,
361421 name : frontmatter . name ?? 'Unnamed Agent' ,
362422 description : frontmatter . role ?? '' ,
363- version : '1.0.0' ,
364- baseSystemPrompt,
365423 // Runtime readers key Honesty-Humility as `honesty`; the frontmatter may
366424 // use either spelling.
367425 personalityTraits : frontmatter . hexaco ? normalizeHexacoTraits ( frontmatter . hexaco ) : undefined ,
368- // Kept as given (an object is copied; anything else passes through) so PersonaValidation can report a malformed value.
369- reasoningTraceConfig :
370- frontmatter . reasoningTrace && typeof frontmatter . reasoningTrace === 'object' && ! Array . isArray ( frontmatter . reasoningTrace )
371- ? { ...frontmatter . reasoningTrace }
372- : ( frontmatter . reasoningTrace as IPersonaDefinition [ 'reasoningTraceConfig' ] ) ,
426+ reasoningTraceConfig : frontmatter . reasoningTrace ? { ...frontmatter . reasoningTrace } : undefined ,
373427 moodAdaptation : frontmatter . defaultMood
374428 ? {
375429 enabled : true ,
@@ -393,9 +447,38 @@ export function frontmatterToPersona(
393447 : undefined ,
394448 hardLimits : frontmatter . hardLimits ,
395449 metadata : frontmatter . metadata ,
396- } as IPersonaDefinition ;
450+ } as SoulPersonaFields ;
451+ }
452+
453+ /**
454+ * The one stable id of a soul: `agentId` as given, else the slug of the soul's `name`, else an id from the agent
455+ * option's `name`; undefined when the soul has neither and the agent has no name. Never a random id.
456+ *
457+ * @param frontmatter - The soul's front matter.
458+ * @param agentName - The agent's `name` option, used only when the soul names no id and no name.
459+ */
460+ export function soulAgentIdOf ( frontmatter : SoulFrontmatter , agentName ?: string ) : string | undefined {
461+ if ( typeof frontmatter . agentId === 'string' && frontmatter . agentId . trim ( ) !== '' ) return frontmatter . agentId ;
462+ const fromSoulName = typeof frontmatter . name === 'string' ? slugify ( frontmatter . name ) : '' ;
463+ if ( fromSoulName ) return fromSoulName ;
464+ const name = agentName ?. trim ( ) ;
465+ return name ? stableIdOfName ( name ) : undefined ;
466+ }
397467
398- return definition ;
468+ /**
469+ * Convert SoulFrontmatter + markdown body into an IPersonaDefinition that
470+ * the existing PersonaOverlayManager and persona overlays can consume.
471+ */
472+ export function frontmatterToPersona (
473+ frontmatter : SoulFrontmatter ,
474+ soulBody : string ,
475+ styleBody ?: string ,
476+ ) : IPersonaDefinition {
477+ const baseSystemPrompt = [ soulBody , styleBody && `## Style\n\n${ styleBody } ` ]
478+ . filter ( Boolean )
479+ . join ( '\n\n' )
480+ . trim ( ) ;
481+ return { ...personaFieldsOf ( frontmatter ) , version : '1.0.0' , baseSystemPrompt } as IPersonaDefinition ;
399482}
400483
401484/**
0 commit comments