Skip to content

Commit 728cb4b

Browse files
committed
feat(souls): one id rule and a front matter check for soul files
Signed-off-by: jddunn <[email protected]>
1 parent b7f05ea commit 728cb4b

3 files changed

Lines changed: 132 additions & 42 deletions

File tree

‎src/api/runtime/gmiPersona.ts‎

Lines changed: 3 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,11 @@
1414
* metaprompts, as the persona loaders expand them, because the GMI runs only the
1515
* persona's `metaPrompts`.
1616
*/
17-
import { createHash, randomUUID } from 'node:crypto';
17+
import { randomUUID } from 'node:crypto';
1818
import { buildSystemPrompt, type AgentOptions } from '../agent.js';
1919
import { resolveModelOption } from '../model.js';
2020
import { normalizeHexacoTraits } from '../../cognition/substrate/personas/hexaco.js';
21+
import { stableIdOfName } from '../../cognition/substrate/personas/stableId.js';
2122
import { normalizePersonaDefinition } from '../../cognition/substrate/personas/personaNormalization.js';
2223
import type { IPersonaDefinition, SentimentTrackingConfig } from '../../cognition/substrate/personas/IPersonaDefinition.js';
2324
import type { ITool } from '../../core/tools/ITool.js';
@@ -27,28 +28,14 @@ import type { ResolvedCognition } from './gmiCognition.js';
2728
/** The session store bounds history, so the GMI's own count window stays out of the way. */
2829
export const GMI_SESSION_MAX_HISTORY_MESSAGES = 100_000;
2930

30-
/**
31-
* A stable persona id from the agent's name: a lowercase ASCII slug, or, for a
32-
* name with no Latin letters or digits, `agent-` and a hash of the name.
33-
*/
34-
function personaIdFor(name: string): string {
35-
const slug = name
36-
.normalize('NFKD')
37-
.replace(/[̀-ͯ]/g, '')
38-
.toLowerCase()
39-
.replace(/[^a-z0-9]+/g, '-')
40-
.replace(/^-+|-+$/g, '');
41-
return slug || `agent-${createHash('sha256').update(name).digest('hex').slice(0, 12)}`;
42-
}
43-
4431
/**
4532
* The persona id of a named agent, which is the same at every build (the slug of its name); `undefined` for an agent
4633
* with no name, whose persona id is new at each build. `gmi()` names the agent's learners by it when `learning.agentKey`
4734
* is unset.
4835
*/
4936
export function stablePersonaIdOf(opts: Pick<AgentOptions, 'name'>): string | undefined {
5037
const name = opts.name?.trim();
51-
return name ? personaIdFor(name) : undefined;
38+
return name ? stableIdOfName(name) : undefined;
5239
}
5340

5441
/**

‎src/cognition/substrate/personas/SoulLoader.ts‎

Lines changed: 109 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ import {
6363
import { ensureMemoryDir, withoutMigratedEndMarker } from '../memory/wiki/migrateMemoryMd.js';
6464
import type { IPersonaDefinition } from './IPersonaDefinition.js';
6565
import { 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
*/
333399
export 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
/**
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @module personas/stableId
3+
* A stable id from a name: the same at every build, and never empty.
4+
*/
5+
import { createHash } from 'node:crypto';
6+
7+
/**
8+
* A lowercase ASCII slug of `name`, or, for a name with no Latin letters or digits, `agent-` and a hash of the name.
9+
*
10+
* @param name - The name; not blank.
11+
*/
12+
export function stableIdOfName(name: string): string {
13+
const slug = name
14+
.normalize('NFKD')
15+
.replace(/[̀-ͯ]/g, '')
16+
.toLowerCase()
17+
.replace(/[^a-z0-9]+/g, '-')
18+
.replace(/^-+|-+$/g, '');
19+
return slug || `agent-${createHash('sha256').update(name).digest('hex').slice(0, 12)}`;
20+
}

0 commit comments

Comments
 (0)