Skip to content

Commit 2642400

Browse files
committed
feat(souls): keep a gmi() agent's learners under the key they were filed under, and add learning.learnerKey
Signed-off-by: jddunn <[email protected]>
1 parent 9b55a88 commit 2642400

10 files changed

Lines changed: 125 additions & 30 deletions

File tree

‎docs/GMI.md‎

Lines changed: 6 additions & 5 deletions
Large diffs are not rendered by default.

‎src/api/AgentOS.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1900,6 +1900,10 @@ export class AgentOS implements IAgentOS {
19001900
if (namespace !== undefined && namespace !== null) {
19011901
refuse("learning.namespace is read by gmi() only; the runtime takes each turn's resolved organizationId.");
19021902
}
1903+
const learnerKey = option === true ? undefined : (option as { learnerKey?: unknown }).learnerKey;
1904+
if (learnerKey !== undefined && learnerKey !== null) {
1905+
refuse("learning.learnerKey is read by gmi() only; the runtime keys learners by the registered persona's id.");
1906+
}
19031907
try {
19041908
resolveLearningConfig(option === true ? {} : option, 'custom');
19051909
} catch (error) {

‎src/api/__tests__/learning-store-and-scopes.e2e.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12183,9 +12183,11 @@ describe('the docs a host reads about it', () => {
1218312183
"A `gmi()` agent with `memory.store` runs it on the adapter of that store's Brain, opened with the agent's memory or at the first call that needs it (in process when the adapter has no transactions).",
1218412184
);
1218512185
expect(gmiDoc).toContain(
12186-
"On a `gmi()` agent, `agent.learning` carries the same calls with the agent's key (`learning.agentKey`, else a named agent's persona id) and namespace (`learning.namespace`, else `''`) filled in",
12186+
"On a `gmi()` agent, `agent.learning` carries the same calls with the agent's key (`learning.agentKey`, else the key its learners are filed under: `learning.learnerKey`, the soul's id, or a named agent's persona id) and namespace (`learning.namespace`, else `''`) filled in",
12187+
);
12188+
expect(gmiDoc).toContain(
12189+
'A call that names a learner on an agent with no key (no `learning.agentKey`, `learning.learnerKey`, soul id or name) rejects, naming `learning.agentKey`.',
1218712190
);
12188-
expect(gmiDoc).toContain('A call that names a learner on an agent with neither `learning.agentKey` nor a name rejects, naming `learning.agentKey`.');
1218912191
expect(gmiDoc).toContain('a memory that does not open fails the call before the tombstone is written');
1219012192
const guide = doc('docs/getting-started/HIGH_LEVEL_API.md');
1219112193
expect(guide).toContain('Of the `MemoryConfig` fields, this path reads `embedding`, `consolidation`, `persistAccessState` and `store`');

‎src/api/gmi.ts‎

Lines changed: 60 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,13 @@ import type { AgentOSUsageAggregate, AgentOSUsageLedgerOptions } from './runtime
8585
import { exportAgentConfig, exportAgentConfigJSON } from './agentExportCore.js';
8686
import { getDeferredCapabilities, isMeaningfullyConfigured } from './runtime/lightweightAgentDiagnostics.js';
8787
import { 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';
8995
import { deferLearnerSession } from '../cognition/learning/LearnerSession.js';
9096
import { InMemoryLearningStore } from '../cognition/learning/store/InMemoryLearningStore.js';
9197
import 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
*/
467475
function 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.

‎src/cognition/learning/LearningLayer.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1266,6 +1266,16 @@ export async function adoptLearningMemory(layer: ILearningLayer, memory: ICognit
12661266
if (layer instanceof LearningLayer) await layer.adoptMemory(memory);
12671267
}
12681268

1269+
/**
1270+
* Whether a layer's learning store holds a learner row for an agent key in a namespace. False for a layer built by
1271+
* another implementation of `ILearningLayer`, a store that did not open, and a store without the question.
1272+
*/
1273+
export async function learningAgentHasLearners(layer: ILearningLayer, namespace: string, agentKey: string): Promise<boolean> {
1274+
if (!(layer instanceof LearningLayer)) return false;
1275+
const ready = await layer.storage();
1276+
return (await ready?.store.agentHasLearners?.(namespace, agentKey)) ?? false;
1277+
}
1278+
12691279
/**
12701280
* Lets a layer go of a memory manager the host has shut down (`LearningLayer.releaseMemory`). A layer built by another
12711281
* implementation of `ILearningLayer` is left as it is.

‎src/cognition/learning/config.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ function processEnv(): Record<string, string | undefined> {
2727
* YAML writes one.
2828
*
2929
* @throws {Error} Naming the field, when a field has a value of the wrong type, `mode` is not a known mode, or
30-
* `agentKey` or `ledgerKey` is blank.
30+
* `agentKey`, `learnerKey` or `ledgerKey` is blank.
3131
*/
3232
export function resolveLearningConfig(config: LearningConfig, profile: LearningProfile): ResolvedLearning {
3333
if (config === null || typeof config !== 'object' || Array.isArray(config)) {
@@ -44,12 +44,12 @@ export function resolveLearningConfig(config: LearningConfig, profile: LearningP
4444
throw new Error(`learning.${key} must be true or false.`);
4545
}
4646
}
47-
for (const key of ['agentKey', 'namespace', 'ledgerKey'] as const) {
47+
for (const key of ['agentKey', 'learnerKey', 'namespace', 'ledgerKey'] as const) {
4848
if (field(key) !== undefined && typeof field(key) !== 'string') {
4949
throw new Error(`learning.${key} must be a string.`);
5050
}
5151
}
52-
for (const key of ['agentKey', 'ledgerKey'] as const) {
52+
for (const key of ['agentKey', 'learnerKey', 'ledgerKey'] as const) {
5353
const value = field(key);
5454
if (value !== undefined && value.trim() === '') throw new Error(`learning.${key} must not be blank.`);
5555
}

‎src/cognition/learning/store/InMemoryLearningStore.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,6 +271,13 @@ class MemoryTx implements LearningStoreTx {
271271
.map(copySession);
272272
}
273273

274+
async agentHasLearners(namespace: string, agentKey: string): Promise<boolean> {
275+
const t = this.open();
276+
for (const row of t.sessions.values()) if (row.namespace === namespace && row.agentKey === agentKey) return true;
277+
for (const head of t.heads.values()) if (head.namespace === namespace && head.agentKey === agentKey && head.userId !== null) return true;
278+
return false;
279+
}
280+
274281
async isForgotten(hash: string): Promise<boolean> {
275282
return this.open().forgotten.has(hash);
276283
}
@@ -365,6 +372,10 @@ export class InMemoryLearningStore extends TransactionalLearningStore {
365372
return this.transaction((tx) => tx.sessionRowsIn!(namespace, agentKey, sessionId));
366373
}
367374

375+
agentHasLearners(namespace: string, agentKey: string): Promise<boolean> {
376+
return this.transaction((tx) => tx.agentHasLearners!(namespace, agentKey));
377+
}
378+
368379
/** Releases nothing: the rows stay with the store until the process ends. */
369380
async close(): Promise<void> {}
370381
}

‎src/cognition/learning/store/LearningStore.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,12 @@ export interface LearningStoreTx {
180180
* host's own store written against an earlier release still opens; `forgetUser` names those scopes unreached on it.
181181
*/
182182
sessionRowsIn?(namespace: string, agentKey: string, sessionId: string): Promise<SessionRow[]>;
183+
/**
184+
* Whether the store holds a learner row for an agent key in a namespace: a session row, or the ledger head of a
185+
* learner's chain. Optional: `gmi()` asks it to keep learners under the key they were first filed under, and a
186+
* store without it is taken to hold none.
187+
*/
188+
agentHasLearners?(namespace: string, agentKey: string): Promise<boolean>;
183189

184190
isForgotten(hash: string): Promise<boolean>;
185191
/** Idempotent. */

‎src/cognition/learning/store/SqlLearningStore.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,17 @@ class SqlTx implements LearningStoreTx {
440440
.sort((a, b) => compareText(a.userId, b.userId) || compareText(a.kind, b.kind));
441441
}
442442

443+
async agentHasLearners(namespace: string, agentKey: string): Promise<boolean> {
444+
if (holdsLoneSurrogate(namespace, agentKey)) return this.none(false);
445+
const session = await this.db.all<Row>('SELECT 1 AS found FROM agentos_learning_sessions WHERE namespace = ? AND agent_key = ? LIMIT 1', [namespace, agentKey]);
446+
if (session.length > 0) return true;
447+
const head = await this.db.all<Row>(
448+
'SELECT 1 AS found FROM agentos_learning_heads WHERE namespace = ? AND agent_key = ? AND user_id IS NOT NULL LIMIT 1',
449+
[namespace, agentKey],
450+
);
451+
return head.length > 0;
452+
}
453+
443454
async isForgotten(hash: string): Promise<boolean> {
444455
if (holdsLoneSurrogate(hash)) return this.none(false);
445456
return Boolean(await this.db.get<Row>('SELECT hash FROM agentos_learning_forgotten WHERE hash = ?', [hash]));
@@ -525,6 +536,10 @@ export class SqlLearningStore extends TransactionalLearningStore {
525536
return this.transaction((tx) => tx.sessionRowsIn!(namespace, agentKey, sessionId));
526537
}
527538

539+
agentHasLearners(namespace: string, agentKey: string): Promise<boolean> {
540+
return this.transaction((tx) => tx.agentHasLearners!(namespace, agentKey));
541+
}
542+
528543
/** Leaves the adapter open: it is the host's. */
529544
async close(): Promise<void> {}
530545
}

‎src/cognition/learning/types.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,12 @@ export interface LearningConfig {
125125
mode?: LearningMode;
126126
/** Names the agent its learners belong to. Unset: the id of the registered persona, or of a named `gmi()` agent. */
127127
agentKey?: string;
128+
/**
129+
* `gmi()` only: the key the agent's learners are filed under when `agentKey` is unset. Unset: the soul's id when the
130+
* agent has one (learners already filed under the slug of the agent's `name` stay there, with one log line), else
131+
* the slug of the agent's `name`. It never names the brain of `memory.store`.
132+
*/
133+
learnerKey?: string;
128134
/**
129135
* The organization of a `gmi()` agent's learners, fixed for the agent. The full runtime takes each turn's resolved
130136
* organization and refuses this field.

0 commit comments

Comments
 (0)