@rolealpha/n8n-nodes-rolealpha 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -48,6 +48,9 @@ next run follows. You don't edit code and you don't republish anything.
48
48
  - **Workflows that follow the organisation.** When a step is created or changed in roleALPHA,
49
49
  or an entity a workflow is bound to changes or is removed, a model proposes what that means for the n8n workflows. The
50
50
  proposal becomes an inactive draft, and only a person filling the deciding role can apply it.
51
+ - **Memory that belongs to the role.** What an agent learns is kept for its role, without
52
+ approval. Give the role to another agent and the memory goes with it. Who decides and who
53
+ fills a role is never kept: it is read from roleALPHA on every run.
51
54
  - **Limits you can change without republishing.** Retries, wait times, run time and tool
52
55
  calls come from a settings table and are clamped to fixed bounds.
53
56
 
@@ -109,13 +112,16 @@ Scheduler (cron) Event router (one webhook)
109
112
  ├ Settings: Resolve (limits from the settings table)
110
113
  ├ Wait: Check Start (lease, duplicate-run guard)
111
114
  ├ Share: Build Input → model → Share: Check (cached)
115
+ ├ Memory: Select (facts of the agent's roles, this step, these records)
112
116
  ├ roleALPHA: Build System Prompt
113
117
  ├ AI Agent (+ data tool limited to the domains of the agent's roles,
114
- │ + roleALPHA: Tool, read only, as the agent)
118
+ │ + roleALPHA: Tool, read only, as the agent,
119
+ │ + remember → Memory: Check Write → add row)
115
120
  └ Wait: Plan After Run (done row, wake-ups, lease released)
116
121
 
117
122
  Scheduler, every tick
118
123
  └ Wait: Find Stale Waits → wake (claimed) · remove dead leases · escalate → Get Circle Lead
124
+ └ Memory: Consolidate → delete replaced, forgotten and expired facts
119
125
  ```
120
126
 
121
127
  **Every read is the agent's own.** With **Connect As: Agent** the node swaps the function
@@ -331,6 +337,66 @@ agent that fills the role. Give these steps custom IDs of one prefix, e.g.
331
337
  `automation:workflow-detect` and `automation:workflow-propose`, and name the prefix in **Own Step
332
338
  Prefixes** on *Propose* (default `automation:`). They then never reach the model.
333
339
 
340
+ ## Memory of roles
341
+
342
+ An agent that runs every month starts every month from nothing, unless it can keep what it
343
+ learned. Here that memory belongs to the **role**, not to the agent. The agent itself carries
344
+ only identity and technology; its work comes from its roles, and so does what it remembers.
345
+ Give the role *Controlling* to another agent, and the new agent knows what the old one
346
+ learned. An agent that no longer fills a role no longer sees its memory.
347
+
348
+ ```
349
+ Runner
350
+ ├ data table: Get rows (Agent Memory)
351
+ ├ Memory: Select only roles the agent fills now (from its bundle), this step and
352
+ │ these records, the newest fact of each topic, within the limits
353
+ ├ Build System Prompt Memory = output of Select: rules for remembering, and the facts
354
+ └ AI Agent
355
+ └ tool remember {fact, role?, scope?, topic?, forget?}
356
+ └ Memory: Check Write → ok: add row · not ok: the reason goes back to the model
357
+ Scheduler
358
+ └ Memory: Consolidate → delete the rows in remove
359
+ ```
360
+
361
+ **Without approval, so the checks decide.** A fact is kept at once; otherwise memory would be
362
+ of no use in daily work. That is why **Check Write** decides what may be kept at all:
363
+
364
+ - Only for a role the agent fills in this run, read from its bundle. Circles and roles the
365
+ agent only reaches through other links do not count, and neither does a role the model
366
+ names on its own.
367
+ - One short fact per call (500 characters). `scope` is `role` (default), `step` (only on this
368
+ step) or `records` (only for these records of this step).
369
+ - A `topic` groups facts: a newer fact on the same role, step, records and topic replaces the
370
+ older one, and `forget` hides the topic. Rows are only ever added; **Consolidate** removes
371
+ what was replaced, forgotten or has expired, and keeps at most `keepMemoryFacts` per role.
372
+ - Secrets (keys, tokens, passwords) are always refused.
373
+ - **What else is never kept, each company decides** in *What Is Never Kept*, since it runs
374
+ its own n8n: e-mail addresses, UUIDs, phone numbers and the names of the persons who fill
375
+ the roles of the step are refused by default. **Blocked Terms** take words such as customer
376
+ names, matched as whole words in any case; an expression can read them from your CRM.
377
+ **Blocked Patterns** take regular expressions, e.g. for an IBAN. The guardrails of the agent
378
+ in roleALPHA still apply: the prompt tells the model not to remember anything they forbid.
379
+
380
+ **Memory is data.** The prompt lists the facts with role, scope and date as notes from earlier
381
+ runs, not as instructions; guardrails, policies and the current step win. The rules tell the
382
+ model never to remember who decides or fills a role: that is read from roleALPHA on every run.
383
+ Something that should change how a role works is not a fact to remember but a change of the
384
+ role or step, proposed as a draft.
385
+
386
+ **Setting it up**
387
+
388
+ 1. Create a data table *Agent Memory* with the columns `role_uuid, step_uuid, record_keys,
389
+ topic, fact, agent_uuid, run_id, at, expires_at`.
390
+ 2. In the runner, read the rows (all, or those whose `role_uuid` is one of the agent's
391
+ roles), run **Memory: Select** and pass its output to **Build System Prompt → Memory**.
392
+ 3. Give the AI Agent a tool `remember`: a sub-workflow that gets `fact`, `role`, `scope`,
393
+ `topic` and `forget` from the model and bundle, step, record keys and run ID from the
394
+ runner, runs **Memory: Check Write** and adds `row` when `ok` is true. It returns the
395
+ result, so the model learns why a fact was refused.
396
+ 4. In the scheduler, run **Memory: Consolidate** on all rows and delete the rows in `remove`.
397
+ Pass the role UUIDs that still exist as **Known Role UUIDs** to remove the memory of
398
+ roles that are gone.
399
+
334
400
  ## Nodes
335
401
 
336
402
  ### roleALPHA (`roleAlpha`)
@@ -350,12 +416,15 @@ Prefixes** on *Propose* (default `automation:`). They then never reach the model
350
416
  | Responsibility | Get Circle Lead | One item per circle of the agent's roles: the role that leads the circle and its holders, e.g. to escalate to. Recognised from a lead flag on the role, else "Lead Link" in its purpose, else a custom ID ending in `:lead`, else the role that decides on or is accountable for the circle. `lead` is null when none is found. | MCP OAuth2 |
351
417
  | Responsibility | Get Role Holders | Returns the persons (with address) and agents filling a role. | MCP OAuth2 |
352
418
  | Tool | Call Tool / List Tools | Calls one roleALPHA MCP tool from an allow list, e.g. as the read tool of an AI agent. Tool name `list` returns the allowed tools with their arguments; the organisation is added. Errors come back as data, a refused run ends it. | MCP OAuth2 |
353
- | Prompt | Build System Prompt | Builds the system prompt from the bundle, the step, the duties and the trigger. Event data is passed as data, never as instructions. With a **Share** it adds the agent's part, what is not its part, the rules for waiting within the step, and returns `task` as the user message. | – |
419
+ | Prompt | Build System Prompt | Builds the system prompt from the bundle, the step, the duties and the trigger. Everything in the bundle's context that is not a role (OKRs, projects, processes, competences, risks, IT systems, …) goes under *Further context*, with the attributes of its link and each value cut to 1,500 characters; the current step is not listed twice. Event data is passed as data, never as instructions. With a **Share** it adds the agent's part, what is not its part, the rules for waiting within the step, and returns `task` as the user message. With **Memory** (output of Memory → Select, also when empty) it adds the rules for remembering and what the agent's roles remember. | – |
354
420
  | Share | Build Input | Prepares the model call that decides the agent's part of a step: only the accountabilities of its own roles count, the other responsible roles of the step are listed with theirs. Returns `systemMessage`, `prompt` and `schema` for a structured output parser. Needs Get Step with Role Details. | – |
355
421
  | Share | Check | Checks the model answer against roleALPHA: drops duties that are no accountability of the agent and needs on roles that are not on the step. Returns `duties` (with `needs`), `notMine`, `waitsFor` and `waitRoleUuids`. | – |
356
422
  | Wait | Plan After Run | Decides what follows a run on a step from the stored wait rows: the `done` row to add, which waiting agents of the same step to wake (their awaited role just delivered), which rows to remove, and which waits are stuck at the attempt limit. Covers a result that arrived while the agent was deciding to wait. | – |
357
423
  | Wait | Check Start | Duplicate-run guard. After the runner added a lease row for its run (`state = running`), the oldest live lease of the same agent, step and records wins. A later start does not run; it returns a `queueRow` that runs when the busy run ends. Leases older than the run timeout are dead and released. Fail-closed when the own lease is missing. | – |
358
424
  | Wait | Find Stale Waits | For a scheduler: waits nobody answered in time (e.g. a person fills the awaited role), queued starts whose busy run died, dead leases, expired rows, and waits at the attempt limit to escalate (`escalate`, reported once). | – |
425
+ | Memory | Check Write | Checks a `remember` call: a role the agent fills (from the bundle), scope, size, secrets, and what the company never keeps. Returns `ok` and the `row` to add, or `error` and `problems` as data. | – |
426
+ | Memory | Select | The facts for the prompt: roles the agent fills now, this step and these records, the newest of each topic, nothing forgotten or expired, within `maxMemoryFacts` and `maxMemoryChars`. Returns `memory` and `omitted`. | – |
427
+ | Memory | Consolidate | For a scheduler: `remove` lists replaced, forgotten and expired rows, rows of roles that are gone (with **Known Role UUIDs**) and rows over `keepMemoryFacts` per role. | – |
359
428
  | Settings | Resolve | Runner limits from defaults and a settings table (`scope, target, key, value`): default < global < step < agent. Every value is clamped to fixed bounds; unknown keys and unusable values are reported in `settingProblems` and never applied. | – |
360
429
  | Schedule | Is Due | Decides from the step `frequency` (and `termin` / due date) whether a run is due in the current period. | – |
361
430
 
@@ -418,6 +487,10 @@ with `scope = global` applies to every run. `step` (target: step UUID or custom
418
487
  | `runTimeoutMinutes` | 15 | 1–120 | A run older than this counts as dead; its lease is released |
419
488
  | `escalate` | true | – | Report stuck waits to the role that leads the circle |
420
489
  | `shareCacheHours` | 24 | 0–720 | Reuse a share decision while step, roles and trigger kind stay the same (0 = never) |
490
+ | `maxMemoryFacts` | 30 | 0–200 | Remembered facts in one prompt (0 = none) |
491
+ | `maxMemoryChars` | 4000 | 0–20000 | Characters of all remembered facts in one prompt |
492
+ | `memoryTtlDays` | 180 | 1–3650 | Days a remembered fact counts; a shorter value also applies to older facts |
493
+ | `keepMemoryFacts` | 200 | 10–2000 | Facts kept per role in the store (Consolidate) |
421
494
 
422
495
  A row with a value outside the bounds is clamped and reported. A wrong row can make the
423
496
  runner more careful, never unbounded.
@@ -442,6 +515,8 @@ record_keys, event, run_id, attempts, progress, at`.
442
515
  change since. The approval link is a signed one-time token for one person and one decision;
443
516
  Check Approver decides at use whether that person may still decide.
444
517
  - Duplicate runs are blocked by leases, and wake-ups are claimed before they fire.
518
+ - Memory belongs to roles the agent fills in the run; secrets are never kept, and what else is
519
+ never kept each company sets itself. Remembered facts reach the prompt as data, with limits.
445
520
  - No credentials are kept in wait, settings or cache rows. The share cache key holds no
446
521
  record content, and a cached answer is checked again like a fresh one.
447
522
 
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Memory of a role. What an agent learns while it does the work of a role belongs to the
3
+ * role, not to the agent: give the role to another agent and the memory goes with it; an
4
+ * agent that loses a role loses its memory. Facts are written without approval, so the
5
+ * checks here decide what may be kept at all.
6
+ *
7
+ * The rows live in a store of the workflow (e.g. an n8n data table); these functions only
8
+ * decide, so the same rules hold wherever the rows are kept. Rows are only ever added:
9
+ *
10
+ * role_uuid the role the fact belongs to (one the agent fills when it writes)
11
+ * step_uuid '' for the whole role, else the step it was learned on
12
+ * record_keys '' unless it concerns certain records of that step
13
+ * topic a newer fact on the same role, step, records and topic replaces an older one
14
+ * fact the fact; '' forgets the topic
15
+ * agent_uuid, run_id, at, expires_at where it came from and until when it counts
16
+ *
17
+ * Safety rules:
18
+ * - Only roles the agent fills in this run, read from its bundle; never one named by the model alone.
19
+ * - Who decides, who fills a role and which rule applies is read from roleALPHA on every run and
20
+ * never kept here. Persons filling the step's roles, e-mail addresses, UUIDs, phone numbers and
21
+ * secrets are refused; each company adds its own terms (e.g. customer names) and patterns.
22
+ * - Memory goes into the prompt as data with its date, never as instructions, and within fixed sizes.
23
+ */
24
+ import type { Step } from './graph';
25
+ import type { BundleItem, ContextBundle } from './prompt';
26
+ /** Name of the tool an agent calls to keep a fact for its role. */
27
+ export declare const REMEMBER_TOOL = "remember";
28
+ export declare const MAX_FACT_CHARS = 500;
29
+ export declare const MAX_TOPIC_CHARS = 80;
30
+ export type MemoryScope = 'role' | 'step' | 'records';
31
+ export interface MemoryRow {
32
+ id?: number | string;
33
+ role_uuid: string;
34
+ step_uuid?: string | null;
35
+ record_keys?: string | null;
36
+ topic?: string | null;
37
+ fact?: string | null;
38
+ agent_uuid?: string | null;
39
+ run_id?: string | null;
40
+ at?: string | null;
41
+ expires_at?: string | null;
42
+ createdAt?: string | null;
43
+ }
44
+ export interface MemoryLimits {
45
+ /** Facts that go into one prompt. */
46
+ maxFacts?: number;
47
+ /** Characters of all facts in one prompt. */
48
+ maxChars?: number;
49
+ /** Days a fact counts after it was written. */
50
+ ttlDays?: number;
51
+ /** Facts kept per role in the store (Consolidate). */
52
+ keepFacts?: number;
53
+ }
54
+ /** What each company decides for itself: its n8n, its rules. */
55
+ export interface MemoryPolicy {
56
+ blockEmails?: boolean;
57
+ blockUuids?: boolean;
58
+ blockPhoneNumbers?: boolean;
59
+ /** Names of the persons who fill the roles of the step (from Get Step with holders). */
60
+ blockPersonNames?: boolean;
61
+ /** Words that may never be kept, e.g. customer names. Whole words, any case. */
62
+ blockedTerms?: string[];
63
+ /** Regular expressions that may never match, e.g. an IBAN. */
64
+ blockedPatterns?: string[];
65
+ }
66
+ export declare const DEFAULT_MEMORY_POLICY: Required<Omit<MemoryPolicy, 'blockedTerms' | 'blockedPatterns'>>;
67
+ export interface RememberRequest {
68
+ fact?: unknown;
69
+ /** Role name or UUID; may be left out when the agent has one role on the step (or one role at all). */
70
+ role?: unknown;
71
+ scope?: unknown;
72
+ topic?: unknown;
73
+ /** Forget the topic instead of keeping a fact. */
74
+ forget?: unknown;
75
+ }
76
+ export interface WriteContext {
77
+ bundle: ContextBundle;
78
+ step?: Pick<Step, 'uuid'> & Partial<Pick<Step, 'responsibleRoles' | 'decidingRoles' | 'accountableRoles'>> | null;
79
+ recordKeys?: unknown;
80
+ runId?: string | null;
81
+ now?: Date;
82
+ ttlDays?: number;
83
+ policy?: MemoryPolicy;
84
+ }
85
+ export type WriteResult = {
86
+ ok: true;
87
+ row: MemoryRow;
88
+ replaces: string;
89
+ } | {
90
+ ok: false;
91
+ error: string;
92
+ problems: string[];
93
+ };
94
+ export interface MemoryFact {
95
+ id: number | string | null;
96
+ role: string;
97
+ roleUuid: string;
98
+ scope: MemoryScope;
99
+ topic: string;
100
+ fact: string;
101
+ at: string | null;
102
+ }
103
+ export interface SelectResult {
104
+ memory: MemoryFact[];
105
+ /** Facts that counted but did not fit into the limits. */
106
+ omitted: number;
107
+ }
108
+ export interface ConsolidateResult {
109
+ /** Row ids to delete: expired, replaced, forgotten, of roles that are gone, beyond the limit per role. */
110
+ remove: Array<number | string>;
111
+ kept: number;
112
+ byRole: Record<string, number>;
113
+ }
114
+ export declare const DEFAULT_MEMORY_LIMITS: Required<MemoryLimits>;
115
+ /** Checks the patterns of a policy once, so a broken one is reported before anything is written. */
116
+ export declare function compilePatterns(patterns: string[] | undefined): RegExp[];
117
+ /** The roles the agent fills itself; circles and roles reached through other links do not count. */
118
+ export declare function ownRoles(bundle: ContextBundle): BundleItem[];
119
+ /** Why a fact may not be kept; empty when it may. */
120
+ export declare function factProblems(fact: string, policy?: MemoryPolicy, step?: WriteContext['step']): string[];
121
+ /** A stable topic: given by the model, else the fact itself, so the same fact twice is kept once. */
122
+ export declare function topicOf(topic: unknown, fact: string): string;
123
+ /** Checks a remember call and returns the row to add. The model gives fact, role, scope and topic; everything else comes from the run. */
124
+ export declare function checkWrite(request: RememberRequest, ctx: WriteContext): WriteResult;
125
+ /** What goes into the prompt: facts of the roles the agent fills now, on this step and these records, newest and closest first. */
126
+ export declare function selectMemory(rowsIn: unknown, ctx: {
127
+ bundle: ContextBundle;
128
+ stepUuid?: string | null;
129
+ recordKeys?: unknown;
130
+ now?: Date;
131
+ limits?: MemoryLimits;
132
+ }): SelectResult;
133
+ /** For a scheduler: which rows to delete, so the store stays small and holds only what still counts. */
134
+ export declare function consolidateMemory(rowsIn: unknown, opts?: {
135
+ now?: Date;
136
+ limits?: MemoryLimits;
137
+ knownRoleUuids?: string[] | null;
138
+ }): ConsolidateResult;
@@ -0,0 +1,325 @@
1
+ "use strict";
2
+ /**
3
+ * Memory of a role. What an agent learns while it does the work of a role belongs to the
4
+ * role, not to the agent: give the role to another agent and the memory goes with it; an
5
+ * agent that loses a role loses its memory. Facts are written without approval, so the
6
+ * checks here decide what may be kept at all.
7
+ *
8
+ * The rows live in a store of the workflow (e.g. an n8n data table); these functions only
9
+ * decide, so the same rules hold wherever the rows are kept. Rows are only ever added:
10
+ *
11
+ * role_uuid the role the fact belongs to (one the agent fills when it writes)
12
+ * step_uuid '' for the whole role, else the step it was learned on
13
+ * record_keys '' unless it concerns certain records of that step
14
+ * topic a newer fact on the same role, step, records and topic replaces an older one
15
+ * fact the fact; '' forgets the topic
16
+ * agent_uuid, run_id, at, expires_at where it came from and until when it counts
17
+ *
18
+ * Safety rules:
19
+ * - Only roles the agent fills in this run, read from its bundle; never one named by the model alone.
20
+ * - Who decides, who fills a role and which rule applies is read from roleALPHA on every run and
21
+ * never kept here. Persons filling the step's roles, e-mail addresses, UUIDs, phone numbers and
22
+ * secrets are refused; each company adds its own terms (e.g. customer names) and patterns.
23
+ * - Memory goes into the prompt as data with its date, never as instructions, and within fixed sizes.
24
+ */
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.DEFAULT_MEMORY_LIMITS = exports.DEFAULT_MEMORY_POLICY = exports.MAX_TOPIC_CHARS = exports.MAX_FACT_CHARS = exports.REMEMBER_TOOL = void 0;
27
+ exports.compilePatterns = compilePatterns;
28
+ exports.ownRoles = ownRoles;
29
+ exports.factProblems = factProblems;
30
+ exports.topicOf = topicOf;
31
+ exports.checkWrite = checkWrite;
32
+ exports.selectMemory = selectMemory;
33
+ exports.consolidateMemory = consolidateMemory;
34
+ const waits_1 = require("./waits");
35
+ /** Name of the tool an agent calls to keep a fact for its role. */
36
+ exports.REMEMBER_TOOL = 'remember';
37
+ exports.MAX_FACT_CHARS = 500;
38
+ exports.MAX_TOPIC_CHARS = 80;
39
+ exports.DEFAULT_MEMORY_POLICY = {
40
+ blockEmails: true,
41
+ blockUuids: true,
42
+ blockPhoneNumbers: true,
43
+ blockPersonNames: true,
44
+ };
45
+ exports.DEFAULT_MEMORY_LIMITS = { maxFacts: 30, maxChars: 4000, ttlDays: 180, keepFacts: 200 };
46
+ const DAY = 86_400_000;
47
+ const lower = (v) => String(v ?? '').trim().toLowerCase();
48
+ const EMAIL = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i;
49
+ const UUID_ANYWHERE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
50
+ /** International numbers (+43 …, 0043 …) and local ones with an area code (0664 1234567). */
51
+ const PHONE = /(?:\+|\b00)\d[\d\s/().-]{6,}\d|\b0\d{2,4}[\s/-]?\d{4,}\b/;
52
+ /** Secrets are refused everywhere; this is not configurable. */
53
+ const SECRETS = [
54
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
55
+ /\b(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{10,}/,
56
+ /\bgh[pousr]_[A-Za-z0-9]{20,}/,
57
+ /\bxox[abpr]-[A-Za-z0-9-]{10,}/,
58
+ /\bagt_[A-Za-z0-9]{10,}/,
59
+ /\bAKIA[0-9A-Z]{16}\b/,
60
+ /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\./,
61
+ /\b(?:passwor[dt]|kennwort|secret|api[_-]?key|token)\s*[:=]\s*\S+/i,
62
+ ];
63
+ function escapeRegExp(s) {
64
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
65
+ }
66
+ /** A term as a whole word, in any case unless asked otherwise, also with umlauts and other letters. */
67
+ function wordPattern(term, caseSensitive = false) {
68
+ return new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(term)}(?![\\p{L}\\p{N}])`, caseSensitive ? 'u' : 'iu');
69
+ }
70
+ /** Checks the patterns of a policy once, so a broken one is reported before anything is written. */
71
+ function compilePatterns(patterns) {
72
+ return (patterns ?? [])
73
+ .map((p) => p.trim())
74
+ .filter(Boolean)
75
+ .map((p) => {
76
+ try {
77
+ return new RegExp(p, 'iu');
78
+ }
79
+ catch (error) {
80
+ throw new Error(`Blocked pattern "${p}" is not a valid regular expression: ${error.message}`);
81
+ }
82
+ });
83
+ }
84
+ /** The roles the agent fills itself; circles and roles reached through other links do not count. */
85
+ function ownRoles(bundle) {
86
+ return (bundle.context ?? []).filter((c) => {
87
+ if (c.kind !== 'role')
88
+ return false;
89
+ const rel = c.provenance?.relType;
90
+ if (rel)
91
+ return rel === 'AGENT_FULFILLS_ROLE';
92
+ return lower(c.body?.subtype) !== 'circle';
93
+ });
94
+ }
95
+ function personNames(step) {
96
+ if (!step)
97
+ return [];
98
+ const roles = [...(step.responsibleRoles ?? []), ...(step.decidingRoles ?? []), ...(step.accountableRoles ?? [])];
99
+ const names = roles.flatMap((r) => (r.holders?.persons ?? []).map((p) => String(p.name ?? '').trim()));
100
+ return Array.from(new Set(names.filter((n) => n.length >= 3)));
101
+ }
102
+ /** Why a fact may not be kept; empty when it may. */
103
+ function factProblems(fact, policy = {}, step = null) {
104
+ const p = { ...exports.DEFAULT_MEMORY_POLICY, ...policy };
105
+ const problems = [];
106
+ if (SECRETS.some((r) => r.test(fact)))
107
+ problems.push('it looks like a secret (key, token or password)');
108
+ if (p.blockEmails && EMAIL.test(fact))
109
+ problems.push('it contains an e-mail address');
110
+ if (p.blockUuids && UUID_ANYWHERE.test(fact))
111
+ problems.push('it contains a UUID');
112
+ if (p.blockPhoneNumbers && PHONE.test(fact))
113
+ problems.push('it contains a phone number');
114
+ if (p.blockPersonNames) {
115
+ // The full name in any case, and each part as written, so "Ada" is caught as well as
116
+ // "ada lovelace", while a first name like "Max" does not refuse "max. 5 per day".
117
+ for (const name of personNames(step)) {
118
+ const parts = name.split(/\s+/).filter((w) => w.length >= 3);
119
+ if (wordPattern(name).test(fact) || parts.some((w) => wordPattern(w, true).test(fact))) {
120
+ problems.push('it names a person who fills a role of this step; who does what is read from roleALPHA on every run');
121
+ break;
122
+ }
123
+ }
124
+ }
125
+ for (const term of (p.blockedTerms ?? []).map((t) => t.trim()).filter(Boolean)) {
126
+ if (wordPattern(term).test(fact)) {
127
+ problems.push('it contains a term this company does not keep in memory');
128
+ break;
129
+ }
130
+ }
131
+ for (const re of compilePatterns(p.blockedPatterns)) {
132
+ if (re.test(fact)) {
133
+ problems.push('it matches a pattern this company does not keep in memory');
134
+ break;
135
+ }
136
+ }
137
+ return problems;
138
+ }
139
+ /** A stable topic: given by the model, else the fact itself, so the same fact twice is kept once. */
140
+ function topicOf(topic, fact) {
141
+ const raw = String(topic ?? '').trim() || fact;
142
+ return raw
143
+ .toLowerCase()
144
+ .replace(/[^\p{L}\p{N}]+/gu, ' ')
145
+ .trim()
146
+ .slice(0, exports.MAX_TOPIC_CHARS)
147
+ .trim();
148
+ }
149
+ function refuse(error, problems = []) {
150
+ return { ok: false, error, problems };
151
+ }
152
+ /** Checks a remember call and returns the row to add. The model gives fact, role, scope and topic; everything else comes from the run. */
153
+ function checkWrite(request, ctx) {
154
+ const now = ctx.now ?? new Date();
155
+ const roles = ownRoles(ctx.bundle);
156
+ if (roles.length === 0)
157
+ return refuse('The agent fills no role in this run, so there is nothing to remember for.');
158
+ // The role: named by UUID or name, else the only own role on the step, else the only own role.
159
+ const wanted = lower(request.role);
160
+ let role;
161
+ if (wanted) {
162
+ role = roles.find((r) => lower(r.uuid) === wanted || lower(r.name) === wanted);
163
+ if (!role)
164
+ return refuse(`"${String(request.role)}" is not a role this agent fills. Use one of: ${roles.map((r) => r.name).join(', ')}.`);
165
+ }
166
+ else {
167
+ const onStep = ctx.step?.responsibleRoles ? roles.filter((r) => ctx.step.responsibleRoles.some((s) => lower(s.uuid) === lower(r.uuid))) : [];
168
+ const candidates = onStep.length ? onStep : roles;
169
+ if (candidates.length !== 1)
170
+ return refuse(`Name the role the fact belongs to: ${candidates.map((r) => r.name).join(', ')}.`);
171
+ role = candidates[0];
172
+ }
173
+ const scope = (lower(request.scope) || 'role');
174
+ if (!['role', 'step', 'records'].includes(scope))
175
+ return refuse('Scope is one of role, step or records.');
176
+ const stepUuid = lower(ctx.step?.uuid);
177
+ const records = (0, waits_1.recordKey)(ctx.recordKeys);
178
+ if (scope !== 'role' && !stepUuid)
179
+ return refuse(`Scope "${scope}" needs a step; this run has none. Use scope role.`);
180
+ if (scope === 'records' && !records)
181
+ return refuse('Scope "records" needs records; this run has none. Use scope step or role.');
182
+ const forget = request.forget === true || lower(request.forget) === 'true';
183
+ const fact = forget ? '' : String(request.fact ?? '').replace(/\s+/g, ' ').trim();
184
+ if (!forget && !fact)
185
+ return refuse('Give the fact to remember, or set forget with the topic.');
186
+ if (fact.length > exports.MAX_FACT_CHARS)
187
+ return refuse(`The fact has ${fact.length} characters; keep it under ${exports.MAX_FACT_CHARS}, one fact per call.`);
188
+ const topic = topicOf(request.topic, fact);
189
+ if (!topic)
190
+ return refuse('Give a topic for what to forget.');
191
+ const problems = factProblems(`${fact} ${String(request.topic ?? '')}`, ctx.policy, ctx.step);
192
+ if (problems.length)
193
+ return refuse(`Not kept: ${problems.join('; ')}.`, problems);
194
+ const ttlDays = ctx.ttlDays ?? exports.DEFAULT_MEMORY_LIMITS.ttlDays;
195
+ const row = {
196
+ role_uuid: lower(role.uuid),
197
+ step_uuid: scope === 'role' ? '' : stepUuid,
198
+ record_keys: scope === 'records' ? records : '',
199
+ topic,
200
+ fact,
201
+ agent_uuid: lower(ctx.bundle.agent?.uuid),
202
+ run_id: ctx.runId ?? '',
203
+ at: now.toISOString(),
204
+ expires_at: new Date(now.getTime() + ttlDays * DAY).toISOString(),
205
+ };
206
+ return { ok: true, row, replaces: groupKey(row) };
207
+ }
208
+ function timeOf(row) {
209
+ const t = Date.parse(String(row.at ?? row.createdAt ?? ''));
210
+ return Number.isFinite(t) ? t : 0;
211
+ }
212
+ function newestFirst(a, b) {
213
+ const d = timeOf(b) - timeOf(a);
214
+ if (d !== 0)
215
+ return d;
216
+ const na = Number(a.id);
217
+ const nb = Number(b.id);
218
+ return Number.isFinite(na) && Number.isFinite(nb) ? nb - na : String(b.id ?? '').localeCompare(String(a.id ?? ''));
219
+ }
220
+ function groupKey(row) {
221
+ return [lower(row.role_uuid), lower(row.step_uuid), (0, waits_1.recordKey)(row.record_keys), lower(row.topic) || topicOf('', String(row.fact ?? ''))].join('|');
222
+ }
223
+ function expired(row, now, ttlDays) {
224
+ const until = Date.parse(String(row.expires_at ?? ''));
225
+ if (Number.isFinite(until) && until <= now)
226
+ return true;
227
+ const at = timeOf(row);
228
+ // A shorter lifetime in the settings counts for rows written before it.
229
+ return at > 0 && at + ttlDays * DAY <= now;
230
+ }
231
+ /** The newest row of each topic; a forgotten topic (empty fact) drops out. */
232
+ function current(rows) {
233
+ const groups = new Map();
234
+ for (const r of rows) {
235
+ const k = groupKey(r);
236
+ groups.set(k, [...(groups.get(k) ?? []), r]);
237
+ }
238
+ const latest = [];
239
+ const replaced = [];
240
+ const forgotten = [];
241
+ for (const list of groups.values()) {
242
+ const [first, ...rest] = [...list].sort(newestFirst);
243
+ replaced.push(...rest);
244
+ if (String(first.fact ?? '').trim())
245
+ latest.push(first);
246
+ else
247
+ forgotten.push(first);
248
+ }
249
+ return { latest, replaced, forgotten };
250
+ }
251
+ function usable(rows) {
252
+ return (Array.isArray(rows) ? rows : []).filter((r) => !!r && typeof r === 'object' && !!r.role_uuid);
253
+ }
254
+ /** What goes into the prompt: facts of the roles the agent fills now, on this step and these records, newest and closest first. */
255
+ function selectMemory(rowsIn, ctx) {
256
+ const limits = { ...exports.DEFAULT_MEMORY_LIMITS, ...ctx.limits };
257
+ const now = (ctx.now ?? new Date()).getTime();
258
+ const roles = new Map(ownRoles(ctx.bundle).map((r) => [lower(r.uuid), r.name]));
259
+ const step = lower(ctx.stepUuid);
260
+ const records = (0, waits_1.recordKey)(ctx.recordKeys);
261
+ const relevant = usable(rowsIn).filter((r) => {
262
+ if (!roles.has(lower(r.role_uuid)))
263
+ return false;
264
+ const rowStep = lower(r.step_uuid);
265
+ if (rowStep && rowStep !== step)
266
+ return false;
267
+ const rowRecords = (0, waits_1.recordKey)(r.record_keys);
268
+ if (rowRecords && (!records || !(0, waits_1.sameRecords)(rowRecords, records)))
269
+ return false;
270
+ return true;
271
+ });
272
+ const { latest } = current(relevant);
273
+ const live = latest.filter((r) => !expired(r, now, limits.ttlDays));
274
+ const rank = (r) => ((0, waits_1.recordKey)(r.record_keys) ? 0 : lower(r.step_uuid) ? 1 : 2);
275
+ live.sort((a, b) => rank(a) - rank(b) || newestFirst(a, b));
276
+ const memory = [];
277
+ let chars = 0;
278
+ for (const r of live) {
279
+ const fact = String(r.fact ?? '').trim().slice(0, exports.MAX_FACT_CHARS);
280
+ if (memory.length >= limits.maxFacts || chars + fact.length > limits.maxChars)
281
+ continue;
282
+ chars += fact.length;
283
+ memory.push({
284
+ id: r.id ?? null,
285
+ role: roles.get(lower(r.role_uuid)) ?? '',
286
+ roleUuid: lower(r.role_uuid),
287
+ scope: (0, waits_1.recordKey)(r.record_keys) ? 'records' : lower(r.step_uuid) ? 'step' : 'role',
288
+ topic: lower(r.topic),
289
+ fact,
290
+ at: r.at ?? r.createdAt ?? null,
291
+ });
292
+ }
293
+ return { memory, omitted: live.length - memory.length };
294
+ }
295
+ /** For a scheduler: which rows to delete, so the store stays small and holds only what still counts. */
296
+ function consolidateMemory(rowsIn, opts = {}) {
297
+ const limits = { ...exports.DEFAULT_MEMORY_LIMITS, ...opts.limits };
298
+ const now = (opts.now ?? new Date()).getTime();
299
+ const known = opts.knownRoleUuids && opts.knownRoleUuids.length ? new Set(opts.knownRoleUuids.map(lower)) : null;
300
+ const rows = usable(rowsIn);
301
+ const remove = new Set();
302
+ const drop = (r) => r.id !== undefined && r.id !== null && r.id !== '' && remove.add(r.id);
303
+ const { latest, replaced, forgotten } = current(rows);
304
+ replaced.forEach(drop);
305
+ forgotten.forEach(drop);
306
+ const byRole = {};
307
+ for (const r of latest) {
308
+ const role = lower(r.role_uuid);
309
+ if (expired(r, now, limits.ttlDays) || (known && !known.has(role))) {
310
+ drop(r);
311
+ continue;
312
+ }
313
+ (byRole[role] ??= []).push(r);
314
+ }
315
+ const counts = {};
316
+ let kept = 0;
317
+ for (const [role, list] of Object.entries(byRole)) {
318
+ list.sort(newestFirst);
319
+ list.slice(limits.keepFacts).forEach(drop);
320
+ counts[role] = Math.min(list.length, limits.keepFacts);
321
+ kept += counts[role];
322
+ }
323
+ return { remove: Array.from(remove), kept, byRole: counts };
324
+ }
325
+ //# sourceMappingURL=memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory.js","sourceRoot":"","sources":["../../lib/memory.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;;;AAsIH,0CAWC;AAGD,4BAOC;AAUD,oC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