↓ Skip to main content
Persistent Memory for MES Agents: Approved Rules and Semantic Search
  1. Posts/

Persistent Memory for MES Agents: Approved Rules and Semantic Search

·16 mins· loading · loading · ·
Table of Contents

An agent should not ask a person the same question twice. It should learn from the answer, and to do that it needs memory.

In last week’s post the agent asked, a person answered, and the answer helped exactly one file. In this post the answer becomes an MES rule that the agent uses on every file after it.


Overview
#

The setup is the one from the agentic framework post: a Connect IoT controller watches a folder, the File Parser for DataCollection agent maps each file to a Data Collection, and when it is unsure it asks a person through a notification.

For this post I dropped the same file into the controller three times on a local MES v12 stack:

RunWhat the agent hasResult
1No rulesneeds_review, a person answers, the agent proposes a rule
2The approved rule, sent in the promptPosted without a review
3No rules in the prompt, plus a search tool over six rules in the MESPosted without a review

The post follows that order. Part 1 is about rules: memory kept as approved MES data. Part 2 is about RAG: the agent searches for the rule that fits its case.

I always shoutout to this great article from IBM about what is RAG (retrieval augmented generation), check it out to learn more on the concept What is RAG (Retrieval Augmented Generation)? | IBM

The Inspection Report
#

The file is a full inspection report of housing A12. The top face flatness was measured twice, once per probe.

HOUSING A12 - FULL INSPECTION REPORT
Feature                         Actual    Unit
Bore D1 Diameter                12.004    mm
Bore D2 Diameter                7.998     mm
Bore Distance D1-D2             41.998    mm
Bore D1 Roundness               0.0040    mm
Bore D2 True Position           0.021     mm
Flatness Top Face (probe 1)     0.012     mm
Flatness Top Face (probe 2)     0.018     mm
Parallelism Top to Base         0.010     mm
Overall Length                  84.512    mm
Overall Width                   32.006    mm

The Data Collection’s Flatness parameter takes one reading per sample, and both values fit it. The agent’s instructions say that when two values in the file could fit the same parameter, it must not choose one. A simple parser would take the first match and post it without any warning.

In this example, probe 1 is the reference probe and probe 2 sits next to the fixture clamp, where clamping can bend the face, so its reading is for information only. The plant’s quality engineer decides which probe is the reference, so a person approves every rule the agent proposes.

Part 1: Rules
#

Run 1: The Agent Asks for a Review
#

The agent answered with needs_review, and the Run Agent task opened a notification. Both flatness readings are under Unmapped, Flatness is under Missing, and Applied Rules is empty.

The review notification
Run 1: needs_review, two flatness candidates, no applied rules.

In the Respond wizard the agent explains the problem: two values, one reading per sample, and “I did not choose between them”.

The agent’s request
The agent’s request in the Respond wizard.

A person can answer for this file only (“use 0.012”) or for every report like it. To get a rule out of it, the answer has to be the second kind:

The answer
“This is a general rule for every Housing A12 inspection report, not only this file… Please propose this as a reusable rule.”

The agent ran again with the answer and returned ok. The task cleared the notification and posted the Data Collection with Flatness Top Face = 0.012.

The request is closed
After one answer the request is closed.
Run 1 posted
DC_Housing_A12_FullInspection-000000015: Flatness Top Face 0.012, the probe 1 reading.

Up to here this is the flow from last week. The controller log shows one new line, between clearing the notification and posting the data:

09:35:51 RunAgent: HITL-12cef2f8-… cleared, the agent's result needs no further review
09:35:51 RunAgent: learned rule 'housing-a12-flatness-use-probe-1-4a35' persisted (waiting for approval)
09:35:52 dataCollection: Successfully performed data into Resource FileParserResource.

The Agent Proposes the Rule, a Person Approves It
#

The agent’s reply now has a proposedRules array next to the mappings. When a result is accepted after at least one human answer, the Run Agent task creates one AgentMemory instance per proposed rule. AgentMemory is a custom MES entity type.

The agent memory entity will store all the information that was added to the contextual information reality provides. The entity will store context and rules so that the agents know if for their case these rules apply.

The proposed rule
The rule the agent wrote from the answer, with IsActive set to No.
PropertyRole
NameWhat the agent cites in appliedRules
AppliesToThe process the rule belongs to (lookup, here FileIntegration)
ScopeThe kind of outcome it leads to (lookup, here DataCollection)
SummaryOne line that is always sent to the agent, enough to tell whether the rule is relevant
WhenThe situation the rule is for
GuidanceWhat to do in that situation
ExampleOptional input and output
IsActive, ApprovedBy, ApprovedOnApproval and who gave it

The situation (When) and the instruction (Guidance) are separate properties on purpose. Part 2 embeds the situation and the one-line Summary, not the full Guidance.

The task creates the rule inactive, because one conversation with one person is not enough to change how every future file is read. A process engineer opens it under Administration → Agent Memory, checks it, and approves it.

Approving the rule
Approval is an edit: IsActive on, ApprovedBy and ApprovedOn set.

Agents that write their own memory have a known problem. In reflection and similar designs, the agent writes lessons from its failures and reuses them in later prompts, and a wrong lesson keeps being applied until someone notices. Some memory systems such let the agent edit its long-term memory itself. The approval step prevents this here, because the agent does not use a rule until a person approves it. In our scenario we want a human in the loop for the creation of rules.

I keep the rules as an MES entity, rather than in a text file or a chat history, because then they get what every other MES record gets: history of every change, security on who can edit and approve, the same Create/Save/Terminate lifecycle, and master data export to other environments. A process engineer can see every rule the agent uses and who approved it. This is sometimes called a procedural memory (how to do a task) kept as MES data instead of model weights.

How Rules Reach the Agent
#

The agent keeps no state between runs, so the rules have to be in the prompt. The RunAgentPrompt service takes the run’s AppliesTo and Scope, selects the active rules for them, newest approval first, and appends an <agent_memory> block to the prompt:

<agent_memory>
Rules from earlier human reviews. If one matches the case, read it in full with get_object_by_name
(entity type AgentMemory) before applying it unless its guidance is shown, follow it over your own
judgement and name it in appliedRules. If none matches and you are unsure, ask for review as you normally would.
housing-a12-flatness-use-probe-1-4a35 · DataCollection · Housing A12 reports with Flatness Top Face per probe: post probe 1 to Flatness, list probe 2 as unmapped. · Map the probe 1 reading to the Flatness parameter with high confidence. …
</agent_memory>

The MES service adds this block after the controller has sent its prompt.

There is one line per rule. The Guidance is included when it is short (up to 300 characters by default). For a longer one, the agent reads the full rule with the stock get_object_by_name tool of the CM MES MCP server. The goal is to provide just enough amount of context, in order for the agent to make decisions, but provide also a way for the agent if he so requires to grab the full information from the MES.

Run 2: Posted Without a Review
#

The same file, with the rule approved:

09:38:15 RunAgent: calling agent 'File Parser for DataCollection' (prompt: 932 characters)
09:38:36 RunAgent: agent 'File Parser for DataCollection' answered in 21549 ms (response: 1954 characters)
09:38:36 dataCollection: Successfully performed data into Resource FileParserResource.

This time the task created no notification. Run 1 stopped on the same file without the rule, so now with the rules for that AppliesTo and Scope the agent had enough information to make a decision without requesting a human in the loop intervention. With different files or different information, those rules may not be enough, in that case the agent will ask the human what to do and in turn generate new rules.

Run 2 posted
-000000016: posted on the first pass with the value the rule gives.

For many plants this is enough. However, every run gets every active rule of its AppliesTo and Scope, relevant or not, and rules are selected by those two labels, not by what the file contains. With five rules that is fine. Beyond that, the cap leaves the oldest rules out, and raising it makes every prompt longer. Even below the cap, a long prompt costs accuracy: models use information in the middle of a long context worse than information at its start or end.

Part 2: RAG and Embeddings
#

Part 1 was leveraging information that we already knew about the scenario and using that to extract and provide immediately all the memory rules. In Part 2 we are going to show a totally different approach, but using the exact same rules.

Searching Rules by Meaning
#

An embedding is a list of numbers (a vector) that a model computes from a text. Texts with similar meaning get vectors that are close to each other. To search, you compute the vector of the question and return the stored texts with the smallest cosine distance to it (0 means the same direction, larger means less related).

That search is the retrieval in Retrieval-Augmented Generation (RAG). The agent no longer gets every rule in the prompt. When it is stuck, it describes its case and gets back the few rules closest to it.

MES v12 Already Keeps the Vectors
#

MES v12 ships a RAG service, core-rag. It indexes every entity type that has Semantic Search Enabled and whose operations publish events to Kafka. When an instance is created, saved or terminated, core-rag asks the MES for the instance’s texts, computes the embedding with the stack’s embedding model and stores the vector in ClickHouse. Every instance that is not terminated is indexed, inactive rules included, and terminated ones are removed. Filtering on IsActive happens later, in the MCP server. For AgentMemory, an install-time process rule turns on Semantic Search and the Kafka events, so we do not run a vector database of our own.

We had to decide two things ourselves.

What gets embedded. By default core-rag embeds the Name and Description. For a rule, the Name is a slug and the Description is not enough. But we can with a simple DEE enrich this a bit more. A DEE on the Post action group of GetEmbeddingAndContextTextsForEntityType replaces both texts for AgentMemory:

texts[id] = new EmbeddingAndContextText
{
    // what a query is matched against: the situation, not the fix
    EmbeddingText = $"# When\n{Value("When")}\n\n# Summary\n{Value("Summary")}",
    // what the search returns: the full rule, in a fixed format the MCP server parses
    ContextText =
        $"# Rule: {Value("Name")}\n" +
        $"AppliesTo: {Value("AppliesTo")}\n" +
        $"Scope: {Value("Scope")}\n" +
        $"IsActive: {(rule.GetNativeValue<bool?>("IsActive") == true ? "true" : "false")}\n" +
        $"\n## Summary\n{Value("Summary")}\n" +
        $"\n## When\n{Value("When")}\n" +
        $"\n## Guidance\n{Value("Guidance")}" +
        (string.IsNullOrWhiteSpace(example) ? "" : $"\n\n## Example\n{example}"),
};

The agent searches with a description of its problem, so the embedded text is the rule’s When and its one-line Summary, which carries a short form of the fix. The full Guidance is left out.  If we embedded the full Guidance, rules would be matched mostly by the fix they prescribe, and the agent does not know the fix when it searches.

Who can search. core-rag answers retrieval requests over HTTP, but none of the stock MCP tools searches the instances of a custom entity type. We wrote a small ASP.NET Core MCP server with one tool, search_agent_memory(query, appliesTo?, scope?, topK). It forwards the caller’s MES token to core-rag, so the user’s data groups and security still apply. It asks for the 20 closest rules, keeps the active ones with the right AppliesTo and Scope, and returns them as JSON with their distances.

Does It Find the Right Rule?
#

With only one rule stored, any search returns it, so before run 3 I added five more approved rules for the same process and category. They are realistic neighbors: a Bore D1 measured before and after deburring, a dial indicator with no recorded unit, two roughness traces, a fixture offset on another part, and a repeated leak test.

I searched them with two different descriptions of the flatness case, and with one about the bore:

QueryClosest rules (cosine distance)
“Flatness Top Face reported twice, probe 1 and probe 2: which reading goes to Flatness?”flatness probe rule 0.253, dial indicator unit 0.420, roughness traces 0.525, … leak test 0.654
“top face flatness measured by two probes, 0.012 and 0.018, one reading per sample”flatness probe rule 0.274, dial indicator unit 0.438, roughness traces 0.488, … leak test 0.680
“Bore D1 diameter as found and after deburr”deburr rule 0.282, dial indicator unit 0.499, fixture offset 0.536, … flatness probe rule 0.623

Both flatness questions put the flatness rule first with a clear gap to the next one, and the bore question puts it near the bottom. These questions share words with the rule (flatness, top face, probe), though, so they do not show whether the search matches meaning or only shared words. The rule’s embedded text is its When, “A Housing A12 inspection report gives Flatness Top Face twice, once per probe (probe 1 and probe 2), and the Flatness parameter accepts only 1 reading per sample.”, plus its Summary, “Housing A12 reports with Flatness Top Face per probe: post probe 1 to Flatness, list probe 2 as unmapped.” I also searched with two paraphrases that share no content word with either:

QueryClosest rules (cosine distance)
“two sensors disagree on how even the upper surface is”flatness probe rule 0.496, roughness traces 0.523, dial indicator unit 0.536, …
“the gauge beside the clamp reads higher than the other one on the lid, which value counts?”dial indicator unit 0.487, flatness probe rule 0.538, deburr rule 0.539, …

Without shared words the right rule is still near the top, but the margin is small or gone. That is why the agent’s instructions tell it to put the label as written in the file into its query, and why a rule’s When should use the words the files use. The search returns five rules, and the agent is instructed to read each one’s When and apply it only when it matches, so a right rule in second place is still among those it receives. Of course in a real scenario we may have thousands of rules, here will be where the semantic search really becomes important.

When the Prompt and the Search Disagree
#

If we keep the rules from the Scope and Applies To, with rules coming from two places, they can contradict each other. The agent’s instructions decide when to search and which rule wins:

* When a mapping is still ambiguous after the rules in the <agent_memory> block, or the message has no
  block, call search_agent_memory (MCP server MESProject Agent Memory) with query = a short description of the
  case: the label as written in the file, its value and unit, and what is ambiguous. Read each returned
  rule's when and apply it only when it matches the case.
* Rules provided in the prompt (the <agent_memory> block and the rules you fetched for it) take
  precedence over rules returned by search_agent_memory. When both cover the case and disagree,
  follow the prompt's rule. Use a searched rule only for what the prompt's rules do not settle.

The rules in the prompt were selected for this process and category. Remember, the search returns the closest matches by meaning, which can include a rule written for a different case. This is one of the great advantages of using RAG which means we can leverage global rule context to make decisions, the downside is that we are giving the responsibility to the model to interpret if that rule applies and makes sense for his use case. That’s why we need to provide as much valuable context and meaning as possible in order for it to make decisions.

Run 3: The Agent Searches
#

To show the search on its own, I switched the prompt index off for this run by setting the index cap to 1 character. No rule line fits, and when no line fits the service adds no <agent_memory> block at all, so the prompt is the same as in run 1. This means that no rules will be provided to the prompt, even if they have a matching Scope or AppliesTo.

Index switched off
For the demo only: IndexMaxCharacters set to 1, so the prompt has no rules.

Then I added the tool to the agent. MCP servers are MES entities, and the AI Agent page has a wizard to choose which of their tools an agent may use:

Attaching the tool
MESProject Agent Memory → search_agent_memory, next to the stock CM MES tools.

The controller log for the same file, with the six rules stored:

11:44:37 RunAgent: calling agent 'File Parser for DataCollection' (prompt: 932 characters)
11:45:01 RunAgent: agent 'File Parser for DataCollection' answered in 24461 ms (response: 2021 characters)
11:45:02 dataCollection: Successfully performed data into Resource FileParserResource.

The MCP server’s log shows the tool call. The tool returns five rules by default, the closest five of the six it retrieved:

info: ModelContextProtocol.Server.McpServer
      Server (Cmf.Custom.MESProject.AgentMemoryMCPServer 1.0.0.0) method 'tools/call' request handler called.
dbug: Cmf.Custom.MESProject.AgentMemoryMCPServer.Tools.AgentMemoryTools
      Agent memory search returned 5 of 6 retrieved rules.
info: ModelContextProtocol.Server.McpServer
      Server (Cmf.Custom.MESProject.AgentMemoryMCPServer 1.0.0.0) method 'tools/call' request handler completed in 940.861ms.

The server logs its outgoing messages at Trace level but not the incoming arguments, so the query the agent wrote is not in the log. The answer it received, in order:

DistanceRule
0.232housing-a12-flatness-use-probe-1-4a35
0.412housing-a12-di2-roundness-micrometres
0.489housing-a12-roughness-two-traces
0.558housing-a12-bore-d1-after-deburr
0.565bracket-b7-length-fixture-offset

As in run 1, the prompt had no rules. The agent’s query put the flatness rule first at 0.232, closer than any of my test queries, and the file was posted without a review.

Run 3 posted
Flatness Top Face 0.012, posted on the first pass after the search returned the flatness rule first.

Rules or RAG?
#

We use both, for different cases.

Rule index in the promptSearch through RAG
How rules are selectedBy AppliesTo and ScopeBy meaning of the case, then filtered by AppliesTo, Scope and IsActive
Number of rulesAbout five with inline Guidance at the default 2000-character cap (adjustable)Not limited by the prompt, since only the closest are returned. Tested here with six; with many similar rules, queries must use the files’ own words (see the paraphrase results)
What each run adds to the promptEvery rule of the category, every runNo rules in the prompt; one tool call when a mapping is still ambiguous
When they disagreeThe prompt’s rule winsUsed for what the prompt does not cover
Cost of the lookup in this demoNone beyond the longer promptThe search took 0.94 s, and the requirement to call external MCPs will probably incur a bigger token cost

Rules that apply to most files of a process belong in the index. A large archive of narrow rules, each for one supplier or one report layout, belongs in the search.

Final Thoughts
#

Last week the human in the loop kept the agent from guessing. With memory, a person’s answer becomes a rule, and the agent uses it on the next file without asking again.

Related