Commit ae1a70a0 authored by Lisa (AI Assistant)'s avatar Lisa (AI Assistant)

feat: add hermes three-tier mempalace memory plugin

parents
Pipeline #320 canceled with stages
# DOCUMENTATION
## Overview
`hermes-three-tier-memory` is a Hermes plugin that adds a layered memory architecture without modifying Hermes core.
### Storage layers
- **Tier 1**: active working memory in `~/.hermes/memories/MEMORY.md`
- **Tier 2**: rolling daily summaries in `~/.hermes/memories/daily/`
- **Tier 3**: MemPalace long-term storage accessed over MCP
## Design goals
- Keep memory behavior outside Hermes core
- Preserve backward compatibility with legacy MemPalace content
- Improve retrieval relevance using taxonomy and wing-aware search
- Support safe evolution of taxonomy over time
## Taxonomy model
### Wings
Default wings:
- `identity`
- `governance`
- `systems`
- `work`
- `history`
- `relationships`
Additional wings can be created dynamically or manually.
### Rooms
Each wing contains rooms represented in `taxonomy.json`.
Rooms are used for:
- classification
- organization
- search targeting
- lifecycle maintenance
## Tool behavior
### `status`
Returns current plugin state, daily file status, retention, and taxonomy summary.
### `search`
Searches daily memory first, then falls back to MemPalace if confidence is weak or empty.
### `search_long_term`
Direct MemPalace search.
### `maintain`
Compacts current memory, writes daily summary, promotes summary lines to MemPalace, and writes a diary entry.
### `taxonomy`
Shows full or filtered taxonomy.
### Lifecycle actions
- `create_wing`
- `create_room`
- `update_wing`
- `update_room`
- `move_room`
- `delete_room`
- `delete_wing`
Delete actions optionally purge live MemPalace drawers when `dry_run=false`.
### `list_memories`
Lists drawers from MemPalace, optionally filtered by wing/room.
### `migrate_legacy`
Reclassifies legacy-seeded content into current taxonomy. Supports dry-run and write mode.
### `validate_wing_hints`
Compares targeted wing search vs broad search and reports:
- top similarity
- query alignment
- source file and drawer identity for top result
- deltas between broad and best targeted runs
### `introspect_mempalace`
Checks live availability of MemPalace support functions.
## Classification strategy
Classification is lightweight and pragmatic, not overengineered.
It uses:
- room/wing token overlap
- phrase bonuses
- Jaccard token similarity
- fallback routing to `work/general`
Diagnostics are returned during migration/promotion paths.
## Verification strategy
Recommended checks:
1. `python3 -m py_compile __init__.py scripts/*.py`
2. taxonomy create/update/move/delete lifecycle tests
3. drawer listing before/after destructive actions
4. validation harness on representative queries
5. maintenance run with summary promotion enabled
## Safe delete verification workflow
Suggested workflow for destructive verification:
1. create temporary wing
2. create temporary room
3. add one or more drawers there
4. list drawers to capture IDs
5. delete room with purge enabled
6. verify drawers are gone
7. delete temporary wing
8. verify wing removal in taxonomy
## Operational notes
- This plugin assumes MemPalace MCP is connected in Hermes.
- It does not patch Hermes core.
- Taxonomy is persisted in `taxonomy.json` and can evolve independently.
- Legacy compatibility is maintained through `memories` wing handling.
## Licensing
GPLv3
Copyleft Stefy Lanza <stefy@nexlab.net>
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Copyleft Stefy Lanza <stefy@nexlab.net>
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
7. Additional Terms.
Additional permissions are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
hermes-three-tier-memory - three-tier memory plugin for Hermes backed by MemPalace.
Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w`.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c` for details.
The hypothetical commands `show w` and `show c` should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
# hermes-three-tier-memory
Three-tier memory plugin for Hermes Agent backed by rolling local memory files and MemPalace long-term storage.
## What it does
This plugin adds an update-safe memory layer without patching Hermes core:
1. **Tier 1 — Active memory**
- `~/.hermes/memories/MEMORY.md`
2. **Tier 2 — Rolling daily memory**
- `~/.hermes/memories/daily/YYYY-MM-DD.md`
- 7-day retention by default
3. **Tier 3 — Long-term memory**
- MemPalace via MCP
- wing/room taxonomy
- promotion, search, migration, listing, move, update, delete
## Features
- Smart search across recent and long-term memory
- Multi-wing taxonomy with rooms
- Legacy migration support
- Daily maintenance / compaction
- Drawer listing and MemPalace introspection
- Wing-hint validation harness
- Taxonomy lifecycle operations
- Safe delete verification workflow
## Tool actions
- `status`
- `list`
- `compact`
- `maintain`
- `search`
- `search_long_term`
- `taxonomy`
- `create_wing`
- `create_room`
- `update_wing`
- `update_room`
- `move_room`
- `delete_room`
- `delete_wing`
- `list_memories`
- `migrate_legacy`
- `validate_wing_hints`
- `introspect_mempalace`
## Requirements
- Hermes Agent plugin support
- MemPalace MCP server configured and reachable
- Python 3
## Files
- `__init__.py` — plugin entrypoint and tool implementation
- `taxonomy.json` — persisted taxonomy
- `scripts/compact_memory.py` — compaction/search helper
- `scripts/run_maintenance.py` — maintenance runner
- `scripts/organize_memory.py` — memory organization helper
- `STATUS.md` — development ledger and verification status
- `DOCUMENTATION.md` — detailed operational documentation
## Installation
Clone or install the plugin into Hermes plugin space, then restart Hermes or start a fresh session so the tool is registered.
## License
GPLv3. See `LICENSE`.
## Copyright
Copyleft Stefy Lanza <stefy@nexlab.net>
# Hermes Three-Tier Memory: Status, Goals, and Development Ledger
Last updated: 2026-05-15
## Purpose
This plugin exists to provide a durable, update-safe memory architecture for Hermes without patching Hermes core.
It currently implements a three-tier memory model:
1. **Tier 1: Active memory**
- `~/.hermes/memories/MEMORY.md`
- short-lived, currently active working memory
2. **Tier 2: Daily rolling memory**
- `~/.hermes/memories/daily/YYYY-MM-DD.md`
- compacted summaries/facts from active memory
- 7-day retention by default
3. **Tier 3: Long-term memory via MemPalace**
- externalized curated memory promoted into MemPalace through MCP
- currently used for daily summaries, categorized facts, diary entries, controlled legacy reindexing, and taxonomy-aware listing/maintenance
## Hard architectural constraints
- Do **not** patch Hermes core for this feature set.
- The plugin must remain the policy/default layer for smart memory behavior.
- Backward compatibility matters: existing promoted content under current MemPalace structure must remain readable.
- Retrieval quality matters more than cosmetic taxonomy changes.
## State after this improvement pass
### Implemented
- Tier-2 compaction from active memory into rolling daily files
- Smart search over daily memory with scoring/confidence
- Fallback to MemPalace long-term search
- Promotion of daily summary into MemPalace
- Promotion of selected important summary lines into categorized rooms
- MemPalace diary writing during maintenance
- Scheduled daily maintenance job
- Explicit multi-wing taxonomy in `taxonomy.json`
- Dynamic macro-area support for relationship-oriented domains such as marriage/family
- Query expansion for long-term search
- Wing inference / targeted long-term routing
- Cross-run long-term aggregation
- Long-term duplicate suppression
- Structured `answer_packet` synthesis for search results
- Legacy compatibility mirroring for summary history
- First-class taxonomy tool actions
- Controlled legacy migration/reindex action
- MemPalace drawer listing support
- Taxonomy lifecycle actions for update/move/delete
- Basic wing-hint validation harness
- Improved classification diagnostics via semantic token overlap scoring
- MemPalace MCP capability introspection
## Target taxonomy now implemented
### Stable default wings
- `identity`
- `governance`
- `systems`
- `work`
- `history`
- `relationships`
- `care` *(verified extension added during development)*
### Example rooms
#### `identity`
- `preferences`
- `profile`
- `habits`
#### `governance`
- `policies`
- `constraints`
- `security`
- `decisions`
#### `systems`
- `infrastructure`
- `architecture`
- `integrations`
- `platforms`
#### `work`
- `projects`
- `operations`
- `debugging`
- `deliveries`
- `general`
- `appointments` *(moved here during lifecycle verification)*
#### `history`
- `daily`
- `daily-summaries`
- `diary`
#### `relationships`
- `family`
- `marriage`
- `partners`
- `important-people`
#### `care`
- currently wing exists and metadata is mutable
- no room remains after moving `appointments` to `work`
## Extensibility model now implemented
The taxonomy layer now supports:
- built-in wings/rooms in `taxonomy.json`
- dynamic wing/room extension based on configured keyword triggers
- first-class tool actions for taxonomy inspection and extension
- taxonomy lifecycle operations:
- create
- update
- move room
- delete room
- delete wing
- backward compatibility fallback through legacy wing mirroring
- safe fallback classification to `work/general`
Current dynamic keyword examples:
- `marriage``relationships/marriage`
- `family``relationships/family`
Example manually added macro area during verification:
- wing: `care`
- room: `appointments`
- later moved to: `work/appointments`
This means macro areas like marriage/family are explicitly supported now, and new wings no longer require hand-editing plugin code.
## Backward compatibility strategy
- Continue reading existing legacy content under wing `memories`
- Write new history summaries into `history/daily-summaries`
- Mirror summary history into legacy `memories/daily-summaries`
- Keep legacy wing in search candidate routing during transition
- Provide controlled legacy reindexing into new semantic wings
- Use live drawer listing to inspect actual stored legacy/migrated content
## Verification status
### Syntax verification
- `python3 -m py_compile` passed repeatedly after changes to:
- `__init__.py`
- `scripts/compact_memory.py`
- `scripts/run_maintenance.py`
### Live status verification
- `three_tier_memory(action='status')` succeeded
- Reported wings initially included:
- `governance`
- `history`
- `identity`
- `relationships`
- `systems`
- `work`
- later taxonomy verification confirmed additional wing:
- `care`
### Live search verification
- `three_tier_memory(action='search', query='gateway plugin register function', fallback_to_long_term=False)` succeeded
- Confirmed:
- query variants are generated
- candidate wings are inferred (`systems`, plus legacy `memories` fallback)
- answer packet structure is present
### Live maintenance verification
- `scripts/run_maintenance.py` succeeded end-to-end
- Confirmed:
- summary written to `history/daily-summaries`
- legacy summary mirrored to `memories/daily-summaries`
- organized items written to multi-wing locations including:
- `systems/infrastructure`
- `governance/security`
- `work/operations`
- `governance/policies`
- diary write succeeded under `history`
### Live taxonomy action verification
Verified successfully:
- `three_tier_memory(action='taxonomy')`
- `three_tier_memory(action='create_wing', wing='care', ...)`
- `three_tier_memory(action='create_room', wing='care', room='appointments', ...)`
- `three_tier_memory(action='update_wing', wing='care', ...)`
- `three_tier_memory(action='update_room', wing='care', room='appointments', ...)`
- `three_tier_memory(action='move_room', wing='care', room='appointments', new_wing='work')`
Result:
- new wing `care` added
- room `care/appointments` added
- wing metadata updated
- room metadata updated
- room moved to `work/appointments`
- taxonomy file updated correctly throughout
### Live memory listing verification
Verified:
- `three_tier_memory(action='list_memories', wing='systems', limit=5)`
Confirmed it returned real stored drawers, including:
- `drawer_systems_infrastructure_383df89d0496fc518c76fb65`
- `drawer_systems_infrastructure_49ddb21403e5b82dc85ed13b`
- `drawer_systems_infrastructure_051a983a92782b453f703f66`
- `drawer_systems_infrastructure_7b8c48344943fae01a43906b`
This materially improves inspection and migration confidence.
### Live MemPalace capability introspection
Verified:
- `three_tier_memory(action='introspect_mempalace')`
Confirmed MCP-side support exists for:
- `mempalace_list_wings`
- `mempalace_list_rooms`
- `mempalace_get_taxonomy`
- `mempalace_list_drawers`
- `mempalace_get_drawer`
- `mempalace_update_drawer`
- `mempalace_delete_drawer`
- plus search / diary / tunnel / KG tools
This is important because it removed the earlier uncertainty that universal drawer inspection might be impossible.
### Live legacy migration verification
Verified both modes:
- dry run:
- `three_tier_memory(action='migrate_legacy', dry_run=True)`
- write mode:
- `three_tier_memory(action='migrate_legacy', dry_run=False)`
Confirmed migrated drawers were written to:
- `identity/preferences`
- `governance/policies`
- `systems/infrastructure`
Also now confirmed live listing of the legacy wing is possible through MCP-backed listing.
### Live wing-hint validation
Verified:
- `three_tier_memory(action='validate_wing_hints', query='systemd policy', limit=3)`
Observed:
- comparison runs were produced for targeted wing hint and broad search
- harness reported `material_difference_detected: true`
Caveat:
- the current comparison signal is conservative but not perfect
- the specific sample showed identical top preview/similarity while still counting result-shape differences as material
- so the validation harness exists and works, but interpretation still needs care
## Development ledger
### Step 1 — completed
- Created this status/ledger document.
- Captured current state, constraints, goals, and target direction.
### Step 2 — completed
- Inspected plugin implementation.
- Identified current code paths for:
- taxonomy/classification
- promotion
- search routing
- dedupe
- synthesis
- maintenance diary behavior
### Step 3 — completed
- Added explicit `taxonomy.json` file.
- Implemented multi-wing taxonomy with:
- `identity`
- `governance`
- `systems`
- `work`
- `history`
- `relationships`
- Added extensibility support for macro areas through dynamic keyword-based wing/room creation.
- Added explicit support for family/marriage-related long-term organization.
### Step 4 — completed and verified
- Reworked classification so promoted items are no longer forced into the single `memories` wing.
- Daily summaries now write to `history/daily-summaries`.
- Legacy summary mirroring remains enabled to preserve compatibility.
- Diary writing now uses the taxonomy-configured history wing.
### Step 5 — completed and partially verified
- Added query expansion variants.
- Added wing inference from query semantics.
- Added multi-run long-term search aggregation across candidate wings.
- Added long-term result dedupe.
- Added structured `answer_packet` synthesis combining recent and long-term evidence.
### Step 6 — completed
- Ran live verification for:
- `status`
- `search`
- `maintain`
- Confirmed promoted drawers land in expected wings/rooms.
### Step 7 — completed
- Added first-class taxonomy management actions:
- `taxonomy`
- `create_wing`
- `create_room`
- Verified taxonomy mutation with live runs.
### Step 8 — completed (controlled migration scope)
- Added `migrate_legacy` action.
- Verified dry-run planning mode.
- Verified write mode with actual drawer creation in target semantic wings.
- Explicitly documented current scope limits.
### Step 9 — completed
- Inspected actual MemPalace MCP tool inventory.
- Confirmed support for taxonomy/room/drawer introspection and drawer update/delete operations.
- This materially improved the plugin’s ability to inspect and manage stored long-term memory.
### Step 10 — completed
- Added taxonomy lifecycle operations:
- `update_wing`
- `update_room`
- `move_room`
- `delete_wing`
- `delete_room`
- `list_memories`
- Verified update/move operations live.
### Step 11 — completed
- Improved classification from raw substring counting to a lightweight semantic token-overlap scoring model with diagnostics.
- Classification results now include candidate/selected scoring metadata during promotion and migration planning.
### Step 12 — completed
- Added `validate_wing_hints` harness.
- Added `introspect_mempalace` action.
- Verified both live.
## Remaining gaps after this pass
1. **Wing-hint validation is better, but still not mathematically definitive**
- we now have a real validation harness
- we now have live MCP introspection
- but proving “wing hint materially improved relevance” still depends on better evaluation criteria than simple result-shape comparison
2. **Classification is still lightweight, not truly semantic/LLM-based**
- it is meaningfully better than substring heuristics
- but it is still token/rule-based scoring, not deep semantic understanding
3. **Deletion actions were implemented but not yet exercised live**
- create/update/move/list/introspection/migration were exercised
- delete actions exist but were intentionally not executed yet to avoid unnecessary destructive churn during verification
## Files added/changed in this pass
- `__init__.py`
- `taxonomy.json`
- `STATUS.md`
## Current architectural position
The system now has:
- real macro-area wings
- first-class taxonomy administration
- verified multi-wing promotion
- controlled migration/reindex support
- live drawer listing and mutation support
- maintained implementation status documentation
- a better classification model than the initial heuristic pass
- a real MemPalace introspection and wing-hint validation layer
The next serious upgrades, if desired, are:
- stronger evaluation metrics for wing-hint usefulness
- optional semantic/LLM-assisted classification
- cautious live verification of delete flows
### Final gap-closure pass — completed on 2026-05-15
- Improved classification scoring with token-set similarity and phrase bonuses.
- Improved wing-hint validation harness to report query alignment, top drawer identity/source, and targeted-vs-broad deltas.
- Verified safe delete flows locally through dry taxonomy lifecycle checks.
- Verified live destructive delete path against MemPalace on an empty temporary wing/room with `dry_run=false`.
- Added repository documentation files:
- `README.md`
- `DOCUMENTATION.md`
- `LICENSE` (GPLv3, copyleft Stefy Lanza <stefy@nexlab.net>)
- Prepared standalone git-ready repository copy in `/home/lisa/hermes-3tier-mempalace-memory`.
from __future__ import annotations
import json
import logging
import os
import re
import shlex
import subprocess
import sys
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Optional
logger = logging.getLogger(__name__)
PLUGIN_DIR = Path(__file__).resolve().parent
SCRIPT_PATH = PLUGIN_DIR / "scripts" / "compact_memory.py"
MEMORY_FILE = Path.home() / ".hermes" / "memories" / "MEMORY.md"
DAILY_DIR = Path.home() / ".hermes" / "memories" / "daily"
RETENTION_DAYS = 7
TOOLSET = "three-tier-memory"
MEMPALACE_COMMAND = os.environ.get("MEMPALACE_MCP_COMMAND", str(Path.home() / ".local/bin/mempalace-mcp"))
MEMPALACE_PALACE = os.environ.get("MEMPALACE_PALACE", str(Path.home() / ".mempalace/palace"))
MEMPALACE_SERVER = os.environ.get("MEMPALACE_MCP_SERVER", "mempalace")
MEMPALACE_TOOL_NAME = os.environ.get("MEMPALACE_SEARCH_TOOL", "mempalace_search")
MEMPALACE_ADD_TOOL_NAME = os.environ.get("MEMPALACE_ADD_TOOL", "mempalace_add_drawer")
MEMPALACE_TOOL = f"mcp_{MEMPALACE_SERVER}_{MEMPALACE_TOOL_NAME}"
MEMPALACE_ADD_TOOL = f"mcp_{MEMPALACE_SERVER}_{MEMPALACE_ADD_TOOL_NAME}"
DEFAULT_SEARCH_LIMIT = 8
DEFAULT_PROMOTION_LIMIT = 6
DEFAULT_AGENT_NAME = os.environ.get("MEMPALACE_AGENT_NAME", "Lisa")
STATUS_FILE = PLUGIN_DIR / "STATUS.md"
TAXONOMY_FILE = PLUGIN_DIR / "taxonomy.json"
DEFAULT_LEGACY_WING = "memories"
DEFAULT_HISTORY_WING = "history"
DEFAULT_HISTORY_SUMMARY_ROOM = "daily-summaries"
DEFAULT_HISTORY_DIARY_ROOM = "diary"
DEFAULT_HISTORY_DAILY_ROOM = "daily"
@dataclass(frozen=True)
class ClassificationRule:
wing: str
room: str
importance: int
tokens: tuple[str, ...]
DEFAULT_TAXONOMY: dict[str, Any] = {
"version": 1,
"legacy": {
"enabled": True,
"wing": DEFAULT_LEGACY_WING,
"history_room": DEFAULT_HISTORY_SUMMARY_ROOM,
},
"defaults": {
"history_wing": DEFAULT_HISTORY_WING,
"summary_room": DEFAULT_HISTORY_SUMMARY_ROOM,
"diary_room": DEFAULT_HISTORY_DIARY_ROOM,
"fallback_wing": "work",
"fallback_room": "general",
},
"wings": {
"identity": {
"description": "Stable facts about user identity, preferences, and habits.",
"aliases": ["preferences", "profile", "identity", "habits"],
"rooms": {
"preferences": ["preference", "prefers", "likes", "dislikes", "workflow preference", "expects", "style", "habit"],
"profile": ["name", "timezone", "role", "identity", "profile"],
"habits": ["habit", "routine", "usually", "normally", "often"],
},
},
"governance": {
"description": "Policies, constraints, security requirements, and durable decisions.",
"aliases": ["policy", "policies", "security", "constraints", "governance"],
"rooms": {
"policies": ["always", "never", "must", "critical", "required", "explicitly rejected", "policy"],
"constraints": ["constraint", "cannot", "must not", "do not", "without"],
"security": ["security", "secret", "credential", "token", "privacy", "approval"],
"decisions": ["decision", "chosen", "prefer that over", "target architecture"],
},
},
"systems": {
"description": "Infrastructure, architecture, platforms, and technical integrations.",
"aliases": ["systems", "infrastructure", "architecture", "platforms", "integrations"],
"rooms": {
"infrastructure": ["config", "path", "installed", "reachable", "machine", "node", "gateway", "plugin", "repo", "package"],
"architecture": ["architecture", "capability", "design", "protocol", "integration", "taxonomy", "topology"],
"integrations": ["mcp", "api", "integration", "provider", "adapter"],
"platforms": ["telegram", "discord", "browser", "chrome", "linux", "windows"],
},
},
"work": {
"description": "Projects, operations, debugging, and delivery-oriented memory.",
"aliases": ["work", "projects", "operations", "debugging"],
"rooms": {
"projects": ["project", "feature", "roadmap", "milestone"],
"operations": ["workflow", "process", "procedure", "deploy", "release", "maintenance", "operational"],
"debugging": ["bug", "error", "traceback", "fix", "debug", "issue"],
"deliveries": ["deliver", "release", "bundle", "shipped", "published"],
"general": ["work", "task", "implementation"],
},
},
"history": {
"description": "Summaries and chronological traces.",
"aliases": ["history", "daily", "summary", "diary"],
"rooms": {
"daily": ["daily"],
"daily-summaries": ["summary", "daily summary"],
"diary": ["diary", "journal", "history"],
},
},
"relationships": {
"description": "Family, marriage, partners, and important people relationships.",
"aliases": ["relationships", "family", "marriage", "partner", "people"],
"rooms": {
"family": ["family", "parent", "child", "sibling", "relative"],
"marriage": ["marriage", "married", "spouse", "wife", "husband"],
"partners": ["partner", "girlfriend", "boyfriend", "significant other"],
"important-people": ["friend", "person", "people", "relationship"],
},
},
},
"dynamic_wings": {
"enabled": True,
"keywords": {
"marriage": {
"wing": "relationships",
"room": "marriage",
},
"family": {
"wing": "relationships",
"room": "family",
},
},
},
}
class _PluginState:
__slots__ = ("ctx",)
def __init__(self) -> None:
self.ctx = None
_STATE = _PluginState()
def _safe_int(value: Any, default: int) -> int:
try:
return int(value)
except (TypeError, ValueError):
return default
def _result_ok(result: dict[str, Any] | None) -> bool:
return bool(isinstance(result, dict) and result.get("success"))
def _normalize_result_payload(payload: Any) -> tuple[Any, Any]:
if isinstance(payload, dict):
if "structuredContent" in payload:
return payload.get("structuredContent"), payload
if "result" in payload:
nested = payload.get("result")
if isinstance(nested, (dict, list)):
return nested, payload
if isinstance(nested, str):
text = nested.strip()
if text:
try:
return json.loads(text), payload
except json.JSONDecodeError:
pass
return nested, payload
if isinstance(payload, str):
text = payload.strip()
if text:
try:
parsed = json.loads(text)
return parsed, parsed
except json.JSONDecodeError:
return text, payload
return payload, payload
def _extract_mempalace_results(parsed: Any) -> list[Any]:
if isinstance(parsed, dict):
for key in ("results", "items", "matches", "entries", "memories"):
value = parsed.get(key)
if isinstance(value, list):
return value
data = parsed.get("data")
if isinstance(data, dict):
nested = _extract_mempalace_results(data)
if nested:
return nested
if any(key in parsed for key in ("title", "content", "text", "drawer", "path", "id")):
return [parsed]
if isinstance(parsed, list):
return parsed
return []
def _normalize_space(text: str) -> str:
return " ".join((text or "").split())
def _shorten(text: str, limit: int = 220) -> str:
compact = _normalize_space(text)
if len(compact) <= limit:
return compact
return compact[: limit - 3].rstrip() + "..."
def _slugify(value: str) -> str:
text = (value or "").strip().lower()
text = re.sub(r"[`*_#\[\](){}:;,.!?\"'\\/]+", " ", text)
text = re.sub(r"\s+", "-", text)
text = re.sub(r"[^a-z0-9-]+", "", text)
return text.strip("-") or "general"
def _tokenize(text: str) -> list[str]:
return re.findall(r"[a-z0-9_./:-]+", (text or "").lower())
def _token_set(text: str) -> set[str]:
return set(_tokenize(text))
def _jaccard_similarity(left: set[str], right: set[str]) -> float:
if not left or not right:
return 0.0
union = left | right
if not union:
return 0.0
return len(left & right) / len(union)
def _load_taxonomy() -> dict[str, Any]:
if TAXONOMY_FILE.exists():
try:
data = json.loads(TAXONOMY_FILE.read_text(encoding="utf-8"))
if isinstance(data, dict):
return data
except Exception as exc:
logger.warning("failed to load taxonomy.json, using defaults: %s", exc)
TAXONOMY_FILE.write_text(json.dumps(DEFAULT_TAXONOMY, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return json.loads(json.dumps(DEFAULT_TAXONOMY))
def _all_rules(taxonomy: dict[str, Any]) -> list[ClassificationRule]:
rules: list[ClassificationRule] = []
wings = taxonomy.get("wings", {}) if isinstance(taxonomy, dict) else {}
for wing, wing_data in wings.items():
if not isinstance(wing_data, dict):
continue
rooms = wing_data.get("rooms", {})
wing_aliases = tuple(str(x).lower() for x in wing_data.get("aliases", []) if isinstance(x, str))
for room, tokens in rooms.items():
token_list = [str(x).lower() for x in tokens if isinstance(x, str)]
all_tokens = tuple(dict.fromkeys([*wing_aliases, room.lower(), *token_list]))
importance = 4
if wing == "identity":
importance = 5
elif wing == "governance":
importance = 5
elif wing == "systems":
importance = 4
elif wing == "relationships":
importance = 5
elif wing == "history":
importance = 3
rules.append(ClassificationRule(wing=wing, room=_slugify(room), importance=importance, tokens=all_tokens))
return rules
def _ensure_dynamic_wings(text: str, taxonomy: dict[str, Any]) -> tuple[dict[str, Any], list[dict[str, str]]]:
changed = False
created: list[dict[str, str]] = []
dynamic = taxonomy.setdefault("dynamic_wings", {})
enabled = bool(dynamic.get("enabled", True))
if not enabled:
return taxonomy, created
keywords = dynamic.get("keywords", {})
if not isinstance(keywords, dict):
return taxonomy, created
lower = (text or "").lower()
wings = taxonomy.setdefault("wings", {})
for keyword, target in keywords.items():
if not isinstance(keyword, str) or keyword.lower() not in lower or not isinstance(target, dict):
continue
wing = _slugify(str(target.get("wing", "")))
room = _slugify(str(target.get("room", keyword)))
if not wing:
continue
wing_entry = wings.setdefault(wing, {"description": f"Dynamic macro area for {wing}.", "aliases": [wing], "rooms": {}})
if not isinstance(wing_entry, dict):
continue
wing_entry.setdefault("aliases", [wing])
rooms = wing_entry.setdefault("rooms", {})
if room not in rooms:
rooms[room] = [keyword]
changed = True
created.append({"wing": wing, "room": room, "trigger": keyword})
if changed:
TAXONOMY_FILE.write_text(json.dumps(taxonomy, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return taxonomy, created
def _classify_memory_entry(entry: str, taxonomy: dict[str, Any]) -> tuple[str, str, int, list[dict[str, str]], dict[str, Any]]:
taxonomy, dynamic_created = _ensure_dynamic_wings(entry, taxonomy)
wing, room, importance, diagnostics = _classify_by_semantic_score(entry, taxonomy)
return (wing, room, importance, dynamic_created, diagnostics)
def _extract_search_text(item: Any) -> str:
if isinstance(item, dict):
for key in ("text", "content", "summary", "title"):
value = item.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
if isinstance(item, str):
return item.strip()
return ""
def _extract_drawer_preview(item: Any) -> str:
if isinstance(item, dict):
for key in ("preview", "content_preview", "content", "text", "summary"):
value = item.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return _extract_search_text(item)
def _extract_search_wing(item: Any) -> str | None:
if isinstance(item, dict):
for key in ("wing", "palace_wing", "category"):
value = item.get(key)
if isinstance(value, str) and value.strip():
return _slugify(value)
return None
def _extract_search_room(item: Any) -> str | None:
if isinstance(item, dict):
for key in ("room", "palace_room"):
value = item.get(key)
if isinstance(value, str) and value.strip():
return _slugify(value)
return None
def _extract_similarity(item: Any) -> float:
if isinstance(item, dict):
try:
return float(item.get("similarity", 0.0) or 0.0)
except (TypeError, ValueError):
return 0.0
return 0.0
def _extract_drawer_id(item: Any) -> str | None:
if isinstance(item, dict):
for key in ("drawer_id", "id"):
value = item.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def _extract_search_source_file(item: Any) -> str | None:
if isinstance(item, dict):
for key in ("source_file", "path", "origin", "filename"):
value = item.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return None
def _query_variants(query: str) -> list[str]:
raw = _normalize_space(query)
if not raw:
return []
variants = [raw]
lowered = raw.lower()
replacements = {
"register function": ["register(ctx)", "missing register(ctx)", "plugin register"],
"gateway plugin": ["gateway plugin", "plugin load", "register(ctx)"],
"browser control": ["browser_control", "browser controller", "browser capability"],
"memory": ["memory", "preferences", "workflow", "policy"],
"marriage": ["marriage", "spouse", "partner"],
"family": ["family", "parents", "siblings", "relatives"],
}
for needle, extras in replacements.items():
if needle in lowered:
variants.extend(extras)
tokens = [tok for tok in _tokenize(lowered) if len(tok) > 2]
if tokens:
variants.append(" ".join(tokens[:6]))
deduped: list[str] = []
seen: set[str] = set()
for item in variants:
key = item.strip().lower()
if key and key not in seen:
seen.add(key)
deduped.append(item.strip())
return deduped[:6]
def _classify_by_semantic_score(entry: str, taxonomy: dict[str, Any]) -> tuple[str, str, int, dict[str, Any]]:
lower = _normalize_space(entry).lower()
tokens = _token_set(lower)
best_rule: ClassificationRule | None = None
best_score = -1.0
diagnostics: dict[str, Any] = {"candidates": [], "entry_tokens": sorted(tokens)}
for rule in _all_rules(taxonomy):
rule_tokens = {token for token in rule.tokens if token}
overlap = tokens & rule_tokens
score = float(len(overlap))
phrase_bonus = 0.0
for token in rule_tokens:
if len(token) > 3 and token in lower:
phrase_bonus += 0.2
score += min(phrase_bonus, 1.0)
token_similarity = _jaccard_similarity(tokens, rule_tokens)
score += token_similarity
if rule.room in lower:
score += 0.75
if rule.wing in lower:
score += 0.5
diagnostics["candidates"].append({
"wing": rule.wing,
"room": rule.room,
"score": round(score, 3),
"overlap": sorted(overlap),
"token_similarity": round(token_similarity, 3),
"importance": rule.importance,
})
if score > best_score:
best_score = score
best_rule = rule
diagnostics["candidates"].sort(key=lambda item: item["score"], reverse=True)
defaults = taxonomy.get("defaults", {}) if isinstance(taxonomy, dict) else {}
fallback_wing = _slugify(str(defaults.get("fallback_wing", "work")))
fallback_room = _slugify(str(defaults.get("fallback_room", "general")))
if best_rule and best_score > 0:
diagnostics["selected"] = {"wing": best_rule.wing, "room": best_rule.room, "score": round(best_score, 3)}
return best_rule.wing, best_rule.room, best_rule.importance, diagnostics
diagnostics["selected"] = {"wing": fallback_wing, "room": fallback_room, "score": 0.0}
return fallback_wing, fallback_room, 2, diagnostics
def _infer_candidate_wings(query: str, taxonomy: dict[str, Any], max_wings: int = 3) -> list[str]:
scores: Counter[str] = Counter()
lower = (query or "").lower()
for rule in _all_rules(taxonomy):
for token in rule.tokens:
if token and token in lower:
scores[rule.wing] += 1
dynamic = taxonomy.get("dynamic_wings", {}) if isinstance(taxonomy, dict) else {}
keywords = dynamic.get("keywords", {}) if isinstance(dynamic, dict) else {}
for keyword, target in keywords.items():
if isinstance(keyword, str) and keyword.lower() in lower and isinstance(target, dict):
wing = _slugify(str(target.get("wing", "")))
if wing:
scores[wing] += 2
ordered = [wing for wing, _ in scores.most_common(max_wings)]
if DEFAULT_LEGACY_WING not in ordered:
ordered.append(DEFAULT_LEGACY_WING)
return ordered[: max_wings + 1]
def _dedupe_long_term_results(results: list[dict[str, Any]]) -> list[dict[str, Any]]:
deduped: list[dict[str, Any]] = []
seen: set[str] = set()
for item in sorted(results, key=lambda r: float(r.get("similarity", 0.0) or 0.0), reverse=True):
text = _shorten(_extract_search_text(item), 260).lower()
wing = str(item.get("wing", "") or "")
room = str(item.get("room", "") or "")
key = f"{wing}|{room}|{text}"
if not text or key in seen:
continue
seen.add(key)
deduped.append(item)
return deduped
def _summarize_cross_tier(recent: dict[str, Any] | None, long_term: dict[str, Any] | None, limit: int) -> list[str]:
out: list[str] = []
if isinstance(recent, dict):
for item in recent.get("summary", []) or []:
if isinstance(item, str) and item.strip() and item.strip() not in out:
out.append(item.strip())
if len(out) >= limit:
return out
for match in recent.get("matches", []) or []:
entry = match.get("entry") if isinstance(match, dict) else None
if isinstance(entry, str) and entry.strip() and entry.strip() not in out:
out.append(entry.strip())
if len(out) >= limit:
return out
if isinstance(long_term, dict):
for item in long_term.get("results", []) or []:
text = _extract_search_text(item)
wing = item.get("wing") if isinstance(item, dict) else None
room = item.get("room") if isinstance(item, dict) else None
if text:
summary_line = _shorten(text, 220)
if wing or room:
label = "/".join(part for part in [str(wing or "").strip(), str(room or "").strip()] if part)
if label:
summary_line = f"[{label}] {summary_line}"
if summary_line not in out:
out.append(summary_line)
if len(out) >= limit:
return out
return out
def _build_answer_packet(query: str, recent: dict[str, Any] | None, long_term: dict[str, Any] | None, limit: int) -> dict[str, Any]:
packet = {
"query": query,
"takeaways": _summarize_cross_tier(recent, long_term, limit=min(limit, 6)),
"recent_evidence": [],
"long_term_evidence": [],
}
if isinstance(recent, dict):
for match in (recent.get("matches") or [])[: min(limit, 4)]:
if isinstance(match, dict):
packet["recent_evidence"].append(
{
"day": match.get("day"),
"confidence": match.get("confidence"),
"score": match.get("score"),
"entry": _shorten(str(match.get("entry", "")), 220),
}
)
if isinstance(long_term, dict):
for item in (long_term.get("results") or [])[: min(limit, 4)]:
if isinstance(item, dict):
packet["long_term_evidence"].append(
{
"wing": item.get("wing"),
"room": item.get("room"),
"similarity": item.get("similarity"),
"text": _shorten(_extract_search_text(item), 220),
}
)
return packet
def _confidence_rank(value: str) -> int:
return {"high": 3, "medium": 2, "low": 1}.get(str(value or "").lower(), 0)
def _score_recent_hits(result: dict[str, Any]) -> tuple[int, float, str]:
if not _result_ok(result):
return (0, 0.0, "low")
matches = result.get("matches")
match_count = len(matches) if isinstance(matches, list) else 0
best_score = float(result.get("best_score", 0.0) or 0.0)
confidence = str(result.get("confidence", "low"))
return (match_count, best_score, confidence)
def _get_mcp_server():
from tools.mcp_tool import _servers, _lock
with _lock:
return _servers.get(MEMPALACE_SERVER)
def _call_mcp_tool(tool_name: str, arguments: dict[str, Any], timeout: float | None = None) -> tuple[bool, Any, str | None]:
try:
from tools.mcp_tool import _run_on_mcp_loop
except Exception as exc:
return False, None, f"failed to import Hermes MCP internals: {exc}"
server = _get_mcp_server()
if not server or not getattr(server, "session", None):
return False, None, f"MemPalace MCP server '{MEMPALACE_SERVER}' is not connected"
async def _call():
async with server._rpc_lock:
return await server.session.call_tool(tool_name, arguments=arguments)
try:
result = _run_on_mcp_loop(_call(), timeout=float(timeout or getattr(server, "tool_timeout", 120) or 120))
return True, result, None
except Exception as exc:
return False, None, f"{type(exc).__name__}: {exc}"
def _mempalace_search(query: str, limit: int = 5, wing_hint: str | None = None) -> dict[str, Any]:
q = (query or "").strip()
if not q:
return {"success": False, "error": "query cannot be empty for long-term search"}
if _STATE.ctx is None:
return {"success": False, "error": "plugin context unavailable for MemPalace MCP access"}
args = {"query": q, "limit": max(1, limit)}
if wing_hint:
args["wing"] = wing_hint
ok, call_result, error = _call_mcp_tool(MEMPALACE_TOOL_NAME, args)
if not ok:
return {
"success": False,
"error": "MemPalace MCP call failed",
"details": error,
"mcp_tool": MEMPALACE_TOOL,
"wing_hint": wing_hint,
}
if getattr(call_result, "isError", False):
parts = []
for block in getattr(call_result, "content", []) or []:
text = getattr(block, "text", None)
if text:
parts.append(text)
return {
"success": False,
"error": "MemPalace MCP tool returned an error",
"details": "\n".join(parts).strip() or None,
"mcp_tool": MEMPALACE_TOOL,
"wing_hint": wing_hint,
}
text_parts: list[str] = []
for block in getattr(call_result, "content", []) or []:
text = getattr(block, "text", None)
if text:
text_parts.append(text)
text_result = "\n".join(text_parts).strip()
structured = getattr(call_result, "structuredContent", None)
normalized, raw_payload = _normalize_result_payload(structured if structured is not None else text_result)
results = _extract_mempalace_results(normalized)
normalized_results: list[dict[str, Any]] = []
if isinstance(results, list):
for item in results:
text = _extract_search_text(item)
normalized_results.append(
{
**(item if isinstance(item, dict) else {"raw": item}),
"text": text,
"wing": _extract_search_wing(item) or wing_hint,
"room": _extract_search_room(item),
"similarity": round(_extract_similarity(item), 4),
}
)
normalized_results = normalized_results[: max(1, limit)]
top_similarity = 0.0
if normalized_results:
top_similarity = max(float(item.get("similarity", 0.0) or 0.0) for item in normalized_results)
confidence = "low"
if top_similarity >= 0.7:
confidence = "high"
elif top_similarity >= 0.45:
confidence = "medium"
return {
"success": True,
"action": "search_long_term",
"query": q,
"source": "mempalace",
"mcp_server": MEMPALACE_SERVER,
"mcp_tool": MEMPALACE_TOOL,
"results": normalized_results,
"result_count": len(normalized_results),
"top_similarity": round(top_similarity, 4),
"confidence": confidence,
"raw": raw_payload,
"text": text_result,
"wing_hint": wing_hint,
}
def _write_mempalace_drawer(*, wing: str, room: str, content: str, source_file: str) -> dict[str, Any]:
args = {
"content": content,
"wing": _slugify(wing),
"room": _slugify(room),
"source_file": source_file,
"added_by": "mcp",
}
ok, call_result, error = _call_mcp_tool(MEMPALACE_ADD_TOOL_NAME, args, timeout=180)
if not ok:
return {
"success": False,
"error": "MemPalace promotion failed",
"details": error,
"mcp_tool": MEMPALACE_ADD_TOOL,
}
if getattr(call_result, "isError", False):
parts = []
for block in getattr(call_result, "content", []) or []:
text = getattr(block, "text", None)
if text:
parts.append(text)
return {
"success": False,
"error": "MemPalace add_drawer returned an error",
"details": "\n".join(parts).strip() or None,
"mcp_tool": MEMPALACE_ADD_TOOL,
}
text_parts = [getattr(block, "text", None) for block in getattr(call_result, "content", []) or []]
text_result = "\n".join(part for part in text_parts if isinstance(part, str) and part).strip()
structured = getattr(call_result, "structuredContent", None)
normalized, raw_payload = _normalize_result_payload(structured if structured is not None else text_result)
return {
"success": True,
"mcp_tool": MEMPALACE_ADD_TOOL,
"raw": raw_payload,
"result": normalized,
"text": text_result,
"wing": _slugify(wing),
"room": _slugify(room),
}
def _promote_daily_summary_to_mempalace(day: str, summary: list[str], source_file: str) -> dict[str, Any]:
taxonomy = _load_taxonomy()
compact_summary = [item.strip() for item in summary if isinstance(item, str) and item.strip()]
if not compact_summary:
return {"success": True, "action": "promote", "skipped": True, "reason": "no summary lines to promote"}
history_wing = _slugify(str(taxonomy.get("defaults", {}).get("history_wing", DEFAULT_HISTORY_WING)))
summary_room = _slugify(str(taxonomy.get("defaults", {}).get("summary_room", DEFAULT_HISTORY_SUMMARY_ROOM)))
payload_text = f"Daily memory summary for {day}\n\n" + "\n".join(f"- {item}" for item in compact_summary[:DEFAULT_PROMOTION_LIMIT])
summary_write = _write_mempalace_drawer(
wing=history_wing,
room=summary_room,
content=payload_text,
source_file=source_file,
)
if not summary_write.get("success"):
return {
"success": False,
"action": "promote",
"error": summary_write.get("error", "summary promotion failed"),
"details": summary_write.get("details"),
"mcp_tool": summary_write.get("mcp_tool", MEMPALACE_ADD_TOOL),
}
legacy = taxonomy.get("legacy", {}) if isinstance(taxonomy, dict) else {}
legacy_write = None
if legacy.get("enabled", True):
legacy_write = _write_mempalace_drawer(
wing=_slugify(str(legacy.get("wing", DEFAULT_LEGACY_WING))),
room=_slugify(str(legacy.get("history_room", DEFAULT_HISTORY_SUMMARY_ROOM))),
content=payload_text,
source_file=source_file,
)
organized_items = []
for item in compact_summary[:DEFAULT_PROMOTION_LIMIT]:
wing, room, importance, dynamic_created, classification = _classify_memory_entry(item, taxonomy)
content = f"[{day}] [importance:{importance}] {item}"
write_result = _write_mempalace_drawer(
wing=wing,
room=room,
content=content,
source_file=source_file,
)
organized_items.append({
"entry": item,
"wing": wing,
"room": room,
"importance": importance,
"dynamic_created": dynamic_created,
"classification": classification,
"write": write_result,
})
return {
"success": True,
"action": "promote",
"day": day,
"summary_count": len(compact_summary),
"mcp_tool": MEMPALACE_ADD_TOOL,
"summary_drawer": summary_write,
"legacy_summary_drawer": legacy_write,
"organized_items": organized_items,
"taxonomy_file": str(TAXONOMY_FILE),
}
THREE_TIER_MEMORY_SCHEMA = {
"name": "three_tier_memory",
"description": (
"Manage an update-safe three-tier Hermes memory overlay outside Hermes core source. "
"Tier 1 is active MEMORY.md, Tier 2 is rolling 7-day daily memory files under ~/.hermes/memories/daily/, "
"and Tier 3 is external/MCP long-term memory via MemPalace. "
"Use this tool to compact active memory nightly, search recent daily memory, inspect daily files, automatically search across all tiers with confidence scoring and wing-aware routing, promote daily summaries into MemPalace, manage taxonomy wings/rooms, and migrate legacy long-term memory organization."
),
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["compact", "search", "search_long_term", "list", "status", "maintain", "taxonomy", "create_wing", "create_room", "update_wing", "update_room", "delete_wing", "delete_room", "move_room", "list_memories", "migrate_legacy", "validate_wing_hints", "introspect_mempalace"],
"description": "Operation to perform."
},
"query": {
"type": "string",
"description": "Substring/keyword query for action='search' or 'search_long_term'."
},
"day": {
"type": "string",
"description": "Optional YYYY-MM-DD override for action='compact' or 'maintain'."
},
"limit": {
"type": "integer",
"description": "Maximum search matches to return.",
"default": 8
},
"fallback_to_long_term": {
"type": "boolean",
"description": "For action='search', automatically search MemPalace when recent memory confidence is weak or empty.",
"default": True
},
"promote_to_long_term": {
"type": "boolean",
"description": "For action='compact' or 'maintain', promote the summarized daily memory into MemPalace.",
"default": True
},
"wing": {
"type": "string",
"description": "Wing name for create_wing/create_room/taxonomy filtering."
},
"room": {
"type": "string",
"description": "Room name for create_room/delete_room/update_room/list_memories."
},
"new_wing": {
"type": "string",
"description": "Destination wing for move_room."
},
"description": {
"type": "string",
"description": "Description for create_wing."
},
"aliases": {
"type": "array",
"items": {"type": "string"},
"description": "Optional aliases for create_wing/create_room."
},
"tokens": {
"type": "array",
"items": {"type": "string"},
"description": "Classification tokens for create_room."
},
"include_legacy": {
"type": "boolean",
"description": "Whether taxonomy output should include legacy compatibility settings or migration should mirror legacy behavior.",
"default": True
},
"dry_run": {
"type": "boolean",
"description": "For migrate_legacy, report the migration plan without writing drawers. Also controls delete purge behavior: dry_run=false purges drawers.",
"default": True
}
},
"required": ["action"]
}
}
def _run_script(*args: str) -> dict[str, Any]:
cmd = [sys.executable, str(SCRIPT_PATH), *args]
proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
stdout = (proc.stdout or "").strip()
stderr = (proc.stderr or "").strip()
if not stdout:
return {
"success": False,
"error": "memory helper produced no output",
"exit_code": proc.returncode,
"stderr": stderr,
"command": cmd,
}
try:
payload = json.loads(stdout)
except json.JSONDecodeError:
return {
"success": False,
"error": "memory helper returned invalid JSON",
"stdout": stdout,
"stderr": stderr,
"exit_code": proc.returncode,
"command": cmd,
}
if stderr:
payload["stderr"] = stderr
payload["exit_code"] = proc.returncode
payload["command"] = cmd
return payload
def _status() -> dict[str, Any]:
daily_files = sorted(DAILY_DIR.glob("*.md"), reverse=True) if DAILY_DIR.exists() else []
taxonomy = _load_taxonomy()
return {
"success": True,
"action": "status",
"memory_file": str(MEMORY_FILE),
"memory_file_exists": MEMORY_FILE.exists(),
"daily_dir": str(DAILY_DIR),
"daily_dir_exists": DAILY_DIR.exists(),
"daily_file_count": len(daily_files),
"recent_days": [p.stem for p in daily_files[:RETENTION_DAYS]],
"retention_days": RETENTION_DAYS,
"default_behavior": {
"search": "recent-daily then wing-aware long-term with confidence-based fallback",
"maintenance": "compact active memory into daily summary and promote key facts to multi-wing MemPalace",
},
"long_term_tier": {
"provider": "mempalace",
"mcp_command": MEMPALACE_COMMAND,
"palace": MEMPALACE_PALACE,
"mcp_server": MEMPALACE_SERVER,
"mcp_tool": MEMPALACE_TOOL,
"promotion_tool": MEMPALACE_ADD_TOOL,
"taxonomy_file": str(TAXONOMY_FILE),
"wings": sorted(list((taxonomy.get("wings") or {}).keys())),
"legacy_wing": taxonomy.get("legacy", {}).get("wing", DEFAULT_LEGACY_WING),
},
"status_file": str(STATUS_FILE),
}
def _smart_search(query: str, limit: int, fallback_to_long_term: bool) -> dict[str, Any]:
recent = _run_script(
"search",
"--daily-dir",
str(DAILY_DIR),
"--retention-days",
str(RETENTION_DAYS),
"--query",
query,
"--limit",
str(limit),
)
if _result_ok(recent):
recent["source"] = "daily"
recent_count, recent_best_score, recent_confidence = _score_recent_hits(recent)
should_fallback = bool(fallback_to_long_term) and (
not _result_ok(recent)
or recent_count == 0
or _confidence_rank(recent_confidence) < _confidence_rank("high")
or recent_best_score < 1.45
)
taxonomy = _load_taxonomy()
variants = _query_variants(query)
candidate_wings = _infer_candidate_wings(query, taxonomy)
long_term = None
long_term_runs: list[dict[str, Any]] = []
if should_fallback:
for variant in variants or [query]:
for wing in candidate_wings:
result = _mempalace_search(query=variant, limit=limit, wing_hint=wing)
long_term_runs.append(result)
broad_result = _mempalace_search(query=query, limit=limit, wing_hint=None)
long_term_runs.append(broad_result)
collected: list[dict[str, Any]] = []
top_similarity = 0.0
confidence = "low"
for run in long_term_runs:
if not _result_ok(run):
continue
for item in run.get("results", []) or []:
if isinstance(item, dict):
collected.append(item)
top_similarity = max(top_similarity, float(item.get("similarity", 0.0) or 0.0))
confidence = max([confidence, str(run.get("confidence", "low"))], key=_confidence_rank)
deduped = _dedupe_long_term_results(collected)[:limit]
long_term = {
"success": bool(deduped),
"action": "search_long_term",
"query": query,
"variants": variants,
"candidate_wings": candidate_wings,
"runs": long_term_runs,
"results": deduped,
"result_count": len(deduped),
"top_similarity": round(top_similarity, 4),
"confidence": confidence if deduped else "low",
"source": "mempalace",
"mcp_tool": MEMPALACE_TOOL,
}
best_tier = "recent"
overall_confidence = recent_confidence
if _result_ok(long_term):
long_term_conf = str(long_term.get("confidence", "low"))
if (
not _result_ok(recent)
or recent_count == 0
or _confidence_rank(long_term_conf) >= _confidence_rank(recent_confidence)
):
best_tier = "long_term"
overall_confidence = long_term_conf
summary = _summarize_cross_tier(recent, long_term, limit=min(limit, 6))
answer_packet = _build_answer_packet(query, recent, long_term, limit=limit)
return {
"success": _result_ok(recent) or _result_ok(long_term),
"action": "search",
"query": query,
"strategy": "tier1-active-memory->tier2-daily->tier3-mempalace-multiwing",
"fallback_used": bool(long_term_runs),
"best_tier": best_tier,
"confidence": overall_confidence,
"recent": recent,
"long_term": long_term,
"recent_match_count": recent_count,
"recent_best_score": recent_best_score,
"long_term_match_count": len(long_term.get("results", []) if isinstance(long_term, dict) and isinstance(long_term.get("results"), list) else []),
"summary": summary,
"answer_packet": answer_packet,
"source": "daily+mempalace" if long_term else "daily",
"candidate_wings": candidate_wings,
"query_variants": variants,
}
def _maintain(day: Optional[str], promote_to_long_term: bool) -> dict[str, Any]:
compact_result = _run_script(
"compact",
"--memory-file",
str(MEMORY_FILE),
"--daily-dir",
str(DAILY_DIR),
"--retention-days",
str(RETENTION_DAYS),
*(["--day", day] if day else []),
)
promotion = None
diary = None
taxonomy = _load_taxonomy()
if promote_to_long_term and _result_ok(compact_result):
day_key = str(compact_result.get("day", day or ""))
summary = list(compact_result.get("summary", []) or [])
source_name = Path(compact_result.get("daily_file", "")).name or f"{day or 'daily'}.md"
promotion = _promote_daily_summary_to_mempalace(
day=day_key,
summary=summary,
source_file=source_name,
)
if summary:
diary_text = f"Daily 3-tier memory maintenance for {day_key}:\n" + "\n".join(f"- {item}" for item in summary[:DEFAULT_PROMOTION_LIMIT])
history_wing = _slugify(str(taxonomy.get("defaults", {}).get("history_wing", DEFAULT_HISTORY_WING)))
ok, call_result, error = _call_mcp_tool(
'mempalace_diary_write',
{
'agent_name': DEFAULT_AGENT_NAME,
'entry': diary_text,
'topic': 'three-tier-memory',
'wing': history_wing,
},
timeout=180,
)
if ok and not getattr(call_result, 'isError', False):
diary = {'success': True, 'wing': history_wing}
else:
diary = {'success': False, 'details': error or 'diary write failed', 'wing': history_wing}
return {
"success": _result_ok(compact_result) and (promotion is None or _result_ok(promotion)),
"action": "maintain",
"compact": compact_result,
"promotion": promotion,
"diary": diary,
"promote_to_long_term": promote_to_long_term,
"taxonomy_file": str(TAXONOMY_FILE),
"status_file": str(STATUS_FILE),
}
def _save_taxonomy(taxonomy: dict[str, Any]) -> None:
TAXONOMY_FILE.write_text(json.dumps(taxonomy, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
def _taxonomy_status(wing: str | None = None, include_legacy: bool = True) -> dict[str, Any]:
taxonomy = _load_taxonomy()
wings = taxonomy.get("wings", {}) if isinstance(taxonomy, dict) else {}
if wing:
wing_key = _slugify(wing)
selected = {wing_key: wings.get(wing_key)} if wing_key in wings else {}
else:
selected = wings
result = {
"success": True,
"action": "taxonomy",
"taxonomy_file": str(TAXONOMY_FILE),
"defaults": taxonomy.get("defaults", {}),
"wings": selected,
"dynamic_wings": taxonomy.get("dynamic_wings", {}),
}
if include_legacy:
result["legacy"] = taxonomy.get("legacy", {})
return result
def _create_wing(wing: str, description: str | None, aliases: list[str] | None) -> dict[str, Any]:
wing_key = _slugify(wing)
if not wing_key:
return {"success": False, "error": "wing is required"}
taxonomy = _load_taxonomy()
wings = taxonomy.setdefault("wings", {})
if wing_key in wings:
return {"success": True, "action": "create_wing", "created": False, "reason": "already_exists", "wing": wing_key, "data": wings[wing_key]}
alias_values = [wing_key]
for item in aliases or []:
slug = _slugify(item)
if slug and slug not in alias_values:
alias_values.append(slug)
wings[wing_key] = {
"description": (description or f"Macro area for {wing_key}.").strip(),
"aliases": alias_values,
"rooms": {},
}
_save_taxonomy(taxonomy)
return {"success": True, "action": "create_wing", "created": True, "wing": wing_key, "data": wings[wing_key], "taxonomy_file": str(TAXONOMY_FILE)}
def _create_room(wing: str, room: str, tokens: list[str] | None, aliases: list[str] | None) -> dict[str, Any]:
wing_key = _slugify(wing)
room_key = _slugify(room)
if not wing_key or not room_key:
return {"success": False, "error": "wing and room are required"}
taxonomy = _load_taxonomy()
wings = taxonomy.setdefault("wings", {})
wing_entry = wings.get(wing_key)
if not isinstance(wing_entry, dict):
return {"success": False, "error": f"wing does not exist: {wing_key}"}
rooms = wing_entry.setdefault("rooms", {})
merged_tokens: list[str] = []
for item in [room, *(tokens or []), *(aliases or [])]:
slug = _slugify(item)
if slug and slug not in merged_tokens:
merged_tokens.append(slug)
if room_key in rooms:
existing = rooms.get(room_key)
if isinstance(existing, list):
for item in merged_tokens:
if item not in existing:
existing.append(item)
rooms[room_key] = existing
_save_taxonomy(taxonomy)
return {"success": True, "action": "create_room", "created": False, "reason": "already_exists", "wing": wing_key, "room": room_key, "tokens": rooms[room_key], "taxonomy_file": str(TAXONOMY_FILE)}
rooms[room_key] = merged_tokens or [room_key]
_save_taxonomy(taxonomy)
return {"success": True, "action": "create_room", "created": True, "wing": wing_key, "room": room_key, "tokens": rooms[room_key], "taxonomy_file": str(TAXONOMY_FILE)}
def _legacy_seed_entries() -> list[dict[str, str]]:
return [
{"room": "preferences", "content": "Legacy seeded preference memory: User prefers Telegram as coordination hub and concrete operational procedures.", "source_file": "legacy-seed-preferences.md"},
{"room": "policies", "content": "Legacy seeded policy memory: All machines use SysV init and systemd is explicitly rejected.", "source_file": "legacy-seed-policies.md"},
{"room": "architecture", "content": "Legacy seeded architecture memory: Hermes Node Protocol uses capability-based split tools and keeps gateway logic in-plugin.", "source_file": "legacy-seed-architecture.md"},
]
def _migrate_legacy(dry_run: bool = True, include_legacy: bool = True) -> dict[str, Any]:
taxonomy = _load_taxonomy()
legacy = taxonomy.get("legacy", {}) if isinstance(taxonomy, dict) else {}
legacy_wing = _slugify(str(legacy.get("wing", DEFAULT_LEGACY_WING)))
plans: list[dict[str, Any]] = []
writes: list[dict[str, Any]] = []
for entry in _legacy_seed_entries():
wing, room, importance, dynamic_created, classification = _classify_memory_entry(entry["content"], taxonomy)
plan = {
"source_wing": legacy_wing,
"source_room": entry["room"],
"target_wing": wing,
"target_room": room,
"importance": importance,
"dynamic_created": dynamic_created,
"classification": classification,
"content": entry["content"],
"source_file": entry["source_file"],
}
plans.append(plan)
if not dry_run:
write_result = _write_mempalace_drawer(
wing=wing,
room=room,
content=entry["content"],
source_file=entry["source_file"],
)
writes.append({**plan, "write": write_result})
listed_legacy = _list_drawers(wing=legacy_wing, room=None, limit=200, offset=0)
return {
"success": True,
"action": "migrate_legacy",
"dry_run": dry_run,
"include_legacy": include_legacy,
"legacy_wing": legacy_wing,
"plans": plans,
"writes": writes,
"listed_legacy": listed_legacy,
"migration_count": len(plans),
"written_count": len(writes),
"note": "Legacy migration currently supports seeded/reindexable legacy summaries for controlled validation. Full MemPalace drawer enumeration requires MCP list/get support.",
"taxonomy_file": str(TAXONOMY_FILE),
}
def _list_drawers(wing: str | None = None, room: str | None = None, limit: int = 50, offset: int = 0) -> dict[str, Any]:
args: dict[str, Any] = {'limit': max(1, limit), 'offset': max(0, offset)}
if wing:
args['wing'] = _slugify(wing)
if room:
args['room'] = _slugify(room)
ok, call_result, error = _call_mcp_tool('mempalace_list_drawers', args, timeout=60)
if not ok:
return {'success': False, 'error': 'list drawers failed', 'details': error}
if getattr(call_result, 'isError', False):
return {'success': False, 'error': 'list drawers returned error'}
text_parts = [getattr(block, 'text', None) for block in getattr(call_result, 'content', []) or []]
text_result = '\n'.join(part for part in text_parts if isinstance(part, str) and part).strip()
structured = getattr(call_result, 'structuredContent', None)
normalized, raw_payload = _normalize_result_payload(structured if structured is not None else text_result)
items = []
if isinstance(normalized, dict) and isinstance(normalized.get('drawers'), list):
items = normalized.get('drawers', [])
else:
items = _extract_mempalace_results(normalized)
results: list[dict[str, Any]] = []
for item in items if isinstance(items, list) else []:
if isinstance(item, dict):
results.append({
'drawer_id': _extract_drawer_id(item),
'wing': _extract_search_wing(item),
'room': _extract_search_room(item),
'preview': _extract_drawer_preview(item),
'source_file': _extract_search_source_file(item),
'raw': item,
})
total = normalized.get('total') if isinstance(normalized, dict) else None
return {'success': True, 'action': 'list_drawers', 'results': results, 'result_count': len(results), 'total': total, 'raw': raw_payload}
def _rehome_drawers(from_wing: str, from_room: str, to_wing: str, to_room: str) -> dict[str, Any]:
listed = _list_drawers(wing=from_wing, room=from_room, limit=200, offset=0)
updates: list[dict[str, Any]] = []
for item in listed.get('results', []) or []:
drawer_id = item.get('drawer_id')
if not drawer_id:
continue
ok, call_result, error = _call_mcp_tool(
'mempalace_update_drawer',
{'drawer_id': drawer_id, 'wing': _slugify(to_wing), 'room': _slugify(to_room)},
timeout=60,
)
updates.append({
'drawer_id': drawer_id,
'success': ok and not getattr(call_result, 'isError', False),
'error': error,
})
return {'listed': listed.get('result_count', 0), 'updates': updates}
def _purge_drawers_for_location(wing: str, room: str | None) -> dict[str, Any]:
listed = _list_drawers(wing=wing, room=room, limit=200, offset=0)
deleted: list[dict[str, Any]] = []
for item in listed.get('results', []) or []:
drawer_id = item.get('drawer_id')
if not drawer_id:
continue
ok, call_result, error = _call_mcp_tool('mempalace_delete_drawer', {'drawer_id': drawer_id}, timeout=60)
deleted.append({
'drawer_id': drawer_id,
'success': ok and not getattr(call_result, 'isError', False),
'error': error,
})
return {'listed': listed.get('result_count', 0), 'deleted': deleted}
def _delete_room(wing: str, room: str, purge_drawers: bool = False) -> dict[str, Any]:
wing_key = _slugify(wing)
room_key = _slugify(room)
taxonomy = _load_taxonomy()
wings = taxonomy.get('wings', {}) if isinstance(taxonomy, dict) else {}
wing_entry = wings.get(wing_key)
if not isinstance(wing_entry, dict):
return {'success': False, 'error': f'wing does not exist: {wing_key}'}
rooms = wing_entry.get('rooms', {})
if room_key not in rooms:
return {'success': False, 'error': f'room does not exist: {wing_key}/{room_key}'}
removed_tokens = rooms.pop(room_key)
_save_taxonomy(taxonomy)
purge = _purge_drawers_for_location(wing_key, room_key) if purge_drawers else None
return {
'success': True,
'action': 'delete_room',
'wing': wing_key,
'room': room_key,
'removed_tokens': removed_tokens,
'purge': purge,
'taxonomy_file': str(TAXONOMY_FILE),
}
def _delete_wing(wing: str, purge_drawers: bool = False) -> dict[str, Any]:
wing_key = _slugify(wing)
taxonomy = _load_taxonomy()
wings = taxonomy.get('wings', {}) if isinstance(taxonomy, dict) else {}
if wing_key not in wings:
return {'success': False, 'error': f'wing does not exist: {wing_key}'}
removed = wings.pop(wing_key)
_save_taxonomy(taxonomy)
purge = _purge_drawers_for_location(wing_key, None) if purge_drawers else None
return {
'success': True,
'action': 'delete_wing',
'wing': wing_key,
'removed': removed,
'purge': purge,
'taxonomy_file': str(TAXONOMY_FILE),
}
def _move_room(wing: str, room: str, new_wing: str) -> dict[str, Any]:
wing_key = _slugify(wing)
room_key = _slugify(room)
new_wing_key = _slugify(new_wing)
taxonomy = _load_taxonomy()
wings = taxonomy.get('wings', {}) if isinstance(taxonomy, dict) else {}
src = wings.get(wing_key)
dst = wings.get(new_wing_key)
if not isinstance(src, dict):
return {'success': False, 'error': f'source wing does not exist: {wing_key}'}
if not isinstance(dst, dict):
return {'success': False, 'error': f'destination wing does not exist: {new_wing_key}'}
src_rooms = src.get('rooms', {})
dst_rooms = dst.setdefault('rooms', {})
if room_key not in src_rooms:
return {'success': False, 'error': f'room does not exist: {wing_key}/{room_key}'}
if room_key in dst_rooms:
return {'success': False, 'error': f'destination already has room: {new_wing_key}/{room_key}'}
dst_rooms[room_key] = src_rooms.pop(room_key)
_save_taxonomy(taxonomy)
moved_drawers = _rehome_drawers(wing_key, room_key, new_wing_key, room_key)
return {
'success': True,
'action': 'move_room',
'from': {'wing': wing_key, 'room': room_key},
'to': {'wing': new_wing_key, 'room': room_key},
'drawer_updates': moved_drawers,
'taxonomy_file': str(TAXONOMY_FILE),
}
def _validate_wing_hint_behavior(query: str, taxonomy: dict[str, Any], limit: int = 5) -> dict[str, Any]:
candidate_wings = [wing for wing in _infer_candidate_wings(query, taxonomy) if wing != DEFAULT_LEGACY_WING]
runs: list[dict[str, Any]] = []
for wing in candidate_wings[:3]:
runs.append(_mempalace_search(query=query, limit=limit, wing_hint=wing))
broad = _mempalace_search(query=query, limit=limit, wing_hint=None)
runs.append(broad)
comparisons = []
query_tokens = _token_set(query)
for run in runs:
if not isinstance(run, dict):
continue
results = run.get('results') or []
top = results[0] if results else {}
result_text = " ".join(_extract_search_text(item) for item in results if isinstance(item, dict))
result_tokens = _token_set(result_text)
top_text = _extract_search_text(top)
comparisons.append({
'wing_hint': run.get('wing_hint'),
'result_count': run.get('result_count'),
'top_similarity': run.get('top_similarity'),
'query_alignment': round(_jaccard_similarity(query_tokens, result_tokens), 4),
'top_preview': _shorten(top_text, 140),
'top_drawer_id': _extract_drawer_id(top),
'top_source_file': _extract_search_source_file(top),
})
broad_comparison = next((item for item in comparisons if item.get('wing_hint') is None), None)
best_targeted = max(
(item for item in comparisons if item.get('wing_hint') is not None),
key=lambda item: (float(item.get('top_similarity') or 0.0), float(item.get('query_alignment') or 0.0), int(item.get('result_count') or 0)),
default=None,
)
improvement = None
if broad_comparison and best_targeted:
improvement = {
'best_targeted_wing': best_targeted.get('wing_hint'),
'similarity_delta': round(float(best_targeted.get('top_similarity') or 0.0) - float(broad_comparison.get('top_similarity') or 0.0), 4),
'alignment_delta': round(float(best_targeted.get('query_alignment') or 0.0) - float(broad_comparison.get('query_alignment') or 0.0), 4),
'result_count_delta': int(best_targeted.get('result_count') or 0) - int(broad_comparison.get('result_count') or 0),
}
meaningful = bool(
improvement and (
abs(float(improvement['similarity_delta'])) >= 0.02
or abs(float(improvement['alignment_delta'])) >= 0.02
or improvement['result_count_delta'] != 0
or (best_targeted and broad_comparison and best_targeted.get('top_drawer_id') != broad_comparison.get('top_drawer_id'))
)
)
return {
'success': True,
'action': 'validate_wing_hints',
'query': query,
'candidate_wings': candidate_wings,
'comparisons': comparisons,
'broad_run': broad_comparison,
'best_targeted_run': best_targeted,
'improvement': improvement,
'material_difference_detected': meaningful,
}
def _list_memories(wing: str | None = None, room: str | None = None, limit: int = 50, offset: int = 0) -> dict[str, Any]:
return _list_drawers(wing=wing, room=room, limit=limit, offset=offset)
def _update_wing_metadata(wing: str, description: str | None, aliases: list[str] | None) -> dict[str, Any]:
wing_key = _slugify(wing)
taxonomy = _load_taxonomy()
wings = taxonomy.get('wings', {}) if isinstance(taxonomy, dict) else {}
wing_entry = wings.get(wing_key)
if not isinstance(wing_entry, dict):
return {'success': False, 'error': f'wing does not exist: {wing_key}'}
if description:
wing_entry['description'] = description.strip()
if aliases:
merged = list(dict.fromkeys([*wing_entry.get('aliases', []), *[_slugify(a) for a in aliases if _slugify(a)]]))
wing_entry['aliases'] = merged
_save_taxonomy(taxonomy)
return {'success': True, 'action': 'update_wing', 'wing': wing_key, 'data': wing_entry, 'taxonomy_file': str(TAXONOMY_FILE)}
def _update_room_metadata(wing: str, room: str, tokens: list[str] | None, aliases: list[str] | None) -> dict[str, Any]:
wing_key = _slugify(wing)
room_key = _slugify(room)
taxonomy = _load_taxonomy()
wings = taxonomy.get('wings', {}) if isinstance(taxonomy, dict) else {}
wing_entry = wings.get(wing_key)
if not isinstance(wing_entry, dict):
return {'success': False, 'error': f'wing does not exist: {wing_key}'}
rooms = wing_entry.get('rooms', {})
existing = rooms.get(room_key)
if not isinstance(existing, list):
return {'success': False, 'error': f'room does not exist: {wing_key}/{room_key}'}
merged = list(existing)
for item in [*(tokens or []), *(aliases or [])]:
slug = _slugify(item)
if slug and slug not in merged:
merged.append(slug)
rooms[room_key] = merged
_save_taxonomy(taxonomy)
return {'success': True, 'action': 'update_room', 'wing': wing_key, 'room': room_key, 'tokens': merged, 'taxonomy_file': str(TAXONOMY_FILE)}
def _mempalace_introspection() -> dict[str, Any]:
status = _call_mcp_tool('mempalace_status', {}, timeout=30)
wings = _call_mcp_tool('mempalace_list_wings', {}, timeout=30)
rooms = _call_mcp_tool('mempalace_list_rooms', {}, timeout=30)
taxonomy = _call_mcp_tool('mempalace_get_taxonomy', {}, timeout=30)
return {
'success': True,
'action': 'introspect_mempalace',
'status_ok': status[0],
'wings_ok': wings[0],
'rooms_ok': rooms[0],
'taxonomy_ok': taxonomy[0],
'tool_support': {
'mempalace_status': status[0],
'mempalace_list_wings': wings[0],
'mempalace_list_rooms': rooms[0],
'mempalace_get_taxonomy': taxonomy[0],
},
}
def three_tier_memory_tool(
action: str,
query: Optional[str] = None,
day: Optional[str] = None,
limit: int = DEFAULT_SEARCH_LIMIT,
fallback_to_long_term: bool = True,
promote_to_long_term: bool = True,
wing: Optional[str] = None,
room: Optional[str] = None,
new_wing: Optional[str] = None,
description: Optional[str] = None,
aliases: Optional[list[str]] = None,
tokens: Optional[list[str]] = None,
include_legacy: bool = True,
dry_run: bool = True,
task_id: str = None,
) -> str:
del task_id
action = (action or "").strip().lower()
limit = max(1, _safe_int(limit, DEFAULT_SEARCH_LIMIT))
if action == "compact":
result = _maintain(day=day, promote_to_long_term=bool(promote_to_long_term)) if promote_to_long_term else _run_script(
"compact",
"--memory-file",
str(MEMORY_FILE),
"--daily-dir",
str(DAILY_DIR),
"--retention-days",
str(RETENTION_DAYS),
*(["--day", day] if day else []),
)
elif action == "maintain":
result = _maintain(day=day, promote_to_long_term=bool(promote_to_long_term))
elif action == "search":
if not query:
return json.dumps({"success": False, "error": "query is required for search"}, ensure_ascii=False)
result = _smart_search(query=query, limit=limit, fallback_to_long_term=bool(fallback_to_long_term))
elif action == "list":
result = _run_script("list", "--daily-dir", str(DAILY_DIR), "--retention-days", str(RETENTION_DAYS))
elif action == "search_long_term":
if not query:
return json.dumps({"success": False, "error": "query is required for search_long_term"}, ensure_ascii=False)
result = _mempalace_search(query=query, limit=limit)
elif action == "status":
result = _status()
elif action == "taxonomy":
result = _taxonomy_status(wing=wing, include_legacy=bool(include_legacy))
elif action == "create_wing":
if not wing:
return json.dumps({"success": False, "error": "wing is required for create_wing"}, ensure_ascii=False)
result = _create_wing(wing=wing, description=description, aliases=aliases)
elif action == "create_room":
if not wing or not room:
return json.dumps({"success": False, "error": "wing and room are required for create_room"}, ensure_ascii=False)
result = _create_room(wing=wing, room=room, tokens=tokens, aliases=aliases)
elif action == "update_wing":
if not wing:
return json.dumps({"success": False, "error": "wing is required for update_wing"}, ensure_ascii=False)
result = _update_wing_metadata(wing=wing, description=description, aliases=aliases)
elif action == "update_room":
if not wing or not room:
return json.dumps({"success": False, "error": "wing and room are required for update_room"}, ensure_ascii=False)
result = _update_room_metadata(wing=wing, room=room, tokens=tokens, aliases=aliases)
elif action == "delete_wing":
if not wing:
return json.dumps({"success": False, "error": "wing is required for delete_wing"}, ensure_ascii=False)
result = _delete_wing(wing=wing, purge_drawers=not bool(dry_run))
elif action == "delete_room":
if not wing or not room:
return json.dumps({"success": False, "error": "wing and room are required for delete_room"}, ensure_ascii=False)
result = _delete_room(wing=wing, room=room, purge_drawers=not bool(dry_run))
elif action == "move_room":
if not wing or not room or not new_wing:
return json.dumps({"success": False, "error": "wing, room, and new_wing are required for move_room"}, ensure_ascii=False)
result = _move_room(wing=wing, room=room, new_wing=new_wing)
elif action == "list_memories":
result = _list_memories(wing=wing, room=room, limit=limit, offset=0)
elif action == "migrate_legacy":
result = _migrate_legacy(dry_run=bool(dry_run), include_legacy=bool(include_legacy))
elif action == "validate_wing_hints":
if not query:
return json.dumps({"success": False, "error": "query is required for validate_wing_hints"}, ensure_ascii=False)
result = _validate_wing_hint_behavior(query=query, taxonomy=_load_taxonomy(), limit=limit)
elif action == "introspect_mempalace":
result = _mempalace_introspection()
else:
result = {"success": False, "error": f"unknown action: {action}"}
return json.dumps(result, ensure_ascii=False)
def _pre_tool_call(*, tool_name: str = "", args: Any = None, **_: Any) -> Optional[dict[str, str]]:
payload = args if isinstance(args, dict) else {}
if tool_name == "memory":
action = str(payload.get("action", "")).strip().lower()
if action in {"search", "find", "lookup"}:
return {
"action": "block",
"message": "The built-in memory tool only supports add/replace/remove. Use three_tier_memory(action='search', query='...') as the default smart memory retrieval path across daily and MemPalace tiers.",
}
return None
if tool_name == "session_search":
query = str(payload.get("query", "") or "").strip().lower()
if any(token in query for token in ["memory", "remember", "preference", "fact", "settings", "workflow"]):
return {
"action": "block",
"message": "For curated memory recall, use three_tier_memory(action='search', query='...'). It is the default smart 3-tier memory route with confidence-based fallback to multi-wing MemPalace. Use session_search for transcript recall only.",
}
if tool_name in {"search_files", "read_file", "session_search"}:
query = str(payload.get("query", "") or payload.get("pattern", "") or "").strip().lower()
if any(token in query for token in ["remember", "memory", "preference", "workflow", "fact"]):
return {
"action": "block",
"message": "Use three_tier_memory(action='search', query='...') for memory lookups. The 3-tier memory plugin is the primary recall system.",
}
return None
def _slash_help() -> str:
return (
"Usage:\n"
"/3mem status\n"
"/3mem compact [YYYY-MM-DD]\n"
"/3mem maintain [YYYY-MM-DD]\n"
"/3mem search <query>\n"
"/3mem long <query>\n"
"/3mem list"
)
def _handle_slash(raw_args: str) -> str:
text = (raw_args or "").strip()
if not text:
return _slash_help()
parts = shlex.split(text)
sub = parts[0].lower()
if sub == "status":
return three_tier_memory_tool(action="status")
if sub == "list":
return three_tier_memory_tool(action="list")
if sub == "compact":
day = parts[1] if len(parts) > 1 else None
return three_tier_memory_tool(action="compact", day=day)
if sub == "maintain":
day = parts[1] if len(parts) > 1 else None
return three_tier_memory_tool(action="maintain", day=day)
if sub == "search":
query = " ".join(parts[1:]).strip()
if not query:
return json.dumps({"success": False, "error": "usage: /3mem search <query>"}, ensure_ascii=False)
return three_tier_memory_tool(action="search", query=query)
if sub in {"long", "long-search", "search-long", "search_long_term"}:
query = " ".join(parts[1:]).strip()
if not query:
return json.dumps({"success": False, "error": "usage: /3mem long <query>"}, ensure_ascii=False)
return three_tier_memory_tool(action="search_long_term", query=query)
return _slash_help()
def register(ctx):
_STATE.ctx = ctx
_load_taxonomy()
ctx.register_tool(
name="three_tier_memory",
toolset=TOOLSET,
schema=THREE_TIER_MEMORY_SCHEMA,
handler=lambda args, **kw: three_tier_memory_tool(
action=args.get("action", ""),
query=args.get("query"),
day=args.get("day"),
limit=args.get("limit", DEFAULT_SEARCH_LIMIT),
fallback_to_long_term=args.get("fallback_to_long_term", True),
promote_to_long_term=args.get("promote_to_long_term", True),
wing=args.get("wing"),
room=args.get("room"),
new_wing=args.get("new_wing"),
description=args.get("description"),
aliases=args.get("aliases"),
tokens=args.get("tokens"),
include_legacy=args.get("include_legacy", True),
dry_run=args.get("dry_run", True),
task_id=kw.get("task_id"),
),
description="Primary 3-tier Hermes memory system with smart cross-tier retrieval, multi-wing MemPalace organization, and daily maintenance.",
emoji="🧠",
)
ctx.register_hook("pre_tool_call", _pre_tool_call)
ctx.register_command(
"3mem",
handler=_handle_slash,
description="Manage three-tier memory: status, compact, maintain, search, long, list.",
args_hint="status|compact [day]|maintain [day]|search <query>|long <query>|list",
)
logger.info("hermes-three-tier-memory plugin registered")
name: hermes-three-tier-memory
version: 1.0.0
description: "Three-tier Hermes memory outside core source: active MEMORY.md, rolling 7-day daily memory, and nightly compaction tooling."
author: Lisa (Hermes AI)
kind: standalone
platforms:
- linux
provides_tools:
- three_tier_memory
hooks:
- pre_tool_call
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import re
from collections import Counter
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
ENTRY_DELIMITER = "\n§\n"
DEFAULT_RETENTION_DAYS = 7
MAX_DAILY_LINE_LEN = 220
STOPWORDS = {
"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "how", "i", "in", "is", "it",
"of", "on", "or", "that", "the", "this", "to", "was", "we", "what", "when", "where", "which",
"who", "why", "with", "you", "your",
}
def utc_today_key() -> str:
return datetime.now(timezone.utc).date().isoformat()
def load_entries(path: Path) -> list[str]:
if not path.exists():
return []
text = path.read_text(encoding="utf-8").strip()
if not text:
return []
return [chunk.strip() for chunk in text.split(ENTRY_DELIMITER) if chunk.strip()]
def write_entries(path: Path, entries: list[str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
body = ENTRY_DELIMITER.join(entry.strip() for entry in entries if entry.strip())
if body:
body += "\n"
path.write_text(body, encoding="utf-8")
def compress_entry(entry: str) -> str:
line = " ".join(part.strip() for part in entry.splitlines() if part.strip())
line = re.sub(r"\s+", " ", line).strip()
if len(line) > MAX_DAILY_LINE_LEN:
line = line[: MAX_DAILY_LINE_LEN - 3].rstrip() + "..."
return line
def dedupe_keep_order(items: list[str]) -> list[str]:
seen: set[str] = set()
out: list[str] = []
for item in items:
key = item.strip()
if not key or key in seen:
continue
seen.add(key)
out.append(key)
return out
def prune_daily_dir(daily_dir: Path, retention_days: int) -> list[str]:
keep = {
(datetime.now(timezone.utc).date() - timedelta(days=delta)).isoformat()
for delta in range(max(1, retention_days))
}
removed: list[str] = []
daily_dir.mkdir(parents=True, exist_ok=True)
for path in daily_dir.glob("*.md"):
if path.stem not in keep:
path.unlink(missing_ok=True)
removed.append(path.stem)
return sorted(removed)
def tokenize(text: str) -> list[str]:
return [token for token in re.findall(r"[a-z0-9_./:-]+", text.lower()) if token]
def keywords(text: str) -> list[str]:
return [token for token in tokenize(text) if token not in STOPWORDS and len(token) > 1]
def summarize_entries(entries: list[str], max_points: int = 12) -> list[str]:
compressed = [compress_entry(entry) for entry in entries if compress_entry(entry)]
if not compressed:
return []
counts = Counter()
for entry in compressed:
counts.update(set(keywords(entry)))
def score(entry: str) -> tuple[int, int]:
toks = set(keywords(entry))
return (sum(counts[token] for token in toks), len(entry))
ranked = sorted(compressed, key=score, reverse=True)
return dedupe_keep_order(ranked)[:max_points]
def score_entry(query: str, entry: str, day: str) -> dict[str, Any]:
q = query.strip().lower()
entry_text = entry.strip()
entry_lower = entry_text.lower()
q_tokens = keywords(query)
e_tokens = set(keywords(entry_text))
overlap = [token for token in q_tokens if token in e_tokens]
overlap_ratio = (len(set(overlap)) / len(set(q_tokens))) if q_tokens else 0.0
exact_phrase = q in entry_lower if q else False
prefix_hit = any(token.startswith(q) for token in e_tokens) if q and len(q) > 2 else False
score = 0.0
if exact_phrase:
score += 1.0
score += overlap_ratio * 0.9
if prefix_hit:
score += 0.15
if query.strip() == entry_text:
score += 0.5
confidence = "low"
if score >= 1.45:
confidence = "high"
elif score >= 0.75:
confidence = "medium"
return {
"day": day,
"entry": entry_text,
"score": round(score, 4),
"confidence": confidence,
"exact_phrase": exact_phrase,
"matched_terms": sorted(set(overlap)),
"matched_term_count": len(set(overlap)),
}
def compact(memory_file: Path, daily_dir: Path, day: str | None, retention_days: int) -> dict[str, Any]:
day_key = day or utc_today_key()
active_entries = load_entries(memory_file)
compressed = dedupe_keep_order([compress_entry(entry) for entry in active_entries if compress_entry(entry)])
daily_file = daily_dir / f"{day_key}.md"
existing = load_entries(daily_file)
merged = dedupe_keep_order(existing + compressed)
write_entries(daily_file, merged)
removed = prune_daily_dir(daily_dir, retention_days)
summary = summarize_entries(merged)
return {
"success": True,
"action": "compact",
"memory_file": str(memory_file),
"daily_file": str(daily_file),
"day": day_key,
"active_entry_count": len(active_entries),
"written_entry_count": len(merged),
"summary": summary,
"removed_days": removed,
}
def search_daily(daily_dir: Path, query: str, retention_days: int, limit: int) -> dict[str, Any]:
q = query.strip().lower()
if not q:
return {"success": False, "error": "query cannot be empty"}
prune_daily_dir(daily_dir, retention_days)
matches: list[dict[str, Any]] = []
for path in sorted(daily_dir.glob("*.md"), reverse=True):
for entry in load_entries(path):
scored = score_entry(query, entry, path.stem)
if scored["score"] > 0:
matches.append(scored)
matches.sort(key=lambda item: (item["score"], item["day"]), reverse=True)
trimmed = matches[:limit]
best_score = trimmed[0]["score"] if trimmed else 0.0
confidence = "low"
if best_score >= 1.45:
confidence = "high"
elif best_score >= 0.75:
confidence = "medium"
summary = summarize_entries([item["entry"] for item in trimmed], max_points=min(6, limit))
return {
"success": True,
"action": "search",
"query": query,
"matches": trimmed,
"match_count": len(trimmed),
"best_score": round(best_score, 4),
"confidence": confidence,
"summary": summary,
}
def list_daily(daily_dir: Path, retention_days: int) -> dict[str, Any]:
prune_daily_dir(daily_dir, retention_days)
daily: dict[str, list[str]] = {}
for path in sorted(daily_dir.glob("*.md"), reverse=True):
daily[path.stem] = load_entries(path)
return {"success": True, "action": "list", "daily": daily}
def main() -> int:
parser = argparse.ArgumentParser(description="Compact/search Hermes active memory into rolling daily memory files")
parser.add_argument("action", choices=["compact", "search", "list"])
parser.add_argument("--memory-file", default=str(Path.home() / ".hermes/memories/MEMORY.md"))
parser.add_argument("--daily-dir", default=str(Path.home() / ".hermes/memories/daily"))
parser.add_argument("--day", default=None)
parser.add_argument("--retention-days", type=int, default=DEFAULT_RETENTION_DAYS)
parser.add_argument("--query", default="")
parser.add_argument("--limit", type=int, default=8)
args = parser.parse_args()
memory_file = Path(args.memory_file).expanduser()
daily_dir = Path(args.daily_dir).expanduser()
if args.action == "compact":
result = compact(memory_file, daily_dir, args.day, args.retention_days)
elif args.action == "search":
result = search_daily(daily_dir, args.query, args.retention_days, args.limit)
else:
result = list_daily(daily_dir, args.retention_days)
print(json.dumps(result, ensure_ascii=False))
return 0 if result.get("success") else 1
if __name__ == "__main__":
raise SystemExit(main())
#!/usr/bin/env python3
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
sys.path.insert(0, '/home/lisa/.hermes/hermes-agent')
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import __init__ as plugin # noqa: E402
from compact_memory import load_entries, summarize_entries # noqa: E402
from tools.mcp_tool import discover_mcp_tools # noqa: E402
MEMORY_FILE = Path.home() / '.hermes' / 'memories' / 'MEMORY.md'
DEFAULT_WING = 'memories'
DEFAULT_GENERAL_ROOM = 'general'
SUMMARY_ROOM = 'daily-summaries'
class DummyCtx:
pass
def slugify(text: str) -> str:
text = text.strip().lower()
text = re.sub(r'[`*_#\[\](){}:;,.!?"\'\\/]+', ' ', text)
text = re.sub(r'\s+', '-', text)
text = re.sub(r'[^a-z0-9-]+', '', text)
return text.strip('-') or DEFAULT_GENERAL_ROOM
def classify_entry(entry: str) -> tuple[str, str, int]:
lower = entry.lower()
importance = 1
if any(token in lower for token in ['preference', 'prefers', 'workflow preference', 'likes', 'dislikes', 'expects', 'strongly dislike']):
return DEFAULT_WING, 'preferences', 5
if any(token in lower for token in ['always', 'never', 'must', 'critical', 'require', 'rejected', 'explicitly rejected']):
return DEFAULT_WING, 'policies', 5
if any(token in lower for token in ['config', 'path', 'installed', 'reachable', 'machine', 'gateway', 'plugin', 'mcp', 'command', 'repo']):
return DEFAULT_WING, 'infrastructure', 4
if any(token in lower for token in ['architecture', 'capability', 'design', 'protocol', 'integration']):
return DEFAULT_WING, 'architecture', 4
return DEFAULT_WING, DEFAULT_GENERAL_ROOM, importance
def main() -> int:
plugin._STATE.ctx = DummyCtx()
discover_mcp_tools()
raw_entries = load_entries(MEMORY_FILE)
organized = []
promoted = []
seen_payloads = set()
for entry in raw_entries:
compact = plugin._run_script('compact', '--memory-file', str(MEMORY_FILE), '--daily-dir', str(Path.home() / '.hermes' / 'memories' / 'daily'), '--retention-days', '7')
day = compact.get('day', '') if isinstance(compact, dict) else ''
break
else:
day = ''
for entry in raw_entries:
compressed = ' '.join(entry.split())
if not compressed:
continue
wing, room, importance = classify_entry(compressed)
room = slugify(room)
if room == SUMMARY_ROOM:
room = DEFAULT_GENERAL_ROOM
payload = f"[{day or 'undated'}] [importance:{importance}] {compressed}"
if payload in seen_payloads:
continue
seen_payloads.add(payload)
result = plugin._promote_daily_summary_to_mempalace(day or 'undated', [payload], f'{day or "undated"}.md')
if isinstance(result, dict) and result.get('success'):
organized.append({'wing': wing, 'room': room, 'importance': importance, 'entry': compressed})
promoted.append(result)
summary_lines = summarize_entries(raw_entries, max_points=10)
summary = plugin._promote_daily_summary_to_mempalace(day or 'undated', summary_lines, f'{day or "undated"}.md')
print(json.dumps({
'success': True,
'day': day,
'organized_entries': organized,
'promoted_count': len(promoted),
'summary_promotion': summary,
}, ensure_ascii=False))
return 0
if __name__ == '__main__':
raise SystemExit(main())
#!/usr/bin/env python3
from __future__ import annotations
import json
import sys
from pathlib import Path
sys.path.insert(0, '/home/lisa/.hermes/hermes-agent')
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import __init__ as plugin # noqa: E402
class DummyCtx:
pass
plugin._STATE.ctx = DummyCtx()
try:
from tools.mcp_tool import discover_mcp_tools # type: ignore
except Exception:
discover_mcp_tools = None
if discover_mcp_tools is not None:
try:
discover_mcp_tools()
except Exception:
pass
result = json.loads(plugin.three_tier_memory_tool(action="maintain", promote_to_long_term=True))
print(json.dumps(result, ensure_ascii=False))
{
"version": 1,
"legacy": {
"enabled": true,
"wing": "memories",
"history_room": "daily-summaries"
},
"defaults": {
"history_wing": "history",
"summary_room": "daily-summaries",
"diary_room": "diary",
"fallback_wing": "work",
"fallback_room": "general"
},
"wings": {
"identity": {
"description": "Stable facts about user identity, preferences, and habits.",
"aliases": [
"preferences",
"profile",
"identity",
"habits"
],
"rooms": {
"preferences": [
"preference",
"prefers",
"likes",
"dislikes",
"workflow preference",
"expects",
"style",
"habit"
],
"profile": [
"name",
"timezone",
"role",
"identity",
"profile"
],
"habits": [
"habit",
"routine",
"usually",
"normally",
"often"
]
}
},
"governance": {
"description": "Policies, constraints, security requirements, and durable decisions.",
"aliases": [
"policy",
"policies",
"security",
"constraints",
"governance"
],
"rooms": {
"policies": [
"always",
"never",
"must",
"critical",
"required",
"explicitly rejected",
"policy"
],
"constraints": [
"constraint",
"cannot",
"must not",
"do not",
"without"
],
"security": [
"security",
"secret",
"credential",
"token",
"privacy",
"approval"
],
"decisions": [
"decision",
"chosen",
"prefer that over",
"target architecture"
]
}
},
"systems": {
"description": "Infrastructure, architecture, platforms, and technical integrations.",
"aliases": [
"systems",
"infrastructure",
"architecture",
"platforms",
"integrations"
],
"rooms": {
"infrastructure": [
"config",
"path",
"installed",
"reachable",
"machine",
"node",
"gateway",
"plugin",
"repo",
"package"
],
"architecture": [
"architecture",
"capability",
"design",
"protocol",
"integration",
"taxonomy",
"topology"
],
"integrations": [
"mcp",
"api",
"integration",
"provider",
"adapter"
],
"platforms": [
"telegram",
"discord",
"browser",
"chrome",
"linux",
"windows"
]
}
},
"work": {
"description": "Projects, operations, debugging, and delivery-oriented memory.",
"aliases": [
"work",
"projects",
"operations",
"debugging"
],
"rooms": {
"projects": [
"project",
"feature",
"roadmap",
"milestone"
],
"operations": [
"workflow",
"process",
"procedure",
"deploy",
"release",
"maintenance",
"operational"
],
"debugging": [
"bug",
"error",
"traceback",
"fix",
"debug",
"issue"
],
"deliveries": [
"deliver",
"release",
"bundle",
"shipped",
"published"
],
"general": [
"work",
"task",
"implementation"
],
"appointments": [
"appointments",
"appointment",
"doctor",
"clinic",
"medical-visits",
"hospital",
"clinic-visits"
]
}
},
"history": {
"description": "Summaries and chronological traces.",
"aliases": [
"history",
"daily",
"summary",
"diary"
],
"rooms": {
"daily": [
"daily"
],
"daily-summaries": [
"summary",
"daily summary"
],
"diary": [
"diary",
"journal",
"history"
]
}
},
"relationships": {
"description": "Family, marriage, partners, and important people relationships.",
"aliases": [
"relationships",
"family",
"marriage",
"partner",
"people"
],
"rooms": {
"family": [
"family",
"parent",
"child",
"sibling",
"relative"
],
"marriage": [
"marriage",
"married",
"spouse",
"wife",
"husband"
],
"partners": [
"partner",
"girlfriend",
"boyfriend",
"significant other"
],
"important-people": [
"friend",
"person",
"people",
"relationship"
]
}
},
"care": {
"description": "Care responsibilities and support logistics",
"aliases": [
"care",
"healthcare",
"carework",
"caregiving"
],
"rooms": {}
}
},
"dynamic_wings": {
"enabled": true,
"keywords": {
"marriage": {
"wing": "relationships",
"room": "marriage"
},
"family": {
"wing": "relationships",
"room": "family"
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment