Skip to content

Commit 5ffc6a5

Browse files
committed
feat(souls): key the wiki scope and the memory.store brain by the soul's id
Signed-off-by: jddunn <[email protected]>
1 parent dcbc388 commit 5ffc6a5

5 files changed

Lines changed: 34 additions & 16 deletions

File tree

‎docs/GMI.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ A soul file's front matter is applied through the loader's one mapping, so the "
137137
- **`memory.embedding`.** `{ provider, model?, dimension? }` picks the embedding model. Unset, the memory uses the global default provider (`setDefaultProvider()`) when agentos has an embedding model for it, else the first of OpenAI, Gemini and Ollama whose `OPENAI_API_KEY`, `GEMINI_API_KEY` or `OLLAMA_BASE_URL` is set, with that provider's default model (`text-embedding-3-small`, `gemini-embedding-2`, `nomic-embed-text`). Anthropic, Groq, Together AI, xAI, MiniMax and the Claude Code and Gemini CLIs have no embedding models in agentos, and `memory.embedding` naming one is refused when the agent is built. `dimension` is required for a model whose output size agentos does not know. Building the memory embeds one test text through the model. When no embedding model is found, or the model cannot answer (an Ollama model that was never pulled) or returns another size than the memory expects, the first session turn rejects with an error naming `memory.embedding`; a build that fails is retried on the next turn.
138138
- **Consolidation.** `memory.consolidation.enabled: true` starts the manager's consolidation cycle, which runs every hour (`interval` is not applied, and a warning says so). A cycle reads the traces filed under the agent's persona id, while the sessions file theirs under their user and scope ids, so it finds none of them, and with no model invoker passed it writes no schema summaries.
139139
- **`memory.persistAccessState`.** `false` turns off the manager's store keeping each trace's stability, access count and reinforcement schedule across a restart ([Access state across restarts](./memory/COGNITIVE_MEMORY.md#access-state-across-restarts)), for one release of before-and-after measurement; the default is `true`. Without `memory.store` the manager keeps its traces in process memory, so neither value changes what a session recalls.
140-
- **`memory.store`.** Durable memory: `{ path }`, a SQLite file agentos opens, or `{ adapter, brainId? }`, a host's [`StorageAdapter`](https://github.com/framerslab/sql-storage-adapter), which agentos never closes. The manager files every trace into a [`Brain`](https://github.com/framerslab/agentos/blob/master/src/cognition/memory/retrieval/store/Brain.ts) there under the brain id `brainId`, else `learning.agentKey`, loads the brain's newest 1,000 traces at its first read and, when a session opens, its learner's own two scopes, or for a session with no learner the two scopes of the session's own form, and keeps an archive over the same adapter for a gist's original; the learning store runs on the same adapter ([The trait row and the ledger](#the-trait-row-and-the-ledger)). An agent built again on the file recalls what its users said and renders the traits its learners have. It needs the learning option and `learning.agentKey`, which names the brain and the learners: `gmi()` throws at construction naming `learning` without the option, and naming `learning.agentKey` without the key (for durable memory with no learning, set `learning: { agentKey, mode: 'off' }`). A value that is neither shape, a blank `path` or `brainId`, or an `adapter` without the storage adapter's methods throws naming the field. A store that does not open fails the session's first send naming `memory.store`, before any model call, and the next send tries again. One process serves a SQLite file; several processes share a Postgres database instead, each through an adapter of its own. A PostgreSQL adapter reads BIGINT as numbers (`typeParsers: { int8: 'number' }`, as `Brain.openPostgres` opens its own): one that reads it as text fails the store's open, naming the option, since a trace's counts and times would load as strings. The manifest's `memory_store` loop names the store. A session id's memory survives a restart, and `agent.close()`; `session.close()` ends it for good, across restarts. The Brain keeps each id's generation in `brain_meta`, a row keyed `session_generation:` and the id's session form, which a session reads as it opens and its `close()` moves on: the id's next opening, in this process or another, files and recalls under a scope id of its own, and what the closed session filed stays in the store under the closed session's. An id no close has ended is at generation 0 and files under its plain session form, as a file written before generations were recorded holds it. Two processes that close one opening of an id at once record one next generation, and a close of an opening another process already ended changes nothing. A `close()` whose end the store does not record rejects naming `memory.store`; the id's next opening on the agent records it before its first turn. The thread notes a host's memory tools file for a session go under its generation too, so the id's next opening finds none of the closed session's with `memory_search`. A host hands an anonymous id to a new person by closing the old session or minting a new id.
140+
- **`memory.store`.** Durable memory: `{ path }`, a SQLite file agentos opens, or `{ adapter, brainId? }`, a host's [`StorageAdapter`](https://github.com/framerslab/sql-storage-adapter), which agentos never closes. The manager files every trace into a [`Brain`](https://github.com/framerslab/agentos/blob/master/src/cognition/memory/retrieval/store/Brain.ts) there under the brain id `brainId`, else `learning.agentKey`, else the soul's id, loads the brain's newest 1,000 traces at its first read and, when a session opens, its learner's own two scopes, or for a session with no learner the two scopes of the session's own form, and keeps an archive over the same adapter for a gist's original; the learning store runs on the same adapter ([The trait row and the ledger](#the-trait-row-and-the-ledger)). An agent built again on the file recalls what its users said and renders the traits its learners have. It needs the learning option and a key that names the brain: `learning.agentKey`, or, with a soul, the soul's id (`agentId`, else the slug of its `name`). `gmi()` throws at construction naming `learning` without the option, and naming `learning.agentKey` without a key, with the advice to set `agentId` when the agent has a soul (for durable memory with no learning, set `learning: { mode: 'off' }` on an agent whose soul has an id, or `learning: { agentKey, mode: 'off' }`). A value that is neither shape, a blank `path` or `brainId`, or an `adapter` without the storage adapter's methods throws naming the field. A store that does not open fails the session's first send naming `memory.store`, before any model call, and the next send tries again. One process serves a SQLite file; several processes share a Postgres database instead, each through an adapter of its own. A PostgreSQL adapter reads BIGINT as numbers (`typeParsers: { int8: 'number' }`, as `Brain.openPostgres` opens its own): one that reads it as text fails the store's open, naming the option, since a trace's counts and times would load as strings. The manifest's `memory_store` loop names the store. A session id's memory survives a restart, and `agent.close()`; `session.close()` ends it for good, across restarts. The Brain keeps each id's generation in `brain_meta`, a row keyed `session_generation:` and the id's session form, which a session reads as it opens and its `close()` moves on: the id's next opening, in this process or another, files and recalls under a scope id of its own, and what the closed session filed stays in the store under the closed session's. An id no close has ended is at generation 0 and files under its plain session form, as a file written before generations were recorded holds it. Two processes that close one opening of an id at once record one next generation, and a close of an opening another process already ended changes nothing. A `close()` whose end the store does not record rejects naming `memory.store`; the id's next opening on the agent records it before its first turn. The thread notes a host's memory tools file for a session go under its generation too, so the id's next opening finds none of the closed session's with `memory_search`. A host hands an anonymous id to a new person by closing the old session or minting a new id.
141141

142142
**`memoryProvider`.** `memoryProvider.getContext()` runs once per turn, within `memoryProviderOptions.timeoutMs`, and its text goes into every model call of the turn as a system message after the leading system messages, where the legacy path puts it. In the sessions of an agent with cognitive memory on, the cognitive memory supplies the context and `getContext()` is skipped; a warning at construction says so. `observe()` runs after each turn that ends without error, for the user's text and the reply, except a structured send whose answer fails to parse. The turn does not wait for it, and a failure to record the turn leaves the turn's result as it is; it is logged with `console.warn` on the provider's first failure and then at its 10th, 100th, 1000th and so on.
143143

‎src/api/gmi.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
* set resolves them on its first call; a build that fails is not kept, and the
1414
* next call builds again.
1515
*
16-
* With `memory.store` (which needs the learning option and `learning.agentKey`)
16+
* With `memory.store` (which needs the learning option and a key for its brain,
17+
* `learning.agentKey` or the soul's id)
1718
* the agent's memory and its learning store share one Brain's adapter, opened on
1819
* first use, and the Brain keeps each session id's generation, so an id that
1920
* session.close() ended stays ended across a restart.
@@ -64,6 +65,7 @@ import { resolveCognition, type ResolvedCognition } from './runtime/gmiCognition
6465
import { personaFromAgentOptions, stablePersonaIdOf } from './runtime/gmiPersona.js';
6566
import { warnSoulBesideSystemBlocks, withOneSoulWarning } from './runtime/soulLoadWarning.js';
6667
import { soulLog } from '../cognition/substrate/personas/soulLog.js';
68+
import { soulAgentIdOf } from '../cognition/substrate/personas/SoulLoader.js';
6769
import { modelNamesAnotherProvider } from './runtime/credentialOwner.js';
6870
import {
6971
assertEmbeddingConfig,
@@ -549,11 +551,15 @@ export function gmi(opts: GmiOptions): GmiHandle {
549551
// generate() and stream() run the light profile, under the agent's own learning option.
550552
const lightCognition = resolveCognition({ cognition: 'light', learning: opts.learning });
551553
const learningConfig = typeof opts.learning === 'object' && opts.learning !== null ? opts.learning : undefined;
552-
/** The agent's key: `learning.agentKey`, else a named agent's persona id; none for an unnamed agent with no key. */
553-
const agentKey = learningConfig?.agentKey?.trim() || stablePersonaIdOf(opts);
554+
/** The soul's one stable id; undefined with no soul, or a soul that gives none on an agent with no name. */
555+
const soulId = soul ? soulAgentIdOf(soul.frontmatter, opts.name) : undefined;
556+
/** The key of the brain behind memory.store: `learning.agentKey`, else the soul's id. */
557+
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);
554560
const memoryStore = cognition.memory ? cognition.memory.store : undefined;
555-
// A durable store needs the learning flag and the agent's key, which names its brain and its learners.
556-
if (memoryStore !== undefined) assertMemoryStore(memoryStore, cognition.learning !== undefined, learningConfig?.agentKey);
561+
// A durable store needs the learning flag and a key that names its brain: learning.agentKey, or the soul's id.
562+
if (memoryStore !== undefined) assertMemoryStore(memoryStore, cognition.learning !== undefined, brainKey, soul !== null);
557563
if (cognition.learning && learningConfig?.store?.kind === 'sql' && !learningConfig.agentKey?.trim()) {
558564
throw new Error(
559565
"gmi(): a SQL learning.store needs learning.agentKey, the stable id of the agent's learners; two agents on one store would otherwise be one agent to the learning layer.",
@@ -564,7 +570,7 @@ export function gmi(opts: GmiOptions): GmiHandle {
564570
* memory generation: `agent.close()` closes it, and the next use opens the file again. A host's adapter keeps one
565571
* Brain for the agent's life, never closed.
566572
*/
567-
const openStoreBrain = () => retryingOnce<AgentMemoryBrain>(() => openAgentMemoryBrain(memoryStore!, learningConfig!.agentKey!.trim()));
573+
const openStoreBrain = () => retryingOnce<AgentMemoryBrain>(() => openAgentMemoryBrain(memoryStore!, brainKey!));
568574
let storeBrain = memoryStore ? openStoreBrain() : undefined;
569575
/** The host calls of `agent.learning` still running: `agent.close()` lets them finish before it closes what they use. */
570576
const runningHostCalls = new Set<Promise<unknown>>();

‎src/api/runtime/agentCognitiveMemory.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -226,14 +226,16 @@ export function assertEmbeddingConfig(memory: MemoryConfig): void {
226226

227227
/**
228228
* Checks `memory.store` at construction: `{ path }` with a non-blank path, or `{ adapter, brainId? }` with a storage
229-
* adapter and a non-blank brain id when it names one; the learning option on; and `learning.agentKey`.
229+
* adapter and a non-blank brain id when it names one; the learning option on; and a key that names the brain,
230+
* `learning.agentKey`, else the soul's id.
230231
*
231232
* @param store - `memory.store` as the agent's options give it.
232233
* @param learningOn - Whether the agent's `learning` option is on.
233-
* @param agentKey - `learning.agentKey`.
234+
* @param agentKey - `learning.agentKey`, else the soul's id.
235+
* @param hasSoul - Whether the agent has a soul: the missing-key error then tells the host to set the soul's `agentId`.
234236
* @throws {Error} Naming the option.
235237
*/
236-
export function assertMemoryStore(store: unknown, learningOn: boolean, agentKey: string | null | undefined): void {
238+
export function assertMemoryStore(store: unknown, learningOn: boolean, agentKey: string | null | undefined, hasSoul = false): void {
237239
const isObject = !!store && typeof store === 'object';
238240
const hasPath = isObject && 'path' in (store as object);
239241
const hasAdapter = isObject && 'adapter' in (store as object);
@@ -256,7 +258,8 @@ export function assertMemoryStore(store: unknown, learningOn: boolean, agentKey:
256258
}
257259
if (typeof agentKey !== 'string' || agentKey.trim() === '') {
258260
throw new Error(
259-
"gmi(): memory.store needs learning.agentKey, the stable id of the agent's brain and its learners; two agents on one store would otherwise be one agent to the learning layer.",
261+
"gmi(): memory.store needs learning.agentKey, the stable id of the agent's brain and its learners; two agents on one store would otherwise be one agent to the learning layer." +
262+
(hasSoul ? " This agent's soul has no agentId and no name: set agentId in SOUL.md's front matter, and the soul's id names the brain." : ''),
260263
);
261264
}
262265
}
@@ -276,7 +279,7 @@ export interface AgentMemoryBrain {
276279
* as strings and an access appends to the count. One that reads BIGINT as text is refused before the Brain opens.
277280
*
278281
* @param store - `memory.store`, checked by {@link assertMemoryStore}.
279-
* @param agentKey - `learning.agentKey`.
282+
* @param agentKey - `learning.agentKey`, else the soul's id.
280283
* @throws {Error} Naming `memory.store`, when the store does not open or its PostgreSQL adapter reads BIGINT as text.
281284
*/
282285
export async function openAgentMemoryBrain(store: NonNullable<MemoryConfig['store']>, agentKey: string): Promise<AgentMemoryBrain> {

‎src/api/souledAgent.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
import { generateText } from './generateText.js';
2929
import type { StreamTextResult } from './streamText.js';
3030
import { Memory } from '../cognition/memory/io/facade/Memory.js';
31+
import { soulAgentIdOf } from '../cognition/substrate/personas/SoulLoader.js';
3132
import { attachMemoryWiki } from '../cognition/memory/io/attachMemoryWiki.js';
3233
import { SemanticChunker } from '../cognition/rag/chunking/SemanticChunker.js';
3334
import { estimateTokens } from '../core/utils/text-utils.js';
@@ -252,7 +253,13 @@ export async function souledAgent(opts: SouledAgentOptions): Promise<SouledAgent
252253
const budget = asSpendBudget(rest.budget);
253254
const ledger = (rest.observability?.usageLedger as AgentOSUsageLedgerOptions | undefined) ?? rest.usageLedger;
254255

255-
const agentId = loaded.frontmatter.agentId ?? opts.name ?? 'agent';
256+
// The soul's one id: the wiki files under it, and nothing files under a shared fallback id.
257+
const agentId = soulAgentIdOf(loaded.frontmatter, opts.name);
258+
if (!agentId) {
259+
throw new Error(
260+
"souledAgent: the soul has no agentId and no name, and the agent has no name; set agentId in SOUL.md's front matter so the agent's memory has one stable id",
261+
);
262+
}
256263

257264
// The markdown memory/ is source of truth; the sqlite is the rebuildable index.
258265
const storeDir = path.join(loaded.memoryDir, '.store');

‎src/api/types.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -114,13 +114,15 @@ export interface MemoryConfig {
114114
/**
115115
* Durable memory on the GMI path (`gmi()`, `agent({ runtime: 'gmi' })`): a SQLite file agentos opens, or a host's
116116
* storage adapter, which agentos never closes. The agent's memory files into a Brain there, under the brain id
117-
* `brainId` or `learning.agentKey`, an archive over the same adapter keeps a gist's original, and the agent's
117+
* `brainId`, else `learning.agentKey`, else the soul's id, an archive over the same adapter keeps a gist's original, and the agent's
118118
* learning store runs on the same adapter. A file is closed by `agent.close()` and opened again by the next session
119119
* or host call that needs it. One process serves a SQLite file; several processes share a Postgres database, each
120120
* through an adapter of its own, opened with `typeParsers: { int8: 'number' }`: the store refuses a PostgreSQL adapter
121121
* that reads BIGINT as text, since a trace's counts and times would load as strings.
122-
* Needs the learning option on and `learning.agentKey`, which names the agent's brain and its learners; for durable
123-
* memory without learning, set `learning: { agentKey, mode: 'off' }`. Without it, memory lives in the process.
122+
* Needs the learning option on and a key that names the agent's brain: `learning.agentKey`, or, with a soul, the
123+
* soul's id (its `agentId`, else the slug of its `name`). A `learning.agentKey` you set wins. For durable memory
124+
* without learning, set `learning: { mode: 'off' }` with a soul that has an id, or `learning: { agentKey, mode: 'off' }`.
125+
* Without it, memory lives in the process.
124126
*/
125127
store?: { path: string } | { adapter: StorageAdapter; brainId?: string };
126128
/**

0 commit comments

Comments
 (0)