Compare commits

...
Author SHA1 Message Date
feitianxiang 70aaa7be85 Merge pull request #170 from Tencent-Hunyuan/fix/upgrade-runtime-and-sdk-memory-map
fix(memhub): install the bundled Runtime on upgrade and show SDK memories
2026-10-24 23:12:03 +08:00
alvinfeiandClaude Opus 5.5 18046152ab feat(memhub): draw the memory map from SDK memories on SDK authority
The default memory view is the map, and on SDK authority it had nothing
to draw: its list and graph read only legacy authority. It now reads SDK
memories (`/api/v2/memory-library`) and `/api/v2/memories/graph` and
draws them with the same map model, so the map stays the default view.
Opening a memory from the map goes to the SDK library, which reads,
edits and deletes it through v2; governed detail is refused there.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 22:22:55 +08:00
alvinfeiandClaude Opus 5.5 7b946a28ef fix(memhub): install the bundled Runtime on upgrade and show SDK memories
Build 21 acceptance found an upgraded App on the previous Runtime and a
memory page that never left "reading":

- Desktop skipped `installPackagedRuntime` whenever the service owner was
  "cli", which it also assumes itself when a plist exists without an owner
  receipt. The App now always installs its bundled Runtime (a newer build
  from `memhub upgrade` is kept) and refuses to start on a `current` older
  than its own build (`packaged_runtime_not_current`). The startup failure
  event now records the cause, with the home path shortened.
- On SDK authority the default memory map loaded nothing: its list and
  graph read only legacy authority. The memory page now opens the v2 SDK
  library there, and `/api/v2/memories/graph` serves the map from SDK
  memories plus the Kuzu overlay. A failed authority probe is retried
  instead of leaving the page unknown forever.
- Every completed SDK write logged RetiredAuthorityAccess: the retired
  Evidence facade raised from `getattr(..., None)`. It now has a no-op
  `release_sdk_staging`.
- A repair of an already migrated home is reported as `complete`, not a
  second `cutover`, and the CLI treats it as non-rollbackable too.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 22:08:14 +08:00
alvinfeiandClaude Opus 5.5 e5ce0cd964 refactor(memhub): remove the private retrieval vector index
All memory and raw reads and writes go through the Hy Memory SDK. The
one_memory.retrieval index kept a second, MemHub-owned vector copy of
conversation text in a private Chroma store under <data_dir>/retrieval-vectors/,
which that rule does not allow. It was experimental and off by default.

Remove the vector store, runtime, provisioning, supervisor, worker, index
store, chunking and mapped content, the offset tokenizer only chunking used,
the semantic raw lanes that read the index, the retrieval_index_enabled and
retrieval_minimum_free_bytes settings, app.state.retrieval_runtime and their
tests. The context route now calls the lexical raw reader directly, which is
exactly what it did with the index disabled; the v2 coordinator keeps its
lexical lane with the same statuses it produced when no index was configured.

Historical migrations and the legacy retrieval tables in the drop list are
unchanged. An existing retrieval-vectors directory is left on disk.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 18:13:47 +08:00
alvinfeiandClaude Opus 5.5 d8837b4fb2 fix(memhub): reattach stranded vectors and read memories back before cutover
Build 20 cut over showing 37 of 3317 memories, with "memory unavailable"
on every page:

- `/api/v2/memory-authority` read the cutover receipt, which cleanup drops
  and a fresh home never has, so the UI chose the legacy views the API
  refuses. It now reads the authority singleton the gates use.
- #145 renamed the SDK vector collections (`one_memory_*` to `memhub_*`)
  and dropped the step that carried old ones over, so every later Runtime
  read an empty collection. `sdk-migrate` now renames them through Chroma's
  public client while the Runtime is stopped, merging any newer writes,
  and also repairs homes that already cut over.
- The cutover only checked the backup. It now opens the public SDK client
  as the Runtime will and reads the legacy memory ids back; every chat
  memory must read back or the run stops before anything irreversible.
  A migrated home is checked against its pre-cutover bundle.

Cleanup also VACUUMs the main database to return the dropped tables' space.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 18:02:53 +08:00
feitianxiang 0c36a6c960 Merge pull request #168 from Tencent-Hunyuan/feat/single-sdk-migrate-command
feat(memhub): migrate every install with one sdk-migrate command
2026-10-24 11:47:25 +08:00
alvinfeiandClaude Opus 5.5 9bdce08847 feat(memhub): migrate every install with one sdk-migrate command
Only Desktop ran the SDK-authority migration, so homes upgraded with
`memhub upgrade` (Linux, and macOS without the App) stayed on legacy
authority for good. The migration was also four Core commands that
Desktop orchestrated, which a second caller would have had to repeat.

Core now has one resumable `sdk-migrate --runtime-build <build>`: it
takes the host capture fence itself, backs up (reusing an existing
bundle), prepares the queue, commits authority and drops the legacy
tables, printing one progress line per step. `migration-bundle`,
`sdk-cutover` and `sdk-cleanup` are folded into it.

`runSdkMigration` in runtime-control keeps the Runtime stopped around
that command and is shared by Desktop startup and CLI install/upgrade.
The CLI runs it with the new Runtime's Core before starting the
service; a failure rolls back, and after cutover a slow start keeps the
new version because an older Runtime refuses a migrated home.

A rehearsal on a real home also showed freezing queue input failed on
completed jobs whose payload the queue had already released; those are
now skipped.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:46:01 +08:00
alvinfeiandClaude Opus 5.5 7cbc2fd632 fix(memhub): migrate to SDK authority without copying memory
Every released build wrote memory and raw turns through the SDK first;
the Governance/Evidence tables only mirrored them. The old migration
still compared the mirror with the SDK item by item, and its layer
labels did not say which Coding store held a row. Build 19 therefore
quarantined experiences that were on disk, quarantine had no exit, and
startup stayed blocked on every retry.

The cutover now copies and compares no memory. It verifies the bundle,
makes the write queue independent of the legacy tables, discards the
staging copy earlier builds left, commits authority and drops the
tables, including the evidence_search index that was left behind.
Invoked legacy tasks and pending deletions are reported, not blocking.
A home blocked by build 19 resumes its run and reuses its bundle.

Also fixes legacy-authority regressions from #145 found by the full
core suite: startup backfill, visibility recompute and deletion retry
were no longer started, deletion rows stayed pending, and correcting a
memory without a model returned 500.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 11:01:33 +08:00
kristinhe1111 6b0bd86679 Merge pull request #156 from Tencent-Hunyuan/fix/build-17-test-index
docs(memhub): regenerate the core test index for build 17
2026-10-23 20:22:05 +08:00
kristinhe1111 91250d7c87 fix(desktop): keep an unknown startup failure code in the dialog
Build 17 routed every startup error through the friendly-text map, so three
desktop contracts that assert the dialog body (page_load_failed,
runtime_broker_unavailable, host_permission_store_unavailable) started failing.

Only codes we wrote copy for become sentences now; anything else keeps the code
it was thrown with, which is what support reads.
2026-10-23 20:02:05 +08:00
kristinhe1111 3c89a535fb docs(memhub): regenerate the core test index for build 17
The build-17 test file was added without regenerating TEST_INDEX.md, so the
public structure gate failed on main. Generated artifact only.
2026-10-23 19:49:44 +08:00
kristinhe1111 1151878265 Merge pull request #155 from Tencent-Hunyuan/release/memhub-build-17
fix(memhub): build 17 — migration fixes carry through to first launch
2026-10-23 19:34:32 +08:00
kristinhe e82c4c939e fix(memhub): name a blocked cutover without its counts
The cutover gate reports sdk_data_plane_cutover_work_pending plus a JSON body of
table counts. That string went straight into the document the startup dialog
reads, so the person saw braces and table names.

Collapse it to sdk_migration_work_pending and let the dialog say the data is
already upgraded but earlier memory work is still finishing. Any other code that
is not a plain identifier becomes sdk_migration_cutover_failed, so no free text
reaches the dialog.
2026-10-23 19:33:31 +08:00
kristinhe ca4a66349b fix(memhub): explain the wait and the failure on first launch
Three things a person meets before the app can open:

- The waiting window had no drag region element, so a frameless window could not
  be moved at all; the CSS alone never applied to anything.
- The page said only that the service was starting. It now says a first launch
  or a memory upgrade can take a few minutes and the app opens by itself, in all
  three interface languages.
- A migration failure surfaced as a raw code in one path and a generic sentence
  in the other. Every migration code now maps to a sentence that says what
  happened, what happens to their memories, and what to do next; the dispatch
  path reuses the same mapping instead of printing error.message.

Build number 17 carries the diagnostics fix and the merged SDK migration fix.
2026-10-23 19:19:06 +08:00
kristinhe 82044d6172 fix(memhub): name the migration failure instead of one opaque code
A full disk, an unconfigured model profile and a Coding classification gap all
reached the person as sdk_migration_backfill_failed, so the startup dialog could
only ever say the upgrade failed.

Classify the exception chain before the code is written: ENOSPC/EDQUOT becomes
sdk_migration_disk_space_insufficient, SDK productivity errors become
sdk_migration_coding_inventory_failed, the legacy working_fact import failure
keeps its own name, and existing sdk_data_plane_/sdk_migration_ codes pass
through. Anything unrecognized keeps its message out of the document.
2026-10-23 19:18:56 +08:00
kristinhe 7f23b74c36 fix(memhub): separate local diagnostics from safe exports 2026-10-23 19:03:50 +08:00
kristinhe 617e2d0ba6 fix(memhub): keep diagnostics from blocking startup 2026-10-23 19:03:50 +08:00
feitianxiang 083b837f32 Merge pull request #154 from Tencent-Hunyuan/fix/sdk-migration-turns-and-coding
fix(memhub): harden SDK migration inventory and fencing
2026-10-23 17:37:15 +08:00
alvinfeiandCursor 1dc7e957c0 fix(memhub): harden SDK migration inventory
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 17:34:59 +08:00
feitianxiang 3b44d8381c Merge pull request #153 from Tencent-Hunyuan/fix/sdk-migration-turns-and-coding
fix(memhub): repair legacy SDK authority migration
2026-10-23 17:27:39 +08:00
alvinfeiandCursor 790d6d3d5e fix(memhub): repair SDK authority migration
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 17:26:40 +08:00
feitianxiang 4c311b2e93 Merge pull request #149 from Tencent-Hunyuan/fix/memhub-1.0.5-release-doc-test
test(memhub): update 1.0.5 release doc expectations
2026-10-22 21:31:04 +08:00
alvinfeiandCursor 801a2af36b test(memhub): update release documentation expectations
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 21:30:31 +08:00
feitianxiang 0a8e43e570 Merge pull request #148 from Tencent-Hunyuan/release/memhub-1.0.5
release(memhub): bump to 1.0.5 and pin hy-memory 2.0.5
2026-10-22 21:22:40 +08:00
alvinfeiandCursor f5a38c38b3 release(memhub): pin hy-memory 2.0.5
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 21:20:40 +08:00
feitianxiang d08e070816 Merge pull request #147 from Tencent-Hunyuan/release/hy-memory-2.0.5
release: hy-memory 2.0.5
2026-10-22 20:58:49 +08:00
alvinfeiandCursor 29bd9146a4 release: hy-memory 2.0.5
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 20:52:21 +08:00
26c33ee40f refactor(sdk): internalize legacy data migration (#146)
* refactor(sdk): keep legacy migration out of client APIs

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(migration): stage SDK data before cutover

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 20:49:23 +08:00
d926844173 refactor(memhub): remove private Hy Memory bridge (#145)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: kristinhe <kristinhe@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 20:02:27 +08:00
de4292ed4e feat(hermes): add managed native prefetch provider (#143)
* feat: add native Hermes memory provider

* feat(hermes): support scoped private CA trust

* feat(hermes): bound write timeout separately from reads

* fix(hermes): support truststore scoped CA snapshots

* feat(hermes): add managed prefetch provider

Co-authored-by: kindong <727777477@qq.com>
Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: kindong <727777477@qq.com>
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 16:51:15 +08:00
366befc2aa feat(memhub): add extensible Chinese, English, and Spanish UI (#142)
* Add Spanish localization and persistent GUI language preferences to MemHub

Co-authored-by: Cursor <cursoragent@cursor.com>

* Extend MemHub Spanish localization to the remaining GUI screens

Move the copy of Applications, memory space and map, matters, workbench,
call history, handoff and arrival panels into shared contracts catalogs.

- Merge domain catalogs without silent overrides: a key shared by two
  catalogs must have identical Chinese and Spanish texts.
- Add Spanish singular variants (`.one`) and count helpers that keep the
  Chinese numbers exactly as they were rendered before.
- Build the Spanish connection prompt from a catalog template; MCP and
  shell snippets are inserted verbatim, the Chinese prompt is unchanged.
- Word host failures at render time so a language switch re-words them.
- Unknown text, names, paths and error codes pass through untranslated;
  unknown graph node types and edge origins keep their previous labels.
- Add catalog parity, interpolation, adapter and regression tests.

* feat(memhub): add Chinese English Spanish localization

Co-authored-by: Nicolas Pirello <nicoalepirello@gmail.com>

Co-authored-by: kristinhe <kristinhe@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>

* style(memhub): satisfy Node workspace lint

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(memhub): align localization fixtures with current keys

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Nicolas Pirello <nicoalepirello@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: kristinhe <kristinhe@tencent.com>
2026-10-22 16:36:37 +08:00
a4c8c7e5fb docs: finalize public runtime and migration contracts (#141)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 15:38:41 +08:00
b7d9f0e0f4 docs: remove internal handoff and stale architecture notes (#140)
* chore: keep HANDSOFF local only

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs: remove internal notes and stale architecture markup

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 15:34:46 +08:00
6d1d29e16d refactor(memhub): move memory authority to SDK (#132)
* docs(memhub): define SDK-owned memory architecture

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(memhub): freeze legacy memory authority debt

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(memhub): define SDK data-plane migration contract

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): add SDK cutover migration ledger

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): create verified SDK migration bundles

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): expose offline migration bundle command

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(memhub): keep durable write scheduling in Core

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): delegate SDK backup to public API

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): restore complete SDK migration bundles

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): route SDK snapshots through bridge

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): persist SDK cutover state

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): add SDK-native memory projection

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): recover writes from SDK outcomes

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(memhub): pin SDK authority dev preview

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): classify legacy and SDK memory inventories

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): trust SDK physical delete receipts

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): execute classified memory migrations

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(memhub): pin exact migration SDK dev preview

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(memhub): preserve source SDK version in migration bundle

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): use one schema-driven legacy migration

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): migrate Evidence into SDK raw

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): run resumable offline SDK backfill

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): expose offline SDK backfill command

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): expose SDK-native memory APIs

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(web): add SDK-native memory client

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): migrate recall scopes by memory id

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): remove fabricated per-memory harness ACL

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(web): remove legacy per-memory recall controls

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(memhub): use SDK source filters for future harness policy

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): remove per-memory scope mutation API

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(web): remove dead recall scope component

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(memhub): pin raw-search SDK dev preview

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): search SDK raw through existing API

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): add honest SDK-native Context v2

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): switch library to sdk authority

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): cut host context over to sdk v2

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(memhub): run migration during app startup

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): add sdk raw scheduling receipts

Co-authored-by: Cursor <cursoragent@cursor.com>

* Revert "refactor(memhub): add sdk raw scheduling receipts"

This reverts commit d07ae91c93.

* refactor(memhub): persist sdk ids after queued add

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): stop governance mirroring after cutover

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): fence startup migration and resume effects

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): release transient evidence after sdk success

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): gate startup authority cutover

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): run sdk migration in app loading

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): block cutover until product paths switch

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): resume sdk staging cleanup on startup

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): add sdk-native ask v2

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): migrate matters to sdk references

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): hydrate matters from sdk references

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): switch matter reads to sdk references

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): queue sdk matter notes

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): discover matters from sdk authority

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): retire legacy digest and boundary after cutover

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): complete sdk raw and matter cutover

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): stop legacy maintenance after cutover

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): retire remaining legacy read surfaces

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(memhub): document sdk matter and raw cutover

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(runtime): allow receipt write under parallel load

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(memhub): publish sdk authority architecture

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(memhub): repair acceptance gate fixtures

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(memhub): separate fresh schema from legacy cleanup

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): finish SDK authority cutover

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(memhub): close CodeQL exposure paths

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(memhub): hash workspace identities without path expansion

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(memhub): add app migration acceptance guide

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 15:24:20 +08:00
feitianxiangandalvinfei c0737acb44 Revert "feat(sdk): process existing raw records (#136)" (#138)
This reverts commit 0244ebe38c.

Co-authored-by: alvinfei <alvinfei@tencent.com>
2026-10-22 06:49:10 +08:00
0244ebe38c feat(sdk): process existing raw records (#136)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 21:45:12 +08:00
e3b5a1bc9c release: publish Hy Memory 2.0.5.dev3 (#135)
* release: prepare Hy Memory 2.0.5.dev3

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(sdk): record 2.0.5.dev3 publication

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 20:50:45 +08:00
8aeb042bb7 feat(sdk): search raw through existing search API (#134)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 17:58:29 +08:00
635d2572c9 release: prepare Hy Memory 2.0.5.dev2 (#133)
* release: prepare Hy Memory 2.0.5.dev2

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(sdk): record 2.0.5.dev2 publication

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 17:19:09 +08:00
6113e2351e feat(sdk): import semantic memories exactly (#131)
* feat(sdk): import semantic memories exactly

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(sdk): record exact memory migration API

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 17:05:24 +08:00
b5a8a78c69 release: prepare Hy Memory 2.0.5.dev1 (#130)
* release: prepare Hy Memory 2.0.5.dev1

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(sdk): record 2.0.5.dev1 publication

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 17:01:12 +08:00
fd12c8f1c0 feat(sdk): add MemHub authority migration contracts (#129)
* feat(sdk): expose memory lifecycle status filters

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(sdk): persist idempotent write outcomes

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(sdk): add explicit exact raw APIs

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(sdk): snapshot quiesced local data plane

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(sdk): restore quiesced local data plane

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(sdk): report incomplete physical deletes

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(sdk): record authority migration contracts

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 16:43:25 +08:00
e089d4b800 fix(coding): default-off search chain_block (diff) injection (#128)
Medium/heavy coding users pay large prompt tokens for the version-evolution
diff block; make MEMORY_CODING_CHAIN_BLOCK_ENABLED opt-in (default false).
Write-side observe is unchanged; HCM_BLOCK_OFF remains an advanced kill switch.

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 14:46:23 +08:00
b370663870 fix(ci): locate nested Linux release artifacts (#36)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 14:14:24 +08:00
8ea6996859 chore(core): retire memory evidence freshness on read paths (#127)
* chore(core): retire memory evidence freshness on read paths

Stop re-validating support_refs against live evidence during library,
context, and call-reference reads. The check hid memories when evidence
changed but caused 503s and segment-key breakage; proofs may still be
written but are ignored until a later teardown removes them.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(docs): align install-docs pin with hy-memory 2.0.4

CI memhub failed because README already documents 2.0.4 / v1.0.4 while
the install-docs contract test still expected 2.0.3 / v1.0.3.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 14:11:57 +08:00
dc740604d2 fix(mysql): merge minute metrics under one row lock (#97)
store_metrics_minute() read the row, merged counters in Python, then wrote
with a separate SELECT + UPDATE/INSERT. Two instances flushing the same
minute could both read the old value and overwrite each other, and a
concurrent insert could lose the whole batch to a duplicate-key error that
the outer except swallowed.

Run the read-merge-write in one transaction with SELECT ... FOR UPDATE and
retry once on a duplicate key or deadlock. Add unit regressions for the
insert and merge paths.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 12:19:55 +08:00
55bf946bcc fix(episode): read series timestamps back in local time (#94)
Series episode memory_at used datetime.utcfromtimestamp() on values produced
by datetime.timestamp(). That yields a naive UTC datetime, which the vector
payload later re-interprets as local time, shifting the stored timestamp by
the machine's UTC offset (8 hours on Asia/Shanghai).

Round-trip through datetime.fromtimestamp() instead, and cover the wall-clock
round trip with a non-UTC TZ regression.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 12:19:51 +08:00
14fcc6fe38 fix(history): query every agent when agent_ids is omitted (#93)
get_recent_history() documented "agent_ids 为空时查询该用户所有 agent" but
constructed the isolation key with the literal "default". History records
are written as "{user_id}:{agent_id}", and add() defaults to
"default_agent", so the documented path usually returned nothing.

Add HistoryStore.get_recent_for_user(), which matches the literal user
prefix with an escaped LIKE, and use it from the client. Add regressions
for multiple agents, a sibling user id and LIKE wildcards in the user id.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 12:19:47 +08:00
1ef0766891 fix(agent): restore the SessionSummaryResult dataclass decorator (#92)
The @dataclass decorator was left at the end of the section-divider comment
line, so SessionSummaryResult was a plain class without __init__. Every
construction raised "takes no arguments" - including the error branch inside
generate_session_summary(), whose TypeError escaped the surrounding except.

Move the decorator onto its own line and add a constructor regression.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 12:19:42 +08:00
3370a715dd fix(client): stop both owned event loops on close (#91)
A solo client creates a write loop and a separate search loop, but close()
stopped only the write loop and __aexit__ stopped neither. Every client
instance against a long-lived process therefore leaked the search thread,
its selector and its 50ms self-wakeup timer. _LoopThread.stop() also left
the loop object unclosed.

Stop every owned loop from one idempotent helper used by both close() and
__aexit__, leave shared-runtime loops to the runtime, and close the loop
after its thread exits. Add lifecycle regressions for both modes.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 12:19:38 +08:00
638d1b7bde fix(server): avoid deadlock when shutting down on signals (#89)
BaseServer.shutdown() waits for serve_forever() to return. The SIGINT /
SIGTERM handlers called it directly, and signal handlers run on the same
thread that is executing serve_forever(), so the server could never exit:
the process hung until SIGKILL and the client was never closed.

Ask a helper thread to call shutdown() and move server_close()/client.close()
into a finally block after serve_forever() returns. Add an in-process test
and a subprocess test that fires SIGALRM while serving on the main thread.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 12:19:33 +08:00
d6890793ec fix(sdk): repair FAISS embedding lookup, dedup pairing, and episode summaries (#84)
* fix(faiss): reconstruct embeddings for dedup and episode summaries

Normal upsert paths store only the payload and the FAISS index position.
get_embeddings() looked for an "embedding" key that only update_payload
ever wrote, so it returned an empty mapping for every upserted node. Search
dedup and episode summaries therefore saw no vectors on the FAISS backend.

Reconstruct the vector from the live index position, guarded by the same
_idx_to_id check search() uses, and keep the stored fallback for nodes
updated through update_payload. Add a regression test.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(search): pair dedup markers with their source search result

The public items are filtered by the requested layers, but the private
dedup view was built with zip(result.memories, public_items). Once one
result is filtered out every later _memory_kind shifts by one, so a
canonical_state can enter fuzzy dedup and be shadowed, or an ordinary fact
can silently skip dedup.

Build both views in the same loop, from the same source element, and add a
regression test for the filtered case.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(episode): use the writer's vector store for background summaries

_schedule_episode_summary accessed self.vector_store, which MemoryWriter
never defines. The AttributeError was swallowed by the task's except block,
so every closed episode silently skipped its L3 summary.

Resolve the store through the existing async _get_vector_store() accessor
and cover the scheduled task with a regression test.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 12:19:28 +08:00
u7-u7andqiye.sjh 32bf05f821 docs: point install instructions at the current releases (#113)
The install blocks still asked for hy-memory 2.0.3 (and 2.0.1 extras),
MemHub 1.0.3 (build 7), and said memhub-cli was unpublished. pyproject.toml
ships 2.0.4, the MemHub workspace ships 1.0.4 (build 13), and README already
announces memhub-cli 1.0.5.

Update the install commands and the release metadata in the root READMEs,
the usage/search guides, the monorepo policy, and the MemHub docs. Historical
CHANGELOG entries are deliberately unchanged.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
2026-10-21 12:19:23 +08:00
u7-u7andqiye.sjh b6e6a3fb43 test(core): skip fixtures that are absent from the public snapshot (#112)
Four test modules import artifacts that are not in this repository:
one_memory.processing_requests and three scripts/bench_*.py files. A public
checkout therefore fails during collection, so the whole core-fast suite
cannot start even though every collected test is fine.

Skip only when the module or script is missing. Builds that carry the private
artifacts keep running the same tests unchanged.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
2026-10-21 12:19:18 +08:00
u7-u7andqiye.sjh 4e44f59026 fix(import): report oversized source files as file_too_large (#108)
The access gate refuses a file over the per-root max_file_bytes with
FILE_TOO_LARGE, but both discovery_failure_code() and _scan_failure_code()
collapsed everything except budget and symlink failures into
UNSUPPORTED_SCHEMA. A user with a 3 GiB Codex rollout therefore saw
"unsupported schema" while the parser was fine; the only problem was size.

Map the access gate's FILE_TOO_LARGE onto the existing ScanIssueCode.
FILE_TOO_LARGE on both paths, and update the enum comment to say it covers
both the import's per-file ceiling and the access gate.

The per-file limit itself is unchanged.

Fixes #102.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
2026-10-21 12:19:14 +08:00
35bd56ddd0 fix(runtime): start the reader when the supervisor owns the Core (#99)
readerEnabled was only honored on the attach path. The normal first launch
spawns its own Core and returned from start() without calling startReader(),
so the read-only Reader never ran: no reader_port in the receipt and every
read fell back to Core.

Start the Reader after every successful owned start (first launch, race
recovery and relaunch). Clear readerChild when it exits so a later restart
can spawn a fresh one, and stop the old Reader before a relaunch. Add a
public-start regression using fake child processes.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 12:19:10 +08:00
2cea39da4f fix(core): drop native store write gate on HY search (#126)
MemHub expects concurrent native reads during precipitation. The
process-local read slot mostly existed for a Chroma/GIL fail-fast and
was never held by writers on main; activating it (as in #98) would only
push recall onto weaker fallbacks. Remove the lock module and the
hy_memory_store_busy path instead.

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 12:15:26 +08:00
059e3a4903 fix(runtime): accept profile-scoped host ids in the host permission layer (#70)
* fix(runtime): accept profile-scoped host ids in the host permission layer

DeepSeek Harness configures recall per profile, so recall-hosts.ts reports
`deepseek-harness:<profile>` as the host id. The CLI accepts that shape and
prints it from `host list`, but the runtime rejected it twice:

  - HostPermissions.supported() tested `[a-z][a-z0-9-]*`, so preview/install
    answered host_permission_transport_unsupported for every Harness profile.
  - HostGrantStore.validHostId() applied the same restriction, so even a
    supported host could not create its installation or pass the load-time
    revalidation.

A host id is an opaque label: the installation directory is a digest of it,
so a colon never becomes a path component. Both checks now allow one optional
`:<profile>` segment, matching the CLI's existing HOST_ID.

Adds an integration test that previews a real `cordis.patch.yml` install for
`deepseek-harness:desktop` and a grant-store test that the colon survives a
reload, plus a regression for malformed ids.

* fix(runtime): share one host-id grammar across CLI, permissions and grants

Review follow-up: the three layers had three different host-id rules, so the
CLI could list an id the permission layer (or the grant store) then refused.
They now import `isHostId` from `@one-memory/contracts`, which is the only
definition:

  - host: 1..64 chars, alphanumeric first, lower-case letters/digits/hyphens
  - optional `:<profile>`: 1..32 chars, alphanumeric first
  - total <= 97, and the pattern asserts true end-of-input so a trailing
    newline cannot pass

Digit-leading ids stay accepted (the CLI always took them), and the profile
segment is the only colon allowed. Boundary cases live in
`packages/contracts/src/host-id.test.ts`; the grant-store and permission tests
cover the same grammar from their side.

Packaging: contracts is a source-only workspace package, so every bundle that
now imports it for a value inlines it (`noExternal`): host-bridge entries,
the built Claude Code hook assets, and the CLI. Without that the emitted CJS
asks Node for a `.js` file that only exists as `.ts` and the MCP entry fails
at startup.

---------

Co-authored-by: Vesper <226942762+VE5PER-17@users.noreply.github.com>
Co-authored-by: Vesper <hb.ran@foxmail.com>
2026-10-21 11:40:28 +08:00
0a9b10dbfc fix(auth): require the local token on reader internal endpoints (#82)
The /internal/semantic-ids, /internal/call-event and
/internal/graph-snapshot routes were registered directly on the app without
the local_api_guard dependency used by every other route. Any local process
could read memory graph content, probe semantic IDs, or forge call events
without authorization.

Mount the same guard on all three routes. The Reader already sends
Authorization: Bearer <core_api_token>, so its calls keep working. Add
regression tests for both the 401 and authorized paths.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 11:40:23 +08:00
3a74a33456 feat(memhub): pair unlisted harnesses with one-time codes (#124)
* feat: pair custom harnesses with one-time codes

* fix(memhub): satisfy biome format checks for custom harness pairing

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-21 11:36:55 +08:00
514bf5c47b fix(intention): preserve isolation scope in L7 recall and dedup (#81)
Session-scoped searches build only isolation_keys and leave user_ids /
agent_ids unset. recall_intentions had no isolation_keys parameter, so the
VDB query ran without any tenancy filter and could return every user's
intentions.

The duplicate bucket also ignored user_id / agent_id. Two users with a
similar intention on the same day were treated as duplicates, and the
loser was hard-deleted through vector_store.delete().

Pass isolation_key / isolation_keys through to the vector search and add
user_id / agent_id to the dedup bucket key. Add regression tests for the
parameter forwarding, cross-user recall, and cross-user dedup.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 11:02:58 +08:00
4bc918af7a fix(coding): apply agent and session scope to coding retrieval (#87)
The public search API accepts agent_ids / session_ids, and the chat reader
applies them, but the coding path dropped both before calling the store.
A caller that relies on agent or session boundaries could therefore recall
facts and experiences written by another agent or session of the same user.

Accept the id lists in the coding store, filter them with IN clauses and
in the post-fetch checks, and forward them from _search_coding. Singular
agent_id / session_id stay supported for existing callers. Add store-level
and client-level regressions for the filtered scopes.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 11:02:52 +08:00
75163a0d1e fix(import): truncate oversized verbatim instead of wedging the job (#95)
A single record above MAX_VERBATIM_CHARACTERS failed EvidenceInput
validation. The import retried it three times, failed the whole job at the
read phase, and the byte checkpoint resumed onto the same record, so every
later record in the source stayed unimported.

Clamp verbatim and raw_verbatim in to_evidence(), keeping the head and an
explicit "...[truncated: original N chars]" marker. The identity hash still
uses the clamped raw_verbatim, and records that were previously rejected
never had a stored identity to collide with.

Add regressions for the oversized and normal paths, and update the Core test
inventory.

Refs #68

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 11:02:44 +08:00
09e4bc8a30 fix(logging): keep user_id namespaces inside the pipeline log root (#83)
PipelineLogWriter derives its subdirectory from the caller-controlled
user_id prefix before "__". That prefix was joined directly to the log
root, so an absolute prefix or ".." escaped it: user_id="/tmp/evil__u1"
created /tmp/evil and appended the daily log there.

Whitelist a single safe path component and, as defence in depth, verify
the resolved directory stays under the configured root. Sanitize
default_subdir the same way. Add regressions for absolute, parent and
nested prefixes plus a malicious default subdir.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 11:02:36 +08:00
4dbf7b6ed2 fix(auth): validate loopback origins as IP addresses (#90)
is_loopback_origin() accepted any hostname starting with "127.". That
includes ordinary DNS names such as 127.0.0.1.attacker.example, which an
attacker can point at 127.0.0.1 and use for DNS rebinding against the
local Core.

Keep the exact loopback names and parse everything else with
ipaddress.ip_address(...).is_loopback. Add regressions for rebinding-style
names and IPv6 loopback.

Co-authored-by: qiye.sjh <shijiahao_0802@youzan.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-10-21 11:02:29 +08:00
Jiazheng Kang 8f1c4045e9 Merge pull request #104 from Tencent-Hunyuan/docs/quantized-models-news
docs: announce Hy-Memory-30B-A3B FP8 and GGUF quantized models
2026-10-20 12:06:49 +08:00
kkjzkangandCursor 8918098fa8 docs: announce Hy-Memory-30B-A3B FP8 and GGUF quantized models
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-20 11:22:16 +08:00
0afe787c95 fix: stop authority-invalid HY retries (#78)
* fix: prevent authority-invalid HY retries

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: align coding authority with conversations

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 15:30:32 +08:00
67ae43f920 fix(memhub): repair visibility dirty trigger conflicts (#77)
* fix(memhub): repair visibility link trigger

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(memhub): make trigger upgrade atomic

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 15:30:11 +08:00
3ce89ea560 fix(sdk): serialize sqlite connection lifecycle (#73)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-19 13:02:22 +08:00
7b7fd217a8 fix(sdk): clarify metadata and allow opt-in raw get (#65)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 22:30:23 +08:00
7efe054e83 fix(core): park writes until a model is active (#63)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 21:43:24 +08:00
fdbcd9934d fix(web): distinguish scanned and saved imports (#60)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 21:10:10 +08:00
3171007b3c fix(core): keep initial sync behind bounded history (#59)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 21:00:54 +08:00
a04fcb50d5 docs: announce MemHub and CLI releases (#56)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 19:56:32 +08:00
a28ade2faf fix(release): hash Runtime symlinks consistently (#55)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 19:56:07 +08:00
1c424928a2 fix(cli): trust GitHub release asset redirects (#54)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 19:49:40 +08:00
kristinhe1111 688878171e chore(release): bump MemHub build number to 13 (#52) 2026-10-18 18:03:08 +08:00
a3f09f4cac release: merge MemHub 1.0.4 development fixes (#50)
* feat(memhub): add model usage audit and cost controls

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(memhub): typed source authorization state and managed-key registry ownership

Closes #29

Issue #29 surfaced as "WorkBuddy plugin cannot be uninstalled / source sync
cannot be turned on", but it is two independent failure domains that were both
being reported as a single opaque `desktop_action_failed`:

1. Source sync domain: the UI could not tell whether a source failed to sync
   because the grant was missing, revoked, or because the source identity or
   root path changed. Every failure collapsed into one error, so the UI could
   only say "failed".

2. Host plugin install domain: WorkBuddy shares three registry files
   (`known_marketplaces.json`, `installed_plugins.json`, `settings.json`) with
   the host. MemHub recorded a whole-file hash at install time and then refused
   to uninstall whenever the host (or a reformat) changed any byte anywhere in
   the file, even in entries MemHub does not own.

What changes

Domain errors (new `packages/host-bridge/src/domain-error.ts`)
- Closed allowlist `DOMAIN_CODES`: grant_required, source_identity_changed,
  host_uninstall_modified_managed_value, host_uninstall_unknown_owned_file,
  host_uninstall_needs_review, host_install_journal_invalid,
  host_install_recovery_required, host_permission_storage_unsafe.
- `DomainError` + `domainCodeOf()` so callers stop string-matching on
  `Error.message`. `diagnosticDomainError()` emits only the code and a
  repo-relative safe stack, never message text, so diagnostics cannot leak
  paths or payloads.
- Re-exported from `runtime-control` (host-bridge owns the type to avoid a
  dependency cycle); desktop `observeDesktopAction` now uses
  `domainCodeOf(error) ?? fallbackCode`.

Source authorization state
- `SourceAuthorizationState` enum: ok / missing_grant / revoked_grant /
  source_identity_changed / source_root_unavailable / candidate_changed, plus
  `SourceGrantStore.authorization_state()` which is read-only and fails closed.
- `/api/v1/sources` now returns `authorization_state` per source; contracts and
  the web app render a concrete next action next to the sync switch instead of
  a generic failure.
- `_change_source_sync` distinguishes sync_prepare_failed,
  sync_config_write_failed, sync_resume_failed, sync_watcher_failed (409 with
  the code as detail) while keeping the existing rollback behaviour.
- Capture refuses silently but now records a fail-open rejection marker
  (`sync_disabled` / grant_missing / grant_revoked) that counts occurrences in a
  time window and carries no payload, path, or session content.

WorkBuddy registry ownership (journal v1 -> v2)
- Ownership is now the value at MemHub's own key, not the whole file. Added
  `canonicalJson`, `registryManagedDigest`, `registryWithoutOurs`,
  `registryHoldsOnlyOurs`.
- Install: the plan records `keyPath` + managed digest; apply compares the
  managed value (CAS) instead of the whole file; the journal writes both the v1
  `installed_hash` and the v2 `installed_managed`.
- Uninstall: `resolveRegistryOwnership()` compares the v2 digest, falls back to
  the v1 hash and `isManagedRegistryEntry`, and otherwise produces a review
  finding instead of throwing. `managedRegistryRemoval()` deletes a file MemHub
  created when it still holds only our entry; removes just our key when the host
  has added its own content; and restores recorded bytes only when the rest of
  the document is unchanged, otherwise patches the current document.
- v1 journals migrate: a whole-file hash mismatch no longer blocks uninstall.

Tests
- `packages/host-bridge/src/domain-error.test.ts` (5): code is carried, message
  never reaches diagnostics, no guessing on unclassified errors, refuses to
  parse codes out of free text, allowlist is closed.
- `workbuddy-plugin-installer.test.ts` (34 total): uninstall survives a host
  reformat, removes only our key when the host changed something else, asks for
  review when a managed entry was changed, migrates a v1 journal, keeps a
  registry the host now uses, installs over a post-plan change.
- `apps/core/tests/test_source_authorization_state.py` (12): every state,
  fail-closed ordering, capture rejection names, marker contains no secret or
  path, recording never raises.
- `apps/web`: authorization note rendered for revoked grant and hidden when ok.

Verification
- host-bridge WorkBuddy suite 34/34; domain-error 5/5.
- apps/web 1906 tests across 105 files pass.
- pnpm -r typecheck clean; biome check clean on touched files.
- core-fast: 232 failed / 4131 passed, identical failure count to the clean
  baseline (232 failed / 4119 passed) with +12 from the new tests; the failures
  are pre-existing and unrelated (confirmed by stashing and re-running).

* feat(memhub): add a start/stop switch for model sedimentation

Shipped builds gave the user no way to stop model calls: the model content
permission switch is gone (removed with its endpoint in #20) and there is no
pause or remove entry either, so a configured model keeps turning
conversations into memories and keeps costing money.

Adds a user switch in settings: stopping keeps the model configuration and
the already imported conversations, leaves queued work pending instead of
failing it, and stops new work, enqueueing and backfill so nothing further
reaches the model. Starting again resumes the same work without re-entering
a key.

The flag lives in Core's own user config (config.json), so no schema
migration is needed, and the supervisor takes it as an optional callback so
every existing caller and test keeps its current behaviour.

* test(desktop): keep host-bridge mocks whole and assert the review contract

The memhub CI job failed four desktop tests after the issue #29 change. Both
were test-side contracts that the new ownership model intentionally moves, not
regressions in the fix itself.

1. `host-control-ownership.test.ts` mocked `@one-memory/host-bridge` with a
   whitelist that carried only `RecallBroker`. Main now imports `domainCodeOf`,
   which runtime-control re-exports from host-bridge, so the mock handed back
   undefined and every error path that called it threw a TypeError instead of
   the error the test was asserting on. The mock now spreads the real module
   and overrides only `RecallBroker`, which is the part it was written for.

2. `host-permissions.test.ts` asserted the pre-#29 contract, where a change
   anywhere in a shared registry made uninstall throw
   `host_uninstall_modified_files`. Ownership is now the value at our own key,
   so a change to that value is reported instead of guessed at: the plan
   schedules no removal, names the file in a review finding, and applying it
   refuses with `host_uninstall_needs_review`. The test keeps the guarantee it
   existed for, that those bytes are never overwritten, and now also asserts
   that apply refuses, so the safety is checked at both steps.

Verification: full desktop suite 38 files / 436 tests pass, `pnpm -r typecheck`
clean, biome reports only two pre-existing warnings on lines this change does
not touch.

* fix(logging): keep info diagnostics actionable

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(memhub): register the sedimentation switch test in the core test inventory

New core test files must appear in TEST_INDEX.md and in the classification
inventory's expected count and digest, and the backfill case needs a settled
turn because an unanswered user tail is not backfill material.

* feat(diagnostics): expose build info and fullscreen logs

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(settings): align help controls and tighten spacing

Co-authored-by: Cursor <cursoragent@cursor.com>

* release: prepare MemHub 1.0.4 build 8

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(memhub): clear pre-existing dev lint errors and flaky SDK dedup tests

Three things blocking CI that came in with dev and are unrelated to the
sedimentation switch itself:

- biome errors in DebugLogPanel.tsx (import order) and ModelUsageView.tsx
  (refreshToken is an intentional refresh trigger, annotated like the
  existing modelVersion trigger in R6Settings).
- test_extractor_prompt_override.py's fake LLM now accepts keyword args the
  real pipeline passes since the usage audit landed (audit_stage).
- the fake embeddings in the intention dedup tests used the process-random
  hash(), so two different texts collided roughly one run in 32 and were
  misread as duplicates; switched to a deterministic md5 index.

* fix(cli): count recall characters as code points

A recall whose hits contain an emoji outside the BMP was reported as
response_invalid even though the data and the search were fine: the CLI
cross-checked the response by summing String.prototype.length, which counts
UTF-16 code units, against Core's used_characters, which Python's len()
counts in code points. One emoji is two units here and one character there,
so any hit set with an emoji failed the check.

The sibling validator in host-bridge (context-protocol.ts) already counted
code points, so the CLI was the odd one out rather than a deliberate choice.

- validateContextResponse now sums through characterCount(), which counts
  code points, matching Core.
- Two regression tests: an emoji hit whose used_characters follows code
  points must stay grounded, and the same response counted as UTF-16 units
  must still be refused, so the cross-check is not simply loosened.
- The contract now states used_characters counts Unicode code points and is
  not an encoding length, so a client in another language does not repeat
  the comparison.

Verified by reverting the source change: the first test fails on the old
implementation and passes with it.

Closes #30

* fix(web): keep the model recovery entry reachable while a probe is pending

Closes #40

A pending model probe fenced the configuration editor, and the only
recovery entry ("核对测试结果") lived inside the area the fence kept
shut. Reaching it required opening the form; opening the form required
having recovered. People with a stuck probe could not change or repair
their model at all.

The fence itself was doing its job and still is. What was wrong is that
refusal also hid the way out.

R6Settings
- openConfiguration() now opens the model area whether or not the editor
  accepts, so the recovery entry inside it is reachable. editProfile()
  and add() still return false while the fence is up; nothing about the
  protection changed.
- The refusal notice is reworded to match: the configuration cannot be
  changed yet, and the next step is down in the area that just opened.
  Saying "cannot be opened" was both untrue now and unhelpful before.

ModelSettings
- A refused open is remembered instead of dropped. Once the fence clears,
  the intent is replayed, so the person lands in the form they asked for.
  Without this they would get a blank new-configuration form the moment
  the probe reconciled, which invites a duplicate entry.
- Replaying only fills fields in. It never sends a request, so no test is
  re-sent implicitly; "核对测试结果" remains the only thing that does.

Tests
- R6Settings: with a current model and without one, the recovery entry is
  reachable while the editor is fenced, and the refusal is still reported.
- ModelSettings: after reconciling, the form reopens on the profile that
  was asked for, and the probe is sent exactly once.
- Both new R6Settings cases and the ModelSettings case fail on the
  previous code.

* perf(runtime-control): decide runtime reuse before staging the payload

Every App launch copied the whole 373MB bundle into a temp directory and
hashed it twice before asking whether the selected runtime could be reused.
On a machine that already runs this build the answer is yes and all of that
work is thrown away: measured on a release Mac bundle, 6.9s to copy and
about 3.8s of hashing (fileDigests, then verifyInstalledDistribution over
the same tree).

installPackagedRuntime now describes the payload in place first. The staged
tree is a byte for byte copy of resources/{core,host-bridge,runtime,web}
plus two generated launchers, so the same relative paths and digests can be
read without copying anything. reuseSelectedSameBuild takes that description
instead of a staged directory, and only a payload that is going to be
installed is ever staged.

The decision itself is unchanged: it still compares every file digest except
bin/node, still repairs the packaged launcher when the App moved, and still
raises installed_version_conflict or distribution_hash_mismatch exactly as
before. Nothing was replaced by a cheaper fingerprint, because a wrong reuse
is what those errors exist to prevent.

Hashing also runs through a small worker pool now; the digests are identical
and the manifest keeps its sorted key order.

New test: describeBundlePayload must equal the manifest the staged copy
produces, so moving the decision ahead of the copy cannot decide something
different. Verified read-only against the installed release bundle:
1534 files, identical file sets, zero digest mismatches.

* perf(desktop): raise a startup window before the runtime and Core come up

Opening the App currently shows nothing at all until initialize finishes.
On this machine that is 55.6s from desktop.initializing to desktop.ready
(about 19s installing and starting the managed runtime, then about 36s for
Core to become ready), and window.requested is logged after desktop.ready.
A launch that slow with no window reads as a launch that failed, and people
click the icon again.

startDesktopLifecycle now takes two optional hooks. showStartupWindow runs
before initialize and loads a placeholder; revealStartupWindow runs after
initialize and swaps that same window onto the real app. Because the window
is reused rather than replaced, there is no second window and no flash.

The placeholder is served from the app protocol as /__startup, in memory,
not as a file in the web bundle. It performs no IPC: it renders before
initialize has registered a single handler, so anything it asked for would
fail and leave the page in an error state for the whole wait. That route is
also reserved, so a file of the same name inside the bundle can never be
reached through it.

Raising the placeholder is best effort. It only fills a wait that would
otherwise be blank; failing to draw it must not stop the services or the
real window.

Tests: five lifecycle cases cover the ordering (placeholder before
initialize, reveal after, reuse of the same window, nothing for a background
launch, and a real window when the placeholder was closed or could not be
raised). The four suites that mock ./app-protocol now spread the real module
instead of whitelisting it, which is what broke when the protocol gained
exports. host-control-ownership gains the BrowserWindow methods the
placeholder path uses, and its "no window" assertion now names the
placeholder, since a placeholder window is expected there by design.

* fix(core): stop the sedimentation switch failing its own request

Turning the switch off answered "停止未能确认,模型可能仍在整理记忆,请重试"
every time. The value was saved and the error was a lie the endpoint told
afterwards: `put_sedimentation` logged `memory_sedimentation.toggled` with
`details={"enabled": ...}`, `enabled` is not in the diagnostic allow-list, and
`_details` raises. That ValueError escaped the endpoint, so the request is
recorded in this machine's log three times as `api.request.failed` /
`core.request.unhandled` with `diagnostic_detail_key_invalid`, and the UI took
the 500 as an unconfirmed stop.

Because the raise sits between the save and the resume, starting again was
broken the same way: `resume_allowed()` never ran, so work parked by a stop
stayed parked.

Three changes, in the order they matter:

1. `enabled` is now a legal detail key. It is a bounded boolean, the same
   shape as `spawned` and `index_complete`.
2. `diagnostic_event` no longer lets a rejected payload reach the caller. It
   already swallowed `OSError` with the comment "Diagnostics must not become a
   new product outage"; an unlisted key is the same failure seen from the
   caller, and it is exactly what turned every external recall into a 500 and
   then killed the process last time. The payload is still wrong and still
   caught in CI — now by every module rather than five.
3. `test_diagnostic_payload_keys.py` walks every module instead of a
   hand-picked list. The two payloads that caused real outages were in files
   nobody thought to add to that list; the only shape of the check that holds
   the line is "every module, always". This file was already failing on dev
   with `api.py:3673: unlisted details key 'enabled'` — the bug was known to
   the suite and shipped anyway.

`DiagnosticLog.write` still raises, so the rejection itself is unchanged and
still tested; only the callers are protected.

* fix(core): let the drain claim a manual note's job

A memory added by hand stayed on "原话已保存,等待整理" indefinitely, with
`task_id: null`: the note's durable job was never claimed, so no task was ever
created for it. On this machine the job is still `pending` with `attempts=0`
more than eight hours after it was saved, while the write gate admits its
source without complaint.

The drain had two different answers to one question. `source_writes_permitted`
is `_source_writes_on`, which admits `one-memory-manual` by its grant. The
claim gate was `_config_store(app).sync_enabled`, the per-app toggle, and
`one-memory-manual` is not a connected app: it never appears in the
configuration document, so that predicate answers False for it. The job
survived the `enabled_sources` prefilter and was then dropped row by row, on
every tick, forever. Nothing ever failed and nothing ever ran.

The claim gate now asks the same question the write gate asks. Admission is
one decision; giving it two predicates is what parked the work.

Two tests pin it. One builds the drain as the composition root does and shows
the job is claimed, and shows the shipped wiring stranding the same job, so the
regression is visible if the toggle comes back. The other records the
asymmetry itself: `_source_writes_on` is True for the manual source while
`sync_enabled` is False, which is why the pair could disagree at all.

No migration and no reinstall: existing pending jobs are picked up on the next
drain tick.

* fix(memhub): make sedimentation pause stop model dispatch

Co-authored-by: Cursor <cursoragent@cursor.com>

* feat(memhub): schedule memory writes by event time

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(core): answer the sedimentation switch before the backlog walk

Turning "用模型沉淀记忆" back on wrote the choice to the store and then
awaited `resume_allowed()` inside the PUT handler. That call is not a nudge:
it runs maintenance over every unfinished task and then a whole-queue scan,
and the bounded scan waited -- holding the scan lock -- for the queue to drop
under its cohort ceiling. With a real backlog the queue never drops, so the
request never returned: one toggle in the field is still open 20+ minutes
later with no `api.request.completed`, while the renderer gave up at its 30s
timeout and showed "启用未能确认,仍显示上次确认的状态;请重试。" for a switch
that had in fact been saved.

The choice is the durable fact; the walk is follow-up work:

- The handler now stores the choice and returns it, and starts the resume as a
  watched background task (same idiom as the other Core background walks).
  Repeated toggles reuse the running walk instead of stacking.
- A bounded scan now stops at its ceiling instead of sleeping under the scan
  lock waiting for capacity, which also un-starves the periodic scan that was
  queued behind it. It reports `queue_saturated` rather than `no_tasks`, so
  the status stops claiming there is nothing to do while hundreds wait.

Verified on the field log first: the failing toggle is the only request in
the window with `api.request.started` and no `api.request.completed`, and its
trace shows `memory_sedimentation.toggled` succeeded 6ms in at
`pending_count` ~500. New tests fail on the old code (timeout) and pass now.

* fix(core): stop a blank author from erasing a whole conversation

A user turn whose host did not say who wrote it carries
`written_by=unknown`. The write binding's allow-list had every other
role/author pair but not that one, so verifying the context raised
`hy_memory_write_verification_context_scope` and the task ended as
`model_content_outcome_unknown` after two attempts: a memory the model may
well have written, that can never be confirmed, and a conversation that is
never sedimented again.

This is not a rare shape. On this machine 1078 user records across 1002
WorkBuddy conversations are `unknown`, and the failures were 42 per 15
minutes in the field log — every one of them a task reporting
`result_count=0` while 402 sat pending.

The author is missing, not the turn: the record is still inside the same
conversation, workspace and source, which is what the binding actually
checks, and the turn assembly already sent it. Accepting it here puts the
verification back in agreement with what was sent, the same reasoning that
added ("user", AGENT) for sub agent questions.

New test fails on the old code at hy_source_context.py:76 — the same frame
as the field stack — and passes now.

* fix(core): stop an abandoned read reporting a failure nobody owns

`in_read_pool` shields the wrapped worker, so a lane that runs out of budget
gives up on the answer without yanking a query out from under SQLite. The
caller cancels; the read runs on. When such an abandoned read then failed,
nothing awaited its future any more: `shield` drops its inner callback as soon
as the outer future is cancelled, so the inner future finished with an
exception that nobody retrieved. asyncio reports that at GC, and the loop
handler files it as `core.loop.task_exception` -- a red error sitting next to a
lane that had already degraded on its own budget and already said so.

On this machine that is the `raw_context_timeout` pair in the field log: a
Future, not a Task, carrying TimeoutError('raw_context_timeout'), reported
three times in half an hour. The lane result itself was right; only the
diagnostics were arguing with themselves.

Retrieving the outcome on completion keeps the diagnostics honest without
hiding anything: awaiting the read still raises for a caller who waited, which
the second case pins down.

The new case fails on the previous code (it reports the TimeoutError) and
passes now.

* fix(core): one task with no inputs no longer strands every unknown task

`MemoryTaskRunner._request` falls back to `chunk[0]` when no record is a
person-written user turn. A task whose inputs are gone yields an empty chunk,
so that fallback raised IndexError -- an error no caller can read. A reconcile
pass catches domain errors per task and moves on, so IndexError did not skip
the task: it ended the pass, and every unknown task behind it stayed unknown
while the retry backed off 1, 2, 4 ... 128 and gave up.

On this machine 68 of 303 unknown tasks had no inputs, which is exactly the
`reconcile_unknown / error_type=IndexError` backing off in the field log. Those
68 cannot be reconciled either way -- there is nothing to ask HY about -- but
the 235 that can must not be held hostage to them, and this is what stands
between a task whose model write may already have landed and its confirmation.

An empty chunk is now a domain error, so the pass skips the task and continues.
Also folds in one formatting hunk left over in this file from the previous
change, so the formatter is clean again.

The new case fails on the previous code at memory_processing.py:1036 with the
same IndexError the log shows, and passes now.

* chore(memhub): bump release build number to 10

The installer refuses a package whose bytes differ while its build number
stays the same, so the four Core fixes on dev need their own number to be
installable over the 1.0.4 / build 9 package already on the machine.

* fix(core): retire a window whose remaining rows FIFO refuses

The event-time window asked only whether its ten-minute range still held
*some* pending row before deciding the anchor was still active. A pending
row that FIFO holds back is not claimable: it may be blocked by an earlier
sibling of the same Harness whose own event time sits outside the range, and
that sibling can never be claimed from inside this window. The anchor then
stayed pinned forever and the whole queue starved.

Live shape on one machine: the anchor sat on 2026-10-07T03:24Z while the four
pending rows inside it were blocked by 929/930/1243/2347 earlier workbuddy
jobs, the earliest of them dated 2026-03-12. Completions stopped at 09:59 and
3.8k queued turns sat at zero output; restarting does not help because the
anchor is persisted.

The contract (docs/contracts/memory-event-time-scheduling-v1.md) retires a
window once every *eligible* pending/running row in the range has settled or
parked, and re-anchors on the next oldest eligible job. Reuse the claim's own
predicate — free lease, no busy Harness, no earlier unsent sibling — so "the
window is busy" and "the window can still be worked" finally agree. Anchor
selection and in-window selection already used it; only the liveness check
did not.

* fix(core): a refused source context is a failure, not an unknown write

Issue #44: an OpenCode import carried `role=user, written_by=unknown`. The
role/author set now admits it, but the row still never moved: `HyWriteBindings`
is built inside `ingest`, and the invocation marker is recorded *before* that
call, so the refusal arrived with the marker already set. The classifier
checked `hy_invoked` first and parked the task as `unknown` — a state that
means "HY may hold a write we cannot confirm" about a request that provably
never reached HY. The reason stayed off the row, the task could not be
re-driven, and the queue behind it stopped.

`hy_memory_write_verification_context_scope` is raised from that construction
alone, and `_check_source_context` (which does run after the call) raises
`hy_memory_evidence_changed` instead, so the code is unambiguous: nothing was
sent. It joins `PRE_SEND_REFUSAL_CODES`, and both classifiers now test that set
before the marker: the durable path settles `failed` with the marker cleared so
reclaim does not treat a row HY never saw as possibly-sent, and the task path
fails with the code instead of marking unknown.

Regression covers both directions: a pre-call refusal must end `failed` with
`hy_invoked=0`, and a post-call refusal (`authority_invalid`) must still be
`unknown` — the fix narrows the unknown set, it does not widen the failure set.

* chore(memhub): bump release build number to 11

Carries the window starvation fix (dc0ba49) and the pre-send refusal
fix (0df84c0). A new build number keeps the package distinguishable from
build 10 and lets it install over the current one.

* refactor(memhub): simplify durable memory scheduling

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(memhub): bump release build number to 12

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(security): parse diagnostic stack paths linearly

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): sync sedimentation switch status to home (#51)

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: kristinhe <kristinhe@tencent.com>
2026-10-18 17:52:59 +08:00
kristinhe1111 0c59413ad8 Merge pull request #43 from Tencent-Hunyuan/kristinhe1111-patch-1
Revise README for clarity and installation instructions
2026-10-18 00:37:45 +08:00
kristinhe1111 625f877b43 Revise README for clarity and installation instructions
Updated README to clarify MemHub's functionality and provide installation guidance.
2026-10-18 00:27:38 +08:00
kristinhe1111 1608a4cfc2 feat(memhub): restore the one-click log export entry in settings (#38)
* feat(memhub): show the help and diagnostics group in settings by default

The settings group that carries the one-click log export was gated behind
VITE_ENABLE_DIAGNOSTICS=true at open-sourcing time, so shipped builds never
showed it and users could not export a diagnostics bundle. Flip the default
to visible and keep VITE_ENABLE_DIAGNOSTICS=false as the opt-out for any
build that must not offer it.

* style(memhub): format rerender call per biome
2026-10-17 22:05:24 +08:00
20b92d8a89 release: prepare MemHub 1.0.3 (#33)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 19:40:33 +08:00
2a4c5e38e7 release: publish Hy Memory 2.0.3 and update MemHub (#31)
* release: publish Hy Memory 2.0.3 and update MemHub

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(memhub): update SDK release documentation contract

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 19:26:56 +08:00
c891a1fd1d fix(runtime): let a notarized bundle replace a same-build runtime (#21)
* fix(runtime): let a notarized bundle replace a same-build runtime

Re-cutting one release keeps its build_number, so a rebuilt package met an
installed runtime carrying the same number and different bytes and was
refused with installed_version_conflict. The app then exited on every
launch, for anyone upgrading or reinstalling without first clearing the
managed install root.

- runtime-control: planLocalInstall takes allowSameBuildReplace, off by
  default so the contract's refusal still holds for every other caller. When
  it is on and the bytes differ, the incoming build lands in its own version
  directory keyed by a payload fingerprint and current moves atomically, so
  the superseded tree stays available as a rollback. Downgrade refusal and
  tamper detection are unchanged.
- desktop: opts in, because the bundle it carries has passed notarization and
  its payload is trusted by construction. A conflict that still cannot be
  reused is answered once by moving the selected tree into quarantine-<ts>/
  and installing again; memory data lives on a different path and is never
  read or written here.
- desktop: the startup dialog explains the failure and says what happens to
  the user's memories instead of printing an internal error code. The code
  stays in the diagnostic event, where support can still match it.
- core + cli: POST /api/v1/onboarding/reset and `memhub onboarding reset`
  send onboarding back to its first-run state and touch nothing else, so the
  cold-start screens can be seen again without deleting a single memory.

* fix(runtime): tighten trusted same-build takeover

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: kristinhe1111 <kristinhe1111@users.noreply.github.com>
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 18:59:29 +08:00
7741e17f09 fix(memhub): keep unknown writes from blocking queues (#27)
* fix(memhub): keep unknown writes from blocking queues

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(memhub): retry unknown writes after ten seconds

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 18:42:24 +08:00
2a4dc2ffa2 feat(memhub): add product memory pipeline diagnostics (#25)
* feat(memhub): add product memory pipeline diagnostics

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(memhub): clarify debug log privacy

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:35:41 +08:00
61b5ef30a9 refactor(memhub): remove HyPermission and trust embedded SDK (#20)
* refactor(memhub): trust embedded SDK native stores

Co-authored-by: Cursor <cursoragent@cursor.com>

* refactor(memhub): remove model content permission UX

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 17:13:08 +08:00
f79770cdb0 release: prepare MemHub 1.0.2 (#19)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 01:54:14 +08:00
9ba602ffd2 ci: upload tagged Linux runtimes to draft releases (#16)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 01:51:58 +08:00
842fbe6044 fix(memhub): relaunch safely with existing runtimes (#18)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 01:50:23 +08:00
772 changed files with 57706 additions and 82118 deletions

No files matched your search

+1
View File
@@ -86,6 +86,7 @@ MEMORY_VECTOR_STORE=chroma
# MEMORY_CODING_DB_PATH= # coding_memory.db 路径(默认 {DATA_DIR}/data/coding_memory.db)
# MEMORY_CODING_TOOL_RESULT_MAX_BYTES=2048 # 单条 tool_result 截断字节上限
# MEMORY_CODING_VERBATIM_FALLBACK_ENABLED=false # 模型无结果时是否保存原文 fact;默认关,避免 tool trace 外泄
# MEMORY_CODING_CHAIN_BLOCK_ENABLED=false # search 是否注入版本演进链块(diff);默认关,省 token
# MEMORY_EXTRACT_HISTORY_TURNS=5 # 除本次 write 外,额外注入 extractor 的历史 user-turn 数
# ── 写入流程开关 ──
+49
View File
@@ -0,0 +1,49 @@
name: Hermes provider
on:
pull_request:
paths:
- "plugins/hermes/**"
- ".github/workflows/hermes-provider.yml"
push:
branches: [main]
paths:
- "plugins/hermes/**"
- ".github/workflows/hermes-provider.yml"
permissions:
contents: read
jobs:
provider:
runs-on: ubuntu-24.04
timeout-minutes: 3
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
persist-credentials: false
- uses: astral-sh/setup-uv@d0d8abe699bfb85fec6de9f7adb5ae17292296ff
with:
python-version: "3.12"
enable-cache: false
- name: Download and verify native Hermes contract
run: |
uv run --no-project --python 3.12 python - <<'PY'
import hashlib
import os
from pathlib import Path
import urllib.request
url = "https://raw.githubusercontent.com/NousResearch/hermes-agent/818c13be1dc4fd28987e1e881a9408224afd4535/agent/memory_provider.py"
with urllib.request.urlopen(url, timeout=30) as response:
data = response.read()
expected = "a4e44a293013fff831ac136ab77c556541cd18817f53bd662e97090cd80bd5a6"
if hashlib.sha256(data).hexdigest() != expected:
raise SystemExit("Hermes contract SHA-256 mismatch")
snapshot = Path(os.environ["RUNNER_TEMP"]) / "hermes-memory-provider.py"
snapshot.write_bytes(data)
with open(os.environ["GITHUB_ENV"], "a") as env:
env.write(f"HERMES_MEMORY_PROVIDER_SNAPSHOT={snapshot}\n")
PY
- name: Test provider with native contract
run: uv run --no-project --python 3.12 --with pytest python -m pytest plugins/hermes/tests -o addopts= -o log_cli=false -q
+68
View File
@@ -102,3 +102,71 @@ jobs:
if-no-files-found: error
compression-level: 0
retention-days: 14
publish-draft-release:
if: ${{ inputs.run_lifecycle && startsWith(github.ref, 'refs/tags/v') }}
needs: matrix
runs-on: ubuntu-24.04
permissions:
contents: write
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
with:
persist-credentials: false
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
with:
pattern: memhub-runtime-linux-*
path: memhub/release-assets
merge-multiple: true
- name: Verify tag and Linux release assets
shell: bash
run: |
set -euo pipefail
shopt -s globstar nullglob
version=$(node -p 'require("./package.json").version')
node scripts/verify-release-version.mjs \
--channel stable \
--version "$version" \
--build-number "$(node -p 'require("./package.json").release.build_number')" \
--tag "$GITHUB_REF_NAME"
mkdir -p publish-assets
for arch in x64 arm64; do
name="memhub-runtime-v${version}-linux-${arch}.tar.gz"
archives=(release-assets/**/"$name")
checksums=(release-assets/**/"$name.sha256")
test "${#archives[@]}" -eq 1
test "${#checksums[@]}" -eq 1
cp -- "${archives[0]}" "publish-assets/$name"
cp -- "${checksums[0]}" "publish-assets/$name.sha256"
(
cd publish-assets
sha256sum -c "$name.sha256"
)
done
- name: Upload Linux assets to a draft GitHub Release
env:
GH_TOKEN: ${{ github.token }}
shell: bash
run: |
set -euo pipefail
if gh release view "$GITHUB_REF_NAME" \
--repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
test "$(
gh release view "$GITHUB_REF_NAME" \
--repo "$GITHUB_REPOSITORY" \
--json isDraft \
--jq .isDraft
)" = "true"
else
gh release create "$GITHUB_REF_NAME" \
--repo "$GITHUB_REPOSITORY" \
--verify-tag \
--draft \
--generate-notes \
--title "$GITHUB_REF_NAME"
fi
gh release upload "$GITHUB_REF_NAME" \
publish-assets/memhub-runtime-v*-linux-*.tar.gz \
publish-assets/memhub-runtime-v*-linux-*.tar.gz.sha256 \
--repo "$GITHUB_REPOSITORY" \
--clobber
+3
View File
@@ -26,6 +26,9 @@ package-lock.json
ui_walkthrough_*/
# Internal release/open-source coordination must never enter the public tree.
HANDSOFF.md
新鲜度_todo.md
memhub/docs/LOCAL_PRODUCT_APP_MIGRATION_TEST.md
OPEN_SOURCE_TODO.md
release_todo.md
+144 -2
View File
@@ -2,6 +2,115 @@
Hy Memory and MemHub are versioned and released independently.
## Unreleased
- Fixed legacy-to-SDK startup migration to adopt native Coding Experience and
Working Fact IDs instead of importing them as Chat layers. Raw migration now
rebuilds bounded user/assistant turns from the latest three days, excludes
tools, and enforces the same rolling retention after cutover.
- Paused host capture writes with a live Desktop migration fence; Cursor
History catch-up resumes from its existing checkpoint after cutover.
- Removed MemHub's private `hy_memory_bridge` implementation. MemHub now calls
public `HyMemoryClient` methods at runtime; prompt/reconcile/response
monkey-patches and private VDB/Coding runtime access were deleted. Kuzu Graph
projection/admin and stopped-writer App migration are the documented product
exceptions.
- Added a MemHub-managed native Hermes MemoryProvider with automatic prefetch,
persistent per-session memory-ID deduplication, authorized Broker reads, and
recall-context stripping to prevent memory recursion.
- Added an extensible MemHub interface-localization layer with Simplified
Chinese, English, and Spanish catalogs shared by Web and Electron-native
surfaces. Interface language remains independent from memory content and
model processing language.
- Fixed governed-memory revisions and repeated evidence links failing when the
visibility dirty-marker trigger encounters the same memory twice. Startup
now replaces the affected legacy trigger without changing schema versions
or governed and visibility data.
- Kept post-write authority verification failures available for read-only
reconciliation while preventing automatic or generic confirmed retries from
invoking the model again. Automatic reconciliation skips those sticky rows
before applying its batch limit, and linked durable jobs exclusively own
retry scheduling for their memory tasks.
- Removed MemHub's task-scoped HyPermission store wrappers and global
model-content consent switch. The trusted embedded Hy Memory SDK now uses
its native local stores directly.
- Existing installations ignore the retired config flag, readmit previously
parked pre-invocation work, and drop only the obsolete
`hy_node_permissions` proof table. Evidence, governed memories, model
profiles, SDK stores, and source/host grants are preserved.
## Hy Memory 2.0.5 — 2026-10-22
- Published
[`hy-memory==2.0.5`](https://pypi.org/project/hy-memory/2.0.5/).
- Extended `get()` across Chat, Coding Experience, Working Fact, and raw IDs;
the returned `layer`, `kind`, and `variant` identify the actual record.
- Added explicit raw retrieval through the existing `search()` and
`list_memories()` contracts, including user, agent, session, and source
filters.
- Added public embedding-service injection and corrected extraction language
detection for structured OpenAI-style messages.
- Added lifecycle status filters, durable idempotent write outcomes, and
quiesced local data-plane snapshot/restore.
- Kept legacy migration mechanics out of the public Client API; separate
migration-only raw/import methods from development previews were removed.
- Physical delete now reports partial VDB/Graph cleanup as failure.
- Coding search no longer injects the version-evolution diff block by default;
opt in with `MEMORY_CODING_CHAIN_BLOCK_ENABLED=true`.
- Serialized SDK SQLite cache/history connection lifecycle and tightened
Coding reconciliation to its agent/session/workspace authority.
- Clarified persistent caller context through `meta`, while `metadata` remains
legacy processing configuration.
## Hy Memory 2.0.5.dev4 — 2026-10-21
- Development preview used for SDK-authority migration validation; not the
final `2.0.5` release.
- Published as
[`hy-memory==2.0.5.dev4`](https://pypi.org/project/hy-memory/2.0.5.dev4/).
## Hy Memory 2.0.5.dev3 — 2026-10-21
- Development preview; not the final `2.0.5` release.
- Published as
[`hy-memory==2.0.5.dev3`](https://pypi.org/project/hy-memory/2.0.5.dev3/).
- Lets the existing `search` API explicitly query SDK raw with
`layers=["l1_raw"]`, including existing source filters.
## Hy Memory 2.0.5.dev2 — 2026-10-21
- Development preview; not the final `2.0.5` release.
- Published as
[`hy-memory==2.0.5.dev2`](https://pypi.org/project/hy-memory/2.0.5.dev2/).
- Adds exact, idempotent semantic-memory import for legacy MemHub cutover
without extraction, reconciliation or identity changes.
## Hy Memory 2.0.5.dev1 — 2026-10-21
- Development preview for the MemHub SDK-authority migration; this is not the
final `2.0.5` release.
- Published as
[`hy-memory==2.0.5.dev1`](https://pypi.org/project/hy-memory/2.0.5.dev1/).
- Adds lifecycle status filtering, durable idempotent write outcomes, exact raw
APIs, offline local data-plane snapshot/restore, and fail-closed physical
delete receipts.
## Hy Memory 2.0.4 — 2026-10-17
- Published
[`hy-memory==2.0.4`](https://pypi.org/project/hy-memory/2.0.4/) as a
maintenance release.
## Hy Memory 2.0.3 — 2026-10-17
- Added an optional runtime HTTP transport factory so embedded products can
enforce request budgets without wrapping or restricting SDK local-store
access.
- Published
[`hy-memory==2.0.3`](https://pypi.org/project/hy-memory/2.0.3/) with
unchanged memory extraction, reconciliation, storage, and Coding/Working
behavior.
## Hy Memory 2.0.2 — 2026-10-17
- Published
@@ -16,11 +125,44 @@ Hy Memory and MemHub are versioned and released independently.
Because PyPI release metadata is immutable, the next SDK patch release must
carry the updated license metadata; `2.0.1` retains its published metadata.
## MemHub 1.0.1 — Unreleased
## MemHub 1.0.5 — Unreleased
- Updated the source version to `1.0.1` (build 5).
- Updated the source version to `1.0.5` (build 14).
- Pinned the public SDK to the stable `hy-memory==2.0.5` release.
## MemHub 1.0.4 — 2026-10-18
- Updated the source version to `1.0.4` (build 13).
- Published the `v1.0.4` source and release metadata.
## MemHub 1.0.3 — 2026-10-17
- Updated the source version to `1.0.3` (build 7).
- Pinned the public SDK to `hy-memory==2.0.3`.
- Removed the HyPermission store wrappers and global model-content consent
switch; the trusted embedded SDK now uses native local stores.
- Prevented uncertain writes from blocking later source work and added one
reconciled automatic retry after ten seconds.
- Added product-facing memory pipeline counters and the log troubleshooting
runbook.
- Allowed a verified packaged Desktop Runtime from a different commit to take
over an equal-build install atomically while preserving downgrade and
tamper refusal.
## MemHub 1.0.2 — 2026-10-17
- Updated the source version to `1.0.2` (build 6).
- Pinned the public SDK to `hy-memory==2.0.2`.
- Pinned `onnxruntime==1.23.2` to retain macOS x64 packaging support.
- Fixed relaunch and upgrade failures when a prior managed Runtime exists.
- Embedded canonical build identity when an external packaging pipeline omits
release environment fields.
- Added automatic Linux Runtime upload to tagged Draft Releases.
## MemHub 1.0.1 — Superseded before release
- The candidate tag was not published as a GitHub Release; `1.0.2` replaces it
after the managed-Runtime relaunch fix.
## MemHub 1.0.0
+12 -9
View File
@@ -32,7 +32,9 @@ English | [中文](README.zh.md)
## Latest News
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **Released** **Hy Memory 2.0 (`hy-memory==2.0.2`)** on [PyPI](https://pypi.org/project/hy-memory/2.0.2/) and open-sourced the **Hy-Memory** monorepo together with **[MemHub](memhub/README.md)**!
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **Open-sourced** quantized **FP8** (**[Hy-Memory-30B-A3B-FP8](https://huggingface.co/tencent/Hy-Memory-30B-A3B-FP8)**) and **GGUF** (**[Hy-Memory-30B-A3B-GGUF](https://huggingface.co/tencent/Hy-Memory-30B-A3B-GGUF)**) versions of **Hy-Memory-30B-A3B** on Hugging Face!
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 📦 **Released [MemHub v1.0.4](https://github.com/Tencent-Hunyuan/Hy-Memory/releases/tag/v1.0.4)** and **[memhub-cli 1.0.5](https://www.npmjs.com/package/memhub-cli/v/1.0.5)**, with a signed macOS desktop app and verified macOS/Linux Runtimes!
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **Released** **Hy Memory 2.0 (`hy-memory==2.0.4`)** on [PyPI](https://pypi.org/project/hy-memory/2.0.4/) and open-sourced the **Hy-Memory** monorepo together with **[MemHub](memhub/README.md)**!
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **Open-sourced** **[Hy-Memory-30B-A3B](https://huggingface.co/tencent/Hy-Memory-30B-A3B)** on Hugging Face along with its [technical report](https://arxiv.org/abs/2610.22196) on attributed reinforcement learning for long-term memory writing!
* *<mark>[new]</mark>* 🔥🔥 **[2026-09]**: 📊 **Released** **[CMB: A Coding Memory Benchmark for Long-Horizon and Interleaved Coding Agents](docs/papers/CMB_A_Coding_Memory_Benchmark_for_Long_Horizon_and_Interleaved_Coding_Agents.pdf)** (submitted to **ICLR 2027**).
* *<mark>[new]</mark>* 🔥🔥 **[2026-08]**: 🎉 **Accepted** at **EMNLP 2026**: **[Memory Beyond Recall: A Dual-Process Cognitive Memory System for Self-Evolving LLM Agents](https://arxiv.org/abs/2606.09483)**!
@@ -63,13 +65,13 @@ Welcome to the **Hy Memory Research Family**, covering cognitive chat memory, lo
### 1. Installation
```bash
pip install hy-memory==2.0.2 # core (includes ChromaDB and Kuzu)
pip install "hy-memory[qdrant]==2.0.2" # + Qdrant
pip install "hy-memory[faiss]==2.0.2" # + FAISS
pip install "hy-memory[graph]==2.0.2" # + Neo4j
pip install "hy-memory[mysql]==2.0.2" # + MySQL cache
pip install "hy-memory[rerank]==2.0.2" # + local multilingual cross-encoder rerank
pip install "hy-memory[all]==2.0.2" # everything
pip install hy-memory==2.0.4 # core (includes ChromaDB and Kuzu)
pip install "hy-memory[qdrant]==2.0.4" # + Qdrant
pip install "hy-memory[faiss]==2.0.4" # + FAISS
pip install "hy-memory[graph]==2.0.4" # + Neo4j
pip install "hy-memory[mysql]==2.0.4" # + MySQL cache
pip install "hy-memory[rerank]==2.0.4" # + local multilingual cross-encoder rerank
pip install "hy-memory[all]==2.0.4" # everything
```
### 2. Configuration
@@ -151,7 +153,7 @@ result = client.search(
result["facts"] # fact layer
result["experiences"] # experience layer
result["chain_block"] # coding only: version-evolution context
result["chain_block"] # coding only: version-evolution context (empty unless MEMORY_CODING_CHAIN_BLOCK_ENABLED)
```
### 5. Routing, Source Isolation & Advanced APIs
@@ -251,6 +253,7 @@ That version is usually not in the working tree or at HEAD either, so it cannot
- [Graph memory design](docs/pro_graph_design.md) — graph projection, rerank, relation paths, and deployment limits
- [Environment template](.env.example) — a copy-ready configuration template
- [MemHub README](memhub/README.md) — local-first desktop & CLI product overview, runtime commands, and privacy boundaries
- [Hermes native memory provider](plugins/hermes/README.md) — explicit owner/agent scope; separate HTTP service; automatic capture and recall opt-in.
- [OpenClaw plugin](plugins/openclaw/README.md) — agent integrations live under `plugins/` (overview: [plugins/README.md](plugins/README.md))
### License
+12 -9
View File
@@ -32,7 +32,9 @@
## 最新动态
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **正式发布** **Hy Memory 2.0 (`hy-memory==2.0.2`)**(已上线 [PyPI](https://pypi.org/project/hy-memory/2.0.2/)),并开源 **Hy-Memory** monorepo 与 **[MemHub](memhub/README.md)**!
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **模型开源** 在 Hugging Face 发布 **Hy-Memory-30B-A3B** 的 **FP8**(**[Hy-Memory-30B-A3B-FP8](https://huggingface.co/tencent/Hy-Memory-30B-A3B-FP8)**)与 **GGUF**(**[Hy-Memory-30B-A3B-GGUF](https://huggingface.co/tencent/Hy-Memory-30B-A3B-GGUF)**)量化版本模型!
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 📦 **正式发布 [MemHub v1.0.4](https://github.com/Tencent-Hunyuan/Hy-Memory/releases/tag/v1.0.4)** 与 **[memhub-cli 1.0.5](https://www.npmjs.com/package/memhub-cli/v/1.0.5)**,提供已签名的 macOS 桌面应用及经过验证的 macOS/Linux Runtime!
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **正式发布** **Hy Memory 2.0 (`hy-memory==2.0.4`)**(已上线 [PyPI](https://pypi.org/project/hy-memory/2.0.4/)),并开源 **Hy-Memory** monorepo 与 **[MemHub](memhub/README.md)**!
* *<mark>[new]</mark>* 🔥🔥🔥 **[2026-10]**: 🚀 **模型开源** 在 Hugging Face 发布 **[Hy-Memory-30B-A3B](https://huggingface.co/tencent/Hy-Memory-30B-A3B)** 长期记忆写入模型及[技术报告](https://arxiv.org/abs/2610.22196)!
* *<mark>[new]</mark>* 🔥🔥 **[2026-09]**: 📊 **基准与方法发布** 推出长周期与交错式编程记忆评测基准 **[CMB: A Coding Memory Benchmark for Long-Horizon and Interleaved Coding Agents](docs/papers/CMB_A_Coding_Memory_Benchmark_for_Long_Horizon_and_Interleaved_Coding_Agents.pdf)**(已投稿 **ICLR 2027**)。
* *<mark>[new]</mark>* 🔥🔥 **[2026-08]**: 🎉 **论文录用** 双系统认知记忆架构论文 **[Memory Beyond Recall: A Dual-Process Cognitive Memory System for Self-Evolving LLM Agents](https://arxiv.org/abs/2606.09483)** 被 **EMNLP 2026** 接收!
@@ -63,13 +65,13 @@
### 1. 安装
```bash
pip install hy-memory==2.0.2 # 核心(含 ChromaDB 与 Kuzu)
pip install "hy-memory[qdrant]==2.0.2" # + Qdrant
pip install "hy-memory[faiss]==2.0.2" # + FAISS
pip install "hy-memory[graph]==2.0.2" # + Neo4j
pip install "hy-memory[mysql]==2.0.2" # + MySQL 缓存
pip install "hy-memory[rerank]==2.0.2" # + 本地多语言 cross-encoder rerank
pip install "hy-memory[all]==2.0.2" # 全部
pip install hy-memory==2.0.4 # 核心(含 ChromaDB 与 Kuzu)
pip install "hy-memory[qdrant]==2.0.4" # + Qdrant
pip install "hy-memory[faiss]==2.0.4" # + FAISS
pip install "hy-memory[graph]==2.0.4" # + Neo4j
pip install "hy-memory[mysql]==2.0.4" # + MySQL 缓存
pip install "hy-memory[rerank]==2.0.4" # + 本地多语言 cross-encoder rerank
pip install "hy-memory[all]==2.0.4" # 全部
```
### 2. 配置
@@ -151,7 +153,7 @@ result = client.search(
result["facts"] # 事实层
result["experiences"] # 经验层
result["chain_block"] # 仅 coding:版本演进上下文
result["chain_block"] # 仅 coding:版本演进上下文(默认空;需 MEMORY_CODING_CHAIN_BLOCK_ENABLED)
```
### 5. 自动路由、来源过滤与进阶 API
@@ -251,6 +253,7 @@ Coding 与 Working **复用同一套双层 pipeline 和数据 schema**,区别
- [Graph 记忆设计](docs/pro_graph_design.md) — 图投影、重排、关系路径与部署限制
- [环境变量模板](.env.example) — 可直接复制的配置模板
- [MemHub 说明文档](memhub/README.md) — 本地优先桌面端与 CLI 产品总览、Runtime 命令与隐私边界
- [Hermes 原生记忆 Provider](plugins/hermes/README.md) — 显式用户与 Agent 隔离,独立 HTTP 服务,自动记录与召回默认关闭。
- [OpenClaw 插件](plugins/openclaw/README.md) — Agent 集成见 `plugins/`(总览:[plugins/README.md](plugins/README.md))
### License
+1
View File
@@ -197,6 +197,7 @@ SDK 不设置 Rerank Search 并发上限。开启后模型在 `HyMemoryClient`
| `MEMORY_HISTORY_DB_PATH` | `{DATA_DIR}/data/history.db` | History SQLite 路径 |
| `MEMORY_HISTORY_RECORD_SEARCHES` | `false` | 是否记录 Search 操作 |
| `MEMORY_CODING_CHAIN_REPO_ROOT` | — | coding 版本链读取本地 Git diff 的仓库根目录 |
| `MEMORY_CODING_CHAIN_BLOCK_ENABLED` | `false` | search(scene=coding) 是否注入版本演进链块(diff / `chain_block`);默认关 |
## HTTP Server
+3 -2
View File
@@ -78,7 +78,8 @@ default 多-query 超过 `MEMORY_QUERY_REWRITE_MAX_CHARS` 时不改写:Coding
Coding 关闭则直接使用最后一条 query。
路由到 `working` / `coding` 后,Search 读取独立生产力记忆库,返回 `facts` /
`experiences`,不使用 chat 三通道结构。`coding` 还返回 `chain_block` / `chain_used`。
`experiences`,不使用 chat 三通道结构。`coding` 还返回 `chain_block` / `chain_used`
(默认空;需 `MEMORY_CODING_CHAIN_BLOCK_ENABLED` 才注入 diff 块)。
## Chat 成功返回结构
@@ -152,7 +153,7 @@ client = HyMemoryClient.from_config({
安装可选依赖:
```bash
pip install 'hy-memory[rerank]==2.0.1'
pip install 'hy-memory[rerank]==2.0.4'
```
启用后,`HyMemoryClient(...)` 构造阶段会完成模型下载/读取、device 放置和一次 dummy
+2 -3
View File
@@ -37,8 +37,7 @@ do not belong in the public source tree.
- Root GitHub workflows run SDK and MemHub checks from their respective working
directories. Native lifecycle workflows produce reviewable Actions artifacts;
tag releases remain fail-closed on public identity, signing and notarization.
- Hy Memory is published as `hy-memory==2.0.2`. MemHub pins that public
distribution; its selected npm package is `memhub-cli`, which is not yet
published.
- Hy Memory is published as `hy-memory==2.0.4`. MemHub pins that public
distribution; its selected npm package is `memhub-cli` 1.0.5.
- Hy-Memory source uses Apache-2.0 at the repository root. Third-party
components retain their own licenses and attribution notices.
+6 -2
View File
@@ -168,9 +168,11 @@ working/coding 搜索返回:
`limit` 分别限制 facts 与 experiences,因此两层最多各返回 `limit` 条。
`scene="coding"` 额外返回 `chain_block` 和 `chain_used`:
`scene="coding"` 额外返回 `chain_block` 和 `chain_used` 字段(键始终存在;默认内容为空):
- `chain_block` 是与已召回 fact 对齐的版本演进上下文;无法挂链时为 `""`。
- 注入 diff / 版本演进块需显式开启 `MEMORY_CODING_CHAIN_BLOCK_ENABLED=true`
(或 `CodingConfig.chain_block_enabled=True`)。默认关闭,以节约 prompt token。
- 开启后,`chain_block` 是与已召回 fact 对齐的版本演进上下文;无法挂链时为 `""`。
- `chain_used` 是已经进入 chain block 的 `facts` 下标。
- SDK 不会从 `facts` 删除这些条目。调用方若要拼成“chain block + 剩余 facts”,需自行按 `chain_used` 过滤。
@@ -222,10 +224,12 @@ working/coding 搜索返回:
| `MEMORY_CODING_DB_PATH` | `{DATA_DIR}/data/coding_memory.db` | working 基础 SQLite 路径;coding/trace 路径由此派生 |
| `MEMORY_CODING_TOOL_RESULT_MAX_BYTES` | `2048` | 单条 tool result 的字节上限 |
| `MEMORY_CODING_VERBATIM_FALLBACK_ENABLED` | `false` | 模型无结果时是否保存原文 fact;默认关闭,避免 assistant/tool trace 直接展示 |
| `MEMORY_CODING_CHAIN_BLOCK_ENABLED` | `false` | search 是否注入版本演进链块(`chain_block` / diff);默认关闭(opt-in) |
| `MEMORY_EXTRACT_HISTORY_TURNS` | `5` | 回读的历史 user-turn 数;当前 prompt 最终最多使用 5 |
| `MEMORY_CODING_CHAIN_REPO_ROOT` | 空 | coding 版本链读取本地 Git diff 的仓库路径 |
`HCM_*` 变量属于版本链的高级调优项,不是稳定的公共配置契约;普通接入不应依赖其默认值。
其中 `HCM_BLOCK_OFF=1` 可在已开启 `MEMORY_CODING_CHAIN_BLOCK_ENABLED` 时做消融(完全不出块)。
## 8. 定向验证
+25 -8
View File
@@ -5,14 +5,14 @@
## 安装与快速开始
```bash
pip install hy-memory==2.0.2
pip install hy-memory==2.0.4
# 可选后端
pip install 'hy-memory[qdrant]==2.0.1'
pip install 'hy-memory[faiss]==2.0.1'
pip install 'hy-memory[graph]==2.0.1' # Neo4j;Kuzu 已在核心依赖中
pip install 'hy-memory[mysql]==2.0.1'
pip install 'hy-memory[rerank]==2.0.1' # 本地多语言 cross-encoder rerank
pip install 'hy-memory[qdrant]==2.0.4'
pip install 'hy-memory[faiss]==2.0.4'
pip install 'hy-memory[graph]==2.0.4' # Neo4j;Kuzu 已在核心依赖中
pip install 'hy-memory[mysql]==2.0.4'
pip install 'hy-memory[rerank]==2.0.4' # 本地多语言 cross-encoder rerank
```
默认 LLM 和 Embedding 均使用 OpenAI-compatible 接口。使用 OpenAI 时可只设置:
@@ -106,6 +106,15 @@ result = client.add(
)
```
`metadata` 与 `meta` 不是同一字段:
- `metadata` 是兼容旧调用方保留的 SDK 处理选项,会进入内部
`WriteRequest.extra`,不保证持久化或随查询结果返回。
- `meta` 是调用方的业务上下文,会持久化并在 `search()`、`get()` 等结果中返回。
同一记忆被多次合并时,各次 `meta` 会按写入顺序保存在列表中。
需要以后读回的数据必须放在 `meta`,不要放在 `metadata`。
`scene` 的公开取值:
- `None`:普通文本直接走 chat;messages 含 tool 时执行快速场景判断。
@@ -201,7 +210,8 @@ result = client.search(
```
`working` / `coding` 路径返回 `scene="productivity"`、`facts`、`experiences`,不使用
chat 的三桶结构;`coding` 还会返回 `chain_block` 和 `chain_used`。
chat 的三桶结构;`coding` 还会返回 `chain_block` 和 `chain_used` 字段(默认空;
需 `MEMORY_CODING_CHAIN_BLOCK_ENABLED=true` 才注入 diff 块)。
#### `search_mode`
@@ -263,6 +273,8 @@ catalog 也可以在没有基础 L0 时形成只读的合成画像。
```python
memory = client.get("memory_id")
# raw ID 返回 L1_RAW,fact ID 返回对应事实层。
raw_memory = client.get("raw_id")
result = client.update("memory_id", "更新后的内容")
result = client.delete("memory_id")
result = client.delete_all(user_id="user_001")
@@ -272,7 +284,7 @@ page = client.list_memories(
limit=100,
offset=0,
order="desc",
layers=None,
layers=["l1_raw"], # 显式列出 raw;不传仍沿用默认语义层列表
with_evolution=False,
)
@@ -282,6 +294,11 @@ result = client.clone_user("user_001", "user_002", agent_id=None)
对应异步方法为 `async_get()`、`async_update()`、`async_delete()`、
`async_delete_all()`、`async_list_memories()`、`async_clone_user()`。
`get()` / `async_get()` 是统一的 ID 精确读取:返回结果的 `layer`、`kind` 和
`variant` 表明实际类型。授权由调用 SDK 前的产品边界完成,不由 SDK 根据 layer
猜测。`list_memories()` 默认仍不包含 `L1_RAW`;显式传
`layers=["l1_raw"]` 时按同一列表合同返回 raw。
普通 `list_memories()` 返回 `vdb` 桶,并在 Graph 有结果时附带 `graph`;传入
`workspace_id` 时返回生产力记忆的 `scene="productivity"` 和 `experiences`。
+25
View File
@@ -55,9 +55,22 @@ except Exception:
from .client import HyMemoryClient
from .inspector import MemoryInspector
from .runtime import SharedRuntime
from .snapshot import (
DataPlaneRestore,
DataPlaneSnapshot,
DataPlaneSnapshotRejected,
restore_local_data_plane,
snapshot_local_data_plane,
)
# ====== 配置 ======
from .config import MemoryConfig
from .embedding import (
EmbeddingDimensionMismatchError,
EmbeddingService,
EmbeddingServiceProtocol,
)
from .retrieval import AmbiguousMemoryIdError, MemoryKind, MemoryVariant
# ====== Embedding 端点覆盖(per-call,不改 model/dims,只换接入端点)======
from .core.embed_service import embed_endpoint_override
@@ -111,8 +124,20 @@ __all__ = [
"HyMemoryClient",
"MemoryInspector",
"SharedRuntime",
"DataPlaneRestore",
"DataPlaneSnapshot",
"DataPlaneSnapshotRejected",
"restore_local_data_plane",
"snapshot_local_data_plane",
# 配置
"MemoryConfig",
# 公共扩展协议 / 精确读取类型
"EmbeddingService",
"EmbeddingServiceProtocol",
"EmbeddingDimensionMismatchError",
"MemoryKind",
"MemoryVariant",
"AmbiguousMemoryIdError",
# Embedding 端点覆盖
"embed_endpoint_override",
# 高级 API
+2 -1
View File
@@ -22,7 +22,8 @@ logger = logging.getLogger(__name__)
# ================================================================
# 数据结构
# ================================================================@dataclass
# ================================================================
@dataclass
class SessionSummaryResult:
"""Session 摘要结果 (V2)"""
success: bool
+13 -3
View File
@@ -39,6 +39,7 @@ import logging
import hashlib
import json
import re
from datetime import datetime
from typing import Any, Dict, List, Optional
import uuid
@@ -252,6 +253,17 @@ def _series_episode_id(
return str(uuid.uuid5(uuid.NAMESPACE_URL, "hy-memory:series-episode:" + raw))
def _series_memory_at(times: List[int]) -> Optional[datetime]:
"""Earliest member timestamp as the same local wall clock it came from.
``_node_timestamp`` produces ``datetime.timestamp()`` values. Reading them
back with ``utcfromtimestamp`` turns them into a naive *UTC* datetime, which
the vector payload later re-interprets as local time and shifts by the
machine's UTC offset.
"""
return datetime.fromtimestamp(min(times)) if times else None
def _node_timestamp(node: Any) -> Optional[int]:
value = getattr(node, "memory_at", None) or getattr(node, "gmt_created", None)
if value is None:
@@ -974,8 +986,6 @@ async def finalize_series_episode_containers(
Stored text is only a title plus a structural intro. Exact L2 bodies remain in
their canonical nodes and are referenced by ID from dated timeline segments.
"""
from datetime import datetime
from ..models.memory import MemoryLayer, MemoryNode, MemoryStatus, SourceType
from ..pipelines._retrieval.session_episode import (
add_parent_episode_membership,
@@ -1061,7 +1071,7 @@ async def finalize_series_episode_containers(
segment["memory_at"] for segment in plan["timeline"]
if segment.get("memory_at") is not None
]
memory_at = datetime.utcfromtimestamp(min(times)) if times else None
memory_at = _series_memory_at(times)
content = f"{plan['title']}. {plan['intro']}".strip()
series = MemoryNode(
node_id=series_id, user_id=user_id,
+2
View File
@@ -1123,6 +1123,7 @@ class Extractor:
max_tokens=self._llm_config.agent_max_tokens,
tools=None,
tool_choice=None,
audit_stage="extract",
)
self._call_count += 1
total_tokens += response.tokens_used
@@ -1233,6 +1234,7 @@ class Extractor:
max_tokens=self._llm_config.agent_max_tokens,
tools=None,
tool_choice=None,
audit_stage="extract",
)
self._call_count += 1
total_tokens += response.tokens_used
+35 -20
View File
@@ -34,6 +34,7 @@ import os
import weakref
from ..config import MemoryConfig
from ..utils.model_call_context import model_call_stage
from ..core.workload import llm_slot
logger = logging.getLogger(__name__)
@@ -348,6 +349,7 @@ class LLMProvider:
stop: List[str] = None,
tools: Optional[List[Dict[str, Any]]] = None,
tool_choice: Optional[Any] = None,
audit_stage: Optional[str] = None,
**kwargs
) -> LLMResponse:
"""
@@ -386,15 +388,16 @@ class LLMProvider:
len(prompt), _content_fingerprint(prompt),
)
response = await self._call_llm(
prompt=prompt,
max_tokens=max_tokens,
temperature=temperature,
stop=stop,
tools=tools,
tool_choice=tool_choice,
**kwargs
)
with model_call_stage(audit_stage):
response = await self._call_llm(
prompt=prompt,
max_tokens=max_tokens,
temperature=temperature,
stop=stop,
tools=tools,
tool_choice=tool_choice,
**kwargs
)
self._total_calls += 1
self._total_tokens += response.tokens_used
@@ -496,11 +499,21 @@ class LLMProvider:
clients = self._clients.setdefault(loop, {})
client = clients.get(client_key)
if client is None:
client_options: Dict[str, Any] = {
"api_key": base_api_key,
"base_url": base_url,
"timeout": self._llm_config.timeout,
"max_retries": 0,
}
transport_factory = getattr(self.config, "http_transport_factory", None)
if callable(transport_factory):
import httpx
client_options["http_client"] = httpx.AsyncClient(
transport=transport_factory()
)
client = AsyncOpenAI(
api_key=base_api_key,
base_url=base_url,
timeout=self._llm_config.timeout,
max_retries=0,
**client_options,
)
clients[client_key] = client
@@ -585,6 +598,7 @@ class LLMProvider:
temperature: Optional[float] = None,
tools: Optional[List[Dict[str, Any]]] = None,
tool_choice: Optional[Any] = None,
audit_stage: Optional[str] = None,
) -> LLMResponse:
"""
多轮 messages 调用(支持 tool results 回传)。
@@ -612,13 +626,14 @@ class LLMProvider:
f"msgs={len(messages)} tools={len(tools) if tools else 0}"
)
response = await self._chat_completions(
messages,
max_tokens=max_tokens,
temperature=temperature,
tools=tools,
tool_choice=tool_choice,
)
with model_call_stage(audit_stage):
response = await self._chat_completions(
messages,
max_tokens=max_tokens,
temperature=temperature,
tools=tools,
tool_choice=tool_choice,
)
self._total_calls += 1
self._total_tokens += response.tokens_used
+2
View File
@@ -669,6 +669,7 @@ class MemoryReconciler:
response = await llm.complete(
prompt=prompt,
max_tokens=500,
audit_stage="reconcile",
)
text = response.content.strip()
if "```json" in text:
@@ -1383,6 +1384,7 @@ class MemoryReconciler:
response = await llm.complete(
prompt=prompt,
max_tokens=dyn_max_tokens,
audit_stage="reconcile",
)
except Exception as e:
# LLM 彻底不可用(provider 已按 max_retries 重试过,网关 500 /
+790 -147
View File
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -647,7 +647,9 @@ class HyCodeMem:
top-k,但它们的 diff 对当前工作区不可能有用,因此挂链前必须做同仓过滤。
"""
facts = facts or []
# 开关: HCM_BLOCK_OFF=1 → 完全不出块, 也不从 bullet 删任何 fact。
# 高级消融开关: HCM_BLOCK_OFF=1 → 完全不出块, 也不从 bullet 删任何 fact。
# 公共 opt-in 见 CodingConfig.chain_block_enabled /
# MEMORY_CODING_CHAIN_BLOCK_ENABLED(默认关;客户端在调用 decorate 前拦截)。
if os.environ.get("HCM_BLOCK_OFF") == "1":
return "", []
picked, used = [], []
+1
View File
@@ -919,6 +919,7 @@ class CodingMemoryExtractor:
resp = await self.llm_provider.complete(
prompt=prompt,
max_tokens=self.max_tokens,
audit_stage="coding_extract",
)
except Exception as e:
logger.warning(f"[coding-extract] LLM call failed: {e}")
+35 -2
View File
@@ -466,7 +466,13 @@ class WorkingFactReconciler:
return [], []
candidates = await self._retrieve_candidates(
drafts, user_id=user_id, source=source,
drafts,
user_id=user_id,
agent_id=agent_id,
session_id=session_id,
workspace_id=workspace_id,
branch=branch,
source=source,
)
try:
@@ -499,7 +505,15 @@ class WorkingFactReconciler:
# ------------------------------------------------------------
async def _retrieve_candidates(
self, drafts: List[WorkingFactDraft], *, user_id: str, source: str
self,
drafts: List[WorkingFactDraft],
*,
user_id: str,
agent_id: str,
session_id: Optional[str],
workspace_id: Optional[str],
branch: Optional[str],
source: str,
) -> List[List[WorkingFact]]:
"""每条 draft 用 statement 召回同 user 的 top-N active 事实。
@@ -512,6 +526,10 @@ class WorkingFactReconciler:
关掉时整份召回原样交给 LLM。适用于 subject 不是稳定实体名的数据集(自由文本、
位置标签),那里精确字符串相等会把同实体判成不同主体,反而拦掉真实更新。
"""
# Empty/legacy session metadata remains readable, but cannot prove
# conversation authority for a destructive SUPERSEDE.
if not session_id:
return [[] for _ in drafts]
try:
embeddings = await self.embed_service.embed_batch(
[d.statement for d in drafts]
@@ -525,6 +543,10 @@ class WorkingFactReconciler:
try:
hits = await self.store.search_facts(
emb, user_id=user_id, top=self.candidates_per_draft,
agent_id=agent_id,
session_id=session_id,
workspace_id=workspace_id,
branch=branch,
# 写入侧同样接词面通道:候选选错了 LLM 就没有机会判对。这里不传
# min_score——写入侧要的是"有哪些可能的前身",让 LLM 看更宽的名单,
# 阈值过滤是读取侧的事。
@@ -571,6 +593,7 @@ class WorkingFactReconciler:
resp = await self.llm_provider.complete(
prompt=prompt,
max_tokens=self.max_tokens,
audit_stage="coding_fact_reconcile",
)
return self._parse_ops(resp.content)
@@ -637,6 +660,7 @@ class WorkingFactReconciler:
resp = await self.llm_provider.complete(
prompt=prompt,
max_tokens=_CHAIN_SUMMARY_MAX_TOKENS,
audit_stage="coding_fact_summary",
)
except Exception as e:
logger.warning(f"[fact-reconcile] chain summary failed: {e}")
@@ -792,6 +816,15 @@ class WorkingFactReconciler:
old = await self.store.get_fact(old_id, user_id=user_id)
if old is None:
continue
if (
old.agent_id != agent_id
or old.session_id != session_id
or old.workspace_id != workspace_id
):
logger.warning(
f"[fact-reconcile] refused cross-authority SUPERSEDE: {old.fact_id}"
)
continue
# 闸门在候选阶段已经拦过一道,这里再拦一次:候选是按 statement 召回的,
# 而 LLM 只能覆盖候选名单里的 id,理论上到不了这儿。真到了就说明前面
# 哪一环漏了,宁可让这次覆盖不生效——多留一条旧事实是可恢复的,删掉
+11 -3
View File
@@ -29,6 +29,9 @@ logger = logging.getLogger(__name__)
_JUDGE_MAX_TURNS = 20
_JUDGE_HEAD_TURNS = 5
_JUDGE_USER_CONTENT_LIMIT = 1_000
_JUDGE_USER_CONTENT_HEAD = 200
_JUDGE_USER_CONTENT_TAIL = 200
_JUDGE_MAX_QUERY_CHARS = 300
_JUDGE_MAX_QUERIES = 20
@@ -186,6 +189,7 @@ async def classify_messages_scene(
prompt=prompt,
max_tokens=max_tokens,
temperature=temperature,
audit_stage="coding_judge",
)
_elapsed = round((time.perf_counter() - _t0) * 1000, 2)
result = _parse_scene_json(resp.content)
@@ -631,9 +635,13 @@ def _format_turns(summary: List[Dict[str, Any]]) -> str:
rows = []
for t in summary:
user = t.get("user", "") or ""
# 单 turn 用户文本截到 200 字符
if len(user) > 200:
user = user[:200] + "..."
if len(user) > _JUDGE_USER_CONTENT_LIMIT:
omitted = len(user) - _JUDGE_USER_CONTENT_HEAD - _JUDGE_USER_CONTENT_TAIL
user = (
user[:_JUDGE_USER_CONTENT_HEAD]
+ f"\n[...{omitted} chars omitted...]\n"
+ user[-_JUDGE_USER_CONTENT_TAIL:]
)
tools = t.get("tools", []) or []
rows.append(
f"- turn {t.get('turn', '?')}: user={user!r}, tools={tools}"
+34 -1
View File
@@ -240,7 +240,7 @@ class CodingMemoryReconciler:
)
# 3. 校验 + 执行
executed = await self._execute(ops, drafts)
executed = await self._execute(ops, drafts, candidates_per_draft)
logger.info(
f"[coding-reconcile] drafts={len(drafts)} ops={len(executed)} "
+ ", ".join(f"{a}={sum(1 for o in executed if o.action == a)}"
@@ -263,6 +263,12 @@ class CodingMemoryReconciler:
"""
result: List[List[CodingMemory]] = []
for d in drafts:
# A coding mutation must be attributable to one conversation.
# Empty/legacy session metadata stays readable through ordinary
# search, but it cannot authorize UPDATE/DELETE.
if not d.session_id:
result.append([])
continue
try:
# task 为主入口,search_keys 为附加入口(去重、去空)
queries = [d.task] + [k for k in (d.search_keys or []) if k and k != d.task]
@@ -274,6 +280,8 @@ class CodingMemoryReconciler:
hits = await self.store.search_by_query_embedding(
emb,
user_id=d.user_id,
agent_id=d.agent_id,
session_id=d.session_id,
workspace_id=d.workspace_id,
branch=d.branch,
top=self.candidates_per_draft * 4,
@@ -310,6 +318,7 @@ class CodingMemoryReconciler:
resp = await self.llm_provider.complete(
prompt=prompt,
max_tokens=self.max_tokens,
audit_stage="coding_reconcile",
)
return self._parse_ops(resp.content), prompt, resp.content, resp
@@ -414,6 +423,7 @@ class CodingMemoryReconciler:
self,
ops: List[ReconcileOp],
drafts: List[CodingMemoryDraft],
candidates_per_draft: List[List[CodingMemory]],
) -> List[ReconcileOp]:
"""
校验 + 执行 ops。返回成功执行的 ops(filter 掉无效 op)。
@@ -453,6 +463,11 @@ class CodingMemoryReconciler:
if not op.target_experience_id:
logger.warning(f"[coding-reconcile] drop UPDATE missing target: {op.to_dict()}")
continue
if not self._target_was_offered(op, candidates_per_draft):
logger.warning(
f"[coding-reconcile] drop UPDATE outside authority scope: {op.to_dict()}"
)
continue
if op.draft_idx in consumed:
logger.warning(f"[coding-reconcile] drop UPDATE on consumed draft: {op.to_dict()}")
continue
@@ -475,6 +490,11 @@ class CodingMemoryReconciler:
if not op.target_experience_id:
logger.warning(f"[coding-reconcile] drop DELETE missing target: {op.to_dict()}")
continue
if not self._target_was_offered(op, candidates_per_draft):
logger.warning(
f"[coding-reconcile] drop DELETE outside authority scope: {op.to_dict()}"
)
continue
# DELETE 需要知道 user_id;通过 draft_idx(如有)或第一个 draft 推断
user_id = self._infer_user_id(op, drafts)
if not user_id:
@@ -511,6 +531,19 @@ class CodingMemoryReconciler:
return executed
@staticmethod
def _target_was_offered(
op: ReconcileOp,
candidates_per_draft: List[List[CodingMemory]],
) -> bool:
"""Only mutate a target frozen into this draft's scoped candidate set."""
if op.draft_idx is None or not (0 <= op.draft_idx < len(candidates_per_draft)):
return False
return any(
candidate.experience_id == op.target_experience_id
for candidate in candidates_per_draft[op.draft_idx]
)
@staticmethod
def _infer_user_id(
op: ReconcileOp, drafts: List[CodingMemoryDraft]
+128 -15
View File
@@ -209,6 +209,14 @@ def _scope_where(
return sql, params
def _in_clause(column: str, values: Optional[List[str]]) -> Tuple[str, List[Any]]:
"""SQL ``column IN (...)`` + parameters; empty values mean no condition."""
if not values:
return "", []
placeholders = ",".join("?" for _ in values)
return f"{column} IN ({placeholders})", list(values)
def _scope_matches(
row_workspace_id: Optional[str],
row_branch: Optional[str],
@@ -408,6 +416,36 @@ class CodingMemoryStore:
self._initialized = False
@staticmethod
def database_path(
config: MemoryConfig,
db_path: Optional[str] = None,
variant: str = "working",
) -> str:
"""Return the authoritative SQLite path without creating anything."""
if db_path is None:
data_dir = (
os.path.dirname(config.history.db_path)
if config.history.db_path else "./data"
)
db_path = os.path.join(data_dir, "coding_memory.db")
normalized = (
"coding"
if str(variant or "").strip().lower() == "coding"
else "working"
)
return _variant_db_path(db_path, "_cv" if normalized == "coding" else "")
@classmethod
def database_exists(
cls,
config: MemoryConfig,
db_path: Optional[str] = None,
variant: str = "working",
) -> bool:
"""Whether a coding namespace has an existing SQLite database."""
return os.path.isfile(cls.database_path(config, db_path, variant))
async def initialize(self) -> None:
if self._initialized:
return
@@ -529,10 +567,20 @@ class CodingMemoryStore:
"""覆盖式更新一条 coding memory。"""
# 拿旧 keys 长度,先删旧 VDB rows
prev = await self.get_by_id(memory.experience_id, user_id=memory.user_id)
prev_key_count = (1 + len(prev.search_keys)) if prev else 0
if prev is None:
raise ValueError("coding_memory_update_target_missing")
if (
not prev.session_id
or not memory.session_id
or prev.agent_id != memory.agent_id
or prev.session_id != memory.session_id
or prev.workspace_id != memory.workspace_id
):
raise ValueError("coding_memory_update_authority_mismatch")
prev_key_count = 1 + len(prev.search_keys)
memory.updated_at = datetime.utcnow()
if memory.created_at is None and prev is not None:
if memory.created_at is None:
memory.created_at = prev.created_at
await _run_in_pool(self._upsert_sql_sync, memory)
# 删旧 VDB
@@ -671,6 +719,10 @@ class CodingMemoryStore:
query_embedding: List[float],
user_id: str,
*,
agent_id: Optional[str] = None,
session_id: Optional[str] = None,
agent_ids: Optional[List[str]] = None,
session_ids: Optional[List[str]] = None,
workspace_id: Optional[str] = None,
branch: Optional[str] = None,
top: int = 40,
@@ -688,21 +740,34 @@ class CodingMemoryStore:
},
...
]
workspace_id / branch 是作用域过滤,规则见 _scope_where:不传则纯语义召回
(行为与加过滤前完全一致);传了则只保留 SQLite 里落在作用域内的经验,并按
作用域的选择率放大向量取数,避免"先取 top-N 再过滤"把召回吃掉。
agent_id / session_id(或 agent_ids / session_ids)是写授权作用域,
传入时精确匹配;workspace_id / branch 的规则见 _scope_where。
不传任何作用域则维持纯语义召回;传了则只保留 SQLite 里落在作用域内的经验,
并按选择率放大向量取数,避免"先取 top-N 再过滤"把召回吃掉。
"""
if self._vec is None:
return []
effective_agent_ids = list(agent_ids) if agent_ids else (
[agent_id] if agent_id else []
)
effective_session_ids = list(session_ids) if session_ids else (
[session_id] if session_id else []
)
allowed: Optional[Set[str]] = None
if workspace_id:
if effective_agent_ids or effective_session_ids or workspace_id:
allowed, total = await _run_in_pool(
self._scoped_experience_ids_sync, user_id, workspace_id, branch
self._authority_scoped_experience_ids_sync,
user_id,
effective_agent_ids,
effective_session_ids,
workspace_id,
branch,
)
if not allowed:
logger.info(
f"[coding-store] no experience in scope: "
f"agent_id={agent_id!r} session_id={session_id!r} "
f"workspace_id={workspace_id!r} branch={branch!r} "
f"(user has {total}); skip vdb search"
)
@@ -778,6 +843,10 @@ class CodingMemoryStore:
query_embedding: List[float],
user_id: str,
*,
agent_id: Optional[str] = None,
session_id: Optional[str] = None,
agent_ids: Optional[List[str]] = None,
session_ids: Optional[List[str]] = None,
workspace_id: Optional[str] = None,
branch: Optional[str] = None,
top: int = 5,
@@ -791,8 +860,9 @@ class CodingMemoryStore:
SUPERSEDE 时向量行已被删掉,理论上召不到 superseded;这里再按 SQLite 的
status 过一道,避免两边不一致时把过期结论放出去。
workspace_id / branch 是作用域过滤,规则见 _scope_where,语义与经验层一致:
不传不过滤,传了按 SQLite 里的值筛,并按选择率放大向量取数。
agent_id / session_id(或 agent_ids / session_ids)是写授权作用域,
传入时精确匹配;workspace_id / branch 的规则见 _scope_where。
不传任何作用域则不过滤,传了按 SQLite 里的值筛,并按选择率放大向量取数。
向量库按 top 的 4 倍过采样:向量行和 SQLite 行不是一个事务里写的,中间挂掉
就会留下"向量还在、SQLite 没了"的孤儿,软删时删向量失败也会留下 superseded
@@ -808,14 +878,27 @@ class CodingMemoryStore:
if self._fact_vec is None:
return []
effective_agent_ids = list(agent_ids) if agent_ids else (
[agent_id] if agent_id else []
)
effective_session_ids = list(session_ids) if session_ids else (
[session_id] if session_id else []
)
fetch = top * 4
if workspace_id:
if effective_agent_ids or effective_session_ids or workspace_id:
scoped, total = await _run_in_pool(
self._count_active_facts_sync, user_id, workspace_id, branch
self._count_active_facts_sync,
user_id,
effective_agent_ids,
effective_session_ids,
workspace_id,
branch,
)
if not scoped:
logger.info(
f"[coding-store] no active fact in scope: "
f"agent_ids={effective_agent_ids!r} "
f"session_ids={effective_session_ids!r} "
f"workspace_id={workspace_id!r} branch={branch!r} "
f"(user has {total}); skip fact vdb search"
)
@@ -852,6 +935,8 @@ class CodingMemoryStore:
alive = [
(f, scores[f.fact_id]) for f in facts
if f.status == "active"
and (not effective_agent_ids or f.agent_id in effective_agent_ids)
and (not effective_session_ids or f.session_id in effective_session_ids)
and _scope_matches(f.workspace_id, f.branch, workspace_id, branch)
]
kept = [(f, s) for f, s in alive if s >= min_score]
@@ -1050,14 +1135,28 @@ class CodingMemoryStore:
by_id = {r["experience_id"]: _row_to_memory(r) for r in rows}
return [by_id[eid] for eid in experience_ids if eid in by_id]
def _scoped_experience_ids_sync(
self, user_id: str, workspace_id: str, branch: Optional[str]
def _authority_scoped_experience_ids_sync(
self,
user_id: str,
agent_ids: Optional[List[str]],
session_ids: Optional[List[str]],
workspace_id: Optional[str],
branch: Optional[str],
) -> Tuple[Set[str], int]:
"""返回 (落在作用域内的 experience_id 集合, 该 user 的经验总数)。
"""返回 (落在授权作用域内的 experience_id 集合, 该 user 的经验总数)。
一次查询同时拿到过滤结果和选择率分母:前者供向量命中做交集,后者定放大倍数。
agent_ids / session_ids 为空表示该维度不筛;非空按 IN 精确匹配。
"""
scope_sql, scope_params = _scope_where(workspace_id, branch)
agent_sql, agent_params = _in_clause("agent_id", agent_ids)
if agent_sql:
scope_sql = f"({agent_sql}) AND ({scope_sql})"
scope_params = [*agent_params, *scope_params]
session_sql, session_params = _in_clause("session_id", session_ids)
if session_sql:
scope_sql = f"({session_sql}) AND ({scope_sql})"
scope_params = [*session_params, *scope_params]
with self._lock:
assert self._conn is not None
cur = self._conn.execute(
@@ -1069,13 +1168,27 @@ class CodingMemoryStore:
return {r["experience_id"] for r in rows if r["in_scope"]}, len(rows)
def _count_active_facts_sync(
self, user_id: str, workspace_id: str, branch: Optional[str]
self,
user_id: str,
agent_ids: Optional[List[str]],
session_ids: Optional[List[str]],
workspace_id: Optional[str],
branch: Optional[str],
) -> Tuple[int, int]:
"""返回 (作用域内 active 事实数, 该 user 的 active 事实总数)。
事实层的过滤在 get_facts 拿到对象之后用 _scope_matches 做,这里只要选择率。
agent_ids / session_ids 为空表示该维度不筛;非空按 IN 精确匹配。
"""
scope_sql, scope_params = _scope_where(workspace_id, branch)
agent_sql, agent_params = _in_clause("agent_id", agent_ids)
if agent_sql:
scope_sql = f"({agent_sql}) AND ({scope_sql})"
scope_params = [*agent_params, *scope_params]
session_sql, session_params = _in_clause("session_id", session_ids)
if session_sql:
scope_sql = f"({session_sql}) AND ({scope_sql})"
scope_params = [*session_params, *scope_params]
with self._lock:
assert self._conn is not None
row = self._conn.execute(
+9 -2
View File
@@ -50,6 +50,7 @@ class CodingWriter:
embed_service: EmbedService,
fact_reconciler: Optional[WorkingFactReconciler] = None,
cache: Any = None,
variant: str = "working",
):
self.store = store
self.extractor = extractor
@@ -59,6 +60,11 @@ class CodingWriter:
self.fact_reconciler = fact_reconciler or WorkingFactReconciler(
store, embed_service, llm_provider
)
self.variant = (
"coding"
if str(variant or "").strip().lower() == "coding"
else "working"
)
# cache 仅用于把 request_id 串给各阶段(各阶段自己打点);writer 不集中打点。
self.cache = cache
@@ -217,6 +223,7 @@ class CodingWriter:
return {
"success": True,
"scene": "productivity",
"variant": self.variant,
"request_id": request_id,
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 2),
"ops": [op.to_dict() for op in ops],
@@ -278,11 +285,11 @@ class CodingWriter:
f"[coding-write] crosslink fact {f.fact_id} failed: {e}"
)
@staticmethod
def _empty_response(request_id: str, t0: float) -> Dict[str, Any]:
def _empty_response(self, request_id: str, t0: float) -> Dict[str, Any]:
return {
"success": True,
"scene": "productivity",
"variant": self.variant,
"request_id": request_id,
"elapsed_ms": round((time.perf_counter() - t0) * 1000, 2),
"ops": [],
+15 -1
View File
@@ -6,7 +6,7 @@ Agent Memory - 配置管理
import os
from dataclasses import dataclass, field
from typing import Optional, Dict, Any, List
from typing import Optional, Dict, Any, Callable, List
from pathlib import Path
@@ -1136,6 +1136,9 @@ class CodingConfig:
# LLM 失败或没有抽出 fact 时,是否把对话原文存成 working fact。
# 默认关闭,避免 assistant/tool 轨迹以 statement 形式直接暴露给消费方。
verbatim_fallback_enabled: bool = None
# search(scene="coding") 是否注入版本演进链块(diff / chain_block)。
# 默认关闭(opt-in):中重度 coding 用户可省下大量 prompt token;写入侧仍可 observe。
chain_block_enabled: bool = None
def __post_init__(self):
if self.enable is None:
@@ -1153,6 +1156,10 @@ class CodingConfig:
self.verbatim_fallback_enabled = _get_env_bool(
"MEMORY_CODING_VERBATIM_FALLBACK_ENABLED", False
)
if self.chain_block_enabled is None:
self.chain_block_enabled = _get_env_bool(
"MEMORY_CODING_CHAIN_BLOCK_ENABLED", False
)
@dataclass
@@ -1252,6 +1259,13 @@ class MemoryConfig:
enable_agent: bool = False
debug: bool = False
metrics_enabled: bool = True
# Runtime-only HTTP transport factory. MemHub uses this for request-cost
# budgeting without restricting the embedded SDK's local store access.
http_transport_factory: Optional[Callable[[], Any]] = field(
default=None,
repr=False,
compare=False,
)
def __post_init__(self):
# enable_graph 跟随 mode 走:mode=ultra 时自动启用,无需独立环境变量
+14 -4
View File
@@ -356,11 +356,21 @@ class EmbedService:
key = self._client_cache_key(base_url, api_key, timeout)
client = self._client_cache.get(key)
if client is None:
client_options = {
"api_key": api_key,
"base_url": base_url or None,
"timeout": timeout,
"max_retries": 0,
}
transport_factory = getattr(self.config, "http_transport_factory", None)
if callable(transport_factory):
import httpx
client_options["http_client"] = httpx.AsyncClient(
transport=transport_factory()
)
client = AsyncOpenAI(
api_key=api_key,
base_url=base_url or None,
timeout=timeout,
max_retries=0,
**client_options,
)
self._client_cache[key] = client
return client
+31
View File
@@ -114,6 +114,37 @@ class CacheBase(ABC):
"""查询 pipeline 中间结果日志"""
...
# ================================================================
# Durable write outcomes
# ================================================================
@abstractmethod
async def claim_write_outcome(
self,
request_id: str,
user_id: str,
agent_id: str,
session_id: str,
operation: str,
) -> Optional[Dict[str, Any]]:
"""Claim one idempotent write; return the existing row if already claimed."""
...
@abstractmethod
async def finish_write_outcome(
self,
request_id: str,
status: str,
result: Dict[str, Any],
) -> bool:
"""Persist the terminal/unknown result for a claimed write."""
...
@abstractmethod
async def get_write_outcome(self, request_id: str) -> Optional[Dict[str, Any]]:
"""Read one durable write outcome by exact request id."""
...
# ================================================================
# Summary Buffer(rolling summary 的未消费 turn 暂存)
#
+130 -16
View File
@@ -81,6 +81,21 @@ _CREATE_TABLES_SQL = [
)
""",
"""
CREATE TABLE IF NOT EXISTS write_outcomes (
request_id VARCHAR(256) NOT NULL,
user_id VARCHAR(255) NOT NULL,
agent_id VARCHAR(255) NOT NULL DEFAULT '',
session_id VARCHAR(255) NOT NULL DEFAULT '',
operation VARCHAR(32) NOT NULL,
status VARCHAR(32) NOT NULL,
result_json LONGTEXT NOT NULL,
created_at VARCHAR(64) NOT NULL,
updated_at VARCHAR(64) NOT NULL,
PRIMARY KEY (request_id),
KEY idx_write_outcomes_owner (user_id, agent_id, session_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
""",
"""
CREATE TABLE IF NOT EXISTS system_metrics (
minute_ts VARCHAR(32) NOT NULL,
data LONGTEXT NOT NULL,
@@ -459,29 +474,128 @@ class MysqlCache(CacheBase):
logger.warning(f"get_pipeline_logs failed: {e}")
return []
async def claim_write_outcome(
self,
request_id: str,
user_id: str,
agent_id: str,
session_id: str,
operation: str,
) -> Optional[Dict[str, Any]]:
now = datetime.now().isoformat()
inserted = await self._execute(
"""
INSERT IGNORE INTO write_outcomes (
request_id, user_id, agent_id, session_id, operation,
status, result_json, created_at, updated_at
) VALUES (%s, %s, %s, %s, %s, 'running', '{}', %s, %s)
""",
(request_id, user_id, agent_id, session_id, operation, now, now),
)
if inserted == 1:
return None
return await self.get_write_outcome(request_id)
async def finish_write_outcome(
self,
request_id: str,
status: str,
result: Dict[str, Any],
) -> bool:
updated = await self._execute(
"""
UPDATE write_outcomes
SET status = %s, result_json = %s, updated_at = %s
WHERE request_id = %s
""",
(
status,
json.dumps(result, ensure_ascii=False, default=str),
datetime.now().isoformat(),
request_id,
),
)
return updated == 1
async def get_write_outcome(self, request_id: str) -> Optional[Dict[str, Any]]:
row = await self._fetchone(
"SELECT * FROM write_outcomes WHERE request_id = %s",
(request_id,),
)
if row is None:
return None
try:
row["result"] = json.loads(row.pop("result_json") or "{}")
except (TypeError, json.JSONDecodeError):
row["result"] = {}
return row
# ================================================================
# System Metrics(分钟粒度落盘)
# ================================================================
async def store_metrics_minute(self, minute_ts: str, data: dict) -> None:
import aiomysql
try:
now = datetime.now().isoformat()
# 尝试 UPSERT
existing = await self._fetchone(
"SELECT data FROM system_metrics WHERE minute_ts = %s", (minute_ts,)
)
if existing:
old_data = json.loads(existing["data"])
merged = self._merge_metric_buckets(old_data, data)
await self._execute(
"UPDATE system_metrics SET data = %s, created_at = %s WHERE minute_ts = %s",
(json.dumps(merged, default=str), now, minute_ts),
)
else:
await self._execute(
"INSERT INTO system_metrics (minute_ts, data, created_at) VALUES (%s, %s, %s)",
(minute_ts, json.dumps(data, default=str), now),
)
# Read-merge-write must be one transaction: two instances flushing
# the same minute used to overwrite each other's counters, and a
# concurrent insert could lose the whole batch to a duplicate key.
for attempt in range(2):
try:
async with self._pool.acquire() as conn:
await conn.begin()
try:
async with conn.cursor(aiomysql.DictCursor) as cur:
await cur.execute(
"SELECT data FROM system_metrics "
"WHERE minute_ts = %s FOR UPDATE",
(minute_ts,),
)
row = await cur.fetchone()
if row is not None:
old_raw = (
row["data"]
if isinstance(row, dict)
else row[0]
)
merged = self._merge_metric_buckets(
json.loads(old_raw), data,
)
await cur.execute(
"UPDATE system_metrics SET data = %s, "
"created_at = %s WHERE minute_ts = %s",
(
json.dumps(merged, default=str),
now,
minute_ts,
),
)
else:
await cur.execute(
"INSERT INTO system_metrics "
"(minute_ts, data, created_at) "
"VALUES (%s, %s, %s)",
(
minute_ts,
json.dumps(data, default=str),
now,
),
)
await conn.commit()
return
except Exception:
await conn.rollback()
raise
except (aiomysql.IntegrityError, aiomysql.OperationalError) as error:
code = error.args[0] if error.args else None
deadlock = code in (1205, 1213)
if attempt or (isinstance(error, aiomysql.OperationalError) and not deadlock):
raise
# A competing writer inserted the row, or InnoDB chose us
# as the deadlock victim. Retry so this batch merges.
continue
except Exception as e:
logger.warning(f"store_metrics_minute failed: {e}")
+232 -125
View File
@@ -7,7 +7,7 @@ Agent Memory V2 - SqliteCache
设计模式跟随 history_store.py:
- 标准库 sqlite3 + _run_in_sqlite_pool()
- WAL 模式 + check_same_thread=False
- threading.Lock 保护写操作
- 每实例 threading.RLock 保护共享连接的全部操作与关闭
三张表:
- memory_operations / pipeline_logs / system_metrics: 审计与观测
@@ -87,6 +87,20 @@ CREATE TABLE IF NOT EXISTS pipeline_logs_v2 (
CREATE INDEX IF NOT EXISTS idx_plog_request ON pipeline_logs_v2(request_id);
CREATE INDEX IF NOT EXISTS idx_plog_user ON pipeline_logs_v2(user_id);
CREATE TABLE IF NOT EXISTS write_outcomes (
request_id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
agent_id TEXT NOT NULL DEFAULT '',
session_id TEXT NOT NULL DEFAULT '',
operation TEXT NOT NULL,
status TEXT NOT NULL,
result_json TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_write_outcomes_owner
ON write_outcomes(user_id, agent_id, session_id);
CREATE TABLE IF NOT EXISTS system_metrics (
minute_ts TEXT PRIMARY KEY,
data TEXT NOT NULL,
@@ -122,7 +136,10 @@ class SqliteCache(CacheBase):
def __init__(self, config: MemoryConfig):
self.config = config
self._conn: Optional[sqlite3.Connection] = None
self._lock = threading.Lock()
# One connection is shared by the executor workers. Use the same lock
# for reads, writes, initialization and close so close() cannot free
# the connection while another worker is inside sqlite3.
self._lock = threading.RLock()
# 读取 db_path
cache_cfg = getattr(config, "cache", None)
@@ -144,35 +161,37 @@ class SqliteCache(CacheBase):
logger.debug(f"SqliteCache initialized: {self._db_path}")
def _init_sync(self) -> None:
db_dir = os.path.dirname(self._db_path)
if db_dir:
os.makedirs(db_dir, exist_ok=True)
self._conn = sqlite3.connect(self._db_path, check_same_thread=False)
self._conn.row_factory = sqlite3.Row
self._conn.execute("PRAGMA journal_mode=WAL;")
self._conn.executescript(_CREATE_TABLES_SQL)
self._migrate_pipeline_logs_columns()
self._conn.commit()
with self._lock:
db_dir = os.path.dirname(self._db_path)
if db_dir:
os.makedirs(db_dir, exist_ok=True)
self._conn = sqlite3.connect(self._db_path, check_same_thread=False)
self._conn.row_factory = sqlite3.Row
self._conn.execute("PRAGMA journal_mode=WAL;")
self._conn.executescript(_CREATE_TABLES_SQL)
self._migrate_pipeline_logs_columns()
self._conn.commit()
def _migrate_pipeline_logs_columns(self) -> None:
"""给旧库的 pipeline_logs_v2 补 namespace/session/event time 列。"""
try:
cols = {
row["name"]
for row in self._conn.execute("PRAGMA table_info(pipeline_logs_v2)")
}
_text_cols = ("namespace", "session_id")
for col in _text_cols:
if col not in cols:
with self._lock:
try:
cols = {
row["name"]
for row in self._conn.execute("PRAGMA table_info(pipeline_logs_v2)")
}
_text_cols = ("namespace", "session_id")
for col in _text_cols:
if col not in cols:
self._conn.execute(
f"ALTER TABLE pipeline_logs_v2 ADD COLUMN {col} TEXT NOT NULL DEFAULT ''"
)
if "event_at_ms" not in cols:
self._conn.execute(
f"ALTER TABLE pipeline_logs_v2 ADD COLUMN {col} TEXT NOT NULL DEFAULT ''"
"ALTER TABLE pipeline_logs_v2 ADD COLUMN event_at_ms INTEGER NOT NULL DEFAULT 0"
)
if "event_at_ms" not in cols:
self._conn.execute(
"ALTER TABLE pipeline_logs_v2 ADD COLUMN event_at_ms INTEGER NOT NULL DEFAULT 0"
)
except Exception as e:
logger.debug(f"[sqlite] pipeline_logs_v2 column migration skipped: {e}")
except Exception as e:
logger.debug(f"[sqlite] pipeline_logs_v2 column migration skipped: {e}")
async def close(self) -> None:
if self._conn is not None:
@@ -180,9 +199,10 @@ class SqliteCache(CacheBase):
logger.info("SqliteCache closed")
def _close_sync(self) -> None:
if self._conn:
self._conn.close()
self._conn = None
with self._lock:
if self._conn:
self._conn.close()
self._conn = None
# ================================================================
# 统计
@@ -255,39 +275,40 @@ class SqliteCache(CacheBase):
"""
try:
def _query():
conditions = []
params = []
if request_id:
conditions.append("request_id = ?")
params.append(request_id)
if memory_id:
conditions.append("memory_id = ?")
params.append(memory_id)
if user_id:
conditions.append("user_id = ?")
params.append(user_id)
with self._lock:
conditions = []
params = []
if request_id:
conditions.append("request_id = ?")
params.append(request_id)
if memory_id:
conditions.append("memory_id = ?")
params.append(memory_id)
if user_id:
conditions.append("user_id = ?")
params.append(user_id)
if not conditions:
return []
if not conditions:
return []
where = " AND ".join(conditions)
rows = self._conn.execute(
f"SELECT * FROM memory_operations_v2 WHERE {where} "
f"ORDER BY id DESC LIMIT ?",
params + [limit],
).fetchall()
result = []
for r in rows:
row = dict(r)
# 反序列化 supersedes JSON 字符串 → list
import json as _json
raw_sup = row.get("supersedes", "")
try:
row["supersedes"] = _json.loads(raw_sup) if raw_sup else []
except Exception:
row["supersedes"] = []
result.append(row)
return result
where = " AND ".join(conditions)
rows = self._conn.execute(
f"SELECT * FROM memory_operations_v2 WHERE {where} "
f"ORDER BY id DESC LIMIT ?",
params + [limit],
).fetchall()
result = []
for r in rows:
row = dict(r)
# 反序列化 supersedes JSON 字符串 → list
import json as _json
raw_sup = row.get("supersedes", "")
try:
row["supersedes"] = _json.loads(raw_sup) if raw_sup else []
except Exception:
row["supersedes"] = []
result.append(row)
return result
return await _run_in_sqlite_pool(_query)
except Exception as e:
@@ -369,43 +390,126 @@ class SqliteCache(CacheBase):
"""
try:
def _query():
conditions = []
params = []
if request_id:
conditions.append("request_id = ?")
params.append(request_id)
if user_id:
conditions.append("user_id = ?")
params.append(user_id)
if step:
conditions.append("step = ?")
params.append(step)
with self._lock:
conditions = []
params = []
if request_id:
conditions.append("request_id = ?")
params.append(request_id)
if user_id:
conditions.append("user_id = ?")
params.append(user_id)
if step:
conditions.append("step = ?")
params.append(step)
if not conditions:
return []
if not conditions:
return []
where = " AND ".join(conditions)
rows = self._conn.execute(
f"SELECT * FROM pipeline_logs_v2 WHERE {where} "
f"ORDER BY id ASC LIMIT ?",
params + [limit],
).fetchall()
out = [dict(r) for r in rows]
# 派生可读的 event_at(ISO ms)供查询接口直接用;event_at_ms 为 0 时留空
from datetime import datetime as _dt
for _r in out:
_ms = _r.get("event_at_ms") or 0
_r["event_at"] = (
_dt.fromtimestamp(_ms / 1000.0).isoformat(timespec="milliseconds")
if _ms else ""
)
return out
where = " AND ".join(conditions)
rows = self._conn.execute(
f"SELECT * FROM pipeline_logs_v2 WHERE {where} "
f"ORDER BY id ASC LIMIT ?",
params + [limit],
).fetchall()
out = [dict(r) for r in rows]
# 派生可读的 event_at(ISO ms)供查询接口直接用;event_at_ms 为 0 时留空
from datetime import datetime as _dt
for _r in out:
_ms = _r.get("event_at_ms") or 0
_r["event_at"] = (
_dt.fromtimestamp(_ms / 1000.0).isoformat(timespec="milliseconds")
if _ms else ""
)
return out
return await _run_in_sqlite_pool(_query)
except Exception as e:
logger.warning(f"get_pipeline_logs failed: {e}")
return []
# ================================================================
# Durable write outcomes
# ================================================================
async def claim_write_outcome(
self,
request_id: str,
user_id: str,
agent_id: str,
session_id: str,
operation: str,
) -> Optional[Dict[str, Any]]:
def _claim():
with self._lock:
now = datetime.now().isoformat()
cursor = self._conn.execute(
"""
INSERT OR IGNORE INTO write_outcomes (
request_id, user_id, agent_id, session_id, operation,
status, result_json, created_at, updated_at
) VALUES (?, ?, ?, ?, ?, 'running', '{}', ?, ?)
""",
(request_id, user_id, agent_id, session_id, operation, now, now),
)
self._conn.commit()
if cursor.rowcount == 1:
return None
row = self._conn.execute(
"SELECT * FROM write_outcomes WHERE request_id = ?",
(request_id,),
).fetchone()
return dict(row) if row else None
existing = await _run_in_sqlite_pool(_claim)
if existing is None:
return None
return await self.get_write_outcome(request_id)
async def finish_write_outcome(
self,
request_id: str,
status: str,
result: Dict[str, Any],
) -> bool:
def _finish():
with self._lock:
cursor = self._conn.execute(
"""
UPDATE write_outcomes
SET status = ?, result_json = ?, updated_at = ?
WHERE request_id = ?
""",
(
status,
json.dumps(result, ensure_ascii=False, default=str),
datetime.now().isoformat(),
request_id,
),
)
self._conn.commit()
return cursor.rowcount == 1
return await _run_in_sqlite_pool(_finish)
async def get_write_outcome(self, request_id: str) -> Optional[Dict[str, Any]]:
def _get():
with self._lock:
row = self._conn.execute(
"SELECT * FROM write_outcomes WHERE request_id = ?",
(request_id,),
).fetchone()
return dict(row) if row else None
row = await _run_in_sqlite_pool(_get)
if row is None:
return None
try:
row["result"] = json.loads(row.pop("result_json") or "{}")
except (TypeError, json.JSONDecodeError):
row["result"] = {}
return row
# ================================================================
# System Metrics(分钟粒度落盘)
# ================================================================
@@ -414,26 +518,27 @@ class SqliteCache(CacheBase):
"""存储一个分钟桶的增量指标数据(UPSERT: 同一分钟多次写入会合并)"""
try:
def _store():
now = datetime.now().isoformat()
# UPSERT: 如果同一分钟已存在,合并数据
existing = self._conn.execute(
"SELECT data FROM system_metrics WHERE minute_ts = ?",
(minute_ts,),
).fetchone()
if existing:
import json as _json
old_data = _json.loads(existing["data"])
merged = self._merge_metric_buckets(old_data, data)
self._conn.execute(
"UPDATE system_metrics SET data = ?, created_at = ? WHERE minute_ts = ?",
(_json.dumps(merged, default=str), now, minute_ts),
)
else:
self._conn.execute(
"INSERT INTO system_metrics (minute_ts, data, created_at) VALUES (?, ?, ?)",
(minute_ts, json.dumps(data, default=str), now),
)
self._conn.commit()
with self._lock:
now = datetime.now().isoformat()
# UPSERT: 如果同一分钟已存在,合并数据
existing = self._conn.execute(
"SELECT data FROM system_metrics WHERE minute_ts = ?",
(minute_ts,),
).fetchone()
if existing:
import json as _json
old_data = _json.loads(existing["data"])
merged = self._merge_metric_buckets(old_data, data)
self._conn.execute(
"UPDATE system_metrics SET data = ?, created_at = ? WHERE minute_ts = ?",
(_json.dumps(merged, default=str), now, minute_ts),
)
else:
self._conn.execute(
"INSERT INTO system_metrics (minute_ts, data, created_at) VALUES (?, ?, ?)",
(minute_ts, json.dumps(data, default=str), now),
)
self._conn.commit()
await _run_in_sqlite_pool(_store)
except Exception as e:
logger.warning(f"store_metrics_minute failed: {e}")
@@ -442,17 +547,18 @@ class SqliteCache(CacheBase):
"""读取指定时间范围内的分钟指标数据"""
try:
def _load():
rows = self._conn.execute(
"SELECT data FROM system_metrics WHERE minute_ts >= ? AND minute_ts <= ? ORDER BY minute_ts",
(start_ts, end_ts),
).fetchall()
results = []
for row in rows:
try:
results.append(json.loads(row["data"]))
except (json.JSONDecodeError, TypeError):
pass
return results
with self._lock:
rows = self._conn.execute(
"SELECT data FROM system_metrics WHERE minute_ts >= ? AND minute_ts <= ? ORDER BY minute_ts",
(start_ts, end_ts),
).fetchall()
results = []
for row in rows:
try:
results.append(json.loads(row["data"]))
except (json.JSONDecodeError, TypeError):
pass
return results
return await _run_in_sqlite_pool(_load)
except Exception as e:
logger.warning(f"load_metrics_range failed: {e}")
@@ -462,11 +568,12 @@ class SqliteCache(CacheBase):
"""删除指定时间之前的 metrics 数据"""
try:
def _cleanup():
self._conn.execute(
"DELETE FROM system_metrics WHERE minute_ts < ?",
(before_ts,),
)
self._conn.commit()
with self._lock:
self._conn.execute(
"DELETE FROM system_metrics WHERE minute_ts < ?",
(before_ts,),
)
self._conn.commit()
await _run_in_sqlite_pool(_cleanup)
except Exception as e:
logger.warning(f"cleanup_old_metrics failed: {e}")
+113 -69
View File
@@ -16,6 +16,7 @@ import json
import logging
import os
import sqlite3
import threading
from datetime import datetime, timezone
from typing import Dict, List, Any, Optional
@@ -65,6 +66,11 @@ def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
def _escape_like(value: str) -> str:
"""Escape LIKE wildcards so a user id is matched literally."""
return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
class HistoryStore:
"""
SQLite 历史存储 - 记录所有内存操作的审计日志。
@@ -89,6 +95,10 @@ class HistoryStore:
"""
self._db_path = config.history.db_path
self._conn: Optional[sqlite3.Connection] = None
# sqlite3.Connection.close() must never race with an execute() on the
# same connection. The lock also serializes operations on this shared
# connection; separate HistoryStore instances remain independent.
self._conn_lock = threading.RLock()
async def initialize(self) -> None:
"""创建表和索引(如果不存在)"""
@@ -97,20 +107,21 @@ class HistoryStore:
def _init_sync(self) -> None:
"""同步初始化:创建目录、连接数据库、建表建索引"""
# 确保目录存在
db_dir = os.path.dirname(self._db_path)
if db_dir:
os.makedirs(db_dir, exist_ok=True)
with self._conn_lock:
# 确保目录存在
db_dir = os.path.dirname(self._db_path)
if db_dir:
os.makedirs(db_dir, exist_ok=True)
self._conn = sqlite3.connect(self._db_path, check_same_thread=False)
self._conn.row_factory = sqlite3.Row
# 开启 WAL 模式,提高并发读写性能
self._conn.execute("PRAGMA journal_mode=WAL;")
self._conn = sqlite3.connect(self._db_path, check_same_thread=False)
self._conn.row_factory = sqlite3.Row
# 开启 WAL 模式,提高并发读写性能
self._conn.execute("PRAGMA journal_mode=WAL;")
self._conn.execute(_CREATE_TABLE_SQL)
for idx_sql in _CREATE_INDEXES_SQL:
self._conn.execute(idx_sql)
self._conn.commit()
self._conn.execute(_CREATE_TABLE_SQL)
for idx_sql in _CREATE_INDEXES_SQL:
self._conn.execute(idx_sql)
self._conn.commit()
# ================================================================
# 记录操作
@@ -218,13 +229,14 @@ class HistoryStore:
return await _run_in_sqlite_pool(self._get_history_sync, memory_id)
def _get_history_sync(self, memory_id: str) -> List[Dict[str, Any]]:
if self._conn is None:
return []
cursor = self._conn.execute(
"SELECT * FROM memory_history WHERE memory_id = ? ORDER BY created_at ASC",
(memory_id,),
)
return [dict(row) for row in cursor.fetchall()]
with self._conn_lock:
if self._conn is None:
return []
cursor = self._conn.execute(
"SELECT * FROM memory_history WHERE memory_id = ? ORDER BY created_at ASC",
(memory_id,),
)
return [dict(row) for row in cursor.fetchall()]
async def get_recent(
self,
@@ -244,14 +256,43 @@ class HistoryStore:
return await _run_in_sqlite_pool(self._get_recent_sync, isolation_key, limit)
def _get_recent_sync(self, isolation_key: str, limit: int) -> List[Dict[str, Any]]:
if self._conn is None:
return []
cursor = self._conn.execute(
"SELECT * FROM memory_history WHERE isolation_key = ? "
"ORDER BY created_at DESC LIMIT ?",
(isolation_key, limit),
with self._conn_lock:
if self._conn is None:
return []
cursor = self._conn.execute(
"SELECT * FROM memory_history WHERE isolation_key = ? "
"ORDER BY created_at DESC LIMIT ?",
(isolation_key, limit),
)
return [dict(row) for row in cursor.fetchall()]
async def get_recent_for_user(
self,
user_id: str,
limit: int = 50,
) -> List[Dict[str, Any]]:
"""获取某 user 下所有 agent 的最近操作。
isolation_key 形如 ``"{user_id}:{agent_id}"``。user_id 里的 LIKE
通配符会被转义,保证只匹配这个 user,不会漏到 ``u1`` 之外。
"""
prefix = _escape_like(f"{user_id}:") + "%"
return await _run_in_sqlite_pool(
self._get_recent_prefix_sync, prefix, limit,
)
return [dict(row) for row in cursor.fetchall()]
def _get_recent_prefix_sync(
self, pattern: str, limit: int,
) -> List[Dict[str, Any]]:
with self._conn_lock:
if self._conn is None:
return []
cursor = self._conn.execute(
"SELECT * FROM memory_history WHERE isolation_key LIKE ? ESCAPE '\\' "
"ORDER BY created_at DESC LIMIT ?",
(pattern, limit),
)
return [dict(row) for row in cursor.fetchall()]
async def count(self, isolation_key: str = "") -> int:
"""
@@ -266,16 +307,17 @@ class HistoryStore:
return await _run_in_sqlite_pool(self._count_sync, isolation_key)
def _count_sync(self, isolation_key: str) -> int:
if self._conn is None:
return 0
if isolation_key:
cursor = self._conn.execute(
"SELECT COUNT(*) FROM memory_history WHERE isolation_key = ?",
(isolation_key,),
)
else:
cursor = self._conn.execute("SELECT COUNT(*) FROM memory_history")
return cursor.fetchone()[0]
with self._conn_lock:
if self._conn is None:
return 0
if isolation_key:
cursor = self._conn.execute(
"SELECT COUNT(*) FROM memory_history WHERE isolation_key = ?",
(isolation_key,),
)
else:
cursor = self._conn.execute("SELECT COUNT(*) FROM memory_history")
return cursor.fetchone()[0]
async def close(self) -> None:
"""关闭数据库连接"""
@@ -284,9 +326,10 @@ class HistoryStore:
logger.info("[HistoryStore] closed")
def _close_sync(self) -> None:
if self._conn:
self._conn.close()
self._conn = None
with self._conn_lock:
if self._conn:
self._conn.close()
self._conn = None
# ================================================================
# 内部
@@ -339,33 +382,34 @@ class HistoryStore:
role: str = "",
extra: Optional[Dict[str, Any]] = None,
) -> int:
if self._conn is None:
return -1
now = _now_iso()
extra_json = json.dumps(extra or {}, ensure_ascii=False)
cursor = self._conn.execute(
"""INSERT INTO memory_history
(memory_id, isolation_key, event,
old_memory, new_memory, old_status, new_status,
change_reason, layer, actor_id, role, extra,
created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
memory_id,
isolation_key,
event,
old_memory,
new_memory,
old_status,
new_status,
change_reason,
layer,
actor_id,
role,
extra_json,
now,
now,
),
)
self._conn.commit()
return cursor.lastrowid
with self._conn_lock:
if self._conn is None:
return -1
now = _now_iso()
extra_json = json.dumps(extra or {}, ensure_ascii=False)
cursor = self._conn.execute(
"""INSERT INTO memory_history
(memory_id, isolation_key, event,
old_memory, new_memory, old_status, new_status,
change_reason, layer, actor_id, role, extra,
created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
memory_id,
isolation_key,
event,
old_memory,
new_memory,
old_status,
new_status,
change_reason,
layer,
actor_id,
role,
extra_json,
now,
now,
),
)
self._conn.commit()
return cursor.lastrowid
+33 -8
View File
@@ -462,14 +462,39 @@ class FaissVectorStore(VectorStoreBase):
return None
async def get_embeddings(self, node_ids: List[str]) -> Dict[str, List[float]]:
"""批量取向量(in-memory _data 直接读 embedding),供去重算 cosine。"""
out: Dict[str, List[float]] = {}
for nid in node_ids:
point_id = self._node_id_to_point_id(nid)
entry = self._data.get(point_id)
if entry and entry.get("embedding"):
out[nid] = list(entry["embedding"])
return out
"""批量取向量,供去重 / episode 摘要计算 cosine。
``_data`` 只保存 payload 与 FAISS 内部下标;普通 upsert 不额外存一份
embedding,向量本体在 FAISS index 里。这里按当前有效下标 reconstruct,
并用 ``_idx_to_id`` 校验,避免读到已被替换的旧下标。
"""
def _get() -> Dict[str, List[float]]:
out: Dict[str, List[float]] = {}
with self._lock:
for nid in node_ids:
point_id = self._node_id_to_point_id(nid)
entry = self._data.get(point_id)
if entry is None:
continue
embedding = entry.get("embedding")
if embedding:
out[nid] = list(embedding)
continue
idx = entry.get("idx")
if (
idx is None
or self._index is None
or self._idx_to_id.get(int(idx)) != point_id
):
continue
try:
out[nid] = self._index.reconstruct(int(idx)).tolist()
except Exception:
continue
return out
return await _run_in_vdb_pool(_get)
# ================================================================
# 删除
+53
View File
@@ -0,0 +1,53 @@
"""Public structural contract for injected embedding services."""
from typing import Any, Dict, List, Protocol, Tuple, runtime_checkable
@runtime_checkable
class EmbeddingService(Protocol):
"""Embedding service accepted by :class:`HyMemoryClient`.
Implementations are borrowed by the client: their lifecycle remains owned
by the caller and ``HyMemoryClient.close()`` will not close them.
"""
async def embed(self, text: str, use_cache: bool = True) -> List[float]:
...
async def embed_with_meta(
self, text: str, use_cache: bool = True
) -> Tuple[List[float], Dict[str, Any]]:
...
async def embed_batch(
self, texts: List[str], use_cache: bool = True
) -> List[List[float]]:
...
async def embed_queued(
self, text: str, use_cache: bool = True
) -> List[float]:
...
async def embed_queued_with_meta(
self, text: str, use_cache: bool = True
) -> Tuple[List[float], Dict[str, Any]]:
...
def get_embedding_dims(self) -> int:
...
# Explicit alias for callers that prefer the conventional Protocol suffix.
EmbeddingServiceProtocol = EmbeddingService
class EmbeddingDimensionMismatchError(ValueError):
"""Raised before initialization when service and store dimensions differ."""
__all__ = [
"EmbeddingService",
"EmbeddingServiceProtocol",
"EmbeddingDimensionMismatchError",
]
+20 -5
View File
@@ -10,8 +10,8 @@ HY Memory - Intention (L7) 召回 + 惰性过期转换 + 复本判定
节点的 layer 改写为 l2_fact(持久化 update_payload),并从意图结果里剔除——
过期意图变成普通历史事实,下次走 normal 召回;
- **判重(重点)**:对幸存意图按下述规则分组,同组只留一条本次返回:
同 user_id + 同一天 memory_at + valid_until 相同(都为 None 或都相等)
+ cosine 相似度 ≥ MEMORY_DEDUP_THRESHOLD (默认 0.95)
同 user_id + 同 agent_id + 同一天 memory_at + valid_until 相同
(都为 None 或都相等)+ cosine 相似度 ≥ MEMORY_DEDUP_THRESHOLD (默认 0.95)
→ 视为同一个意图的复本(extractor 复读机 / 多 session 重复表达)。
保留组里 `gmt_created` 最早的(老的先来先得,稳定 id);
- **异步删库**:其余复本 fire-and-forget 从 VDB 删除,不影响本次调用 RT。
@@ -112,11 +112,19 @@ def _partition_duplicates(
if len(hits) < 2:
return list(hits), []
# 1. 按 (memory_at day, valid_until day) 分桶
buckets: Dict[Tuple[Any, Any], List[int]] = {}
# 1. 按 (user_id, agent_id, memory_at day, valid_until day) 分桶。
# user_id / agent_id 必须进键:多用户检索时不同用户的同一天意图可能
# 文本、日期都相同,但它们是两个独立的租户数据;只按日期分桶会把其中
# 一个判成复本并硬删除。
buckets: Dict[Tuple[Any, Any, Any, Any], List[int]] = {}
for idx, h in enumerate(hits):
node = h.get("node")
key = (_memory_at_day(node), _valid_until_key(node))
key = (
getattr(node, "user_id", None) if node else None,
getattr(node, "agent_id", None) if node else None,
_memory_at_day(node),
_valid_until_key(node),
)
buckets.setdefault(key, []).append(idx)
def _gmt(h: Dict[str, Any]) -> float:
@@ -229,6 +237,8 @@ async def recall_intentions(
*,
user_ids: Optional[List[str]] = None,
agent_ids: Optional[List[str]] = None,
isolation_key: str = "",
isolation_keys: Optional[List[str]] = None,
limit: int = 10,
now: Optional[datetime] = None,
stats_out: Optional[Dict[str, Any]] = None,
@@ -243,6 +253,9 @@ async def recall_intentions(
query_embedding: 查询向量
user_ids: 用户隔离(单/多用户)
agent_ids: 可选 agent 过滤
isolation_key / isolation_keys: 精确的 (user, agent, session) 隔离键。
与其它召回通道一致:调用方在按 session 过滤时只生成这两项,
user_ids / agent_ids 为 None;不把它们透传下去就会退化成全库检索。
limit: 召回上限(返回给上游的条数)
now: 当前时间(默认 datetime.now(),测试可注入)
stats_out: 可选 dict,本函数把分段耗时与数量**原地回填**进去,供调用方落
@@ -283,6 +296,8 @@ async def recall_intentions(
query_embedding=query_embedding,
user_ids=user_ids or None,
agent_ids=agent_ids,
isolation_key=isolation_key,
isolation_keys=isolation_keys,
layers=[MemoryLayer.L7_INTENTION],
limit=fetch_limit,
score_threshold=0.0, # intention 不设语义门槛
+2
View File
@@ -1840,6 +1840,8 @@ class BaseReadPipeline(ReadPipeline):
query_embedding,
user_ids=isolation_params.get("user_ids"),
agent_ids=isolation_params.get("agent_ids"),
isolation_key=isolation_params.get("isolation_key") or "",
isolation_keys=isolation_params.get("isolation_keys"),
limit=request.intention_limit,
stats_out=_intent_stats,
include_sources=request.include_sources,
+9 -3
View File
@@ -19,6 +19,7 @@ import logging
from .base import WritePipeline, ReadPipeline
from ..config import MemoryConfig
from ..core.embed_service import EmbedService
from ..embedding import EmbeddingService
from ..data.vector_store import create_vector_store
from ..data.vector_store_base import VectorStoreBase
@@ -50,7 +51,12 @@ class ComponentFactory:
s2 = await factory.get_system2_writer() # System2Writer (ultra mode)
"""
def __init__(self, config: Optional[MemoryConfig] = None):
def __init__(
self,
config: Optional[MemoryConfig] = None,
*,
embedding_service: Optional[EmbeddingService] = None,
):
self.config = config or MemoryConfig.from_env()
# 实例缓存(单例)
@@ -62,7 +68,7 @@ class ComponentFactory:
self._readers: Dict[str, ReadPipeline] = {}
# 共享资源
self._shared_embed_service: Optional[EmbedService] = None
self._shared_embed_service: Optional[EmbeddingService] = embedding_service
self._shared_vector_store: Optional[VectorStoreBase] = None
self._shared_vector_store_initialized: bool = False
self._shared_graph_store = None
@@ -72,7 +78,7 @@ class ComponentFactory:
# 共享资源
# ================================================================
def _get_shared_embed_service(self) -> EmbedService:
def _get_shared_embed_service(self) -> EmbeddingService:
if self._shared_embed_service is None:
self._shared_embed_service = EmbedService(self.config)
return self._shared_embed_service
+1 -1
View File
@@ -968,7 +968,7 @@ class MemoryWriter(WritePipeline):
async def _run():
try:
nid = await summarize_closed_episode(
vector_store=self.vector_store,
vector_store=await self._get_vector_store(),
embed_service=self.embed_service,
llm_provider=self.llm_provider,
episode_id=episode_id,
+23
View File
@@ -0,0 +1,23 @@
"""Public types and errors for exact memory-ID lookup."""
from typing import Literal, Sequence
MemoryKind = Literal["chat", "experience", "fact"]
MemoryVariant = Literal["working", "coding"]
class AmbiguousMemoryIdError(LookupError):
"""An ID exists in more than one public memory namespace."""
def __init__(self, memory_id: str, namespaces: Sequence[str]):
self.memory_id = memory_id
self.namespaces = tuple(namespaces)
joined = ", ".join(self.namespaces)
super().__init__(
f"memory ID {memory_id!r} is ambiguous across namespaces: {joined}; "
"pass kind and/or variant to disambiguate"
)
__all__ = ["MemoryKind", "MemoryVariant", "AmbiguousMemoryIdError"]
+19 -6
View File
@@ -29,7 +29,7 @@ import logging
import os
import re
import signal
import sys
import threading
from datetime import datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Dict, Optional
@@ -495,6 +495,16 @@ class MemoryHTTPHandler(BaseHTTPRequestHandler):
_json_response(self, 200, result)
def _request_shutdown(server: ThreadingHTTPServer) -> None:
"""Ask ``serve_forever`` to stop without blocking the calling thread.
``BaseServer.shutdown()`` waits for the ``serve_forever`` loop to exit. A
signal handler runs on the very thread executing that loop, so calling it
there deadlocks forever. Hand the call to a helper thread instead.
"""
threading.Thread(target=server.shutdown, daemon=True).start()
def run_server(port: int = 19527, host: str = "127.0.0.1"):
"""Start the HTTP server (blocking)."""
# Configure logging — basicConfig for root; hy_memory level set after client init
@@ -523,13 +533,12 @@ def run_server(port: int = 19527, host: str = "127.0.0.1"):
logger.info(f"[server] Listening on http://{host}:{port}")
logger.info(f"[server] Health check: http://{host}:{port}/healthz")
# Graceful shutdown
# Graceful shutdown. The signal handler only asks a helper thread to stop
# the loop; cleanup runs after serve_forever() returns so it cannot race
# the request threads or deadlock the serving thread.
def _shutdown(signum, frame):
logger.info("[server] Shutting down...")
server.shutdown()
if _client is not None:
_client.close()
sys.exit(0)
_request_shutdown(server)
signal.signal(signal.SIGINT, _shutdown)
signal.signal(signal.SIGTERM, _shutdown)
@@ -538,6 +547,10 @@ def run_server(port: int = 19527, host: str = "127.0.0.1"):
server.serve_forever()
except KeyboardInterrupt:
_shutdown(None, None)
finally:
server.server_close()
if _client is not None:
_client.close()
def main():
+150
View File
@@ -0,0 +1,150 @@
"""Public, offline snapshot support for the SDK-owned local data plane."""
from __future__ import annotations
import hashlib
import os
import shutil
from dataclasses import dataclass
from pathlib import Path
class DataPlaneSnapshotRejected(RuntimeError):
def __init__(self, code: str) -> None:
super().__init__(code)
self.code = code
@dataclass(frozen=True)
class DataPlaneSnapshot:
source_root: Path
snapshot_root: Path
files: tuple[dict[str, object], ...]
total_bytes: int
@dataclass(frozen=True)
class DataPlaneRestore:
restored_root: Path
previous_root: Path | None
files_restored: int
total_bytes: int
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def snapshot_local_data_plane(
*,
source_root: Path,
target_root: Path,
writers_stopped: bool,
) -> DataPlaneSnapshot:
"""Copy one quiesced local SDK root and return a verified inventory.
Remote providers require their own export implementation and must not call
this local-path contract.
"""
if not writers_stopped:
raise DataPlaneSnapshotRejected("data_plane_snapshot_writers_running")
source = source_root.resolve()
target = target_root.resolve()
if source.is_symlink() or not source.is_dir():
raise DataPlaneSnapshotRejected("data_plane_snapshot_source_invalid")
if target.exists():
raise DataPlaneSnapshotRejected("data_plane_snapshot_target_exists")
try:
target.mkdir(parents=True)
for root, directories, files in os.walk(source, followlinks=False):
root_path = Path(root)
relative = root_path.relative_to(source)
target_directory = target / relative
target_directory.mkdir(parents=True, exist_ok=True)
for name in directories:
if (root_path / name).is_symlink():
raise DataPlaneSnapshotRejected("data_plane_snapshot_symlink")
for name in files:
item = root_path / name
if item.is_symlink():
raise DataPlaneSnapshotRejected("data_plane_snapshot_symlink")
shutil.copy2(item, target_directory / name)
inventory: list[dict[str, object]] = []
for path in sorted(item for item in target.rglob("*") if item.is_file()):
inventory.append(
{
"path": path.relative_to(target).as_posix(),
"bytes": path.stat().st_size,
"sha256": _sha256(path),
}
)
for item in inventory:
copied = target / str(item["path"])
if copied.stat().st_size != item["bytes"] or _sha256(copied) != item["sha256"]:
raise DataPlaneSnapshotRejected("data_plane_snapshot_verify_failed")
except DataPlaneSnapshotRejected:
shutil.rmtree(target, ignore_errors=True)
raise
except OSError as error:
shutil.rmtree(target, ignore_errors=True)
raise DataPlaneSnapshotRejected("data_plane_snapshot_failed") from error
return DataPlaneSnapshot(
source_root=source,
snapshot_root=target,
files=tuple(inventory),
total_bytes=sum(int(item["bytes"]) for item in inventory),
)
def restore_local_data_plane(
*,
snapshot_root: Path,
target_root: Path,
writers_stopped: bool,
protective_root: Path | None = None,
) -> DataPlaneRestore:
"""Replace one local SDK root from a verified snapshot with rollback."""
if not writers_stopped:
raise DataPlaneSnapshotRejected("data_plane_restore_writers_running")
source = snapshot_root.resolve()
target = target_root.resolve()
protective = (
protective_root.resolve()
if protective_root is not None
else target.parent / f".{target.name}.pre-restore"
)
staging = target.parent / f".{target.name}.restore.tmp"
if target.is_symlink() or protective.exists() or staging.exists():
raise DataPlaneSnapshotRejected("data_plane_restore_target_unsafe")
copied = snapshot_local_data_plane(
source_root=source,
target_root=staging,
writers_stopped=True,
)
previous: Path | None = None
try:
if target.exists():
target.replace(protective)
previous = protective
staging.replace(target)
except OSError as error:
if previous is not None and previous.exists() and not target.exists():
previous.replace(target)
previous = None
shutil.rmtree(staging, ignore_errors=True)
raise DataPlaneSnapshotRejected("data_plane_restore_replace_failed") from error
return DataPlaneRestore(
restored_root=target,
previous_root=previous,
files_restored=len(copied.files),
total_bytes=copied.total_bytes,
)
+68 -6
View File
@@ -8,6 +8,7 @@ Uses a two-tier strategy:
This avoids langdetect's known weakness with short Chinese text.
"""
import json
import logging
import re
from typing import List, Optional
@@ -135,6 +136,30 @@ def detect_language(text: str) -> str:
return "zh" if ratio > 0.1 else "en"
def _spoken_text(value: str) -> str:
"""Ignore text-block metadata when a message content is structured JSON."""
text = value.strip()
if text.startswith("["):
try:
blocks = json.loads(text)
except (ValueError, TypeError):
pass
else:
if (
isinstance(blocks, list)
and blocks
and all(
isinstance(block, dict)
and isinstance(block.get("type"), str)
and block["type"] in {"text", "input_text", "output_text"}
and isinstance(block.get("text"), str)
for block in blocks
)
):
return "\n".join(block["text"] for block in blocks)
return text
def extract_content_for_detection(
content: str = "",
messages: Optional[List] = None,
@@ -153,20 +178,57 @@ def extract_content_for_detection(
Concatenated content text suitable for language detection.
"""
if content and content.strip():
return content.strip()
value = content.strip()
# Writer serializes message batches to JSON before calling Extractor.
# Detect the spoken text, not the leading ASCII keys (role/content),
# without changing the raw evidence sent to the model.
if value.startswith("["):
try:
decoded = json.loads(value)
except (ValueError, TypeError):
pass
else:
if (
isinstance(decoded, list)
and decoded
and all(
isinstance(item, dict)
and isinstance(item.get("role"), str)
and isinstance(item.get("content"), str)
for item in decoded
)
):
# In a mixed batch, the latest user turn is the clearest
# instruction for the language; assistant/tool metadata
# must not decide it first.
user_text = [
_spoken_text(item["content"])
for item in decoded
if item["role"] == "user" and item["content"].strip()
]
if user_text:
return user_text[-1]
spoken = "\n".join(_spoken_text(item["content"]) for item in decoded)
if spoken.strip():
return spoken
return _spoken_text(value)
if messages:
parts = []
user_parts = []
for msg in messages:
if isinstance(msg, dict):
c = msg.get("content", "")
c, role = msg.get("content", ""), msg.get("role")
elif hasattr(msg, "content"):
c = msg.content
c, role = msg.content, getattr(msg, "role", None)
else:
continue
if c and c.strip():
parts.append(c.strip())
return "\n".join(parts)
if isinstance(c, str) and c.strip():
text = _spoken_text(c)
parts.append(text)
if role == "user":
user_parts.append(text)
return user_parts[-1] if user_parts else "\n".join(parts)
return ""
+24
View File
@@ -0,0 +1,24 @@
"""Context propagated to host-provided HTTP transports for cost accounting."""
from collections.abc import Iterator
from contextlib import contextmanager
from contextvars import ContextVar, Token
_model_call_stage: ContextVar[str] = ContextVar(
"hy_memory_model_call_stage",
default="other",
)
def current_model_call_stage() -> str:
return _model_call_stage.get()
@contextmanager
def model_call_stage(stage: str | None) -> Iterator[None]:
normalized = (stage or "other").strip().lower() or "other"
token: Token[str] = _model_call_stage.set(normalized)
try:
yield
finally:
_model_call_stage.reset(token)
+35 -4
View File
@@ -18,12 +18,32 @@ from __future__ import annotations
import json
import logging
import re
from datetime import datetime
from pathlib import Path
from typing import Any, List, Optional
logger = logging.getLogger(__name__)
#: A namespace is a single path component, not a path. `\w` keeps Unicode
#: names working while excluding separators, drive letters and NUL.
_SAFE_SUBDIR = re.compile(r"[\w.-]{1,64}", re.UNICODE)
def _safe_subdir(value: str) -> Optional[str]:
"""Return ``value`` if it is safe as one directory name, else ``None``.
``user_id`` is caller-controlled. Without this check a value such as
``"/tmp/evil__u1"`` makes ``Path(base) / "/tmp/evil"`` discard ``base``
entirely; ``"../.."`` escapes it the same way.
"""
candidate = (value or "").strip()
if not candidate or candidate in {".", ".."}:
return None
if not _SAFE_SUBDIR.fullmatch(candidate):
return None
return candidate
# 兼容旧 import
TraceFileWriter = None # set after class definition
@@ -40,7 +60,7 @@ class PipelineLogWriter:
def __init__(self, log_dir: str, default_subdir: str = "default"):
self._log_dir = log_dir
self._default_subdir = default_subdir or "default"
self._default_subdir = _safe_subdir(default_subdir) or "default"
try:
(Path(self._log_dir) / self._default_subdir).mkdir(parents=True, exist_ok=True)
except Exception:
@@ -49,7 +69,7 @@ class PipelineLogWriter:
def _resolve_subdir(self, user_id: str) -> str:
"""从 user_id 的 "{prefix}__{user_id}" 前缀取 prefix 作为子目录;无前缀则回落。"""
if user_id and "__" in user_id:
prefix = user_id.split("__", 1)[0].strip()
prefix = _safe_subdir(user_id.split("__", 1)[0])
if prefix:
return prefix
return self._default_subdir
@@ -80,7 +100,11 @@ class PipelineLogWriter:
split_namespace_user,
)
tokens = (prompt_tokens or 0) + (completion_tokens or 0) + (total_tokens or 0)
# Providers define total_tokens as prompt+completion. Adding all
# three fields doubled every cost estimate in this JSONL.
tokens = (total_tokens or 0) or (
(prompt_tokens or 0) + (completion_tokens or 0)
)
namespace, uid = split_namespace_user(user_id or "")
if not is_llm_content_logging_enabled():
prompt = redact_content(prompt)
@@ -111,7 +135,14 @@ class PipelineLogWriter:
line = json.dumps(record, ensure_ascii=False, default=str)
date_str = datetime.now().strftime("%Y-%m-%d")
subdir = self._resolve_subdir(user_id)
log_dir = Path(self._log_dir) / subdir
base_dir = Path(self._log_dir).resolve()
log_dir = (base_dir / subdir).resolve()
# Defence in depth: even if a future change lets a suspicious
# component through, never write outside the configured root.
try:
log_dir.relative_to(base_dir)
except ValueError:
log_dir = base_dir / self._default_subdir
log_dir.mkdir(parents=True, exist_ok=True)
log_file = log_dir / f"{date_str}.log"
with open(log_file, "a", encoding="utf-8") as f:
+8 -1
View File
@@ -1,6 +1,6 @@
# Contributing
感谢你参与 One Memory。
感谢你参与 MemHub。
## 开发环境
@@ -27,3 +27,10 @@ pnpm check
涉及外部源码时,必须记录项目、固定版本或 commit、许可证、采用文件和修改说明。不得提交
密钥、内部地址、真实对话、个人路径、模型权重或签名证书。
## 界面翻译
新增或修改界面语言时遵循
[`docs/LOCALIZATION.md`](docs/LOCALIZATION.md):使用稳定语义 key,保持所有
locale 的 key 与占位符一致,不翻译用户内容、路径、标识符或外部错误正文。语言
catalog 与无关产品行为应拆成不同 PR。
+90 -179
View File
@@ -1,97 +1,71 @@
# Hy Memory 使用与配置
更新:2026-10-12
更新:2026-10-21
本文说明 MemHub 当前使用的 Hy Memory SDK、配置边界,以及直接使用 SDK 时如何
write、search,并把搜索结果格式化为可交给模型的 memory text chunk。
架构边界以 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) 为准。
仓库内仍以 One Memory 命名的 Evidence、权限和 Governance 层属于 MemHub 的历史兼容
模块;产品代码不应绕过这些层直接调用 SDK。本文中的
原生 SDK 示例主要用于开发、调试和独立验证。
---
## Architecture Principles
1. Memory 读写与存储 backend **只经 SDK**(config / env)。
2. MemHub 运行时对 memory 的原子操作 **只经 SDK 公共 Client**;缺正常业务
接口先补 SDK。Runtime writers 停止后的 App 启动迁移可直接操作底层存储,
但不得把迁移专用方法加入公共 Client。
3. MemHub **不存 memory 实体**;**可以存 `memory_id`** 做组织/回执。原文进入 **SDK raw**。
4. SDK raw 只保留滚动三天;一条 raw 对应一个完整 turn,只含真人 user 与
assistant,tool 不持久化。提取后的高层 memory 不受该窗口影响。
生产入口通过共享 Runtime 租约取得公开 `HyMemoryClient`;MemHub 只在调用前执行
模型配置、密钥和 harness/model 门禁,不维护第二套 memory 正文权威。
来源授权、模型授权和宿主召回授权仍是 MemHub 管理面门禁;memory
数据平面的权威在 SDK。
## 当前版本状态
当前源码固定使用:
当前源码固定使用(以仓库 pin / lockfile 为准):
```text
distribution: hy-memory
version: 2.0.2
version: 见 pyproject / lock(文档数字可能滞后)
mode: 按运行时配置选择
reader: hybrid
```
仓库 pin、lockfile 和运行时版本守卫均固定到公开的 `hy-memory==2.0.2`。
MemHub 在本地 Runtime 内嵌入 SDK,但不绕过自身的来源授权、模型授权、Evidence、
Governance 和撤权边界。
## MemHub 运行时边界
MemHub 对 SDK 使用以下公开、可复现的本地策略:
MemHub 通过公开 `HyMemoryClient` 配置使用可复现的本地策略:
- vector store 使用受管数据目录中的 Chroma;
- graph store 使用受管数据目录中的 Kuzu;
- cache 与 history 使用 SQLite;
- reader 使用 `hybrid`;
- reranker 默认关闭,不引入 Torch、Transformers 或额外模型;
- 模型与远程 embedding 参数来自版本化 Model Profile;
- API Key 进入系统安全存储,不写入仓库、安装包、日志或 HY metadata;
- 服务端数据库、租户队列及宿主 shell 中的 ambient 凭据不会进入 SDK config。
- vector / graph / cache / history / coding 等 **一律 SDK config/env**;
- 模型与 embedding 来自版本化 Model Profile;密钥进安全存储;
- MemHub 管理库可存 harness/model/队列状态与 **`memory_id` 引用**。
发布包固定应用以下 SDK 行为配置:
MemHub 不再通过 import-time 环境变量覆盖 SDK 的提取、reconcile、episode、
intention、few-shot、summary 或去重策略。产品只配置模型/密钥/endpoint、本地
backend 路径、公开 embedding service,以及每次公开 Client 调用的参数。
| 环境变量 | 值 |
|---|---|
| `MEMORY_MODE` | `ultra` |
| `MEMORY_ENABLE_GRAPH` | `true` |
| `MEMORY_GRAPH_RERANK_ENABLED` | `false` |
| `MEMORY_GRAPH_TEMPORAL_SPINE` | `true` |
| `MEMORY_TOPIC_SUMMARY_ENABLED` | `false` |
| `MEMORY_EPISODE_SUMMARY_ENABLED` | `false` |
| `MEMORY_EPISODE_RECALL_ENABLED` | `true` |
| `MEMORY_DYNAMIC_EPISODE_ENABLED` | `true` |
| `MEMORY_SESSION_EPISODE_ENABLED` | `false` |
| `MEMORY_SESSION_EPISODE_CONTEXT_ENABLED` | `false` |
| `MEMORY_EPISODE_CAPSULE_CONTEXT_ENABLED` | `true` |
| `MEMORY_EPISODE_CAPSULE_QUERY_MIN` | `0.65` |
| `MEMORY_EPISODE_CAPSULE_ASSIGNMENT_MIN` | `0.60` |
| `MEMORY_EPISODE_CAPSULE_FIRST_RANK_MAX` | `3` |
| `MEMORY_EPISODE_CAPSULE_MEMBER_LIMIT` | `3` |
| `MEMORY_ENABLE_INTENTION` | `false` |
| `MEMORY_ENABLE_QUERY_REWRITE` | `false` |
| `MEMORY_FEW_SHOT_ENABLED` | `true` |
| `MEMORY_HYBRID_V2_QUERY_EXPAND` | `1` |
| `MEMORY_HYBRID_V2_GEO_INTENT_PRIOR` | `0.6` |
| `MEMORY_HYBRID_V2_DIVERSITY` | `1` |
| `MEMORY_HYBRID_V2_TEMPORAL_ADMIT_PRIOR` | `0.55` |
| `MEMORY_HYBRID_V2_TEMPORAL_BOOST` | `0.18` |
| `MEMORY_CROSS_DOMAIN_CON_THRESHOLD` | `0.5` |
| `MEMORY_READER_ENABLE_SUMMARY` | `false` |
| `MEMORY_SUMMARY_ENABLED_IN_SYS2` | `false` |
| `MEMORY_LOCAL_RERANK_ENABLED` | `false` |
| `RECONCILE_ENABLED` | `true` |
| `HY_MEMORY_READER` | `hybrid` |
这些默认值集中在
`apps/core/src/one_memory/hy_runtime_config.py`,并由发布测试和 lockfile 共同约束。
独立脚本若绕过 MemHub 直接导入 SDK,应自行显式配置存储目录和模型端点。
独立脚本直连 SDK 时须自配存储目录与模型端点。
## 原生 SDK 初始化
下面是独立调试示例。产品代码应使用 One Memory 的 `HyMemoryBridge`,因为它额外提供来源
授权、模型授权、Evidence 绑定、写后核验、Governance 和撤权保护。
下面是独立调试示例。
产品代码经 `hy_sdk_runtime.SdkClientHandle` 获取已配置的公开 client;memory I/O
由 SDK 完成。
```python
from hy_memory import HyMemoryClient, MemoryConfig
config = MemoryConfig.from_env()
# 本地优先示例;实际目录应由调用方传入,不能依赖 ~/.hy_memory 默认值。
# 本地优先示例;实际目录应由调用方传入。
config.vector_store.provider = "chroma"
config.vector_store.persist_directory = "/path/to/one-memory/hy-memory/governed-v2/vector"
config.vector_store.persist_directory = "/path/to/one-memory/hy-memory/vector"
config.graph_store.provider = "kuzu"
config.graph_store.db_path = "/path/to/one-memory/hy-memory/governed-v2/graph"
config.graph_store.db_path = "/path/to/one-memory/hy-memory/graph"
config.cache.backend = "sqlite"
config.cache.db_path = "/path/to/one-memory/hy-memory/governed-v2/cache.sqlite3"
config.cache.db_path = "/path/to/one-memory/hy-memory/cache.sqlite3"
config.llm.provider = "openai"
config.llm.model = "your-model"
@@ -107,12 +81,11 @@ config.embedder.embedding_dims = 1024
client = HyMemoryClient(config=config, mode="ultra")
```
`embedding_dims` 必须与模型实际输出宽度以及已有向量/图存储一致。更换 embedding 模型、
端点或维度不能直接复用旧 collection;One Memory 会检测图宽度不一致并拒绝静默重建。
`embedding_dims` 必须与模型输出及已有向量/图存储一致。
## Write:写入对话
推荐把一段连续对话作为 OpenAI messages 写入:
推荐把一段连续对话作为 OpenAI messages 写入;含原文时由 SDK 接管 raw:
```python
from datetime import UTC, datetime
@@ -131,47 +104,54 @@ result = client.add(
request_id=str(uuid4()),
metadata={
"source_id": "cursor",
"evidence_ids": ["evidence-001", "evidence-002"],
"workspace_ids": ["workspace-abc"],
"input_kind": "raw_conversation",
},
)
```
参数规则:
| 参数 | 填法 | 约束 |
| --- | --- | --- |
| `data` | 字符串或 `[{role, content}]` | 对话优先用 messages;不混入 tool 参数、reasoning、密钥和隐藏系统提示 |
| `user_id` | 稳定用户 ID | 一级隔离键;不能为空 |
| `agent_id` | 记忆 scope | One Memory 中不是宿主 App 名的简单替代;跨 App scope 由授权和路由决定 |
| `session_id` | 稳定会话 ID | 同一会话增量写入时保持一致 |
| `memory_at` | 有时区的 `datetime` | 历史导入必须传原始发生时间,不能用导入时间替代 |
| `scene` | `"chat"` 或 `"working"` | 普通对话明确传 `chat`;代码/tool 会话才用 `working` |
| `request_id` | 每次写入唯一 ID | 用于幂等、追踪和写后核验 |
| `metadata` | 来源和 Evidence 引用 | 不放秘密;One Memory 至少保存 source/evidence/workspace/input kind |
| `meta` | 业务透传数据 | 不参与 embedding 和过滤;只放可安全返回的数据 |
| `embed_override` | 临时 embedding 端点 | 只能换 endpoint/key/header/timeout;模型和维度不能改变 |
| `data` | 字符串或 `[{role, content}]` | 对话优先 messages;不混入密钥与隐藏系统提示 |
| `user_id` / `agent_id` / `session_id` | 隔离与会话键 | 产品侧授权决定合法 scope |
| `memory_at` | 有时区 datetime | 历史导入用原始发生时间 |
| `scene` | `chat` / `working` | 明确传入 |
| `request_id` | 每次写入唯一 | 幂等与追踪 |
| `metadata` / `meta` | 来源与透传 | 不放秘密 |
返回值至少检查:
MemHub Runtime 对应用和 CLI 暴露等价的本机 HTTP 合同:
```text
POST /api/v2/memory-writes
GET /api/v2/user-profile
memhub write submit --messages-file messages.json --session <id>
memhub profile
```
`messages.json` 是 OpenAI 文本 messages 数组,当前接受 `user`、
`assistant`、`tool`;系统/开发者隐藏提示不得作为记忆输入。Core 将输入冻结进
`memory_write_jobs`,worker 对 SDK 执行一次 `add()`,成功后清除队列正文。
`user-profile` / `memhub profile` 调用 SDK `get_user_profile()`,返回组装后的
用户长期画像,不通过普通 Search 拼装。
返回值:
```python
if result.get("success") is not True:
raise RuntimeError("HY write failed")
memory_ids = result.get("memory_ids") or []
memory_ids = list(result.get("memory_ids") or [])
if result.get("memory_id"):
memory_ids.append(result["memory_id"])
# 需要组织或回执时,MemHub 只持久化这些 memory_id。
```
不要只相信 `success=True`。One Memory 还会按返回 ID `get()` 回读、核对 request/source/
Evidence 支持关系,并在 Governance 层记录版本。生产路径不能用直接 `client.add()` 代替这些
检查。
以 SDK 合同为准做成功判定;需要写后核验时使用 SDK `get` 回读。缺少所需
核验能力时扩展 SDK API,不在 MemHub 新建镜像台账。
### 写入已抽取的记忆
只有输入本身就是已有记忆内容、且原始对话不可用时才使用:
```python
result = client.add_extracted(
["用户长期偏好简洁、直接的回答。"],
@@ -182,18 +162,16 @@ result = client.add_extracted(
request_id=str(uuid4()),
metadata={
"source_id": "memory-export",
"evidence_ids": ["evidence-003"],
"input_kind": "memory_content_without_raw",
},
)
```
它跳过 Extractor,但不能跳过 HY reconcile、持久化、One Memory Evidence 绑定和 Governance。
该入口仍走 SDK reconcile/持久化;MemHub 只做管理面门禁与可选
`memory_id` 记录。
## Search:搜索记忆
普通 chat 搜索:
```python
result = client.search(
"用户偏好怎样的回答风格?",
@@ -210,114 +188,47 @@ result = client.search(
)
```
参数规则:
| 参数 | 填法 | 说明 |
| --- | --- | --- |
| `query` | 当前问题 | 与 `queries` 二选一 |
| `queries` | 多轮查询文本 | 最后一条是目标;只有需要 SDK 判断上下文时使用 |
| `user_ids` | 获授权用户列表 | 必填且不能空;不要用空列表扩大范围 |
| `agent_ids` | 获授权 scope 列表 | 空列表在 SDK 中表示所有 agent,产品代码必须先完成授权判断 |
| `session_ids` | 可选会话范围 | 多 agent 与多 session 不能同时使用 |
| `limit` | normal top-k | 默认 10;注入模型前还要受字符预算限制 |
| `min_score` | normal 阈值 | One Memory 当前内部语义检索使用 0.25 |
| `profile_min_score` | profile 阈值 | One Memory 当前使用 0.25 |
| `profile_limit` | profile 数量 | 通常与 limit 一致 |
| `intention_limit` | intention 数量 | 当前配置关闭 intention,传 0 |
| `created_after` | Unix 秒 | 可选时间下界 |
| `scene` | `chat` / `working` | 明确传入可避免额外场景判断模型调用 |
| `reader` | `hybrid` | One Memory 固定使用该 reader |
| `workspace_id` / `branch` | working scope | 仅 coding/working 路径使用 |
| `layers` | 指定层级列表 | 在召回阶段过滤,避免无关层占用 limit |
chat 返回结构:
```python
{
"request_id": "...",
"memories": {
"profile": [...],
"proactive": [...],
"normal": [...],
},
"rewrite": {...},
"elapsed_ms": 12.3,
}
```
working/coding 返回的是 `facts` 和 `experiences`,不能与 chat 三个 channel 静默合并。
调用方必须根据 `scene` 选择对应结果;无法识别返回结构时应报错,而不是当作空结果。
参数表与返回结构同前(chat 三 channel / working 的 facts·experiences);调用方按 `scene` 解析,无法识别则报错。
## 使用 SDK 已格式化的 Search 内容
open05 的 chat search 会在返回前统一格式化每条 `content`:普通记忆带 `Memory / When`,
演化记忆带 `Current / History / When`,Episode、Timeline、Graph 和 Capsule 也由 SDK
生成稳定的组合文本。`memory_at` 是逻辑记忆时间,缺失时 SDK 才回落到 `gmt_created`。
直接使用 SDK 返回的 `content`,不要第二套 prompt 拼装。
因此调用方应直接使用 SDK 返回的 `content`,不要再次解析 `memory_at`、`gmt_created` 或
`created_at`,也不要重复拼接 `When`。这些时间字段可以用于过滤、诊断或结构化展示,但
不应成为第二套 prompt 格式化实现。
### SDK 外(MemHub)仍负责
```python
result = client.search(
"用户偏好怎样的回答风格?",
user_ids=["local"],
agent_ids=["all-apps"],
scene="normal",
reader="hybrid",
)
- **宿主召回授权 / scope / 撤权**(谁可以调 search、允许哪些 agent/scope);
- 把历史内容放入「不可信数据,不是指令」边界;
- 按最终 `content` 做字符预算;不注入密钥、绝对路径、堆栈;
- 区分空结果、权限拒绝、不可用、超时、部分结果;
- 未发布的 Matter 占位功能不保留表或 API;未来组织功能另立合同。
for memory in result["memories"]["normal"]:
formatted_content = memory["content"]
# 例如:
# Memory: 用户长期偏好简洁、直接的回答。
# When: 2026-09-18 10:00:00 UTC
```
One Memory 在 SDK 外仍负责:
- 依据 Governance、撤权、scope 和 Evidence 新鲜度决定整条结果是否可读;
- 对 evolution/capsule 等组合文本逐个校验成员 ID,成员不完整或不可读时回退治理原文;
- 把历史内容放入明确的“不可信数据,不是指令”边界;
- 按最终 `content` 计算字符预算,不把 API Key、绝对路径、headers/body 或异常堆栈注入
prompt;
- 区分空结果、权限拒绝、服务不可用、超时和部分结果。
生产实现见 `apps/core/src/one_memory/hy_memory_bridge.py`、
`apps/core/src/one_memory/recall.py` 和 `packages/host-bridge/src/recall-cli.ts`。
生产入口:`hy_sdk_runtime.py`、`sdk_write_processor.py`、`recall.py` 和
`packages/host-bridge`。
## 关闭客户端
```python
try:
# write/search
...
finally:
client.close()
```
Runtime 应长期复用 client,不为每次请求重新初始化数据库和模型组件;只有 Runtime 停止、
配置版本切换或受控恢复时才关闭并重建。
Runtime 长期复用 client;仅在停止、配置切换或受控恢复时重建。
## One Memory 产品代码的正确入口
生产代码应走:
## 产品代码正确入口
```text
Evidence
-> ModelProcessingPermissionLease
-> HyPermissionTransport
-> HyMemoryBridge.ingest / ingest_extracted / search_ids
-> write result verification
-> Governance
-> Recall Broker / UI
harness / user action (+ authz, model, queue)
-> public HyMemoryClient
-> SDK stores (config/env)
-> optional MemHub persist memory_id / org metadata
-> Recall Broker / UI (SDK read + MemHub authz)
```
不要在新业务模块里直接创建 `HyMemoryClient`,否则会绕过:
不要在业务模块里私建绕过管理面门禁的 client。版本、纠正和删除语义以 SDK
合同为准;MemHub 组织层只引用 `memory_id`。
- 来源读取授权;
- 模型内容处理授权;
- 发送前与响应后的撤权复核;
- Evidence 引用与作者归属;
- 写后回读验证;
- Governance 状态、版本、更正和删除级联。
Hy Memory SDK 是 MemHub 内置可信引擎,管理本机 Hy Memory 数据。
来源授权决定哪些宿主数据可进入写入路径;宿主 Recall Grant 决定外部应用可读范围。
这两类边界 **不** 意味着 MemHub 再存一套 memory 实体。
+29 -11
View File
@@ -1,18 +1,30 @@
# MemHub / One Memory
# MemHub
MemHub 是一个本地优先的共享记忆产品:把用户授权的多个 AI 产品中的历史对话和新增内容
汇总到同一份记忆,并让这些 AI 在独立授权后复用它。Hy Memory 是 MemHub 使用的 Python
SDK 和记忆引擎。One Memory / `one-memory` 是历史模块、数据目录、服务和兼容命令名称。
MemHub是一个本地优先的共享记忆产品。它把用户明确授权的AI对话和编码记录汇总到一份本地记忆中,再由用户分别授权给支持的AI工具调用。你可以继续使用熟悉的客户端,同时保留跨工具延续的上下文。Hy Memory是MemHub使用的Python SDK和记忆引擎。
# 💡❤️ MemHub 刚刚开源,欢迎一起优化共建! ❤️💡
**# 💭 MemHub处于preview阶段,当前公开版本可以下载和体验,部分平台制品、安装路径与宿主体验仍在持续优化验证。安装前请先查看Release里的实际制品和版本说明。**
> 🙋 如果你遇到问题/有建议:欢迎提交Issue,并附上MemHub版本、操作系统与芯片架构、复现步骤、预期结果、实际结果和经过脱敏的日志。请不要上传APIKey、真实对话、个人路径或其他敏感信息。
> 我们会公开跟进可复现的问题,持续发布修复,并根据真实反馈完善安装、同步和召回体验。
**# 感谢每一条反馈,期待你和我们一起打磨MemHub的体验 :)**
> 💗 MemHub has just been open-sourced and is under active development. The current public release is available for download andevaluation. Some platform packages, installation paths, and host integrations are still being completed and verified. Check the assets
and release notes before installing.
If you run into a problem, please open an Issue with the version, platform,reproduction steps, and sanitized logs, We wilreviewreports, publish fixes, and keep the support matrix up to date.
## 发行与平台合同
公共 Python SDK 为 `hy-memory==2.0.2`。MemHub 源码版本为 `1.0.1`
(build 5),GitHub 仓库为
源码当前固定使用公开 PyPI 正式版 `hy-memory==2.0.5`。MemHub 源码版本为 `1.0.5`
(build 14),GitHub 仓库为
[`Tencent-Hunyuan/Hy-Memory`](https://github.com/Tencent-Hunyuan/Hy-Memory),npm 包名为
`memhub-cli`。当前代码架构见
[`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md)。
`v1.0.1` 的发行目标是 Linux x64/arm64 Runtime 与 macOS arm64/x64 App 和 Runtime。
`v1.0.5` 的发行目标是 Linux x64/arm64 Runtime 与 macOS arm64/x64 App 和 Runtime。
Linux 制品由 GitHub Actions 在原生架构 runner 上构建并完成生命周期验收;macOS
制品由发行流水线完成 Developer ID 签名、公证和验收后手动上传。Windows 不支持。
只有同时出现在 GitHub Release 与 `release-manifest.json` 中、且通过公开校验的制品才属于
@@ -25,23 +37,29 @@ Linux 制品由 GitHub Actions 在原生架构 runner 上构建并完成生命
## 核心原则
- 一次安装、一个 Runtime、一份数据、多种客户端。
- Python Core 是唯一记忆数据面和唯一业务数据库写入者。
- Hy Memory SDK 是 memory/raw/vector/graph/coding 数据面的唯一权威;Python Core
管理授权、模型、异步队列和 Runtime 状态。
- 来源读取、模型处理和宿主读取是相互独立的授权边界。
- 正式记忆链路保持 `Evidence -> Hy Memory -> Governance -> Matters/Wiki`。
- 正式写链路为 `memory_write_jobs -> SDK add() -> raw/memory ID receipt`。
- 产品不包含屏幕、Accessibility / AXTree、OCR、键鼠、剪贴板或后台录音采集。
## 仓库结构
- `apps/core`:Python / FastAPI Kernel,负责 Evidence、Hy Memory、治理、检索与 API。
- `apps/core`:Python / FastAPI Kernel,负责授权、模型、队列、SDK Runtime 边界与 API。
- `apps/cli`:安装、控制和诊断共享 Runtime 的 `one-memory` CLI。
- `apps/web`:React / TypeScript 管理界面。
- `apps/desktop`:Electron 桌面壳与图形安装入口。
- `packages/contracts`:公共 API 类型。
- `packages/i18n`:Web 与 Electron 共用的界面语言合同和 catalog。
- `packages/host-bridge`:AI App 的 Skill、Hook、插件和 MCP 接入。
- `packages/runtime-control`:Core、Host Gateway 和 Runtime 生命周期控制。
架构详情见 [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) 和
[`docs/contracts/runtime-unification.md`](docs/contracts/runtime-unification.md)。
界面语言架构与社区翻译规则见
[`docs/LOCALIZATION.md`](docs/LOCALIZATION.md)。
产品、测试和一线支持排查导入与记忆沉淀时,使用
[`docs/PRODUCT_LOG_TROUBLESHOOTING.md`](docs/PRODUCT_LOG_TROUBLESHOOTING.md)。
## 开发环境
@@ -99,7 +117,7 @@ MemHub 的 SQLite 数据默认位于 `~/.one-memory`,不在 npm 包或 Runtime
## Hy Memory
当前开发依赖固定为公开 PyPI 包 `hy-memory==2.0.2`。SDK 配置、权限边界及 search
SDK 依赖固定为公开 PyPI 正式版 `hy-memory==2.0.5`。SDK 配置、权限边界及 search
返回格式见 [`MEMORY.md`](MEMORY.md)。HY search 返回的 `content` 已包含 SDK 统一生成的
逻辑时间和演化上下文;调用方不应再次转换时间戳或重复拼接 `When`。
+25 -3
View File
@@ -3,9 +3,9 @@
"dataLicense": "CC0-1.0",
"SPDXID": "SPDXRef-DOCUMENT",
"name": "one-memory",
"documentNamespace": "https://one-memory.local/spdx/2026-10-15T17:26:47Z",
"documentNamespace": "https://one-memory.local/spdx/2026-10-22T13:18:16Z",
"creationInfo": {
"created": "2026-10-15T17:26:47Z",
"created": "2026-10-22T13:18:16Z",
"creators": [
"Tool: one-memory-generate-sbom"
]
@@ -88,6 +88,23 @@
}
]
},
{
"SPDXID": "SPDXRef-Package-npm-i18next",
"name": "i18next",
"versionInfo": "25.10.10",
"downloadLocation": "NOASSERTION",
"filesAnalyzed": false,
"licenseConcluded": "NOASSERTION",
"licenseDeclared": "NOASSERTION",
"copyrightText": "NOASSERTION",
"externalRefs": [
{
"referenceCategory": "PACKAGE-MANAGER",
"referenceType": "purl",
"referenceLocator": "pkg:npm/i18next@25.10.10"
}
]
},
{
"SPDXID": "SPDXRef-Package-npm-lucide-react",
"name": "lucide-react",
@@ -2335,7 +2352,7 @@
{
"SPDXID": "SPDXRef-Package-hy-memory",
"name": "hy-memory",
"versionInfo": "2.0.2",
"versionInfo": "2.0.5",
"downloadLocation": "NOASSERTION",
"filesAnalyzed": false,
"licenseConcluded": "Apache-2.0",
@@ -2380,6 +2397,11 @@
"relationshipType": "DEPENDS_ON",
"relatedSpdxElement": "SPDXRef-Package-npm-https-proxy-agent"
},
{
"spdxElementId": "SPDXRef-Package-one-memory",
"relationshipType": "DEPENDS_ON",
"relatedSpdxElement": "SPDXRef-Package-npm-i18next"
},
{
"spdxElementId": "SPDXRef-Package-one-memory",
"relationshipType": "DEPENDS_ON",
+4 -3
View File
@@ -2,14 +2,14 @@
MemHub itself is licensed under Apache-2.0 (see `LICENSE`).
It bundles the runtime dependencies listed below.
Generated from the installed dependency tree on 2026-10-15T17:26:47Z
Generated from the installed dependency tree on 2026-10-22T13:18:16Z
by `python3 scripts/generate_sbom.py`. Do not edit by hand.
Per-package license texts are not reproduced here yet; the license
column is filled in as part of release review, and the SBOM records
`NOASSERTION` until then rather than guessing.
## hy-memory 2.0.2
## hy-memory 2.0.5
License: Apache-2.0
@@ -112,12 +112,13 @@ Adaptation boundary:
No Memmy brand, icon, font or mascot assets are distributed.
## JavaScript (npm) — 10 packages
## JavaScript (npm) — 11 packages
- @tanstack/react-query 5.103.2
- axios 1.20.0
- fflate 0.8.3
- https-proxy-agent 7.0.0
- i18next 25.10.10
- lucide-react 1.43.0
- proxy-from-env 2.1.0
- react 19.2.8
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@one-memory/cli",
"version": "1.0.1",
"version": "1.0.5",
"description": "MemHub bootstrap CLI for installing and managing the local-first shared memory runtime",
"license": "Apache-2.0",
"repository": {
@@ -12,7 +12,6 @@
* It is generated rather than hand-written so the two cannot drift: this reads
* the real package.json and only strips what is provably not needed at runtime.
*/
import { execFileSync } from "node:child_process";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { dirname, resolve } from "node:path";
@@ -20,12 +19,14 @@ import { fileURLToPath } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
const root = resolve(here, "..");
const repositoryRoot = resolve(root, "../..");
const require = createRequire(import.meta.url);
const { resolveBuildVersion } = require("../../../scripts/release-version.cjs");
const releaseVersion = resolveBuildVersion(process.env, repositoryRoot);
const { assertSemver } = require("../../../scripts/release-version.cjs");
const pkgPath = resolve(root, "package.json");
const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
const publishVersion = assertSemver(
process.env.MEMHUB_NPM_VERSION?.trim() || pkg.version,
"MEMHUB_NPM_VERSION",
);
const publishName = process.env.MEMHUB_NPM_PACKAGE?.trim();
if (!publishName || !/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(publishName)) {
throw new Error(
@@ -53,7 +54,7 @@ mkdirSync(outDir, { recursive: true });
const published = { ...pkg };
published.name = publishName;
published.version = releaseVersion;
published.version = publishVersion;
for (const section of ["dependencies", "devDependencies", "peerDependencies"]) {
if (!published[section]) continue;
published[section] = Object.fromEntries(
@@ -29,11 +29,9 @@ const REQUIRED_COMMAND_SURFACE = [
"sources",
"sync",
"memories",
"profile",
"calls",
"import-file",
"notes",
"permission",
"extraction",
"graph",
"models",
"host",
@@ -56,7 +54,6 @@ const REQUIRED_COMMAND_SURFACE = [
"scan",
"progress",
"jobs",
"processing",
"path",
"adapter",
"write",
@@ -77,25 +74,21 @@ const REQUIRED_MARKERS = [
/**
* Sub-commands the UI-write parity work added. A package can declare the
* parent command (`permission`, `models`) while still missing the new verb, so
* parent command (`models`) while still missing the new verb, so
* checking command names alone would pass a stale bundle. The marker is the
* exact literal the catalog usage string contains.
*/
const REQUIRED_SUBCOMMANDS = [
{ command: "calls", marker: "memhub calls clear" },
{ command: "import-file", marker: "memhub import-file upload" },
{ command: "import-file", marker: "memhub import-file commit" },
{ command: "import-file", marker: "memhub import-file discard" },
{ command: "notes", marker: "memhub notes add" },
{ command: "notes", marker: "memhub notes process" },
{ command: "permission", marker: "memhub permission status" },
{ command: "permission", marker: "memhub permission allow" },
{ command: "permission", marker: "memhub permission deny" },
{ command: "extraction", marker: "memhub extraction set" },
{ command: "memories", marker: "memhub memories update" },
{ command: "memories", marker: "memhub memories delete" },
{ command: "write", marker: "memhub write submit" },
{ command: "write", marker: "memhub write status" },
{ command: "graph", marker: "memhub graph width" },
{ command: "models", marker: "memhub models edit" },
{ command: "models", marker: "memhub models activate" },
{ command: "processing", marker: "memhub processing extract" },
{ command: "jobs", marker: "memhub jobs start" },
{ command: "jobs", marker: "memhub jobs <pause|resume|cancel>" },
];
@@ -126,24 +119,6 @@ const STOPPED_DESTRUCTIVE_PROBES = [
name: "calls_clear_all_apply",
args: ["calls", "clear", "--all", "--confirm"],
},
{
name: "import_file_commit_apply",
args: [
"import-file",
"commit",
"22222222-2222-4222-8222-222222222222",
"--confirm",
],
},
{
name: "import_file_discard_apply",
args: [
"import-file",
"discard",
"22222222-2222-4222-8222-222222222222",
"--confirm",
],
},
{
name: "notes_process_apply",
args: [
@@ -153,20 +128,10 @@ const STOPPED_DESTRUCTIVE_PROBES = [
"--confirm",
],
},
{ name: "permission_allow", args: ["permission", "allow"] },
{ name: "permission_deny", args: ["permission", "deny"] },
{
name: "extraction_set_apply",
args: ["extraction", "set", "--window", "6m", "--confirm"],
},
{
name: "graph_width_apply",
args: ["graph", "width", "--decision", "keep_existing", "--confirm"],
},
{
name: "processing_extract_apply",
args: ["processing", "extract", "--confirm"],
},
{
name: "models_activate_apply",
args: [
+42 -1
View File
@@ -1,6 +1,7 @@
import { mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
import { mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { inflateRawSync } from "node:zlib";
import { DiagnosticLogger } from "@one-memory/runtime-control";
import { afterEach, expect, it, vi } from "vitest";
@@ -29,6 +30,27 @@ async function fixture() {
return dataDir;
}
function readZipEntry(archive: Buffer, expected: string): string {
let offset = 0;
while (archive.readUInt32LE(offset) === 0x04034b50) {
const method = archive.readUInt16LE(offset + 8);
const compressedSize = archive.readUInt32LE(offset + 18);
const nameLength = archive.readUInt16LE(offset + 26);
const extraLength = archive.readUInt16LE(offset + 28);
const nameStart = offset + 30;
const dataStart = nameStart + nameLength + extraLength;
const name = archive.subarray(nameStart, nameStart + nameLength).toString();
const compressed = archive.subarray(dataStart, dataStart + compressedSize);
if (name === expected) {
if (method === 0) return compressed.toString();
if (method === 8) return inflateRawSync(compressed).toString();
throw new Error("unsupported zip compression");
}
offset = dataStart + compressedSize;
}
throw new Error(`missing ${expected}`);
}
it("prints matching diagnostic events as NDJSON without starting Runtime", async () => {
const dataDir = await fixture();
let stdout = "";
@@ -74,6 +96,25 @@ it("exports one support zip to the requested downloads directory", async () => {
});
expect(receipt.path).toMatch(/MemHub-日志-3800-\d{8}-\d{4}\.zip$/);
expect(await readdir(downloads)).toEqual([path.basename(receipt.path)]);
const archive = await readFile(receipt.path);
expect(JSON.parse(readZipEntry(archive, "summary.json")).commit).toBeNull();
});
it("fails closed for an explicitly supplied invalid commit", async () => {
const dataDir = await fixture();
const downloads = await mkdtemp(path.join(os.tmpdir(), "om-cli-downloads-"));
roots.push(downloads);
vi.spyOn(process.stdout, "write").mockImplementation(() => true);
await expect(
run(["logs", "export", "--json"], {
ONE_MEMORY_DATA_DIR: dataDir,
ONE_MEMORY_EXPORT_DIR: downloads,
ONE_MEMORY_BUILD_NUMBER: "3800",
ONE_MEMORY_COMMIT: "unknown",
}),
).rejects.toThrow("diagnostic_commit_invalid");
expect(await readdir(downloads)).toEqual([]);
});
it("never emits a secret from a malformed manually written event", async () => {
+111 -6
View File
@@ -57,6 +57,11 @@ const runtimeMocks = vi.hoisted(() => ({
})),
uninstallUserService: vi.fn(async (..._args: unknown[]) => "removed"),
restartUserService: vi.fn(async () => undefined),
runSdkMigration: vi.fn(
async (): Promise<{ state: string; code?: string }> => ({
state: "not_required",
}),
),
rollbackLocalInstall: vi.fn(async () => undefined),
planCliLink: vi.fn(async ({ home, installRoot }) => ({
schema_version: 1,
@@ -126,6 +131,7 @@ vi.mock("@one-memory/runtime-control", async (importOriginal) => {
installUserService: runtimeMocks.installUserService,
uninstallUserService: runtimeMocks.uninstallUserService,
restartUserService: runtimeMocks.restartUserService,
runSdkMigration: runtimeMocks.runSdkMigration,
rollbackLocalInstall: runtimeMocks.rollbackLocalInstall,
planCliLink: runtimeMocks.planCliLink,
installCliLink: runtimeMocks.installCliLink,
@@ -889,6 +895,108 @@ describe("public One Memory CLI", () => {
expect(runtimeMocks.restartUserService).toHaveBeenCalledTimes(2);
});
const upgradeArguments = [
"upgrade",
"--source",
"/tmp/dist",
"--home",
"/tmp/home",
"--install-root",
"/tmp/install",
"--data-dir",
"/tmp/custom data",
"--yes",
];
const presentCliLink = {
schema_version: 1 as const,
platform: "linux" as const,
home: "/tmp/home",
install_root: "/tmp/install",
bin_directory: "/tmp/bin",
status: "present" as const,
blocked_reason: null,
link_path: "/tmp/bin/one-memory",
target_path: "/tmp/install/current/bin/one-memory",
};
it("migrates the home with the new Core before restarting the Runtime", async () => {
vi.clearAllMocks();
runtimeMocks.planCliLink.mockResolvedValueOnce(presentCliLink);
const order: string[] = [];
runtimeMocks.runSdkMigration.mockImplementationOnce(async () => {
order.push("migrate");
return { state: "cutover" };
});
runtimeMocks.restartUserService.mockImplementationOnce(async () => {
order.push("restart");
});
const output = captureStdout();
let code: number;
try {
code = await run(
upgradeArguments,
{},
{ waitForRuntimeReady: async () => true },
);
} finally {
output.restore();
}
expect(code!).toBe(0);
expect(order).toEqual(["migrate", "restart"]);
expect(runtimeMocks.runSdkMigration).toHaveBeenCalledWith(
expect.objectContaining({ dataDir: "/tmp/custom data" }),
);
});
it("rolls back to the previous version when the migration does not finish", async () => {
vi.clearAllMocks();
runtimeMocks.planCliLink.mockResolvedValueOnce(presentCliLink);
runtimeMocks.runSdkMigration.mockResolvedValueOnce({
state: "deferred",
code: "sdk_migration_disk_space_insufficient",
});
const streams = captureStreams();
let code: number;
try {
code = await run(
upgradeArguments,
{},
{ waitForRuntimeReady: async () => true },
);
} finally {
streams.restore();
}
expect(code!).toBe(1);
expect(JSON.parse(streams.stderr())).toMatchObject({
command: "upgrade",
code: "sdk_migration_disk_space_insufficient",
});
expect(runtimeMocks.rollbackLocalInstall).toHaveBeenCalledOnce();
});
it("keeps the new version when a migrated home is slow to come up", async () => {
vi.clearAllMocks();
runtimeMocks.planCliLink.mockResolvedValueOnce(presentCliLink);
runtimeMocks.runSdkMigration.mockResolvedValueOnce({ state: "cutover" });
const streams = captureStreams();
let code: number;
try {
code = await run(
upgradeArguments,
{},
{ waitForRuntimeReady: async () => false },
);
} finally {
streams.restore();
}
expect(code!).toBe(1);
expect(JSON.parse(streams.stderr())).toMatchObject({
command: "upgrade",
code: "runtime_not_ready_after_sdk_migration",
});
expect(runtimeMocks.rollbackLocalInstall).not.toHaveBeenCalled();
});
it("reports success once the upgraded Runtime is healthy", async () => {
vi.clearAllMocks();
runtimeMocks.planCliLink.mockResolvedValueOnce({
@@ -1785,14 +1893,11 @@ describe("stopped Runtime is exit 3, not a usage error", () => {
["task", "--id", "nope", "--json"],
[
"write",
"submit",
"--session",
"s",
"--from",
"1",
"--to",
"1",
"--evidence",
"e",
"--messages-file",
"/tmp/messages.json",
"--json",
],
["backup", "create", "--target", "/tmp/x", "--yes", "--json"],
+402 -131
View File
@@ -4,7 +4,11 @@ import { createReadStream } from "node:fs";
import { access } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { HealthResponse, ImportJob } from "@one-memory/contracts";
import {
type HealthResponse,
type ImportJob,
isHostId,
} from "@one-memory/contracts";
import {
type AcquiredRuntimeDistribution,
acquireRuntimeDistribution,
@@ -35,7 +39,9 @@ import {
rollbackCliLink,
rollbackLocalInstall,
runRuntimeCli,
runSdkMigration,
runtimeInstallLayout,
type SdkMigrationResult,
stopRuntimeProcess,
} from "@one-memory/runtime-control";
import axios from "axios";
@@ -76,11 +82,13 @@ import {
createCoreReader,
createUiSessionRequest,
deleteModelProfile,
parseOpenAIMessages,
probeAdapter,
readAdapters,
readMemoryWrite,
readScanRoots,
removeScanRoot,
resetOnboarding,
submitBackup,
submitMemoryWrite,
submitScan,
@@ -94,7 +102,6 @@ import {
createCoreOperations,
} from "./core-operations.js";
import {
MEMORY_STATUSES,
type SourceConnectionCandidate,
validateImportJob,
validateSourceConnectionCandidates,
@@ -190,13 +197,6 @@ import {
renderMemoryDetailText,
renderMemoryPageText,
} from "./memory-report.js";
import {
type ModelContentPermissionDocument,
modelContentPermissionExitCode,
readModelContentPermission,
renderModelContentPermissionText,
setModelContentPermission,
} from "./model-content-permission-flow.js";
import {
executeModelProbe,
inspectModelProbePlan,
@@ -217,12 +217,10 @@ import {
executeModelProfileActivate,
executeModelProfileEdit,
type ModelWriteDocument,
type ModelWritePlan,
modelWriteExitCode,
planModelProfileActivate,
planModelProfileEdit,
renderModelWriteText,
validateModelWritePlan,
} from "./model-write-flows.js";
import { claimPlanAttempt } from "./operation-journal.js";
import {
@@ -339,7 +337,7 @@ import {
renderVersion,
renderVersionDocument,
} from "./usage.js";
import { CLI_VERSION, PRODUCT } from "./version.js";
import { CLI_VERSION, PRODUCT, RUNTIME_RELEASE_VERSION } from "./version.js";
import { runWatchLoop, type WatchEvent, type WatchRead } from "./watch-loop.js";
export interface RunControls {
@@ -358,6 +356,9 @@ export interface RunControls {
/** Wait for a restarted Runtime to become healthy after `upgrade`.
* Injectable so the upgrade tests do not spend real seconds polling. */
waitForRuntimeReady?: (dataDir: string) => Promise<boolean>;
/** Run the SDK data migration before install/upgrade starts the new
* Runtime. Injectable so the tests do not spawn a real Core. */
migrateSdkData?: typeof migrateSdkDataBeforeStart;
restartManagedRuntime?: typeof restartManagedService;
stopRuntime?: typeof stopRuntimeProcess;
ensureRuntime?: typeof ensureRuntimeProcess;
@@ -425,7 +426,8 @@ async function selectInstallSource(
throw new Error("release_manifest_url_unavailable");
}
const manifestUrl =
explicitManifestUrl ?? template.replaceAll("{version}", CLI_VERSION);
explicitManifestUrl ??
template.replaceAll("{version}", RUNTIME_RELEASE_VERSION);
const allowedHosts = parseAllowedReleaseHosts(
environment.MEMHUB_RELEASE_ALLOWED_HOSTS,
);
@@ -470,7 +472,7 @@ async function resolveRemoteInstallPreview(
): Promise<ResolvedRuntimeRelease> {
return (controls.resolveRuntimeRelease ?? resolveRuntimeRelease)({
manifestUrl: selection.manifestUrl,
expectedVersion: CLI_VERSION,
expectedVersion: RUNTIME_RELEASE_VERSION,
channel: selection.channel,
platform: process.platform,
arch: process.arch,
@@ -484,7 +486,7 @@ async function acquireRemoteInstallSource(
): Promise<AcquiredRuntimeDistribution> {
return (controls.acquireRuntimeDistribution ?? acquireRuntimeDistribution)({
manifestUrl: selection.manifestUrl,
expectedVersion: CLI_VERSION,
expectedVersion: RUNTIME_RELEASE_VERSION,
channel: selection.channel,
platform: process.platform,
arch: process.arch,
@@ -697,6 +699,36 @@ async function runCommand(
// `path list` and `adapter list` are read-only: they have no plan to confirm,
// so they are answered here rather than falling into the two-phase branch
// (which would reject them for having nothing to apply).
// Back to the cold-start screens on purpose. Deleting the app cannot do this
// (the completion flag lives with the memories, by design), and deleting the
// data to get there would cost the user everything they have stored.
if (named === "onboarding" && arguments_.includes("reset")) {
if (
arguments_.filter((item) => item === "--json").length > 1 ||
arguments_.filter((item) => item !== "--json").join(" ") !==
"onboarding reset"
) {
return usage();
}
const attachment = await attachToRuntime(
resolveRuntimeCliConfig(environment, process.argv[1]).dataDir,
);
if (attachment === null) {
return runtimeUnavailable(descriptor, asJson);
}
const state = await resetOnboarding(attachment);
if (state === null) {
return reject(descriptor, asJson, "引导状态端点不可用。");
}
if (asJson) {
process.stdout.write(`${JSON.stringify(state)}\n`);
return EXIT_OK;
}
process.stdout.write(
`引导流程已回到首次运行(status=${state.status}),记忆数据未改动。\n`,
);
return EXIT_OK;
}
if (named === "path" && arguments_.includes("list")) {
if (
arguments_.filter((item) => item === "--json").length > 1 ||
@@ -895,7 +927,36 @@ async function runCommand(
if (attachment === null) {
return runtimeUnavailable(descriptor, asJson);
}
const receipt = await submitMemoryWrite(attachment, parsed);
if (parsed.kind === "status") {
const receipt = await readMemoryWrite(attachment, parsed.id);
process.stdout.write(
asJson
? `${JSON.stringify({ schema_version: 1, write: receipt })}\n`
: receipt === null
? "未找到该 request id。\n"
: `request_id: ${receipt.request_id}\nstate: ${receipt.state}\n`,
);
return EXIT_OK;
}
const document = await readBoundedJson(parsed.messages_file);
const messages = parseOpenAIMessages(document);
if (messages === null) {
return reject(
descriptor,
asJson,
"messages 文件必须是含 user/assistant/tool 文本消息的 OpenAI messages 数组。",
);
}
const receipt = await submitMemoryWrite(attachment, {
session: parsed.session,
source: parsed.source,
request_id: parsed.request_id ?? randomUUID(),
messages,
...(parsed.memory_at === undefined
? {}
: { memory_at: parsed.memory_at }),
...(parsed.priority === undefined ? {} : { priority: parsed.priority }),
});
process.stdout.write(
asJson
? `${JSON.stringify({ schema_version: 1, write: receipt })}\n`
@@ -992,15 +1053,21 @@ async function runCommand(
entry: "cli",
}));
const target = path.join(downloads, diagnosticZipFilename(build));
const environmentCommit = environment.ONE_MEMORY_COMMIT?.trim();
const embeddedCommit =
typeof __ONE_MEMORY_COMMIT__ === "string"
? __ONE_MEMORY_COMMIT__.trim()
: "";
const commit =
environmentCommit ||
(embeddedCommit && embeddedCommit !== "unknown"
? embeddedCommit
: undefined);
const receipt = await exportDiagnosticZip({
dataDir: config.dataDir,
target,
productVersion: build,
commit:
environment.ONE_MEMORY_COMMIT?.trim() ||
(typeof __ONE_MEMORY_COMMIT__ === "string"
? __ONE_MEMORY_COMMIT__
: "unknown"),
...(commit === undefined ? {} : { commit }),
coreSha256: await sha256File(config.coreCommand).catch(() => undefined),
home: os.homedir(),
crashReportsDir: path.join(
@@ -2267,6 +2334,75 @@ async function runCommand(
emitReadDocument(named, document, asJson);
return sourceProgressExitCode(document);
}
if (named === "profile") {
if (arguments_.slice(1).some((value) => value !== "--json")) return usage();
const config = resolveRuntimeCliConfig(environment, process.argv[1]);
const attached = await attachClients(config.dataDir, {
readerTimeoutMs: 15_000,
});
if (!attached.reader) {
const document = {
schema_version: 2,
product: PRODUCT,
state: "unavailable",
code: attached.failure ?? "runtime_attach_failed",
};
emit(
asJson
? `${JSON.stringify(document)}\n`
: `用户画像读取失败:${document.code}\n`,
);
return EXIT_RUNTIME_STOPPED;
}
const outcome = await attached.reader<unknown>("/api/v2/user-profile");
if (outcome.state !== "ok") {
const document = {
schema_version: 2,
product: PRODUCT,
state: outcome.state,
code: outcome.code,
};
emit(
asJson
? `${JSON.stringify(document)}\n`
: `用户画像读取失败:${outcome.code}\n`,
);
return EXIT_FAILED;
}
const value = outcome.data as {
request_id?: unknown;
profile?: unknown;
elapsed_ms?: unknown;
};
if (
typeof value.request_id !== "string" ||
!(
value.profile === null ||
(typeof value.profile === "object" && !Array.isArray(value.profile))
) ||
typeof value.elapsed_ms !== "number"
) {
return reject(descriptor, asJson, "用户画像响应格式无效。");
}
const document = {
schema_version: 2,
product: PRODUCT,
state: "ok",
...value,
};
const content =
value.profile && typeof value.profile === "object"
? (value.profile as { content?: unknown }).content
: null;
emit(
asJson
? `${JSON.stringify(document)}\n`
: value.profile === null
? "尚未形成用户长期画像。\n"
: `${typeof content === "string" ? content : JSON.stringify(value.profile)}\n`,
);
return EXIT_OK;
}
if (named === "memories") {
const parsed = await parseMemoryCommand(arguments_.slice(1));
if (!parsed) return usage();
@@ -2299,6 +2435,8 @@ async function runCommand(
}
if (blocked || !reader) {
if (
parsed.kind === "update" ||
parsed.kind === "delete" ||
parsed.kind === "plan-add" ||
parsed.kind === "plan-existing" ||
parsed.kind === "apply"
@@ -2347,6 +2485,62 @@ async function runCommand(
);
return document.memory.state === "ok" ? EXIT_OK : EXIT_FAILED;
}
if (parsed.kind === "update" || parsed.kind === "delete") {
const content =
parsed.kind === "update"
? await readMemoryContentFile(parsed.contentFile)
: null;
if (parsed.kind === "update" && content === null) return usage();
const plan = {
schema_version: 2,
product: PRODUCT,
state: "preview",
operation: parsed.kind,
memory_id: parsed.memoryId,
...(content === null
? {}
: {
content_sha256: createHash("sha256")
.update(content)
.digest("hex"),
}),
};
if (!parsed.confirmed) {
emit(
asJson
? `${JSON.stringify(plan)}\n`
: `计划:${parsed.kind} ${parsed.memoryId}\n使用 --confirm 执行。\n`,
);
return EXIT_OK;
}
if (!operations) return EXIT_FAILED;
const writable = operations as CoreOperations &
CorePutOperations &
CoreDeleteOperations;
const path = `/api/v2/memories/${encodeURIComponent(parsed.memoryId)}`;
const outcome =
parsed.kind === "update"
? await writable.put<unknown>(path, { content })
: await writable.delete<unknown>(path);
const document = {
schema_version: 2,
product: PRODUCT,
state: outcome.state,
operation: parsed.kind,
memory_id: parsed.memoryId,
...(outcome.state === "committed"
? { result: outcome.data }
: { code: outcome.code }),
};
emit(
asJson
? `${JSON.stringify(document)}\n`
: outcome.state === "committed"
? `已${parsed.kind === "update" ? "更新" : "删除"}记忆 ${parsed.memoryId}\n`
: `操作失败:${outcome.code}\n`,
);
return outcome.state === "committed" ? EXIT_OK : EXIT_FAILED;
}
if (parsed.kind === "plan-add") {
const content = await readMemoryContentFile(parsed.contentFile);
if (content === null) return usage();
@@ -2370,7 +2564,6 @@ async function runCommand(
operation: parsed.operation,
memoryId: parsed.memoryId,
...(content === undefined ? {} : { content }),
...(parsed.scopes.length === 0 ? {} : { scopes: parsed.scopes }),
});
emitMemoryFlow(document, asJson);
return memoryFlowExitCode(document);
@@ -2462,45 +2655,6 @@ async function runCommand(
);
return uiWriteExitCode(document);
}
if (named === "permission") {
const parsed = parsePermissionCommand(arguments_.slice(1));
if (!parsed) return usage();
const config = resolveRuntimeCliConfig(environment, process.argv[1]);
const runtime = await inspectRuntimeStatus({
dataDir: config.dataDir,
probeIdentity,
requireServiceReceipt: true,
});
const attached =
runtime.state === "running"
? await attachClients(config.dataDir)
: { reader: null, operations: null, failure: runtime.code };
if (
runtime.state !== "running" ||
(parsed === "status" ? !attached.reader : !attached.operations)
) {
const document: ModelContentPermissionDocument = {
schema_version: 1,
product: PRODUCT,
state: "unknown",
code:
runtime.state !== "running"
? runtime.code
: (attached.failure ?? "runtime_attach_failed"),
};
emitModelContentPermissionDocument(document, asJson);
return runtime.state === "stopped" ? 3 : 1;
}
const document =
parsed === "status"
? await readModelContentPermission(attached.reader!)
: await setModelContentPermission(
attached.operations!,
parsed === "allow",
);
emitModelContentPermissionDocument(document, asJson);
return modelContentPermissionExitCode(document);
}
if (named === "notes" || named === "extraction" || named === "graph") {
const parsed = parseExtendedWriteCommand(
named as "notes" | "extraction" | "graph",
@@ -3000,6 +3154,7 @@ async function runCommand(
null;
let installReceiptWritten = false;
let serviceApplied = false;
let migrated = false;
let previousOwner:
| Awaited<ReturnType<typeof claimCliServiceOwnership>>
| undefined;
@@ -3010,6 +3165,23 @@ async function runCommand(
}
shellPathReceipt = await applyShellPath(shellPath);
previousOwner = await claimCliServiceOwnership(layout.dataDir);
// `install` over an existing home (reinstall, App-to-CLI takeover) must
// migrate it too, before the new Runtime starts serving it.
const migration = await (
controls.migrateSdkData ?? migrateSdkDataBeforeStart
)({
coreCommand: layout.coreCommand,
dataDir: layout.dataDir,
runtimeBuild: String(plan.build_number ?? plan.version),
asJson: true,
});
if (migration.state === "deferred") {
throw new SdkMigrationDeferred(
migration.code ?? "sdk_migration_incomplete",
);
}
migrated =
migration.state === "cutover" || migration.state === "complete";
await applyPreparedServiceInstall(preparedService);
serviceApplied = true;
// The receipt exists so a later command can find the data dir without
@@ -3061,6 +3233,13 @@ async function runCommand(
);
}
};
if (migrated) {
// An older Runtime refuses a migrated home: keep this install.
process.stderr.write(
`${JSON.stringify(notReadyAfterMigration("install"), null, 2)}\n`,
);
return EXIT_FAILED;
}
if (serviceApplied) {
await rollbackPreparedServiceInstall(
preparedService,
@@ -3070,7 +3249,13 @@ async function runCommand(
await rollbackFilesAndOwner();
}
process.stderr.write(
`${JSON.stringify(serviceErrorDocument("install", error), null, 2)}\n`,
`${JSON.stringify(
error instanceof SdkMigrationDeferred
? sdkMigrationFailure("install", error.code)
: serviceErrorDocument("install", error),
null,
2,
)}\n`,
);
return EXIT_FAILED;
}
@@ -3432,6 +3617,7 @@ async function runCommand(
let previousOwner:
| Awaited<ReturnType<typeof claimCliServiceOwnership>>
| undefined;
let migrated = false;
const rollbackUpgrade = async (
dataDir: string | undefined,
): Promise<void> => {
@@ -3463,6 +3649,25 @@ async function runCommand(
memhubReceipts.push(await installManagedCliLink(link));
}
previousOwner = await claimCliServiceOwnership(layout.dataDir);
const migration = await (
controls.migrateSdkData ?? migrateSdkDataBeforeStart
)({
coreCommand: layout.coreCommand,
dataDir: parsed.dataDir ?? layout.dataDir,
runtimeBuild: String(plan.build_number ?? plan.version),
asJson,
});
if (migration.state === "deferred") {
await rollbackUpgrade(parsed.dataDir);
process.stderr.write(
`${JSON.stringify(sdkMigrationFailure("upgrade", migration.code ?? "sdk_migration_incomplete"), null, 2)}\n`,
);
return EXIT_FAILED;
}
// An older Runtime refuses a migrated home, so from here a failure
// keeps the new version instead of rolling back to one that cannot start.
migrated =
migration.state === "cutover" || migration.state === "complete";
await restartUserService(layout, serviceOptions);
// A restart that returns without error only means launchd/systemd
// accepted the command. O-22: the first `upgrade` implementation
@@ -3474,6 +3679,12 @@ async function runCommand(
const ready = await (controls.waitForRuntimeReady ?? waitForRuntimeReady)(
dataDir,
);
if (!ready && migrated) {
process.stderr.write(
`${JSON.stringify(notReadyAfterMigration("upgrade"), null, 2)}\n`,
);
return EXIT_FAILED;
}
if (!ready) {
await rollbackUpgrade(parsed.dataDir);
process.stderr.write(
@@ -3501,9 +3712,9 @@ async function runCommand(
});
}
} catch (error) {
await rollbackUpgrade(parsed.dataDir);
if (!migrated) await rollbackUpgrade(parsed.dataDir);
process.stderr.write(
`${JSON.stringify(serviceErrorDocument("upgrade", error), null, 2)}\n`,
`${JSON.stringify(migrated ? notReadyAfterMigration("upgrade") : serviceErrorDocument("upgrade", error), null, 2)}\n`,
);
return EXIT_FAILED;
}
@@ -3871,6 +4082,79 @@ export function runtimeIsReady(
);
}
const SDK_MIGRATION_STEPS: Record<string, string> = {
bundle: "正在备份记忆数据,数据较多时需要几分钟……",
prepare: "正在整理待处理的写入任务……",
cutover: "正在切换记忆数据源……",
cleanup: "正在清理旧数据表……",
};
/**
* Migrate a home written by an older release before the new Runtime serves it.
*
* Runs the new Runtime's own Core with the Runtime stopped. Progress goes to
* stderr so stdout stays one result document.
*/
async function migrateSdkDataBeforeStart(options: {
coreCommand: string;
dataDir: string;
runtimeBuild: string;
asJson: boolean;
}): Promise<SdkMigrationResult> {
return runSdkMigration({
dataDir: options.dataDir,
core: { command: options.coreCommand },
runtimeBuild: options.runtimeBuild,
onProgress: (step) => {
process.stderr.write(
options.asJson
? `${JSON.stringify({ schema_version: 1, product: PRODUCT, event: "sdk_migration.progress", step })}\n`
: `${SDK_MIGRATION_STEPS[step] ?? step}\n`,
);
},
});
}
class SdkMigrationDeferred extends Error {
constructor(readonly code: string) {
super(code);
}
}
function notReadyAfterMigration(command: "install" | "upgrade") {
return {
schema_version: 1,
product: PRODUCT,
command,
status: "error",
code: "runtime_not_ready_after_sdk_migration",
message:
"记忆数据已迁移到新版本,但新版本 Runtime 没有在限定时间内就绪。旧版本无法打开已迁移的数据,所以没有回滚。请运行 memhub restart,或 memhub doctor 查看原因。",
};
}
const SDK_MIGRATION_FAILURES: Record<string, string> = {
sdk_migration_disk_space_insufficient:
"磁盘空间不足,记忆数据迁移没有完成,已回滚到上一版本。请腾出与记忆数据同等大小的空间后重试;原有记忆数据不会丢失。",
sdk_migration_memory_unreadable:
"核对发现新版本还读不到你的全部记忆,没有切换数据源,已回滚到上一版本。请把这个错误码反馈给我们;原有记忆数据不会丢失。",
sdk_migration_model_profile_required:
"迁移需要先有可用的模型配置,用来核对新版本能否读回记忆。已回滚到上一版本;请先用 memhub models setup 完成配置后再升级。",
};
function sdkMigrationFailure(command: "install" | "upgrade", code: string) {
return {
schema_version: 1,
product: PRODUCT,
command,
status: "error",
code,
message:
SDK_MIGRATION_FAILURES[code] ??
"记忆数据迁移没有完成,已回滚到上一版本。请重试;如果仍然失败,请把这个错误码反馈给我们。原有记忆数据不会丢失。",
};
}
async function waitForRuntimeReady(
dataDir: string,
timeoutMs = 45_000,
@@ -4587,10 +4871,10 @@ async function runMaintenanceRestore(options: {
const instanceId = randomUUID();
const child = spawn(options.coreCommand, ["serve", "--maintenance"], {
env: {
// Do not pass the caller's Runtime tuning variables (for example
// retrieval-index flags) into a maintenance process: a restore must
// start the product's minimal maintenance configuration, not inherit
// an unrelated experiment from the shell.
// Do not pass the caller's Runtime tuning variables into a
// maintenance process: a restore must start the product's minimal
// maintenance configuration, not inherit an unrelated experiment from
// the shell.
PATH: process.env.PATH,
HOME: process.env.HOME,
LANG: process.env.LANG,
@@ -5124,18 +5408,6 @@ function parseHeadlessCommand(
: null;
}
function parsePermissionCommand(
rest: readonly string[],
): "status" | "allow" | "deny" | null {
if (rest.filter((item) => item === "--json").length > 1) return null;
const tokens = rest.filter((item) => item !== "--json");
const action = tokens[0];
return tokens.length === 1 &&
(action === "status" || action === "allow" || action === "deny")
? action
: null;
}
function unwrapPlan(value: unknown): unknown {
if (
value &&
@@ -5184,10 +5456,10 @@ type HostCommand =
args: unknown[];
};
// `deepseek-harness:web` is a real id — that host is configured per profile —
// and `host list` prints it. Rejecting it here would mean listing a host the
// CLI then refuses to act on.
const HOST_ID = /^[a-z0-9][a-z0-9-]{0,31}(:[a-z0-9][a-z0-9-]{0,31})?$/;
// Host ids are read with the same grammar as the permission layer and the
// grant store (`@one-memory/contracts`): `deepseek-harness:web` is a real id —
// that host is configured per profile — and `host list` prints it, so rejecting
// it here would mean listing a host the CLI then refuses to act on.
const FINGERPRINT = /^[0-9a-f]{64}$/;
/** Host subcommands.
@@ -5210,7 +5482,7 @@ function parseHostCommand(rest: readonly string[]): HostCommand | null {
const token = tokens[index];
if (token === "--host") {
const value = tokens[index + 1];
if (!value || !HOST_ID.test(value)) return null;
if (!value || !isHostId(value)) return null;
if (hostId !== undefined) return null;
hostId = value;
index += 1;
@@ -5243,7 +5515,7 @@ function parseHostCommand(rest: readonly string[]): HostCommand | null {
qualifier !== undefined &&
(verb === "status" || verb === "install" || verb === "uninstall")
) {
if (!HOST_ID.test(qualifier)) return null;
if (!isHostId(qualifier)) return null;
hostId = qualifier;
// Drop the consumed host positional so the verb/qualifier checks below see
// the same shape as the flag form.
@@ -5259,7 +5531,7 @@ function parseHostCommand(rest: readonly string[]): HostCommand | null {
positional[2] !== undefined
) {
const trailing = positional[2];
if (!HOST_ID.test(trailing)) return null;
if (!isHostId(trailing)) return null;
hostId = trailing;
positional.splice(2, 1);
verb = positional[0];
@@ -5323,17 +5595,6 @@ function emitModelReportDocument(
);
}
function emitModelContentPermissionDocument(
document: ModelContentPermissionDocument,
asJson: boolean,
): void {
process.stdout.write(
asJson
? `${JSON.stringify(document)}\n`
: renderModelContentPermissionText(document),
);
}
function emitSourceSyncDocument(
document: SourceSyncFlowDocument,
asJson: boolean,
@@ -5819,6 +6080,13 @@ function emitReadDocument(
type MemoryCommand =
| { kind: "list"; query: MemoryQuery }
| { kind: "show"; memoryId: string }
| {
kind: "update";
memoryId: string;
contentFile: string;
confirmed: boolean;
}
| { kind: "delete"; memoryId: string; confirmed: boolean }
| {
kind: "plan-add";
contentFile: string;
@@ -5828,10 +6096,9 @@ type MemoryCommand =
}
| {
kind: "plan-existing";
operation: "correct" | "delete" | "scope";
operation: "correct" | "delete";
memoryId: string;
contentFile?: string;
scopes: string[];
}
| { kind: "apply"; planFile: string; contentFile?: string };
@@ -5847,6 +6114,33 @@ async function parseMemoryCommand(
? { kind: "show", memoryId }
: null;
}
if (action === "update" || action === "delete") {
const memoryId = tokens[1];
if (!memoryId || !isMemoryId(memoryId)) return null;
let contentFile: string | undefined;
let confirmed = false;
for (let index = 2; index < tokens.length; index += 1) {
const flag = tokens[index];
if (flag === "--confirm") {
if (confirmed) return null;
confirmed = true;
continue;
}
const value = tokens[index + 1];
if (value === undefined || value.startsWith("--")) return null;
if (flag !== "--content-file" || contentFile !== undefined) return null;
contentFile = value;
index += 1;
}
if (action === "update")
return contentFile
? { kind: "update", memoryId, contentFile, confirmed }
: null;
return contentFile === undefined
? { kind: "delete", memoryId, confirmed }
: null;
}
if (action === "plan" || action === "apply") return null;
if (action === "plan") return parseMemoryPlanCommand(tokens.slice(1));
if (action === "apply") {
let planFile: string | undefined;
@@ -5872,10 +6166,7 @@ async function parseMemoryCommand(
: null;
}
if (action !== "list") return null;
let query: string | undefined;
let queryFile: string | undefined;
let status: string | undefined;
let source: string | undefined;
let offset = 0;
let limit = 100;
let offsetSet = false;
@@ -5884,11 +6175,7 @@ async function parseMemoryCommand(
const flag = tokens[index];
const value = tokens[index + 1];
if (value === undefined || value.startsWith("--")) return null;
if (flag === "--query" && query === undefined) query = value;
else if (flag === "--query-file" && queryFile === undefined)
queryFile = value;
else if (flag === "--status" && status === undefined) status = value;
else if (flag === "--source" && source === undefined) source = value;
if (flag === "--status" && status === undefined) status = value;
else if (flag === "--limit" && !limitSet) {
limit = Number(value);
limitSet = true;
@@ -5897,24 +6184,11 @@ async function parseMemoryCommand(
offsetSet = true;
} else return null;
}
if (query !== undefined && queryFile !== undefined) return null;
if (queryFile !== undefined) {
query = (await readQueryFile(queryFile)) ?? undefined;
if (query === undefined) return null;
}
if (
query !== undefined &&
(query.length === 0 || query.length > QUERY_MAX_CHARACTERS)
) {
if (status !== undefined && (status.length === 0 || status.length > 64))
return null;
}
if (status !== undefined && !MEMORY_STATUSES.includes(status as never)) {
return null;
}
if (source !== undefined && source.length === 0) return null;
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500) return null;
if (!Number.isSafeInteger(offset) || offset < 0) return null;
return { kind: "list", query: { query, status, source, offset, limit } };
return { kind: "list", query: { status, offset, limit } };
}
function parseMemoryPlanCommand(
@@ -5922,7 +6196,7 @@ function parseMemoryPlanCommand(
): MemoryCommand | null {
const operation = tokens[0];
const add = operation === "add";
if (!add && !["correct", "delete", "scope"].includes(operation)) {
if (!add && !["correct", "delete"].includes(operation)) {
return null;
}
const memoryId = add ? undefined : tokens[1];
@@ -5941,7 +6215,7 @@ function parseMemoryPlanCommand(
else if (flag === "--kind" && add && !kindSet) {
memoryKind = value;
kindSet = true;
} else if (flag === "--scope" && !scopes.includes(value))
} else if (flag === "--scope" && add && !scopes.includes(value))
scopes.push(value);
else if (flag === "--evidence" && add && !evidenceIds.includes(value))
evidenceIds.push(value);
@@ -5961,18 +6235,15 @@ function parseMemoryPlanCommand(
}
if (
(operation === "correct" && !contentFile) ||
(operation === "scope" && scopes.length === 0) ||
(!["correct", "scope"].includes(operation) &&
(contentFile !== undefined || scopes.length > 0))
(operation === "delete" && (contentFile !== undefined || scopes.length > 0))
) {
return null;
}
return {
kind: "plan-existing",
operation: operation as "correct" | "delete" | "scope",
operation: operation as "correct" | "delete",
memoryId: memoryId as string,
...(contentFile ? { contentFile } : {}),
scopes,
};
}
@@ -6560,7 +6831,7 @@ function parseInstallOptions(
...(releaseManifestUrl ? { releaseManifestUrl } : {}),
releaseChannel:
releaseChannel ??
(CLI_VERSION.includes("-") ? "prerelease" : "stable"),
(RUNTIME_RELEASE_VERSION.includes("-") ? "prerelease" : "stable"),
installRoot: resolvedInstallRoot,
home: resolvedHome,
uid: uid ?? process.getuid?.(),
+22 -91
View File
@@ -347,22 +347,6 @@ export const COMMANDS: readonly CommandDescriptor[] = [
],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
},
{
name: "processing",
summary: "手动推进待处理证据;默认只预览,确认后执行。",
usage:
"memhub processing extract [--evidence <id> ...] [--confirm] [--json]",
options: [
{
flag: "--evidence <id>",
summary:
"processing extract 要提前处理的证据 ID,可重复;不给则推进下一批。",
},
DIRECT_CONFIRM_OPTION,
JSON_OPTION,
],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
},
{
name: "models",
summary:
@@ -387,25 +371,14 @@ export const COMMANDS: readonly CommandDescriptor[] = [
},
{
name: "memories",
summary:
"列出/查看记忆,或生成并显式确认带版本与 request identity 的治理操作计划。",
summary: "通过 SDK 数据面列出、查看、修改或物理删除记忆。",
usage:
"memhub memories list [--query <text>] [--query-file <path>] [--status <state>] [--source <id>] [--offset <n>] [--limit <n>] [--json]\n memhub memories show <memory-id> [--json]\n memhub memories plan add --content-file <path> --scope <scope> --evidence <id> [--kind <kind>] [--json]\n memhub memories plan <correct|delete|scope> <memory-id> [--content-file <path>] [--scope <scope>] [--json]\n memhub memories apply --plan-file <path> --confirm [--content-file <path>] [--json]",
"memhub memories list [--status <state>] [--offset <n>] [--limit <n>] [--json]\n memhub memories show <memory-id> [--json]\n memhub memories update <memory-id> --content-file <path> [--confirm] [--json]\n memhub memories delete <memory-id> [--confirm] [--json]",
options: [
{
flag: "--query <text>",
summary:
"按内容过滤;会出现在 shell 历史里,敏感词请改用 --query-file。",
},
{
flag: "--query-file <path>",
summary: "从文件读取过滤词,避免查询内容进入命令行历史。",
},
{
flag: "--status <state>",
summary: `记忆状态,取值 ${MEMORY_STATUSES.join("、")}。`,
},
{ flag: "--source <id>", summary: "只看某个来源产生的记忆。" },
{ flag: "--offset <n>", summary: "跳过前 n 条,默认 0。" },
{
flag: "--limit <n>",
@@ -416,24 +389,18 @@ export const COMMANDS: readonly CommandDescriptor[] = [
summary:
"从有界普通文件读取新增/纠正正文;计划只保存摘要,执行时再次校验。",
},
{
flag: "--kind <chat|working|coding|schema|intention>",
summary: "新增记忆的类型,默认 chat。",
},
{
flag: "--scope <scope>",
summary: "记忆使用范围,可重复;private 必须独占。",
},
{
flag: "--evidence <id>",
summary: "新增记忆引用的 Evidence ID,可重复。",
},
PLAN_FILE_OPTION,
EXPLICIT_CONFIRM_OPTION,
DIRECT_CONFIRM_OPTION,
JSON_OPTION,
],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
},
{
name: "profile",
summary: "读取 SDK 组装后的用户长期画像(L0 + 已启用的长期画像补充)。",
usage: "memhub profile [--json]",
options: [DATA_DIR_OPTION, JSON_OPTION],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
},
{
name: "calls",
summary:
@@ -454,28 +421,6 @@ export const COMMANDS: readonly CommandDescriptor[] = [
],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
},
{
name: "import-file",
summary:
"上传、提交或丢弃一份历史导入文件;提交与丢弃默认只出计划,需 --confirm。",
usage:
"memhub import-file upload --file <path> [--kind raw_conversation|memory_content] [--confirm] [--json]\n memhub import-file commit <upload-id> [--confirm] [--json]\n memhub import-file discard <upload-id> [--confirm] [--json]",
options: [
{
flag: "--file <path>",
summary:
"要上传的普通文件(非符号链接,<=128 MiB,.zip/.json/.md/.txt)。",
},
{
flag: "--kind <kind>",
summary:
"输入类型,默认 raw_conversation;memory_content 用于记忆正文。",
},
DIRECT_CONFIRM_OPTION,
JSON_OPTION,
],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
},
{
name: "notes",
summary:
@@ -493,28 +438,6 @@ export const COMMANDS: readonly CommandDescriptor[] = [
],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
},
{
name: "permission",
summary: "读取或直接设置全局模型内容外发许可。",
usage:
"memhub permission status [--json]\n memhub permission allow [--json]\n memhub permission deny [--json]",
options: [JSON_OPTION],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
},
{
name: "extraction",
summary: "设置提取窗口;默认只出计划,--confirm 后才写入。",
usage: "memhub extraction set --window <3m|6m|1y|all> [--confirm] [--json]",
options: [
{
flag: "--window <preset>",
summary: "提取窗口预设:3m、6m、1y 或 all。",
},
DIRECT_CONFIRM_OPTION,
JSON_OPTION,
],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_RUNTIME_STOPPED],
},
{
name: "graph",
summary: "图谱宽度不匹配时的用户决定;默认只出计划,--confirm 后才执行。",
@@ -659,6 +582,14 @@ export const COMMANDS: readonly CommandDescriptor[] = [
],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE, EXIT_PLAN_BLOCKED],
},
{
name: "onboarding",
summary:
"onboarding reset 回到首次运行的引导流程。只清除引导完成状态:不删记忆数据,也不需要卸载重装。",
usage: "memhub onboarding reset [--json]",
options: [JSON_OPTION],
exit_codes: [EXIT_OK, EXIT_FAILED, EXIT_USAGE],
},
{
name: "help",
summary: "显示总帮助或单个命令的用法。",
@@ -722,16 +653,16 @@ export const COMMANDS: readonly CommandDescriptor[] = [
},
{
name: "write",
summary:
"提交一次记忆写入,返回可查询的 request id;写入异步完成,不可重复提交。",
summary: "提交 OpenAI messages 到 SDK 写入队列,或按 request id 查询状态。",
usage:
"memhub write --session <id> --from <round> --to <round> --evidence <id> [--evidence <id>...] [--live] [--json]",
"memhub write submit --messages-file <path> --session <id> [--source <id>] [--request-id <id>] [--memory-at <RFC3339>] [--live] [--json]\n memhub write status --id <request-id> [--json]",
options: [DATA_DIR_OPTION, JSON_OPTION],
exit_codes: [EXIT_OK, EXIT_USAGE, EXIT_FAILED],
},
{
name: "task",
summary: "查询写入任务状态;unknown 表示结果待定,不可据此重发。",
summary:
"兼容别名:按 request id 查询写入状态;新脚本请使用 write status。",
usage: "memhub task --id <request-id> [--json]",
options: [DATA_DIR_OPTION, JSON_OPTION],
exit_codes: [EXIT_OK, EXIT_USAGE, EXIT_FAILED],
+11 -6
View File
@@ -74,15 +74,12 @@ const COMMANDS = [
"sync",
"progress",
"jobs",
"processing",
"models",
"memories",
"profile",
// C6 App BLOCK (25f4ecf): UI write operations that had no CLI equivalent.
"calls",
"import-file",
"notes",
"permission",
"extraction",
"graph",
"host",
"recall",
@@ -93,6 +90,7 @@ const COMMANDS = [
"uninstall",
"upgrade",
"delete-data",
"onboarding",
"help",
"version",
// A6 product commands. Appended, not inserted: the catalog is a stable
@@ -259,7 +257,14 @@ describe("CLI-22 shared output contract", () => {
describe("argument validation", () => {
it("fails unknown commands without printing data or running anything", async () => {
for (const argv of [["unknown"], ["unknown", "--help"], ["--typo"]]) {
for (const argv of [
["unknown"],
["unknown", "--help"],
["--typo"],
["permission", "status"],
["permission", "allow"],
["permission", "deny"],
]) {
const streams = captureStreams();
try {
expect(await run(argv, {})).toBe(2);
@@ -555,7 +560,7 @@ describe("documented commands", () => {
// `sync <pause|resume>` is documented as one alternation, so it is
// checked as an entry rather than as two literal subcommands.
sync: ["status", "<pause|resume>"],
memories: ["list", "show", "plan", "apply"],
memories: ["list", "show", "update", "delete"],
host: ["list", "status", "install", "uninstall", "sync"],
};
@@ -384,6 +384,101 @@ describe("unified context search", () => {
expect(streams.stdout()).not.toContain("must-not-print");
});
it("counts characters as code points so an emoji hit stays grounded", async () => {
// Core reports used_characters with Python's len(), which counts code
// points: this text is 10 characters there and 12 UTF-16 units here.
const text = "消费保 📍 扩展 📡";
expect(text.length).toBe(12);
expect(Array.from(text).length).toBe(10);
transport.post.mockResolvedValue({
status: 200,
data: {
...RESPONSE,
paths: {
...RESPONSE.paths,
memory: {
...RESPONSE.paths.memory,
status: "empty",
returned_count: 0,
},
},
items: [
{
...(RESPONSE.items[0] as Record<string, unknown>),
messages: [
{
...(
RESPONSE.items[0] as {
messages: Array<Record<string, unknown>>;
}
).messages[0],
text,
},
],
},
],
used_characters: 10,
},
});
const streams = captureStreams();
try {
expect(await run(["recall", "test", "--json"])).toBe(0);
} finally {
streams.restore();
}
expect(JSON.parse(streams.stdout())).toMatchObject({
state: "grounded",
used_characters: 10,
items: [{ kind: "raw", messages: [{ text }] }],
});
});
it("still rejects a response whose character total does not match", async () => {
// The same text counted as UTF-16 units is exactly what Core does not mean,
// so the cross-check must keep failing instead of accepting both totals.
const text = "消费保 📍 扩展 📡";
transport.post.mockResolvedValue({
status: 200,
data: {
...RESPONSE,
paths: {
...RESPONSE.paths,
memory: {
...RESPONSE.paths.memory,
status: "empty",
returned_count: 0,
},
},
items: [
{
...(RESPONSE.items[0] as Record<string, unknown>),
messages: [
{
...(
RESPONSE.items[0] as {
messages: Array<Record<string, unknown>>;
}
).messages[0],
text,
},
],
},
],
used_characters: 12,
},
});
const streams = captureStreams();
try {
expect(await run(["recall", "test", "--json"])).toBe(1);
} finally {
streams.restore();
}
expect(JSON.parse(streams.stdout())).toMatchObject({
state: "invalid",
code: "response_invalid",
});
});
it("reports endpoint denial without exposing the response body", async () => {
transport.post.mockResolvedValue({
status: 403,
+13 -2
View File
@@ -181,9 +181,9 @@ function validateContextResponse(
items.push(item);
characters +=
item.kind === "memory"
? String(item.content).length
? characterCount(item.content)
: (item.messages as Array<Record<string, unknown>>).reduce(
(sum, message) => sum + String(message.text).length,
(sum, message) => sum + characterCount(message.text),
0,
);
}
@@ -330,6 +330,17 @@ function record(value: unknown): Record<string, unknown> | null {
: null;
}
/**
* Count characters the way Core does. Python's len() counts Unicode code
* points; String.prototype.length counts UTF-16 code units, so an emoji outside
* the BMP is one character to Core and two here. Comparing the two totals made
* every response containing an emoji fail the used_characters cross-check and
* surface as response_invalid.
*/
function characterCount(value: unknown): number {
return Array.from(String(value)).length;
}
function boundedText(
value: unknown,
maximum: number,
+89 -10
View File
@@ -8,7 +8,6 @@ import axios from "axios";
*/
const READ_ONLY_PATHS = [
"/api/v1/call-events",
"/api/v1/model-content-permission",
"/api/v1/home-summary",
"/api/v1/import-jobs",
"/api/v1/live-sync",
@@ -17,7 +16,10 @@ const READ_ONLY_PATHS = [
"/api/v1/memory-tasks",
"/api/v1/model-profiles",
"/api/v1/sources",
"/api/v2/memory-library",
"/api/v2/user-profile",
] as const;
const SDK_MEMORY_DETAIL = /^\/api\/v2\/memories\/[A-Za-z0-9][\w.-]{0,127}$/;
/** Contract (C0, H25): the one-time loopback code exchange for `memhub ui`.
* It is a POST because it mints a short-lived code; the CLI sends the bearer
@@ -196,6 +198,7 @@ export function isReadOnlyPath(path: string): boolean {
if (IMPORT_JOB.test(path)) return true;
if (OPERATION_RECEIPT.test(path)) return true;
if (MEMORY_MUTATION_RECEIPT.test(path)) return true;
if (SDK_MEMORY_DETAIL.test(path)) return true;
if (!MEMORY_DETAIL.test(path)) return false;
const segment = path.slice("/api/v1/memories/".length);
return !(RESERVED_MEMORY_SEGMENTS as readonly string[]).includes(segment);
@@ -212,6 +215,43 @@ export interface MemoryWriteReceipt {
created_at: string;
updated_at: string;
detail?: string;
raw_ids?: string[];
memory_ids?: string[];
}
export interface OpenAIMessage {
role: "user" | "assistant" | "tool";
content: string;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
export function parseOpenAIMessages(value: unknown): OpenAIMessage[] | null {
const candidate = Array.isArray(value)
? value
: isRecord(value) && Array.isArray(value.messages)
? value.messages
: null;
if (candidate === null || candidate.length < 1 || candidate.length > 200)
return null;
const messages: OpenAIMessage[] = [];
for (const item of candidate) {
if (!isRecord(item)) return null;
if (!["user", "assistant", "tool"].includes(String(item.role))) return null;
if (
typeof item.content !== "string" ||
item.content.length < 1 ||
item.content.length > 12_000
)
return null;
messages.push({
role: item.role as OpenAIMessage["role"],
content: item.content,
});
}
return messages.some((message) => message.role === "user") ? messages : null;
}
/** A6: submit a write through the durable entry every entry shares.
@@ -238,19 +278,23 @@ export async function submitMemoryWrite(
attachment: RuntimeAttachmentLike,
request: {
session: string;
first_round: number;
last_round: number;
evidence_ids: readonly string[];
source: string;
request_id: string;
messages: readonly OpenAIMessage[];
memory_at?: string;
priority?: "live" | "normal";
},
): Promise<MemoryWriteReceipt> {
const response = await axios.post<MemoryWriteReceipt>(
`${baseUrlOf(attachment)}/api/v1/memory-writes`,
`${baseUrlOf(attachment)}/api/v2/memory-writes`,
{
internal_session_id: request.session,
first_round: request.first_round,
last_round: request.last_round,
evidence_ids: [...request.evidence_ids],
request_id: request.request_id,
session_id: request.session,
source_id: request.source,
messages: [...request.messages],
...(request.memory_at === undefined
? {}
: { memory_at: request.memory_at }),
...(request.priority === undefined ? {} : { priority: request.priority }),
},
{
@@ -381,7 +425,7 @@ export async function readMemoryWrite(
): Promise<MemoryWriteReceipt | null> {
try {
const response = await axios.get<MemoryWriteReceipt>(
`${baseUrlOf(attachment)}/api/v1/memory-writes/${encodeURIComponent(requestId)}`,
`${baseUrlOf(attachment)}/api/v2/memory-writes/${encodeURIComponent(requestId)}`,
{
headers: { Authorization: `Bearer ${attachment.apiToken}` },
timeout: 10_000,
@@ -398,6 +442,41 @@ export async function readMemoryWrite(
}
}
export interface OnboardingState {
status: string;
selected_source_ids: string[];
started_at: string | null;
completed_at: string | null;
}
/** Send onboarding back to its first-run state.
*
* Returns null when the endpoint is not there, so an older runtime degrades to
* "not available" instead of failing the command. Only the completion flag
* moves: memories, sources and settings live in other tables, which is what
* makes this the honest way to see the cold-start screens again.
*/
export async function resetOnboarding(
attachment: RuntimeAttachmentLike,
): Promise<OnboardingState | null> {
try {
const response = await axios.post<OnboardingState>(
`${baseUrlOf(attachment)}/api/v1/onboarding/reset`,
undefined,
{
headers: { Authorization: `Bearer ${attachment.apiToken}` },
timeout: 15_000,
proxy: false,
maxRedirects: 0,
maxContentLength: MAX_RESPONSE_BYTES,
},
);
return response.data;
} catch {
return null;
}
}
export async function readScanRoots(
attachment: RuntimeAttachmentLike,
): Promise<{
+3 -4
View File
@@ -6,6 +6,7 @@ const WRITE_PATHS = [
] as const;
const MEMORY_WRITE_PATH =
/^\/api\/v1\/memories(?:\/[A-Za-z0-9][\w.-]{0,127}\/(?:correct|scopes|actions\/delete))?$/;
const SDK_MEMORY_PATH = /^\/api\/v2\/memories\/[A-Za-z0-9][\w.-]{0,127}$/;
const MODEL_PROBE_PATH =
/^\/api\/v1\/model-profiles\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/probe$/;
const MODEL_PROFILE_PATH =
@@ -30,7 +31,6 @@ const IMPORT_FILE =
const MEMORY_NOTES_PATH = "/api/v1/memory-notes";
const MEMORY_NOTE_PROCESS =
/^\/api\/v1\/memory-notes\/[A-Za-z0-9][\w.:-]{0,127}\/process$/;
const MODEL_CONTENT_PERMISSION_PATH = "/api/v1/model-content-permission";
const EXTRACTION_SETTINGS_PATH = "/api/v1/extraction-settings";
const GRAPH_WIDTH_PATH = "/api/v1/graph-width";
const MANUAL_EXTRACT_PATH = "/api/v1/memory-processing/manual-extract";
@@ -134,7 +134,6 @@ export function createCoreOperations(attachment: {
!IMPORT_FILE_COMMIT.test(path) &&
path !== MEMORY_NOTES_PATH &&
!MEMORY_NOTE_PROCESS.test(path) &&
path !== MODEL_CONTENT_PERMISSION_PATH &&
path !== GRAPH_WIDTH_PATH &&
path !== MANUAL_EXTRACT_PATH &&
path !== ONBOARDING_COMPLETE_PATH &&
@@ -172,7 +171,7 @@ export function createCoreOperations(attachment: {
body: Record<string, unknown>,
signal?: AbortSignal,
) {
if (path !== EXTRACTION_SETTINGS_PATH) {
if (path !== EXTRACTION_SETTINGS_PATH && !SDK_MEMORY_PATH.test(path)) {
throw new Error("core_operation_path_not_allowed");
}
let response: { status: number; data: unknown };
@@ -234,7 +233,7 @@ export function createCoreOperations(attachment: {
};
},
async delete<T>(path: string, signal?: AbortSignal) {
if (!IMPORT_FILE.test(path)) {
if (!IMPORT_FILE.test(path) && !SDK_MEMORY_PATH.test(path)) {
throw new Error("core_operation_path_not_allowed");
}
let response: { status: number; data: unknown };
+5 -12
View File
@@ -259,7 +259,7 @@ describe("A2 dual-mode init", () => {
expect(streams.value()).toContain("处理:已开启");
});
it("continues the TTY wizard through model probe and content permission", async () => {
it("continues the TTY wizard through model setup and probe", async () => {
const profileId = "22222222-2222-4222-8222-222222222222";
const profile = {
profile_id: profileId,
@@ -361,12 +361,6 @@ describe("A2 dual-mode init", () => {
};
}
if (url.endsWith("/activate")) return { status: 200, data: profile };
if (url === "/api/v1/model-content-permission") {
return {
status: 200,
data: { allowed: body.allowed },
};
}
if (url === "/api/v1/onboarding/complete") {
return {
status: 200,
@@ -383,7 +377,7 @@ describe("A2 dual-mode init", () => {
},
);
const prompt = extendedPrompter(
["", "", "", "", "", "", "", "", "n"],
["", "", "", "", "", "", "", "n"],
"sk-never-print-this",
);
const streams = captureStdout();
@@ -402,7 +396,6 @@ describe("A2 dual-mode init", () => {
streams.restore();
}
expect(streams.value()).toContain("已接入来源:codex");
expect(prompt.written.join("\n")).toContain("模型内容外发:已允许");
expect(streams.value()).toContain("首次设置完成。");
expect(`${streams.value()}\n${prompt.written.join("\n")}`).not.toContain(
"sk-never-print-this",
@@ -412,10 +405,10 @@ describe("A2 dual-mode init", () => {
expect.objectContaining({ api_key: "sk-never-print-this" }),
undefined,
);
expect(transport.post).toHaveBeenCalledWith(
expect(transport.post).not.toHaveBeenCalledWith(
"/api/v1/model-content-permission",
{ allowed: true },
undefined,
expect.anything(),
expect.anything(),
);
expect(transport.post).toHaveBeenCalledWith(
"/api/v1/onboarding/complete",
@@ -132,12 +132,6 @@ function clients(options: { failedProbes?: number } = {}) {
if (path.endsWith("/activate")) {
return { state: "committed" as const, data: profile(true) };
}
if (path === "/api/v1/model-content-permission") {
return {
state: "committed" as const,
data: { allowed: body.allowed },
};
}
return {
state: "rejected" as const,
code: "unexpected_path",
@@ -160,8 +154,8 @@ function clients(options: { failedProbes?: number } = {}) {
}
describe("interactive model setup", () => {
it("uses App defaults, keeps the key out of output, and allows model content", async () => {
const prompt = prompter(["", "", "", "", "", ""]);
it("uses App defaults and keeps the key out of output", async () => {
const prompt = prompter(["", "", ""]);
const api = clients();
const result = await runInteractiveModelSetup(prompt.value, api, {
@@ -170,10 +164,7 @@ describe("interactive model setup", () => {
installHosts: false,
});
expect(result).toMatchObject({
state: "configured",
model_content_allowed: true,
});
expect(result).toMatchObject({ state: "configured" });
expect(api.post).toHaveBeenCalledWith(
"/api/v1/model-profiles",
expect.objectContaining({
@@ -184,9 +175,10 @@ describe("interactive model setup", () => {
embedding_provider_kind: "local_onnx",
}),
);
expect(api.post).toHaveBeenCalledWith("/api/v1/model-content-permission", {
allowed: true,
});
expect(api.post).not.toHaveBeenCalledWith(
"/api/v1/model-content-permission",
expect.anything(),
);
expect(prompt.written.join("\n")).not.toContain("sk-do-not-print");
});
@@ -205,7 +197,7 @@ describe("interactive model setup", () => {
});
it("removes an unverified profile before skipping after a failed probe", async () => {
const prompt = prompter(["", "", "", "n", "0"]);
const prompt = prompter(["", "", "", "0"]);
const api = clients();
api.post.mockImplementation(
async (path: string, body: Record<string, unknown>) => {
@@ -280,7 +272,7 @@ describe("interactive model setup", () => {
});
it("cleans a failed probe and lets the user re-enter the model settings", async () => {
const prompt = prompter(["", "", "", "", "", "", "", "", "", "", ""]);
const prompt = prompter(["", "", "", "", "", "", ""]);
const api = clients({ failedProbes: 1 });
const result = await runInteractiveModelSetup(prompt.value, api, {
@@ -289,10 +281,7 @@ describe("interactive model setup", () => {
installHosts: false,
});
expect(result).toMatchObject({
state: "configured",
model_content_allowed: true,
});
expect(result).toMatchObject({ state: "configured" });
expect(api.remove).toHaveBeenCalledTimes(1);
expect(
api.post.mock.calls.filter(([path]) => path === "/api/v1/model-profiles"),
@@ -305,7 +294,7 @@ describe("interactive model setup", () => {
const prompt = prompter(["", "", ""]);
prompt.value.ask = async () => {
asked += 1;
if (asked === 4) throw new Error("interrupted");
if (asked === 3) throw new Error("interrupted");
return "";
};
const api = clients();
@@ -322,7 +311,7 @@ describe("interactive model setup", () => {
});
it("installs selected detected hosts through preview and fingerprint apply", async () => {
const prompt = prompter(["", "", "", "n", "", ""]);
const prompt = prompter(["", "", "", "", ""]);
const api = clients();
const read = vi
.fn()
@@ -360,7 +349,6 @@ describe("interactive model setup", () => {
expect(result).toMatchObject({
state: "configured",
model_content_allowed: false,
installed_hosts: ["codex"],
});
expect(read).toHaveBeenNthCalledWith(
@@ -373,7 +361,7 @@ describe("interactive model setup", () => {
});
it("lists and installs only hosts that are actually present", async () => {
const prompt = prompter(["", "", "", "n", "", ""]);
const prompt = prompter(["", "", "", "", ""]);
const api = clients();
const read = vi
.fn()
@@ -420,7 +408,7 @@ describe("interactive model setup", () => {
});
it("completes the wizard and keeps onboarding reachable when one host install fails", async () => {
const prompt = prompter(["", "", "", "n", "", ""]);
const prompt = prompter(["", "", "", "", ""]);
const api = clients();
const read = vi
.fn()
@@ -469,7 +457,6 @@ describe("interactive model setup", () => {
// calling the install a failure.
expect(result).toMatchObject({
state: "configured",
model_content_allowed: false,
installed_hosts: ["codex"],
});
const summary = prompt.written.join("\n");
@@ -479,7 +466,7 @@ describe("interactive model setup", () => {
});
it("tells the user to install App-only hosts in the App instead of calling them failed", async () => {
const prompt = prompter(["", "", "", "n", "", ""]);
const prompt = prompter(["", "", "", "", ""]);
const api = clients();
const read = vi
.fn()
@@ -506,7 +493,6 @@ describe("interactive model setup", () => {
// only the App can install, so nothing counts as "installed".
expect(result).toMatchObject({
state: "configured",
model_content_allowed: false,
installed_hosts: [],
});
const summary = prompt.written.join("\n");
@@ -11,7 +11,6 @@ import {
} from "./headless-flows.js";
import { approvalFingerprint, listHosts, readHost } from "./host-flow.js";
import { parseSelection, type WizardPrompter } from "./init-wizard.js";
import { setModelContentPermission } from "./model-content-permission-flow.js";
import { executeModelProbe, planModelProbe } from "./model-probe-flow.js";
import {
executeModelProfileActivate,
@@ -122,7 +121,6 @@ export type InteractiveModelSetupState =
| {
state: "configured";
profile: ModelProfile;
model_content_allowed: boolean;
installed_hosts: string[];
}
| { state: "skipped" }
@@ -289,15 +287,11 @@ async function installHosts(
function writeSummary(
prompter: WizardPrompter,
profile: ModelProfile,
modelContentAllowed: boolean,
installedHosts: readonly string[],
failedHosts: readonly { hostId: string; label: string }[],
): void {
prompter.write("配置摘要:");
prompter.write(` 模型:${profile.name} / ${profile.model}`);
prompter.write(
` 模型内容外发:${modelContentAllowed ? "已允许" : "已禁止"}`,
);
prompter.write(
` 应用接入:${installedHosts.length > 0 ? installedHosts.join("、") : "已跳过"}`,
);
@@ -353,14 +347,6 @@ export async function runInteractiveModelSetup(
prompter.write("未填写 API Key。输入 back 返回,或重新选择模型服务。");
continue;
}
const permissionAnswer = (
await prompter.ask("允许将对话内容发送给模型以整理记忆?[Y/n]: ")
)
.trim()
.toLowerCase();
const modelContentAllowed = !["n", "no", "否", "0"].includes(
permissionAnswer,
);
const hostApi = options.hostApi ?? { list: listHosts, read: readHost };
const selectedHosts = options.installHosts
? await chooseDetectedHosts(prompter, options.hostHome, hostApi)
@@ -452,13 +438,6 @@ export async function runInteractiveModelSetup(
return { state: "failed", code: "model_activate_failed" };
}
const permission = await setModelContentPermission(
clients.operations,
modelContentAllowed,
);
if (permission.state !== "ok") {
return { state: "failed", code: "model_content_permission_set_failed" };
}
const { installed, failed } = await installHosts(
options.dataDir,
selectedHosts,
@@ -467,7 +446,6 @@ export async function runInteractiveModelSetup(
writeSummary(
prompter,
profile,
modelContentAllowed,
installed,
failed.map((hostId) => ({
hostId,
@@ -477,7 +455,6 @@ export async function runInteractiveModelSetup(
return {
state: "configured",
profile,
model_content_allowed: modelContentAllowed,
installed_hosts: installed,
};
}
+3
View File
@@ -180,5 +180,8 @@ describe("import-job write allow-list", () => {
await expect(
operations.post("/api/v1/import-jobs/job-1/delete", {}),
).rejects.toThrow("core_operation_path_not_allowed");
await expect(
operations.post("/api/v1/model-content-permission", { allowed: true }),
).rejects.toThrow("core_operation_path_not_allowed");
});
});
+31 -1
View File
@@ -1,4 +1,4 @@
import { mkdtemp, rm } from "node:fs/promises";
import { mkdtemp, rm, symlink } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { DiagnosticLogger } from "@one-memory/runtime-control";
@@ -41,11 +41,15 @@ it("redacts unsafe details and absolute stack frames from the read surface", ()
session_id: "11111111-1111-4111-8111-111111111111",
details: {
count: 1,
reason: "/Users/me/private-query.txt",
status: "sk-live-secret-token",
source_id: "credential.private",
prompt: "secret-token-123",
authorization: "Bearer secret-token-123",
} as unknown as Record<string, string | number | boolean | null>,
safe_stack: [
"packages/runtime-control/src/example.ts:42:7",
"packages/runtime/sk-live-secret-token.ts:1:1",
"/Users/me/private.py:1",
"C:\\Users\\me\\private.py:1",
],
@@ -56,6 +60,8 @@ it("redacts unsafe details and absolute stack frames from the read surface", ()
"packages/runtime-control/src/example.ts:42:7",
]);
expect(JSON.stringify(redacted)).not.toContain("secret-token-123");
expect(JSON.stringify(redacted)).not.toContain("sk-live-secret-token");
expect(JSON.stringify(redacted)).not.toContain("credential.private");
expect(JSON.stringify(redacted)).not.toContain("/Users/me");
expect(JSON.stringify(redacted)).not.toContain("C:\\\\Users");
});
@@ -132,3 +138,27 @@ it("follows a newly appended event without stopping Runtime", async () => {
});
expect(seen).toEqual(["service.ready", "core.failed"]);
});
it("fails follow mode when the diagnostic directory is unsafe", async () => {
const dataDir = await mkdtemp(
path.join(os.tmpdir(), "om-cli-follow-unsafe-"),
);
const external = await mkdtemp(
path.join(os.tmpdir(), "om-cli-follow-external-"),
);
roots.push(dataDir, external);
await symlink(external, path.join(dataDir, "logs"));
const query = parseLogQuery(["--follow"]);
expect(query).not.toBeNull();
if (!query) throw new Error("query_missing");
await expect(
followLogs({
dataDir,
query,
signal: new AbortController().signal,
maxEvents: 1,
emit: () => undefined,
wait: async () => undefined,
}),
).rejects.toThrow("log_directory_unreadable");
});
+6 -102
View File
@@ -3,6 +3,7 @@ import path from "node:path";
import type { DiagnosticEventV1 } from "@one-memory/runtime-control";
import {
diagnosticLogFiles,
projectDiagnosticEventForSafeOutput,
readDiagnosticEvents,
} from "@one-memory/runtime-control";
@@ -24,54 +25,6 @@ export interface LogQuery {
const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/;
const NAME = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+){0,15}$/;
const SAFE_DETAIL_KEYS = new Set([
"action",
"attempt",
"count",
"method",
"mode",
"phase",
"platform",
"reason",
"result_count",
"source_id",
"spawned",
"status",
"version",
"parent_session_id",
"invalid_lines",
"truncated",
"runtime_state",
"core_state",
"broker_state",
"instance_id",
"open_file_count",
"memory_bytes",
"thread_count",
"database_error_count",
"file_count",
"sqlite_file_count",
"byte_file_count",
"total_bytes",
"copied_bytes",
"bytes_per_second",
"stored_count",
"revised_count",
"skipped_count",
"error_count",
"pending_count",
"prepared_count",
"queue_depth",
"in_flight_count",
"call_count",
"created_count",
"updated_count",
"superseded_count",
"deleted_count",
"operation_kind",
"file_kind",
]);
export function parseLogQuery(arguments_: readonly string[]): LogQuery | null {
if (arguments_.filter((item) => item === "--json").length > 1) return null;
const values: Partial<LogQuery> = { errorsOnly: false, follow: false };
@@ -237,63 +190,13 @@ export function renderLogText(
return `${lines.join("\n")}\n`;
}
/** Defence in depth for the CLI read surface. `DiagnosticLogger` already
* allow-lists keys, but a future writer, a manually edited log, or a malformed
* line must not turn `memhub logs` into an exfiltration path. */
/** Defence in depth for the CLI read surface. Local writers accept arbitrary
* bounded scalar keys, so every outward read surface must reuse the same
* field-and-value projection as the support-bundle exporter. */
export function redactDiagnosticEvent(
event: DiagnosticEventV1,
): DiagnosticEventV1 {
const redacted: DiagnosticEventV1 = {
schema_version: 1,
timestamp: event.timestamp,
level: event.level,
service: event.service,
component: event.component,
event: event.event,
outcome: event.outcome,
session_id: event.session_id,
...(event.trace_id === undefined ? {} : { trace_id: event.trace_id }),
...(event.incident_id === undefined
? {}
: { incident_id: event.incident_id }),
...(event.instance_id === undefined
? {}
: { instance_id: event.instance_id }),
...(event.operation_id === undefined
? {}
: { operation_id: event.operation_id }),
...(event.request_id === undefined ? {} : { request_id: event.request_id }),
...(event.job_id === undefined ? {} : { job_id: event.job_id }),
...(event.task_id === undefined ? {} : { task_id: event.task_id }),
...(event.duration_ms === undefined
? {}
: { duration_ms: event.duration_ms }),
...(event.state_before === undefined
? {}
: { state_before: event.state_before }),
...(event.state_after === undefined
? {}
: { state_after: event.state_after }),
...(event.error_code === undefined ? {} : { error_code: event.error_code }),
...(event.error_type === undefined ? {} : { error_type: event.error_type }),
...(event.safe_stack === undefined
? {}
: {
safe_stack: event.safe_stack.filter(
(frame) =>
!frame.startsWith("/") &&
!/^[A-Za-z]:\\/.test(frame) &&
!frame.includes(".."),
),
}),
};
const details = Object.fromEntries(
Object.entries(event.details ?? {}).filter(([key]) =>
SAFE_DETAIL_KEYS.has(key),
),
);
if (Object.keys(details).length > 0) redacted.details = details;
return redacted;
return projectDiagnosticEventForSafeOutput(event);
}
export async function followLogs(options: {
@@ -315,6 +218,7 @@ export async function followLogs(options: {
...options.query,
tail: 5_000,
});
if (report.failure) throw new Error(report.failure);
for (const event of report.events) {
const identity = JSON.stringify(event);
if (seen.has(identity)) continue;
-718
View File
@@ -1,718 +0,0 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { run } from "./cli.js";
import type { CoreReader } from "./core-client.js";
import type { CoreOperations } from "./core-operations.js";
import {
executeMemoryMutation,
inspectMemoryPlan,
memoryPlanAcceptsContent,
planExistingMemoryMutation,
planMemoryAdd,
readMemoryMutationReceipt,
} from "./memory-flows.js";
import { readMemoryDetail } from "./memory-report.js";
const transport = vi.hoisted(() => ({
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
patch: vi.fn(),
delete: vi.fn(),
}));
vi.mock("axios", () => ({
default: { create: vi.fn(() => transport), get: vi.fn() },
}));
const runtime = vi.hoisted(() => ({
inspectRuntimeStatus: vi.fn(),
discoverRuntimeAttachment: vi.fn(),
stopRuntimeProcess: vi.fn(),
}));
vi.mock("@one-memory/runtime-control", async (importOriginal) => ({
...(await importOriginal<typeof import("@one-memory/runtime-control")>()),
...runtime,
}));
const MEMORY = {
memory_id: "memory-1",
user_id: "local",
kind: "working",
status: "confirmed",
content: "Existing synthetic memory.",
scopes: ["all-apps"],
evidence_ids: ["evidence-1"],
origin: "extracted",
tags: ["synthetic"],
revision: 3,
created_at: "2026-09-19T00:00:00Z",
updated_at: "2026-09-19T00:00:01Z",
deleted_at: null,
};
const DETAIL = {
memory: MEMORY,
evidence: [
{
evidence_id: "evidence-1",
available: true,
source_id: "codex",
written_by: "person",
created_at: "2026-09-19T00:00:00Z",
verbatim: "Synthetic source text.",
},
],
history: [
{
revision: 3,
action: "create",
status: "confirmed",
content: "Existing synthetic memory.",
scopes: ["all-apps"],
created_at: "2026-09-19T00:00:01Z",
},
],
index_sync: null,
};
const ATTACHED = {
instanceId: "instance-1",
apiToken: "synthetic-runtime-token",
host: "127.0.0.1" as const,
port: 8765,
servicePid: 4242,
health: {
status: "ok",
service: "one-memory-core",
version: "1.2.3",
instance_id: "instance-1",
},
};
beforeEach(() => {
vi.clearAllMocks();
runtime.inspectRuntimeStatus.mockResolvedValue({
state: "running",
code: "runtime_verified",
instanceId: "instance-1",
host: "127.0.0.1",
port: 8765,
version: "1.2.3",
});
runtime.discoverRuntimeAttachment.mockResolvedValue(ATTACHED);
transport.get.mockImplementation(async (url: string) =>
url === "/api/v1/memories/memory-1"
? { status: 200, data: DETAIL }
: { status: 404, data: {} },
);
});
describe("memory governance plans", () => {
it("plans a manual memory without putting private content in the plan", () => {
const result = planMemoryAdd({
content: "Private synthetic addition.",
memoryKind: "working",
scopes: ["all-apps"],
evidenceIds: ["evidence-1"],
});
expect(result.state).toBe("preview");
expect(JSON.stringify(result)).not.toContain("Private synthetic addition.");
if (result.state !== "preview") throw new Error("preview expected");
expect(result.plan).toMatchObject({
operation: "add",
memory_kind: "working",
scopes: ["all-apps"],
evidence_ids: ["evidence-1"],
content_characters: 27,
});
expect(inspectMemoryPlan(result.plan)).toMatchObject({
operationId: result.plan.request_id,
needsContent: true,
});
expect(
memoryPlanAcceptsContent(result.plan, "Private synthetic addition."),
).toBe(true);
expect(memoryPlanAcceptsContent(result.plan, "Different content.")).toBe(
false,
);
});
it("binds correction to the current version, source, author and scopes", async () => {
const result = await planExistingMemoryMutation(detailReader(), {
operation: "correct",
memoryId: "memory-1",
content: "Corrected synthetic memory.",
scopes: ["codex"],
});
expect(result.state).toBe("preview");
if (result.state !== "preview") throw new Error("preview expected");
expect(result.plan).toMatchObject({
memory_id: "memory-1",
expected_revision: 3,
expected_status: "confirmed",
expected_origin: "extracted",
scopes: ["codex"],
current: {
revision: 3,
evidence: [
{
evidence_id: "evidence-1",
source_id: "codex",
written_by: "person",
},
],
},
});
expect(JSON.stringify(result)).not.toContain("Corrected synthetic memory.");
});
it("posts a confirmed plan once and validates the bound receipt", async () => {
const preview = planMemoryAdd({
content: "Private synthetic addition.",
memoryKind: "working",
scopes: ["all-apps"],
evidenceIds: ["evidence-1"],
});
if (preview.state !== "preview") throw new Error("preview expected");
const post = vi.fn().mockResolvedValue({
state: "committed",
data: {
...MEMORY,
memory_id: "created-1",
content: "Private synthetic addition.",
status: "confirmed",
origin: "manual",
revision: 1,
},
});
const result = await executeMemoryMutation(
preview.plan,
"Private synthetic addition.",
{ post } as CoreOperations,
);
expect(result.state).toBe("committed");
expect(post).toHaveBeenCalledWith(
"/api/v1/memories",
expect.objectContaining({
request_id: preview.plan.request_id,
draft: expect.objectContaining({
origin: "manual",
content: "Private synthetic addition.",
}),
}),
);
expect(JSON.stringify(result)).not.toContain("Private synthetic addition.");
});
it("does not take a created memory that is not in effect as the add", async () => {
const preview = planMemoryAdd({
content: "Private synthetic addition.",
memoryKind: "working",
scopes: ["all-apps"],
evidenceIds: ["evidence-1"],
});
if (preview.state !== "preview") throw new Error("preview expected");
const result = await executeMemoryMutation(
preview.plan,
"Private synthetic addition.",
{
post: vi.fn().mockResolvedValue({
state: "committed",
data: {
...MEMORY,
memory_id: "created-1",
content: "Private synthetic addition.",
status: "deleted",
origin: "manual",
revision: 1,
},
}),
} as CoreOperations,
);
expect(result).toMatchObject({
state: "unknown",
code: "memory_receipt_invalid",
});
});
it.each([["delete", "/actions/delete", "deleted"]] as const)(
"executes %s against the revision-bound action route",
async (operation, suffix, status) => {
const preview = await planExistingMemoryMutation(detailReader(), {
operation,
memoryId: "memory-1",
});
if (preview.state !== "preview") throw new Error("preview expected");
const post = vi.fn().mockResolvedValue({
state: "committed",
data: { ...MEMORY, status, revision: 4 },
});
const result = await executeMemoryMutation(preview.plan, undefined, {
post,
} as CoreOperations);
expect(result.state).toBe("committed");
expect(post).toHaveBeenCalledWith(`/api/v1/memories/memory-1${suffix}`, {
request_id: preview.plan.request_id,
expected_revision: 3,
});
},
);
it("executes correction and scope changes without changing origin", async () => {
for (const operation of ["correct", "scope"] as const) {
const content =
operation === "correct" ? "Corrected synthetic memory." : undefined;
const preview = await planExistingMemoryMutation(detailReader(), {
operation,
memoryId: "memory-1",
...(content ? { content } : {}),
scopes: ["codex"],
});
if (preview.state !== "preview") throw new Error("preview expected");
const post = vi.fn().mockResolvedValue({
state: "committed",
data: {
...MEMORY,
content: content ?? MEMORY.content,
scopes: ["codex"],
revision: 4,
},
});
const result = await executeMemoryMutation(preview.plan, content, {
post,
} as CoreOperations);
expect(result.state).toBe("committed");
expect(post.mock.calls[0][0]).toBe(
`/api/v1/memories/memory-1/${operation === "scope" ? "scopes" : "correct"}`,
);
expect(post.mock.calls[0][1]).toMatchObject({
request_id: preview.plan.request_id,
expected_revision: 3,
scopes: ["codex"],
});
}
});
it("treats a misbound HTTP 200 receipt as unknown", async () => {
const preview = await planExistingMemoryMutation(detailReader(), {
operation: "delete",
memoryId: "memory-1",
});
if (preview.state !== "preview") throw new Error("preview expected");
const result = await executeMemoryMutation(preview.plan, undefined, {
post: vi.fn().mockResolvedValue({
state: "committed",
data: {
...MEMORY,
memory_id: "another-memory",
status: "deleted",
revision: 4,
},
}),
});
expect(result).toMatchObject({
state: "unknown",
code: "memory_receipt_invalid",
operation_id: preview.plan.request_id,
});
});
it("recovers only an exactly bound governance transaction receipt", async () => {
const preview = await planExistingMemoryMutation(detailReader(), {
operation: "delete",
memoryId: "memory-1",
});
if (preview.state !== "preview") throw new Error("preview expected");
const result = await readMemoryMutationReceipt(
receiptReader({
schema_version: 2,
request_id: preview.plan.request_id,
state: "committed",
operation: "delete",
memory_id: "memory-1",
result_revision: 4,
result_status: "deleted",
memory_state: "deleted",
migrated_from: null,
}),
preview.plan,
);
expect(result).toMatchObject({
state: "recovered",
operation_id: preview.plan.request_id,
receipt: {
operation: "delete",
memory_id: "memory-1",
result_revision: 4,
result_status: "deleted",
},
});
expect(JSON.stringify(result)).not.toContain("content_sha256");
});
it.each([
["operation", "correct"],
["memory_id", "memory-2"],
["result_revision", 5],
["result_status", "confirmed"],
["migrated_from", "reject"],
] as const)("refuses a receipt with wrong %s", async (field, wrong) => {
const preview = await planExistingMemoryMutation(detailReader(), {
operation: "delete",
memoryId: "memory-1",
});
if (preview.state !== "preview") throw new Error("preview expected");
const result = await readMemoryMutationReceipt(
receiptReader({
schema_version: 2,
request_id: preview.plan.request_id,
state: "committed",
operation: "delete",
memory_id: "memory-1",
result_revision: 4,
result_status: "deleted",
memory_state: "deleted",
migrated_from: null,
[field]: wrong,
}),
preview.plan,
);
expect(result).toMatchObject({
state: "unknown",
code: "memory_mutation_receipt_invalid",
});
});
it("keeps not-found, denied and unavailable lookups unresolved", async () => {
const preview = await planExistingMemoryMutation(detailReader(), {
operation: "delete",
memoryId: "memory-1",
});
if (preview.state !== "preview") throw new Error("preview expected");
const notFound = await readMemoryMutationReceipt(
receiptReader({
schema_version: 2,
request_id: preview.plan.request_id,
state: "not_found",
operation: null,
memory_id: null,
result_revision: null,
result_status: null,
memory_state: null,
migrated_from: null,
}),
preview.plan,
);
expect(notFound).toMatchObject({
state: "unknown",
code: "memory_mutation_receipt_not_found_after_attempt",
});
for (const state of ["denied", "unavailable"] as const) {
const result = await readMemoryMutationReceipt(
async () => ({ state, code: `synthetic_${state}` }),
preview.plan,
);
expect(result).toMatchObject({
state: "unknown",
code: `memory_mutation_receipt_synthetic_${state}`,
});
}
});
it("maps an add plan only to the Core create receipt", async () => {
const preview = planMemoryAdd({
content: "Private synthetic addition.",
memoryKind: "working",
scopes: ["all-apps"],
evidenceIds: ["evidence-1"],
});
if (preview.state !== "preview") throw new Error("preview expected");
const result = await readMemoryMutationReceipt(
receiptReader({
schema_version: 2,
request_id: preview.plan.request_id,
state: "committed",
operation: "create",
memory_id: "created-1",
result_revision: 1,
result_status: "confirmed",
memory_state: "present",
migrated_from: null,
}),
preview.plan,
);
expect(result).toMatchObject({
state: "recovered",
receipt: {
operation: "create",
memory_id: "created-1",
result_revision: 1,
result_status: "confirmed",
},
});
});
it("shows bounded history fields including scopes and status", async () => {
const result = await readMemoryDetail(detailReader(), "memory-1");
expect(result.history[0]).toMatchObject({
revision: 3,
action: "create",
status: "confirmed",
scopes: ["all-apps"],
content: "Existing synthetic memory.",
});
});
});
describe("memory pending fence", () => {
it("rejects missing confirmation and invalid plans before any write", async () => {
for (const argv of [
["memories", "apply", "--plan-file", "/synthetic/plan", "--json"],
["memories", "plan", "delete", "graph", "--json"],
["memories", "plan", "delete", "memory-1", "--scope", "codex", "--json"],
["memories", "plan", "confirm", "memory-1", "--json"],
["memories", "plan", "reject", "memory-1", "--json"],
[
"memories",
"plan",
"add",
"--content-file",
"/synthetic/content",
"--scope",
"all-apps",
"--json",
],
]) {
const streams = captureStreams();
try {
expect(await run(argv)).toBe(2);
} finally {
streams.restore();
}
}
expect(transport.post).not.toHaveBeenCalled();
});
it("generates a bounded correction preview without writing", async () => {
const directory = await mkdtemp(
path.join(os.tmpdir(), "om-memory-preview-"),
);
const contentFile = path.join(directory, "content.txt");
await writeFile(contentFile, "Corrected synthetic memory.");
const streams = captureStreams();
try {
expect(
await run([
"memories",
"plan",
"correct",
"memory-1",
"--content-file",
contentFile,
"--scope",
"codex",
"--json",
]),
).toBe(0);
} finally {
streams.restore();
await rm(directory, { recursive: true, force: true });
}
const output = JSON.parse(streams.stdout());
expect(output).toMatchObject({
state: "preview",
plan: {
operation: "correct",
memory_id: "memory-1",
expected_revision: 3,
scopes: ["codex"],
},
});
expect(streams.stdout()).not.toContain("Corrected synthetic memory.");
expect(transport.post).not.toHaveBeenCalled();
});
it("checks content identity before claiming the durable fence", async () => {
const preview = planMemoryAdd({
content: "Private synthetic addition.",
memoryKind: "working",
scopes: ["all-apps"],
evidenceIds: ["evidence-1"],
});
if (preview.state !== "preview") throw new Error("preview expected");
const directory = await mkdtemp(
path.join(os.tmpdir(), "om-memory-content-"),
);
const planFile = path.join(directory, "plan.json");
const wrongFile = path.join(directory, "wrong.txt");
const correctFile = path.join(directory, "correct.txt");
await writeFile(planFile, JSON.stringify(preview));
await writeFile(wrongFile, "Different content.");
await writeFile(correctFile, "Private synthetic addition.");
const wrong = captureStreams();
try {
expect(
await run([
"memories",
"apply",
"--plan-file",
planFile,
"--content-file",
wrongFile,
"--confirm",
"--json",
]),
).toBe(2);
} finally {
wrong.restore();
}
transport.post.mockResolvedValue({
status: 200,
data: {
...MEMORY,
memory_id: "created-1",
content: "Private synthetic addition.",
status: "confirmed",
origin: "manual",
revision: 1,
},
});
const correct = captureStreams();
try {
expect(
await run([
"memories",
"apply",
"--plan-file",
planFile,
"--content-file",
correctFile,
"--confirm",
"--json",
]),
).toBe(0);
} finally {
correct.restore();
await rm(directory, { recursive: true, force: true });
}
expect(transport.post).toHaveBeenCalledTimes(1);
});
it("recovers an unknown mutation after restart without reposting", async () => {
const preview = await planExistingMemoryMutation(detailReader(), {
operation: "delete",
memoryId: "memory-1",
});
if (preview.state !== "preview") throw new Error("preview expected");
const directory = await mkdtemp(path.join(os.tmpdir(), "om-memory-plan-"));
const planFile = path.join(directory, "plan.json");
await writeFile(planFile, JSON.stringify(preview));
transport.post.mockRejectedValue(new Error("synthetic disconnect"));
let receiptLookups = 0;
transport.get.mockImplementation(async (url: string) => {
if (url === "/api/v1/memories/memory-1") {
return { status: 200, data: DETAIL };
}
if (url === `/api/v1/memory-mutations/${preview.plan.request_id}`) {
receiptLookups += 1;
if (receiptLookups === 1) throw new Error("synthetic lookup outage");
return {
status: 200,
data: {
schema_version: 2,
request_id: preview.plan.request_id,
state: "committed",
operation: "delete",
memory_id: "memory-1",
result_revision: 4,
result_status: "deleted",
memory_state: "deleted",
migrated_from: null,
},
};
}
return { status: 404, data: {} };
});
const first = captureStreams();
try {
expect(
await run([
"memories",
"apply",
"--plan-file",
planFile,
"--confirm",
"--json",
]),
).toBe(1);
} finally {
first.restore();
}
expect(JSON.parse(first.stdout())).toMatchObject({
state: "unknown",
code: "memory_mutation_receipt_transport_failed",
});
const second = captureStreams();
try {
expect(
await run([
"memories",
"apply",
"--plan-file",
planFile,
"--confirm",
"--json",
]),
).toBe(0);
} finally {
second.restore();
await rm(directory, { recursive: true, force: true });
}
expect(JSON.parse(second.stdout())).toMatchObject({
state: "recovered",
receipt: {
operation: "delete",
memory_id: "memory-1",
result_revision: 4,
result_status: "deleted",
},
});
expect(transport.post).toHaveBeenCalledTimes(1);
expect(receiptLookups).toBe(2);
});
});
function captureStreams() {
let stdout = "";
let stderr = "";
const out = vi.spyOn(process.stdout, "write").mockImplementation((chunk) => {
stdout += String(chunk);
return true;
});
const error = vi
.spyOn(process.stderr, "write")
.mockImplementation((chunk) => {
stderr += String(chunk);
return true;
});
return {
stdout: () => stdout,
stderr: () => stderr,
restore: () => {
out.mockRestore();
error.mockRestore();
},
};
}
function detailReader(): CoreReader {
return async <T>() => ({ state: "ok", data: DETAIL as T });
}
function receiptReader(receipt: unknown): CoreReader {
return async <T>() => ({ state: "ok", data: receipt as T });
}
+7 -32
View File
@@ -4,15 +4,11 @@ import {
buildMemoryActionRequest,
buildMemoryCorrectRequest,
buildMemoryCreateRequest,
buildMemoryScopesRequest,
parseMemoryReceipt,
} from "@one-memory/operations";
import type { CoreReader } from "./core-client.js";
import type { CoreOperations } from "./core-operations.js";
import {
validateGovernedMemory,
validateMemoryDetail,
} from "./core-responses.js";
import { validateMemoryDetail } from "./core-responses.js";
import { isMemoryId } from "./memory-report.js";
import { PRODUCT } from "./version.js";
@@ -23,7 +19,7 @@ const MEMORY_KINDS = [
"schema",
"intention",
] as const;
const OPERATIONS = ["add", "correct", "delete", "scope"] as const;
const OPERATIONS = ["add", "correct", "delete"] as const;
const MEMORY_ORIGINS = ["extracted", "answered", "agent", "manual"] as const;
const MUTATION_RECEIPT_KEYS = new Set([
"schema_version",
@@ -145,15 +141,12 @@ export async function planExistingMemoryMutation(
operation: Exclude<(typeof OPERATIONS)[number], "add">;
memoryId: string;
content?: string;
scopes?: string[];
},
): Promise<MemoryFlowDocument> {
if (
!isMemoryId(input.memoryId) ||
(input.operation === "correct" && input.content === undefined) ||
(input.content !== undefined && !validContent(input.content)) ||
((input.operation === "scope" || input.scopes !== undefined) &&
!validScopes(input.scopes ?? []))
(input.content !== undefined && !validContent(input.content))
) {
return invalid("memory_plan_input_invalid");
}
@@ -176,7 +169,6 @@ export async function planExistingMemoryMutation(
expected_revision: memory.revision,
expected_status: memory.status,
expected_origin: memory.origin,
...(input.scopes ? { scopes: input.scopes } : {}),
...(input.content ? contentIdentity(input.content) : {}),
current: {
status: memory.status,
@@ -407,15 +399,7 @@ function operationRequest(
plan.memory_id as string,
plan.expected_revision as number,
content as string,
plan.scopes,
plan.request_id,
);
}
if (plan.operation === "scope") {
return buildMemoryScopesRequest(
plan.memory_id as string,
plan.expected_revision as number,
plan.scopes ?? [],
undefined,
plan.request_id,
);
}
@@ -451,10 +435,7 @@ function matchesReceipt(
return false;
}
if (plan.operation === "delete" && memory.status !== "deleted") return false;
if (
(plan.operation === "correct" || plan.operation === "scope") &&
memory.status !== plan.expected_status
) {
if (plan.operation === "correct" && memory.status !== plan.expected_status) {
return false;
}
if (plan.operation === "correct" && memory.content !== content) return false;
@@ -490,11 +471,7 @@ function validateMutationReceipt(
: null;
}
const expectedOperation =
plan.operation === "add"
? "create"
: plan.operation === "scope"
? "set_scopes"
: plan.operation;
plan.operation === "add" ? "create" : plan.operation;
const expectedRevision =
plan.operation === "add" ? 1 : (plan.expected_revision as number) + 1;
const expectedStatus = plan.operation === "delete" ? "deleted" : "confirmed";
@@ -561,9 +538,7 @@ function validatePlan(value: unknown): MemoryMutationPlan | null {
plan.expected_status !== "confirmed" ||
!oneOf(plan.expected_origin, MEMORY_ORIGINS) ||
!validCurrent(plan) ||
(plan.operation === "correct" && !contentFields(plan)) ||
((plan.operation === "scope" || plan.scopes !== undefined) &&
!validScopes(plan.scopes))
(plan.operation === "correct" && !contentFields(plan))
) {
return null;
}
@@ -17,7 +17,7 @@ const FIXTURE = JSON.parse(
),
"utf8",
),
) as { receipts: Record<"add" | "correct" | "scope" | "delete", Receipt> };
) as { receipts: Record<"add" | "correct" | "delete", Receipt> };
interface Receipt {
schema_version: number;
@@ -103,11 +103,8 @@ describe("memory mutation receipt v2 from Core", () => {
});
});
it.each<
["correct" | "scope" | "delete", { content?: string; scopes?: string[] }]
>([
it.each<["correct" | "delete", { content?: string }]>([
["correct", { content: "Corrected synthetic memory." }],
["scope", { scopes: ["codex"] }],
["delete", {}],
])(
"recovers %s from the receipt Core returns for it",
+77 -69
View File
@@ -1,6 +1,5 @@
import type { GovernedMemory } from "@one-memory/contracts";
import type { SdkMemoryPage, SdkMemoryRecord } from "@one-memory/contracts";
import { type CoreReader, RESERVED_MEMORY_SEGMENTS } from "./core-client.js";
import { validateMemoryDetail, validateMemoryPage } from "./core-responses.js";
import { PRODUCT } from "./version.js";
/** Output budget: a long memory is shortened visibly, never dropped silently. */
@@ -47,10 +46,8 @@ export async function readMemoryPage(
offset: query.offset,
limit: query.limit,
};
if (query.query !== undefined) parameters.query = query.query;
if (query.status !== undefined) parameters.status = query.status;
if (query.source !== undefined) parameters.source = query.source;
const outcome = await reader<unknown>("/api/v1/memory-library", parameters);
if (query.status !== undefined) parameters.statuses = query.status;
const outcome = await reader<unknown>("/api/v2/memory-library", parameters);
if (outcome.state !== "ok") {
return {
schema_version: 1,
@@ -59,7 +56,7 @@ export async function readMemoryPage(
memories: [],
};
}
const page = validateMemoryPage(outcome.data, query);
const page = sdkMemoryPage(outcome.data);
if (page === null) {
return {
schema_version: 1,
@@ -68,7 +65,7 @@ export async function readMemoryPage(
memories: [],
};
}
const items = page.items;
const items = page.memories;
return {
schema_version: 1,
product: PRODUCT,
@@ -88,7 +85,7 @@ export async function readMemoryDetail(
reader: CoreReader,
memoryId: string,
): Promise<MemoryDetailDocument> {
const outcome = await reader<unknown>(`/api/v1/memories/${memoryId}`);
const outcome = await reader<unknown>(`/api/v2/memories/${memoryId}`);
if (outcome.state !== "ok") {
return {
schema_version: 1,
@@ -98,8 +95,8 @@ export async function readMemoryDetail(
history: [],
};
}
const detail = validateMemoryDetail(outcome.data, memoryId);
if (detail === null) {
const memory = sdkMemory(outcome.data);
if (memory === null || memory.memory_id !== memoryId) {
return {
schema_version: 1,
product: PRODUCT,
@@ -111,33 +108,9 @@ export async function readMemoryDetail(
return {
schema_version: 1,
product: PRODUCT,
memory: { state: "ok", ...describeMemory(detail.memory) },
evidence: (detail.evidence ?? []).map((item) => {
const budgeted = budget(item.verbatim ?? "");
return {
evidence_id: item.evidence_id,
available: item.available,
source_id: item.source_id,
written_by: item.written_by,
created_at: item.created_at,
excerpt: budgeted.text,
excerpt_truncated: budgeted.truncated,
excerpt_characters: budgeted.characters,
};
}),
history: (detail.history ?? []).map((item) => {
const content = budget(item.content);
return {
revision: item.revision,
action: item.action,
status: item.status,
scopes: item.scopes,
created_at: item.created_at,
content: content.text,
content_truncated: content.truncated,
content_characters: content.characters,
};
}),
memory: { state: "ok", ...describeMemory(memory) },
evidence: [],
history: [],
};
}
@@ -156,9 +129,7 @@ export function renderMemoryPageText(document: MemoryPageDocument): string {
];
for (const memory of document.memories) {
lines.push(
`- ${memory.memory_id} ${memory.status}/${memory.kind} rev ${memory.revision} scopes=${
(memory.scopes as string[]).join(",") || "无"
}`,
`- ${memory.memory_id} ${memory.status}/${memory.layer} source=${memory.source ?? "未知"}`,
` ${memory.content}${memory.content_truncated ? ` …(共 ${memory.content_characters} 字)` : ""}`,
);
}
@@ -177,54 +148,91 @@ export function renderMemoryDetailText(document: MemoryDetailDocument): string {
}
const lines = [
`记忆 ${memory.memory_id}`,
`状态:${memory.status} 类型:${memory.kind} 来源方式:${memory.origin} 版本:${memory.revision}`,
`授权范围:${(memory.scopes as string[]).join(",") || "无"}`,
`证据:${(memory.evidence_ids as string[]).join(",") || "无"}`,
`更新时间:${memory.updated_at}`,
`状态:${memory.status} 层:${memory.layer} 来源:${memory.source ?? "未知"}`,
`owner:${memory.owner ?? "未知"} latest:${memory.is_latest}`,
`raw IDs:${(memory.source_raw_ids as string[]).join(",") || "无"}`,
"",
String(memory.content),
memory.content_truncated ? `…(共 ${memory.content_characters} 字)` : "",
"",
"原文摘录:",
"SDK memory 数据不在 MemHub 中保留 Evidence/版本副本。",
];
for (const item of document.evidence) {
lines.push(
`- ${item.evidence_id} 来源=${item.source_id ?? "未知"} 作者=${item.written_by ?? "未知"} 可读=${item.available}`,
` ${item.excerpt}${item.excerpt_truncated ? ` …(共 ${item.excerpt_characters} 字)` : ""}`,
);
}
if (document.evidence.length === 0) lines.push("(无可读原文)");
lines.push("", "版本历史:");
for (const item of document.history) {
lines.push(
`- rev ${item.revision} ${item.action} ${item.status} scopes=${(item.scopes as string[]).join(",")}`,
` ${item.content}${item.content_truncated ? ` …(共 ${item.content_characters} 字)` : ""}`,
);
}
if (document.history.length === 0) lines.push("(无)");
lines.push("");
return lines.join("\n");
}
function describeMemory(memory: GovernedMemory): Record<string, unknown> {
function describeMemory(memory: SdkMemoryRecord): Record<string, unknown> {
const budgeted = budget(memory.content ?? "");
return {
memory_id: memory.memory_id,
status: memory.status,
kind: memory.kind,
origin: memory.origin,
revision: memory.revision,
scopes: memory.scopes ?? [],
evidence_ids: memory.evidence_ids ?? [],
layer: memory.layer,
is_latest: memory.is_latest,
owner: memory.owner,
source: memory.source,
source_raw_ids: memory.source_raw_ids,
supersedes: memory.supersedes,
superseded_by: memory.superseded_by,
tags: memory.tags ?? [],
created_at: memory.created_at,
updated_at: memory.updated_at,
memory_at: memory.memory_at,
gmt_created: memory.gmt_created,
content: budgeted.text,
content_truncated: budgeted.truncated,
content_characters: budgeted.characters,
};
}
function sdkMemoryPage(value: unknown): SdkMemoryPage | null {
if (!record(value) || !Array.isArray(value.memories)) return null;
const memories = value.memories.map(sdkMemory);
if (memories.some((item) => item === null)) return null;
if (!integer(value.total) || !integer(value.limit) || !integer(value.offset))
return null;
return {
memories: memories as SdkMemoryRecord[],
total: value.total,
limit: value.limit,
offset: value.offset,
};
}
function sdkMemory(value: unknown): SdkMemoryRecord | null {
if (
!record(value) ||
!text(value.memory_id) ||
typeof value.content !== "string" ||
!text(value.layer) ||
!text(value.status) ||
typeof value.is_latest !== "boolean" ||
!strings(value.supersedes) ||
!strings(value.superseded_by) ||
!strings(value.tags) ||
!strings(value.source_raw_ids) ||
!text(value.user_id) ||
!text(value.agent_id)
)
return null;
return value as unknown as SdkMemoryRecord;
}
function record(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function text(value: unknown): value is string {
return typeof value === "string" && value.length > 0;
}
function strings(value: unknown): value is string[] {
return (
Array.isArray(value) && value.every((item) => typeof item === "string")
);
}
function integer(value: unknown): value is number {
return Number.isInteger(value) && Number(value) >= 0;
}
function budget(value: string): {
text: string;
truncated: boolean;
@@ -1,154 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { run } from "./cli.js";
const transport = vi.hoisted(() => ({
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
patch: vi.fn(),
delete: vi.fn(),
}));
vi.mock("axios", () => ({
default: { create: vi.fn(() => transport), get: vi.fn() },
}));
const runtime = vi.hoisted(() => ({
inspectRuntimeStatus: vi.fn(),
discoverRuntimeAttachment: vi.fn(),
}));
vi.mock("@one-memory/runtime-control", async (importOriginal) => ({
...(await importOriginal<typeof import("@one-memory/runtime-control")>()),
...runtime,
}));
beforeEach(() => {
vi.clearAllMocks();
runtime.inspectRuntimeStatus.mockResolvedValue({
state: "running",
code: "runtime_verified",
instanceId: "instance-1",
host: "127.0.0.1",
port: 8765,
version: "1.2.3",
});
runtime.discoverRuntimeAttachment.mockResolvedValue({
instanceId: "instance-1",
apiToken: "synthetic-runtime-token",
host: "127.0.0.1",
port: 8765,
servicePid: 4242,
health: {
status: "ok",
service: "one-memory-core",
version: "1.2.3",
instance_id: "instance-1",
},
});
});
describe("model content permission CLI", () => {
it("documents only final-state permission and manual extraction commands", async () => {
const permission = await capturedRun(["help", "permission"]);
expect(permission.code).toBe(0);
expect(permission.stdout).toContain("memhub permission allow");
expect(permission.stdout).toContain("memhub permission deny");
expect(permission.stdout).not.toMatch(
/\b(preview|confirm|process|revoke)\b/,
);
expect(permission.stdout).not.toContain("revision");
expect(permission.stdout).not.toContain("receipt");
const processing = await capturedRun(["help", "processing"]);
expect(processing.code).toBe(0);
expect(processing.stdout).toContain("memhub processing extract");
expect(processing.stdout).not.toMatch(/\b(plan|apply|receipt)\b/);
expect(processing.stdout).not.toContain("backlog");
});
it("reads the final state", async () => {
transport.get.mockResolvedValue({ status: 200, data: { allowed: true } });
const result = await capturedRun(["permission", "status", "--json"]);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({
state: "ok",
allowed: true,
});
expect(transport.get).toHaveBeenCalledWith(
"/api/v1/model-content-permission",
undefined,
);
});
it.each([
["allow", true],
["deny", false],
] as const)("sets %s directly with only allowed", async (verb, allowed) => {
transport.post.mockResolvedValue({ status: 200, data: { allowed } });
const result = await capturedRun(["permission", verb, "--json"]);
expect(result.code).toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({ state: "ok", allowed });
expect(transport.post).toHaveBeenCalledWith(
"/api/v1/model-content-permission",
{ allowed },
undefined,
);
});
it.each(["preview", "confirm", "process", "revoke"])(
"rejects removed %s commands before runtime access",
async (verb) => {
const result = await capturedRun(["permission", verb, "--json"]);
expect(result.code).toBe(2);
expect(runtime.inspectRuntimeStatus).not.toHaveBeenCalled();
expect(transport.get).not.toHaveBeenCalled();
expect(transport.post).not.toHaveBeenCalled();
},
);
it.each(["plan", "apply", "receipt"])(
"rejects removed processing %s commands before runtime access",
async (verb) => {
const result = await capturedRun(["processing", verb, "--json"]);
expect(result.code).toBe(2);
expect(runtime.inspectRuntimeStatus).not.toHaveBeenCalled();
expect(transport.get).not.toHaveBeenCalled();
expect(transport.post).not.toHaveBeenCalled();
},
);
});
async function capturedRun(arguments_: string[]) {
let stdout = "";
let stderr = "";
const stdoutSpy = vi
.spyOn(process.stdout, "write")
.mockImplementation((chunk) => {
stdout += String(chunk);
return true;
});
const stderrSpy = vi
.spyOn(process.stderr, "write")
.mockImplementation((chunk) => {
stderr += String(chunk);
return true;
});
try {
return {
code: await run(arguments_, {
ONE_MEMORY_DATA_DIR: "/synthetic/data",
}),
stdout,
stderr,
};
} finally {
stdoutSpy.mockRestore();
stderrSpy.mockRestore();
}
}
@@ -1,66 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import type { CoreReader } from "./core-client.js";
import type { CoreOperations } from "./core-operations.js";
import {
readModelContentPermission,
setModelContentPermission,
} from "./model-content-permission-flow.js";
describe("model content permission flow", () => {
it("reads the single final-state boolean", async () => {
const reader = vi.fn().mockResolvedValue({
state: "ok",
data: { allowed: true },
});
await expect(
readModelContentPermission(reader as CoreReader),
).resolves.toMatchObject({ state: "ok", allowed: true });
expect(reader).toHaveBeenCalledWith("/api/v1/model-content-permission");
});
it.each([
["allow", true],
["deny", false],
] as const)(
"sets %s directly without revision or receipt fields",
async (_, allowed) => {
const post = vi.fn().mockResolvedValue({
state: "committed",
data: { allowed },
});
await expect(
setModelContentPermission({ post } as CoreOperations, allowed),
).resolves.toMatchObject({ state: "ok", allowed });
expect(post).toHaveBeenCalledWith("/api/v1/model-content-permission", {
allowed,
});
},
);
it("does not accept a malformed or mismatched success response", async () => {
const malformed = vi.fn().mockResolvedValue({
state: "committed",
data: { allowed: true, revision: 1 },
});
await expect(
setModelContentPermission({ post: malformed } as CoreOperations, true),
).resolves.toMatchObject({
state: "unknown",
code: "model_content_permission_response_invalid",
});
const mismatched = vi.fn().mockResolvedValue({
state: "committed",
data: { allowed: false },
});
await expect(
setModelContentPermission({ post: mismatched } as CoreOperations, true),
).resolves.toMatchObject({
state: "unknown",
code: "model_content_permission_state_mismatch",
});
});
});
@@ -1,96 +0,0 @@
import type { CoreReader } from "./core-client.js";
import type { CoreOperations } from "./core-operations.js";
import { PRODUCT } from "./version.js";
export type ModelContentPermissionDocument =
| {
schema_version: 1;
product: string;
state: "ok";
allowed: boolean;
}
| {
schema_version: 1;
product: string;
state: "rejected" | "unknown";
code: string;
};
export async function readModelContentPermission(
reader: CoreReader,
): Promise<ModelContentPermissionDocument> {
const outcome = await reader<unknown>("/api/v1/model-content-permission");
if (outcome.state !== "ok") {
return failure("unknown", outcome.code);
}
return permissionState(
outcome.data,
"model_content_permission_response_invalid",
);
}
export async function setModelContentPermission(
operations: CoreOperations,
allowed: boolean,
): Promise<ModelContentPermissionDocument> {
const outcome = await operations.post<unknown>(
"/api/v1/model-content-permission",
{ allowed },
);
if (outcome.state === "rejected") {
return failure("rejected", outcome.code);
}
if (outcome.state === "unknown") {
return failure("unknown", outcome.code);
}
const document = permissionState(
outcome.data,
"model_content_permission_response_invalid",
);
return document.state === "ok" && document.allowed !== allowed
? failure("unknown", "model_content_permission_state_mismatch")
: document;
}
export function modelContentPermissionExitCode(
document: ModelContentPermissionDocument,
): number {
return document.state === "ok" ? 0 : 1;
}
export function renderModelContentPermissionText(
document: ModelContentPermissionDocument,
): string {
if (document.state === "ok") {
return `模型内容外发:${document.allowed ? "允许" : "禁止"}\n`;
}
return `模型内容权限未更新:${document.state}(${document.code})\n`;
}
function permissionState(
value: unknown,
invalidCode: string,
): ModelContentPermissionDocument {
if (
value === null ||
typeof value !== "object" ||
Array.isArray(value) ||
Object.keys(value).length !== 1 ||
typeof (value as Record<string, unknown>).allowed !== "boolean"
) {
return failure("unknown", invalidCode);
}
return {
schema_version: 1,
product: PRODUCT,
state: "ok",
allowed: (value as { allowed: boolean }).allowed,
};
}
function failure(
state: "rejected" | "unknown",
code: string,
): ModelContentPermissionDocument {
return { schema_version: 1, product: PRODUCT, state, code };
}
+11 -16
View File
@@ -122,7 +122,9 @@ describe("package matrix harness", () => {
process.execPath,
[script, runtimeDist, "--stopped-commands", "--json"],
{ env: isolatedEnv },
);
).catch((error: { stdout?: string; stderr?: string }) => {
throw new Error(`${error.stdout ?? ""}\n${error.stderr ?? ""}`);
});
const document = JSON.parse(positive.stdout) as {
state: string;
commands: {
@@ -137,8 +139,8 @@ describe("package matrix harness", () => {
};
expect(document.state).toBe("verified");
const results = document.commands.stopped_destructive.results;
// 13 destructive commands, each unknown/runtime_not_running with exit 3.
expect(Object.keys(results)).toHaveLength(13);
// Every destructive command fails closed while Runtime is stopped.
expect(Object.keys(results)).toHaveLength(7);
for (const [name, result] of Object.entries(results)) {
expect(result, `${name} did not fail closed`).toEqual({
exit: 3,
@@ -162,7 +164,7 @@ describe("package matrix harness", () => {
const shim = [
"#!/usr/bin/env node",
"const a=process.argv.slice(2);",
"if(['calls','import-file','notes','permission','extraction','graph','models'].includes(a[0])||(a[0]==='processing'&&a[1]==='extract')){",
"if(['calls','notes','graph','models','memories'].includes(a[0])){",
' process.stdout.write(\'{"schema_version":1,"product":"memhub","state":"committed","operation_id":"x","receipt":{}}\\n\');',
" process.exit(0);",
"}",
@@ -188,7 +190,7 @@ describe("package matrix harness", () => {
expect(failure?.state).toBe("failed");
expect(
failure?.failures.filter((item) => item.includes("did not fail closed")),
).toHaveLength(13);
).toHaveLength(7);
});
it("can require an expected bundle SHA and reports bundle metadata", {
@@ -280,20 +282,17 @@ describe("package matrix harness", () => {
});
it("rejects a catalog that declares the parent command but not the new verb", async () => {
// A bundle can still declare `permission`/`models` while missing
// `permission allow` or `models activate`. Names alone would pass it; the
// usage marker must not.
// A bundle can still declare `models` while missing `models activate`.
// Names alone would pass it; the usage marker must not.
const declared = [
"install",
"init",
"sources",
"sync",
"memories",
"profile",
"calls",
"import-file",
"notes",
"permission",
"extraction",
"graph",
"models",
"host",
@@ -316,7 +315,6 @@ describe("package matrix harness", () => {
"scan",
"progress",
"jobs",
"processing",
"path",
"adapter",
"write",
@@ -342,14 +340,11 @@ describe("package matrix harness", () => {
},
};
const failures = harness.validateCatalog(catalog);
expect(failures).toContain(
'command "permission" is missing usage "memhub permission allow"',
);
expect(failures).toContain(
'command "models" is missing usage "memhub models activate"',
);
expect(failures).toContain(
'command "import-file" is missing usage "memhub import-file discard"',
'command "memories" is missing usage "memhub memories update"',
);
expect(failures).toContain(
'command "jobs" is missing usage "memhub jobs start"',
@@ -146,23 +146,22 @@ describe("memhub short-command contract", () => {
).join("\n");
for (const shortForm of [
"memhub calls clear",
"memhub import-file upload",
"memhub import-file commit",
"memhub import-file discard",
"memhub notes add",
"memhub notes process",
"memhub permission status",
"memhub permission allow",
"memhub permission deny",
"memhub models setup",
"memhub models activate",
"memhub models edit",
"memhub extraction set",
"memhub graph width",
"memhub processing extract",
"memhub write submit",
"memhub write status",
"memhub memories update",
"memhub memories delete",
]) {
expect(flattened).toContain(shortForm);
}
expect(COMMANDS.some((command) => command.name === "permission")).toBe(
false,
);
});
it("ships a memhub bin entry pointing at a real bundle path", () => {
+54 -54
View File
@@ -6,6 +6,7 @@
import { describe, expect, it } from "vitest";
import { parseOpenAIMessages } from "./core-client.js";
import {
asPlanDocument,
describe as describePlan,
@@ -259,93 +260,92 @@ describe("unknown flags are rejected", () => {
describe("write", () => {
const base = [
"submit",
"--session",
"s1",
"--from",
"1",
"--to",
"5",
"--evidence",
"e1",
"--messages-file",
"/tmp/messages.json",
];
it("accepts a well-formed write", () => {
const parsed = parseWriteCommand(base);
expect(parsed).toEqual({
kind: "submit",
session: "s1",
first_round: 1,
last_round: 5,
evidence_ids: ["e1"],
source: "memhub-cli",
messages_file: "/tmp/messages.json",
});
});
it("rejects a write with no evidence", () => {
expect(
parseWriteCommand(["--session", "s1", "--from", "1", "--to", "5"]),
).toBeNull();
it("rejects a write with no messages file", () => {
expect(parseWriteCommand(["submit", "--session", "s1"])).toBeNull();
});
it("rejects a descending round range", () => {
it("accepts source, request identity, and RFC3339 time", () => {
expect(
parseWriteCommand([
"--session",
"s1",
"--from",
"5",
"--to",
"1",
"--evidence",
"e1",
...base,
"--source",
"cursor",
"--request-id",
"request-1",
"--memory-at",
"2026-10-22T00:00:00+08:00",
]),
).toBeNull();
).toMatchObject({
source: "cursor",
request_id: "request-1",
memory_at: "2026-10-22T00:00:00+08:00",
});
});
it("rejects a round starting below one", () => {
it("rejects a timestamp without timezone", () => {
expect(
parseWriteCommand([
"--session",
"s1",
"--from",
"0",
"--to",
"5",
"--evidence",
"e1",
]),
parseWriteCommand([...base, "--memory-at", "2026-10-22T00:00:00"]),
).toBeNull();
});
it("rejects a non-integer round", () => {
expect(
parseWriteCommand([
"--session",
"s1",
"--from",
"x",
"--to",
"5",
"--evidence",
"e1",
]),
).toBeNull();
});
it("accepts several evidence ids", () => {
const parsed = parseWriteCommand([...base, "--evidence", "e2"]);
expect(parsed?.evidence_ids).toEqual(["e1", "e2"]);
it("parses status under write", () => {
expect(parseWriteCommand(["status", "--id", "request-1"])).toEqual({
kind: "status",
id: "request-1",
});
});
it("marks --live as priority live", () => {
expect(parseWriteCommand([...base, "--live"])?.priority).toBe("live");
expect(parseWriteCommand([...base, "--live"])).toMatchObject({
kind: "submit",
priority: "live",
});
});
it("leaves priority unset by default", () => {
expect(parseWriteCommand(base)?.priority).toBeUndefined();
expect(parseWriteCommand(base)).not.toHaveProperty("priority");
});
it("rejects a repeated --json", () => {
expect(parseWriteCommand([...base, "--json", "--json"])).toBeNull();
});
it("validates OpenAI text messages and requires a user turn", () => {
expect(
parseOpenAIMessages({
messages: [
{ role: "user", content: "Remember Tuesday." },
{ role: "assistant", content: "Understood.", ignored: true },
],
}),
).toEqual([
{ role: "user", content: "Remember Tuesday." },
{ role: "assistant", content: "Understood." },
]);
expect(
parseOpenAIMessages([{ role: "assistant", content: "No user turn." }]),
).toBeNull();
expect(
parseOpenAIMessages([{ role: "system", content: "Hidden prompt." }]),
).toBeNull();
});
});
describe("task", () => {
+44 -23
View File
@@ -255,52 +255,73 @@ export function restoreConfirmationMatches(
return confirmPath === source;
}
export interface WriteCommand {
export interface WriteSubmitCommand {
readonly kind: "submit";
readonly session: string;
readonly first_round: number;
readonly last_round: number;
readonly evidence_ids: readonly string[];
readonly source: string;
readonly messages_file: string;
readonly request_id?: string;
readonly memory_at?: string;
readonly priority?: "live" | "normal";
}
/** Parse `write`. Evidence is required: no write without something to cite. */
export interface WriteStatusCommand {
readonly kind: "status";
readonly id: string;
}
export type WriteCommand = WriteSubmitCommand | WriteStatusCommand;
/** Parse SDK-native `write submit|status`. */
export function parseWriteCommand(
args: readonly string[],
): WriteCommand | null {
if (args.filter((item) => item === "--json").length > 1) return null;
const meaningful = args.filter((item) => item !== "--json");
if (meaningful[0] === "status") {
const status = parseTaskCommand(meaningful.slice(1));
return status === null ? null : { kind: "status", id: status.id };
}
const input = meaningful[0] === "submit" ? meaningful.slice(1) : meaningful;
let session: string | undefined;
let first: number | undefined;
let last: number | undefined;
let source = "memhub-cli";
let messagesFile: string | undefined;
let requestId: string | undefined;
let memoryAt: string | undefined;
let priority: "live" | "normal" | undefined;
const evidence: string[] = [];
for (let index = 0; index < args.length; index += 1) {
const arg = args[index];
if (arg === "--json") continue;
for (let index = 0; index < input.length; index += 1) {
const arg = input[index];
if (arg === "--live") {
priority = "live";
continue;
}
const value = args[index + 1];
const value = input[index + 1];
if (value === undefined || value.startsWith("--")) return null;
index += 1;
if (arg === "--session") session = value;
else if (arg === "--from") first = Number(value);
else if (arg === "--to") last = Number(value);
else if (arg === "--evidence") evidence.push(value);
else if (arg === "--source") source = value;
else if (arg === "--messages-file") messagesFile = value;
else if (arg === "--request-id") requestId = value;
else if (arg === "--memory-at") memoryAt = value;
else return null;
}
if (session === undefined || first === undefined || last === undefined)
if (session === undefined || messagesFile === undefined || !source)
return null;
if (!Number.isInteger(first) || first < 1) return null;
if (!Number.isInteger(last) || last < first) return null;
if (evidence.length === 0) return null;
const command: WriteCommand = {
if (
memoryAt !== undefined &&
(!Number.isFinite(Date.parse(memoryAt)) ||
!/(?:Z|[+-]\d\d:\d\d)$/.test(memoryAt))
)
return null;
const command: WriteSubmitCommand = {
kind: "submit",
session,
first_round: first,
last_round: last,
evidence_ids: evidence,
source,
messages_file: messagesFile,
...(requestId === undefined ? {} : { request_id: requestId }),
...(memoryAt === undefined ? {} : { memory_at: memoryAt }),
};
return priority === undefined ? command : { ...command, priority };
}
+6 -1
View File
@@ -48,7 +48,11 @@ describe("publish manifest is production-safe", () => {
execFileSync("node", ["scripts/prepare-publish-manifest.mjs"], {
cwd: root,
stdio: "pipe",
env: { ...process.env, MEMHUB_NPM_PACKAGE: "@example/memhub-cli" },
env: {
...process.env,
MEMHUB_NPM_PACKAGE: "@example/memhub-cli",
MEMHUB_NPM_VERSION: "1.0.5",
},
});
const published = JSON.parse(
readFileSync(path.join(root, "dist-publish", "package.json"), "utf8"),
@@ -56,6 +60,7 @@ describe("publish manifest is production-safe", () => {
expect(published.dependencies).toBeUndefined();
expect(published.private).toBe(false);
expect(published.name).toBe("@example/memhub-cli");
expect(published.version).toBe("1.0.5");
expect(published.bin).toMatchObject({
memhub: "dist/one-memory.cjs",
"memhub-cli": "dist/one-memory.cjs",
+76 -77
View File
@@ -197,6 +197,9 @@ const READ_ONLY_PATHS = [
"/api/v1/home-summary",
"/api/v1/memory-library",
"/api/v1/memories/",
"/api/v2/memory-library",
"/api/v2/memories/",
"/api/v2/user-profile",
];
const BACKGROUND_HEALTHY = {
@@ -562,6 +565,43 @@ describe("CLI-20 status summary", () => {
});
});
describe("SDK user profile", () => {
it("prints the assembled long-term profile from the v2 endpoint", async () => {
transport.get.mockImplementation(async (url: string) =>
url === "/api/v2/user-profile"
? {
status: 200,
data: {
request_id: "profile-request",
profile: {
memory_id: "l0-head",
content: "name is Alice",
layer: "L0_BASIC_INFO",
basic_info: { name: "Alice" },
},
elapsed_ms: 1.2,
},
}
: { status: 404, data: {} },
);
const streams = captureStreams();
try {
expect(await run(["profile", "--json"], {})).toBe(0);
} finally {
streams.restore();
}
expect(transport.get).toHaveBeenCalledWith(
"/api/v2/user-profile",
undefined,
);
expect(JSON.parse(streams.stdout())).toMatchObject({
schema_version: 2,
state: "ok",
profile: { memory_id: "l0-head", content: "name is Alice" },
});
});
});
describe("CLI-21 memory reads", () => {
it("keeps memory reads open long enough for a busy Core and explains failure", async () => {
const axios = (await import("axios")).default as unknown as {
@@ -610,14 +650,14 @@ describe("CLI-21 memory reads", () => {
it("lists a page and states truthfully that more remains", async () => {
transport.get.mockImplementation(async (url: string) => {
if (url !== "/api/v1/memory-library") return { status: 404, data: {} };
if (url !== "/api/v2/memory-library") return { status: 404, data: {} };
return {
status: 200,
data: {
total: 12,
offset: 0,
limit: 2,
items: [memory("m1", "第一条记忆"), memory("m2", "x".repeat(400))],
memories: [memory("m1", "第一条记忆"), memory("m2", "x".repeat(400))],
},
};
});
@@ -640,10 +680,8 @@ describe("CLI-21 memory reads", () => {
});
expect(report.memories[0]).toMatchObject({
memory_id: "m1",
status: "confirmed",
revision: 3,
scopes: ["all-apps"],
evidence_ids: ["e1"],
status: "active",
layer: "L2_FACT",
content_truncated: false,
});
expect(report.memories[1]).toMatchObject({
@@ -658,12 +696,8 @@ describe("CLI-21 memory reads", () => {
[
"memories",
"list",
"--query",
"部署",
"--status",
"confirmed",
"--source",
"codex",
"active",
"--offset",
"10",
"--limit",
@@ -672,30 +706,23 @@ describe("CLI-21 memory reads", () => {
],
{},
).catch(() => undefined);
expect(transport.get).toHaveBeenCalledWith("/api/v1/memory-library", {
expect(transport.get).toHaveBeenCalledWith("/api/v2/memory-library", {
params: {
query: "部署",
status: "confirmed",
source: "codex",
statuses: "active",
offset: 10,
limit: 5,
},
});
});
it("reads a sensitive query from a file so it stays out of shell history", async () => {
it("rejects retired memory query flags before calling Core", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "om-cli-query-"));
const file = path.join(directory, "query.txt");
await writeFile(file, "机密查询\n", { mode: 0o600 });
await run(["memories", "list", "--query-file", file, "--json"], {}).catch(
() => undefined,
);
expect(transport.get).toHaveBeenCalledWith(
"/api/v1/memory-library",
expect.objectContaining({
params: expect.objectContaining({ query: "机密查询" }),
}),
);
expect(
await run(["memories", "list", "--query-file", file, "--json"], {}),
).toBe(2);
expect(transport.get).not.toHaveBeenCalled();
});
it("rejects contradictory or unreadable query input before calling Core", async () => {
@@ -705,7 +732,7 @@ describe("CLI-21 memory reads", () => {
["memories", "list", "--limit", "0"],
["memories", "list", "--limit", "501"],
["memories", "list", "--offset", "-1"],
["memories", "list", "--status", "unknown-status"],
["memories", "list", "--status", ""],
["memories", "show"],
["memories"],
]) {
@@ -723,7 +750,7 @@ describe("CLI-21 memory reads", () => {
it("distinguishes an empty page from a denied or missing one", async () => {
transport.get.mockResolvedValue({
status: 200,
data: { total: 0, offset: 0, limit: 100, items: [] },
data: { total: 0, offset: 0, limit: 100, memories: [] },
});
const empty = captureStreams();
try {
@@ -763,33 +790,10 @@ describe("CLI-21 memory reads", () => {
});
});
it("shows one memory with its source, version and evidence", async () => {
it("shows one SDK memory without fabricated Evidence or versions", async () => {
transport.get.mockResolvedValue({
status: 200,
data: {
memory: memory("m1", "记忆正文"),
evidence: [
{
evidence_id: "e1",
available: true,
source_id: "codex",
written_by: "user",
created_at: "T",
verbatim: "y".repeat(500),
},
],
history: [
{
memory_id: "m1",
revision: 3,
action: "correct",
status: "confirmed",
content: "记忆正文",
scopes: ["all-apps"],
created_at: "T",
},
],
},
data: memory("m1", "记忆正文"),
});
const streams = captureStreams();
try {
@@ -799,28 +803,17 @@ describe("CLI-21 memory reads", () => {
}
const report = JSON.parse(streams.stdout());
expect(transport.get).toHaveBeenCalledWith(
"/api/v1/memories/m1",
"/api/v2/memories/m1",
undefined,
);
expect(report.memory).toMatchObject({
state: "ok",
memory_id: "m1",
revision: 3,
scopes: ["all-apps"],
});
expect(report.evidence[0]).toMatchObject({
evidence_id: "e1",
source_id: "codex",
excerpt_truncated: true,
excerpt_characters: 500,
});
expect(report.history[0]).toMatchObject({
revision: 3,
action: "correct",
status: "confirmed",
scopes: ["all-apps"],
content: "记忆正文",
layer: "L2_FACT",
status: "active",
});
expect(report.evidence).toEqual([]);
expect(report.history).toEqual([]);
});
// Core registers /api/v1/memories/graph before /{memory_id}, and that static
@@ -840,6 +833,9 @@ describe("CLI-21 memory reads", () => {
expect(isReadOnlyPath("/api/v1/memories/graph")).toBe(false);
expect(isReadOnlyPath("/api/v1/memories/ask")).toBe(false);
expect(isReadOnlyPath("/api/v1/memories/m1")).toBe(true);
expect(isReadOnlyPath("/api/v2/memory-library")).toBe(true);
expect(isReadOnlyPath("/api/v2/memories/m1")).toBe(true);
expect(isReadOnlyPath("/api/v1/model-content-permission")).toBe(false);
expect(
isReadOnlyPath(
"/api/v1/memory-mutations/123e4567-e89b-12d3-a456-426614174000",
@@ -1136,17 +1132,20 @@ function memory(id: string, content: string) {
return {
memory_id: id,
user_id: "local",
kind: "chat",
status: "confirmed",
agent_id: "one-memory",
layer: "L2_FACT",
status: "active",
is_latest: true,
supersedes: [],
superseded_by: [],
content,
scopes: ["all-apps"],
evidence_ids: ["e1"],
origin: "extracted",
tags: [],
revision: 3,
created_at: "T",
updated_at: "T",
deleted_at: null,
owner: "user",
source_raw_ids: ["raw-1"],
session_id: "s1",
source: "codex",
memory_at: null,
gmt_created: null,
};
}
+3 -3
View File
@@ -160,7 +160,7 @@ describe("calls clear", () => {
});
});
describe("import-file", () => {
describe.skip("retired import-file", () => {
it("never uploads without --confirm", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "om-import-"));
const file = path.join(directory, "export.json");
@@ -356,7 +356,7 @@ describe("notes / extraction / graph / manual extract", () => {
expect(JSON.parse(applied.stdout).state).toBe("committed");
});
it("plans then applies the extraction window", async () => {
it.skip("plans then applies the extraction window", async () => {
const preview = await capturedRun([
"extraction",
"set",
@@ -417,7 +417,7 @@ describe("notes / extraction / graph / manual extract", () => {
);
});
it("plans manual extraction and applies it only on confirm", async () => {
it.skip("plans manual extraction and applies it only on confirm", async () => {
const preview = await capturedRun([
"processing",
"extract",
+15 -6
View File
@@ -1,5 +1,9 @@
declare const __ONE_MEMORY_VERSION__: string;
declare const __ONE_MEMORY_BUILD_NUMBER__: string;
declare const __MEMHUB_DEFAULT_RUNTIME_VERSION__: string;
const SEMVER =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
const embeddedVersion =
typeof __ONE_MEMORY_VERSION__ === "string"
@@ -9,13 +13,18 @@ const embeddedBuildNumber =
typeof __ONE_MEMORY_BUILD_NUMBER__ === "string"
? __ONE_MEMORY_BUILD_NUMBER__.trim()
: "";
const embeddedRuntimeVersion =
typeof __MEMHUB_DEFAULT_RUNTIME_VERSION__ === "string"
? __MEMHUB_DEFAULT_RUNTIME_VERSION__.trim()
: "";
export const CLI_VERSION =
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(
embeddedVersion,
)
? embeddedVersion
: "development";
export const CLI_VERSION = SEMVER.test(embeddedVersion)
? embeddedVersion
: "development";
export const RUNTIME_RELEASE_VERSION = SEMVER.test(embeddedRuntimeVersion)
? embeddedRuntimeVersion
: CLI_VERSION;
export const CLI_BUILD_NUMBER = /^\d+$/.test(embeddedBuildNumber)
? Number(embeddedBuildNumber)
+17 -2
View File
@@ -2,11 +2,22 @@ import { createRequire } from "node:module";
import { defineConfig } from "tsup";
const require = createRequire(import.meta.url);
const { resolveBuildVersion } =
const { assertSemver, resolveBuildVersion } =
require("../../scripts/release-version.cjs") as {
assertSemver(value: string, label?: string): string;
resolveBuildVersion(environment?: NodeJS.ProcessEnv, root?: string): string;
};
const releaseVersion = resolveBuildVersion(process.env);
const packageVersion = (require("./package.json") as { version: string })
.version;
const cliVersion = assertSemver(
process.env.MEMHUB_NPM_VERSION?.trim() || packageVersion,
"MEMHUB_NPM_VERSION",
);
const runtimeReleaseVersion = assertSemver(
process.env.MEMHUB_DEFAULT_RUNTIME_VERSION?.trim() || releaseVersion,
"MEMHUB_DEFAULT_RUNTIME_VERSION",
);
export default defineConfig({
entry: { "one-memory": "src/entry.ts" },
@@ -15,7 +26,7 @@ export default defineConfig({
outDir: "dist",
clean: true,
define: {
__ONE_MEMORY_VERSION__: JSON.stringify(releaseVersion),
__ONE_MEMORY_VERSION__: JSON.stringify(cliVersion),
__ONE_MEMORY_BUILD_NUMBER__: JSON.stringify(
process.env.ONE_MEMORY_BUILD_NUMBER ?? "unknown",
),
@@ -25,11 +36,15 @@ export default defineConfig({
__MEMHUB_DEFAULT_RELEASE_MANIFEST_URL_TEMPLATE__: JSON.stringify(
process.env.MEMHUB_DEFAULT_RELEASE_MANIFEST_URL_TEMPLATE ?? "",
),
__MEMHUB_DEFAULT_RUNTIME_VERSION__: JSON.stringify(runtimeReleaseVersion),
},
// The shared operations package ships TypeScript sources, so it must be
// inlined into the CJS bundle the same way runtime-control is; otherwise the
// emitted bundle tries to `require` a `.js` file that only exists as `.ts`.
// `@one-memory/contracts` is the same kind of package and is imported for a
// value (the host-id grammar), so it has to be inlined too.
noExternal: [
"@one-memory/contracts",
"@one-memory/operations",
"@one-memory/runtime-control",
"axios",
+1
View File
@@ -11,6 +11,7 @@ export default defineConfig({
__ONE_MEMORY_BUILD_NUMBER__: JSON.stringify("unknown"),
__ONE_MEMORY_COMMIT__: JSON.stringify("unknown"),
__MEMHUB_DEFAULT_RELEASE_MANIFEST_URL_TEMPLATE__: JSON.stringify(""),
__MEMHUB_DEFAULT_RUNTIME_VERSION__: JSON.stringify(version),
},
test: {
testTimeout: 120_000,
+1 -1
View File
@@ -11,7 +11,7 @@ folder_layout = layout == 'folder'
datas = [('src/one_memory/embedding_assets', 'one_memory/embedding_assets')]
binaries = []
# Loaded lazily by the API; static dependency analysis cannot discover it.
hiddenimports = ['one_memory.hy_permission_context']
hiddenimports = []
tmp_ret = collect_all('hy_memory')
datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2]
tmp_ret = collect_all('chromadb')
+4 -3
View File
@@ -4,7 +4,7 @@ build-backend = "uv_build"
[project]
name = "one-memory"
version = "1.0.1"
version = "1.0.5"
description = "MemHub local-first memory core"
readme = "README.md"
requires-python = ">=3.12"
@@ -12,8 +12,9 @@ dependencies = [
"fastapi>=0.141.1",
"filelock>=3.32.4",
# Public SDK version validated against MemHub's permission and recall contracts.
"hy-memory==2.0.2",
# Retrieval's derived vector index directly consumes these locked versions.
"hy-memory==2.0.5",
# chromadb arrives through the HY SDK; locked here so an unrelated upgrade
# cannot move the SDK's store. Built-in embedding consumes numpy directly.
"chromadb==1.5.9",
"numpy==2.5.2",
"httpx>=0.28.1",
@@ -42,12 +42,10 @@ TARGETED = (
"tests/test_database_contention.py",
"tests/test_main_database_fairness.py",
"tests/test_soak_probe_effectiveness.py",
"tests/test_evidence_reconcile_primitive.py",
"tests/test_sqlite_semantics_gate.py",
"tests/test_store_binding.py",
"tests/test_store_binding_ratchet.py",
"tests/test_main_database_entry.py",
"tests/test_memory_processing.py",
"tests/test_extraction_window.py",
"tests/test_extraction_defer.py",
"tests/test_active_memory_window.py",
@@ -2,11 +2,5 @@
import os
from one_memory.hy_runtime_config import configure_hy_behavior_environment
# HY has a few reader switches evaluated at module import time. Fix the
# product-owned, non-secret behavior before any one_memory module imports HY.
configure_hy_behavior_environment()
_version = os.environ.get("ONE_MEMORY_VERSION", "").strip()
__version__ = _version if _version else "development"
File diff suppressed because it is too large. Load diff
+10 -1
View File
@@ -1,4 +1,5 @@
import hmac
import ipaddress
from collections.abc import Callable
from urllib.parse import urlsplit
@@ -35,7 +36,15 @@ def is_loopback_origin(origin: str) -> bool:
host = parsed.hostname
if not host:
return False
return host in LOOPBACK_HOSTNAMES or host.startswith("127.")
if host in LOOPBACK_HOSTNAMES:
return True
# A prefix check is not enough: "127.attacker.example" is a perfectly valid
# DNS name that resolves wherever its owner wants (including 127.0.0.1 via
# DNS rebinding). Parse the address and ask the standard library.
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False
def local_api_guard(
@@ -175,6 +175,22 @@ async def in_interactive_read[T](
return await in_read_pool(interactive_read_pool(), work, *args, **kwargs)
def _retrieve[T](future: "asyncio.Future[T]") -> None:
"""Mark a shielded read's outcome as seen.
`in_read_pool` shields the wrapped worker, so a caller that gives up and
cancels leaves the read running to completion. When that read then fails,
nothing awaits the future any more: asyncio reports the orphan at GC as
"Future exception was never retrieved", the loop handler turns it into a
`core.loop.task_exception` error diagnostic, and a lane that degraded on
its own budget -- correctly, and already reported -- looks like a crashed
task on top of it. Retrieving here keeps the diagnostics honest. Awaiting
still raises for callers that are still there, so no failure is hidden.
"""
if not future.cancelled():
future.exception()
async def in_read_pool[T](
pool: ThreadPoolExecutor,
work: Callable[..., T],
@@ -193,7 +209,9 @@ async def in_read_pool[T](
_interactive_reads -= 1
worker.add_done_callback(released)
return await asyncio.shield(asyncio.wrap_future(worker))
pending = asyncio.wrap_future(worker)
pending.add_done_callback(_retrieve)
return await asyncio.shield(pending)
async def wait_for_interactive_reads() -> None:
@@ -76,8 +76,7 @@ def _memory(db: sqlite3.Connection, reference: CallReference) -> SourceRecordRef
if row["status"] == "deleted" or row["deleted_at"] is not None:
return _hidden(reference)
# Same local revocation/ownership predicate as SourceReadAccess.memories,
# evaluated BEFORE freshness (which can read support text), in this snapshot.
# Same local revocation/ownership predicate as SourceReadAccess.memories.
# Its public methods open their own connections, so cannot be used here.
access = db.execute(
"SELECT EXISTS (SELECT 1 FROM governed_memory_evidence "
@@ -121,8 +120,8 @@ def resolve_call_references(database_path: Path, event: CallEvent) -> list[Sourc
Local-owner only: event host attribution is NOT authorization. Explicit local
source revocations deny access; absent grants retain legacy local semantics.
A memory needs at least one accessible active citation. No proof preserves
shared freshness compatibility, not a claim of verified historical freshness.
A memory needs at least one accessible active citation. Evidence freshness
proofs are retired and do not affect availability.
Any read/parse/budget failure raises a fixed whole-request error, never a
partial result or per-item deletion. The route owner must map this separately
+256 -11
View File
@@ -29,13 +29,51 @@ def _end_by(seconds: str | None) -> None:
if __name__ == "__main__" and sys.argv[1:2] == ["capture"]:
_end_by(os.environ.get("ONE_MEMORY_CAPTURE_DEADLINE_S"))
import errno # noqa: E402
import json # noqa: E402
from collections.abc import Sequence # noqa: E402
import re # noqa: E402
from collections.abc import Iterator, Sequence # noqa: E402
from typing import TextIO # noqa: E402
from one_memory.config import load_settings # noqa: E402
from one_memory.runtime_client import RuntimeStatus, inspect_runtime # noqa: E402
# The startup dialog can only act on the name it is given: running out of disk
# and a damaged backup are different next steps. These are the names that reach
# it.
_SAFE_MIGRATION_CODE = re.compile(r"^[a-z][a-z0-9_]{0,95}$")
_OUT_OF_SPACE = frozenset({errno.ENOSPC, getattr(errno, "EDQUOT", errno.ENOSPC)})
def _exception_chain(error: BaseException) -> Iterator[BaseException]:
seen: set[int] = set()
current: BaseException | None = error
while current is not None and id(current) not in seen:
seen.add(id(current))
yield current
current = current.__cause__ or current.__context__
def migration_failure_code(
error: BaseException, *, fallback: str = "sdk_migration_preflight_failed"
) -> str:
"""Name a migration failure; never guess a code from free text.
Errs toward the caller's generic code: an exception this does not recognize
keeps its message out of the document Desktop reads.
"""
chain = list(_exception_chain(error))
for item in chain:
if isinstance(item, OSError) and item.errno in _OUT_OF_SPACE:
return "sdk_migration_disk_space_insufficient"
for item in chain:
code = getattr(item, "code", "")
if not isinstance(code, str) or not _SAFE_MIGRATION_CODE.match(code):
continue
if code.startswith(("sdk_data_plane_", "sdk_migration_")):
return code
return fallback
def main() -> None:
if sys.argv[1:] == ["--keychain-read"]:
@@ -75,6 +113,10 @@ def run(arguments: Sequence[str], *, output: TextIO | None = None) -> int:
command, *options = arguments
if command == "restore":
return restore(options, stream)
if command == "sdk-migrate":
return sdk_migrate(options, stream)
if command == "sdk-migration-status":
return sdk_migration_status(options, stream)
if command == "boundary" and not options:
from one_memory.workbuddy_boundary import write_hook
@@ -95,6 +137,8 @@ def run(arguments: Sequence[str], *, output: TextIO | None = None) -> int:
stream.write(
"Usage: one-memory [serve [--maintenance|--reader]|status [--json]|doctor [--json]"
"|restore --source <managed-backup> --yes [--json]"
"|sdk-migrate --runtime-build <build> --yes [--json]"
"|sdk-migration-status [--json]"
"|boundary [--peek|--ack TOKEN]|capture SOURCE]\n"
)
return 2
@@ -139,8 +183,6 @@ def restore(options: Sequence[str], stream: TextIO) -> int:
return 2
settings = load_settings()
from one_memory.managed_restore import RestoreRejected, restore_managed_backup
status = inspect_runtime(settings.data_dir)
if status.state != "stopped":
document = {
@@ -160,8 +202,48 @@ def restore(options: Sequence[str], stream: TextIO) -> int:
}
_write_restore(stream, as_json, document, "预览通过;加 --yes 才会覆盖当前数据库。")
return 4
from one_memory.managed_restore import RestoreRejected, restore_managed_backup
from one_memory.sdk_migration_bundle import (
MigrationBundleRejected,
restore_sdk_migration_bundle,
)
is_sdk_bundle = source.endswith(".sdk-bundle")
if is_sdk_bundle:
try:
sdk_result = restore_sdk_migration_bundle(
data_dir=settings.data_dir,
source=source,
runtime_stopped=True,
)
except MigrationBundleRejected as error:
document = {
"schema_version": 1,
"state": "failed",
"code": error.code,
}
_write_restore(stream, as_json, document, f"恢复失败:{error.code}")
return 1
document = {
"schema_version": 1,
"state": "restored",
"bundle_id": sdk_result.bundle_id,
"restored_files": sdk_result.restored_files,
"restored_bytes": sdk_result.restored_bytes,
"previous_database_path": str(sdk_result.previous_database_path),
"previous_sdk_root": (
str(sdk_result.previous_sdk_root) if sdk_result.previous_sdk_root else None
),
}
_write_restore(
stream,
as_json,
document,
f"已恢复完整迁移备份:{sdk_result.bundle_id}。",
)
return 0
try:
result = restore_managed_backup(data_dir=settings.data_dir, source=source)
managed_result = restore_managed_backup(data_dir=settings.data_dir, source=source)
except RestoreRejected as error:
document = {
"schema_version": 1,
@@ -173,15 +255,15 @@ def restore(options: Sequence[str], stream: TextIO) -> int:
document = {
"schema_version": 1,
"state": "restored",
"restored_bytes": result.restored_bytes,
"previous_backup_path": str(result.previous_backup_path),
"source_schema_version": result.source_schema_version,
"restored_bytes": managed_result.restored_bytes,
"previous_backup_path": str(managed_result.previous_backup_path),
"source_schema_version": managed_result.source_schema_version,
}
_write_restore(
stream,
as_json,
document,
f"已恢复:{result.previous_backup_path} 为保护性备份。",
f"已恢复:{managed_result.previous_backup_path} 为保护性备份。",
)
return 0
@@ -198,6 +280,151 @@ def _write_restore(
stream.write(f"{text}\n")
def sdk_migrate(options: Sequence[str], stream: TextIO) -> int:
"""Bring a stopped home to SDK authority in one resumable command.
Backs up the home, makes queue work independent of the legacy tables,
commits SDK authority and drops those tables. The SDK already holds every
memory and raw turn, so nothing is copied. With `--json`, each step is one
progress line and the last line is the result.
"""
runtime_build: str | None = None
confirmed = False
as_json = False
index = 0
while index < len(options):
option = options[index]
if option == "--runtime-build" and index + 1 < len(options):
runtime_build = options[index + 1]
index += 2
continue
if option == "--yes":
confirmed = True
index += 1
continue
if option == "--json":
as_json = True
index += 1
continue
stream.write(f"one-memory: 参数无效:{option}\n")
return 2
if not runtime_build:
stream.write("one-memory: sdk-migrate 需要 --runtime-build <build>\n")
return 2
settings = load_settings()
status = inspect_runtime(settings.data_dir)
if status.state != "stopped":
document = {
"schema_version": 1,
"state": "blocked",
"code": "sdk_migration_runtime_running",
"runtime_state": status.state,
}
_write_restore(stream, as_json, document, "Runtime 仍在运行;不能迁移。")
return 4
if not confirmed:
document = {"schema_version": 1, "state": "preview", "requires_confirmation": True}
_write_restore(stream, as_json, document, "预览通过;加 --yes 后执行迁移。")
return 4
from one_memory.hy_runtime_config import HY_MEMORY_NAMESPACE, HY_MEMORY_VERSION
from one_memory.sdk_migration_runner import run_startup_migration
step_names = {
"bundle": "正在备份记忆数据……",
"prepare": "正在整理待处理的写入任务……",
"cutover": "正在切换数据源……",
"vectors": "正在接回旧版本的向量数据……",
"verify": "正在用新版本核对记忆能否读回……",
"cleanup": "正在删除旧表……",
}
def progress(step: str) -> None:
if as_json:
stream.write(
json.dumps({"schema_version": 1, "state": "running", "step": step}) + "\n"
)
else:
stream.write(f"{step_names.get(step, step)}\n")
stream.flush()
try:
result = run_startup_migration(
data_dir=settings.data_dir,
runtime_build=runtime_build,
sdk_version=HY_MEMORY_VERSION,
namespace=HY_MEMORY_NAMESPACE,
progress=progress,
)
except Exception as error:
from one_memory.sdk_migration_verify import MemoryReadbackFailed
code = migration_failure_code(error)
failed: dict[str, object] = {"schema_version": 1, "state": "failed", "code": code}
if isinstance(error, MemoryReadbackFailed):
failed["readback"] = error.report.as_document()
_write_restore(stream, as_json, failed, f"迁移未完成:{code}")
return 1
messages = {
"not_required": "不需要迁移。",
"complete": "迁移已完成;遗留的旧表或向量已处理。",
"cutover": "迁移完成:记忆数据已以 SDK 为准。",
}
_write_restore(stream, as_json, result.as_document(), messages[result.state])
return 0
def sdk_migration_status(options: Sequence[str], stream: TextIO) -> int:
"""Read-only probe: does this home need `sdk-migrate`?"""
if list(options) not in ([], ["--json"]):
stream.write("one-memory: sdk-migration-status 只接受 --json\n")
return 2
as_json = "--json" in options
settings = load_settings()
database_path = settings.data_dir / "one-memory.sqlite3"
if not database_path.is_file():
document: dict[str, object] = {
"schema_version": 1,
"authority": "sdk",
"state": "not_required",
}
else:
from one_memory.hy_runtime_config import HY_MEMORY_NAMESPACE
from one_memory.sdk_data_plane_migration import (
MemoryAuthority,
SdkDataPlaneMigrationStore,
)
from one_memory.sdk_migration_runner import abandoned_staging_present
from one_memory.sdk_migration_verify import read_active_profile
from one_memory.sdk_vector_reattach import legacy_vector_collections
from one_memory.target_schema import legacy_tables_present
authority = SdkDataPlaneMigrationStore(database_path).authority()
if authority is MemoryAuthority.SDK:
profile = read_active_profile(database_path)
leftovers = bool(
legacy_tables_present(database_path)
or abandoned_staging_present(
data_dir=settings.data_dir,
namespace=HY_MEMORY_NAMESPACE,
)
or (
profile is not None
and legacy_vector_collections(settings.data_dir, profile)
)
)
state = "required" if leftovers else "not_required"
else:
state = "required"
document = {"schema_version": 1, "authority": authority.value, "state": state}
if as_json:
stream.write(f"{json.dumps(document, ensure_ascii=False)}\n")
else:
stream.write(f"SDK migration: {document['state']} (authority={document['authority']})\n")
return 0
def _status_text(command: str, status: RuntimeStatus) -> str:
if status.state == "running":
location = f"{status.host}:{status.port}"
@@ -266,7 +493,13 @@ def serve(*, maintenance: bool = False, reader: bool = False) -> None:
)
application = create_reader_app(reader_settings)
print(f"reader_port:{port}", file=sys.stderr, flush=True)
uvicorn.run(application, host=settings.host, port=port, reload=False)
uvicorn.run(
application,
host=settings.host,
port=port,
reload=False,
access_log=False,
)
return
from one_memory.api import create_app
@@ -297,9 +530,21 @@ def serve(*, maintenance: bool = False, reader: bool = False) -> None:
)
if maintenance:
with CoreRuntime(settings, publish_receipt=False):
uvicorn.run(application, host=settings.host, port=settings.port, reload=False)
uvicorn.run(
application,
host=settings.host,
port=settings.port,
reload=False,
access_log=False,
)
else:
uvicorn.run(application, host=settings.host, port=settings.port, reload=False)
uvicorn.run(
application,
host=settings.host,
port=settings.port,
reload=False,
access_log=False,
)
if __name__ == "__main__":
@@ -23,10 +23,6 @@ class Settings(BaseSettings):
live_sync_enabled: bool = True
automatic_memory_processing: bool = True
imports_enabled: bool = True
# Experimental and unreleased: ownership/error shutdown still requires acceptance.
# Resume only explicitly initialized generations; never migrate at startup.
retrieval_index_enabled: bool = False
retrieval_minimum_free_bytes: int = Field(default=256 * 1024 * 1024, ge=0)
# Bounded metadata only: query, original text and answers are never stored.
call_event_retention_days: int | None = Field(default=30, ge=1, le=365)
call_event_max_events: int | None = Field(default=10_000, ge=1, le=100_000)
@@ -89,6 +89,51 @@ class MemoryContextItem(BaseModel):
ContextItem = Annotated[RawContextItem | MemoryContextItem, Field(discriminator="kind")]
class SdkRawContextItem(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid")
kind: Literal["raw"] = "raw"
raw_id: str = Field(min_length=1, max_length=512)
content: str = Field(max_length=20000)
source: str = Field(min_length=1, max_length=128)
session_id: str = Field(min_length=1, max_length=512)
memory_at: datetime | None = None
score: float = Field(ge=0, le=1)
truncated: bool = False
class SdkMemoryContextItem(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid")
kind: Literal["memory"] = "memory"
memory_id: str = Field(min_length=1, max_length=512)
content: str = Field(max_length=20000)
layer: str = Field(max_length=64)
status: str = Field(max_length=32)
source: str | None = Field(default=None, max_length=128)
updated_at: datetime | None = None
score: float = Field(ge=0, le=1)
truncated: bool = False
SdkContextItem = Annotated[
SdkRawContextItem | SdkMemoryContextItem,
Field(discriminator="kind"),
]
class SdkContextSearchResponse(BaseModel):
model_config = ConfigDict(frozen=True, extra="forbid")
schema_version: Literal[2] = 2
request_id: str = Field(min_length=1, max_length=64)
state: Literal["grounded", "empty", "partial", "unavailable"]
items: tuple[SdkContextItem, ...] = Field(max_length=20)
used_characters: int = Field(ge=0, le=20000)
truncated: bool
total_ms: float = Field(ge=0)
class ContextLaneResult(BaseModel):
"""Internal bounded adapter result; the aggregator applies shared budgets."""
@@ -196,7 +196,7 @@ def read_raw_context(
if _prefers_declared_facts(request.query)
else "1"
)
person_authored = "CASE WHEN e.written_by='person' THEN 1 ELSE 0 END"
person_authored = "CASE WHEN e.role='user' THEN 1 ELSE 0 END"
query_echo = (
"CASE WHEN trim(e.verbatim)=? OR trim(e.verbatim)=? THEN 0 ELSE 1 END"
if _prefers_declared_facts(request.query)
@@ -470,9 +470,8 @@ def revalidate_raw_context(
)
except (ValueError, TypeError):
break
if (row["role"], row["written_by"], created) != (
if (row["role"], created) != (
message.role,
message.written_by,
message.created_at,
):
break
@@ -66,12 +66,12 @@ def _field(text: str) -> ResumeField | None:
return None
def _raw_class(written_by: str, evidence_id: str, accepted: frozenset[str]) -> EvidenceClass:
if written_by == "person":
def _raw_class(role: str, evidence_id: str, accepted: frozenset[str]) -> EvidenceClass:
if role == "user":
return "person_statement"
if written_by == "agent":
if role == "assistant":
return "agent_report"
if written_by == "tool" and evidence_id in accepted:
if role == "tool" and evidence_id in accepted:
return "system_acceptance"
return "tool_output"
@@ -118,7 +118,7 @@ def assemble_resume_packet(
field=_field(message.text) or "unclassified",
text=message.text,
evidence_class=_raw_class(
message.written_by,
message.role,
message.evidence_id,
verified_system_evidence_ids,
),
@@ -4,7 +4,9 @@ import asyncio
import sqlite3
import time
from collections.abc import Sequence
from datetime import UTC, datetime
from typing import cast
from uuid import uuid4
from fastapi import APIRouter, HTTPException, Request, Response
from fastapi.params import Depends
@@ -31,13 +33,23 @@ from one_memory.context_models import (
ContextSemanticStatus,
MemoryContextItem,
RawContextItem,
SdkContextItem,
SdkContextSearchResponse,
SdkMemoryContextItem,
SdkRawContextItem,
)
from one_memory.context_raw import revalidate_raw_context
from one_memory.context_raw import read_raw_context, revalidate_raw_context
from one_memory.context_search import search_context
from one_memory.diagnostic_log import diagnostic_event, diagnostic_exception
from one_memory.external_memory_access import external_access
from one_memory.hy_runtime_config import HY_MEMORY_READER
from one_memory.hy_sdk_runtime import sdk_relevance_floor
from one_memory.hy_sdk_types import (
HySdkMemoryRecord,
parse_sdk_raw_search,
parse_sdk_search,
)
from one_memory.imports.storage import EvidenceStore
from one_memory.retrieval.raw_lane import read_raw_indexed_context
from one_memory.semantic_deadline import hy_wait_budget, search_within
CALL_EVENT_RESPONSE_BUDGET_MS = 250
@@ -86,12 +98,11 @@ def context_router(dependencies: Sequence[Depends]) -> APIRouter:
read = asyncio.create_task(
in_read_pool(
raw_read_pool(),
read_raw_indexed_context,
read_raw_context,
database,
value,
source_ids=authority.raw_sources,
deadline=lane_end,
index=getattr(request.app.state, "retrieval_runtime", None),
)
)
done, _ = await asyncio.wait({read}, timeout=max(0, lane_end - time.monotonic()))
@@ -420,3 +431,177 @@ def context_router(dependencies: Sequence[Depends]) -> APIRouter:
return final
return router
def sdk_context_router(dependencies: Sequence[Depends]) -> APIRouter:
"""SDK-native context: no Evidence/Governance ids or fabricated revisions."""
router = APIRouter(prefix="/api/v2/context", dependencies=dependencies)
@router.post("/search", response_model=SdkContextSearchResponse)
async def search(
value: ContextSearchRequest,
request: Request,
response: Response,
) -> SdkContextSearchResponse:
response.headers["Cache-Control"] = "no-store"
started = time.monotonic()
access = external_access(request.headers)
database = cast(EvidenceStore, request.app.state.evidence_store).database_path
try:
authority = await asyncio.to_thread(
resolve_context_authority,
value,
access,
database,
deadline=started + value.timeout_ms / 1000,
)
except HTTPException:
raise
except Exception:
raise HTTPException(503, "context_authority_unavailable") from None
client_handle = getattr(request.app.state, "sdk_client_handle", None)
if client_handle is None:
raise HTTPException(503, "sdk_context_unavailable")
try:
client = await client_handle.client()
except Exception:
raise HTTPException(503, "sdk_context_unavailable") from None
async def raw_lane() -> tuple[SdkRawContextItem, ...]:
if "raw" not in value.kinds or not authority.raw_allowed:
return ()
raw = await asyncio.to_thread(
client.search,
value.query,
user_ids=["local"],
agent_ids=[],
include_sources=list(authority.raw_sources or ()),
limit=value.limit,
min_score=0.0,
schema_min_score=0.0,
schema_limit=0,
intention_limit=0,
scene="chat",
reader=HY_MEMORY_READER,
layers=["l1_raw"],
)
hits = parse_sdk_raw_search(raw)
return tuple(
SdkRawContextItem(
raw_id=hit.raw_id,
content=hit.content,
source=hit.source,
session_id=hit.session_id,
memory_at=(
datetime.fromtimestamp(hit.memory_at, tz=UTC)
if hit.memory_at is not None
else None
),
score=hit.score,
)
for hit in hits
)
async def memory_lane() -> tuple[SdkMemoryContextItem, ...]:
if "memory" not in value.kinds or not authority.memory_allowed:
return ()
raw = await asyncio.to_thread(
client.search,
value.query,
user_ids=["local"],
agent_ids=[],
limit=value.limit,
min_score=sdk_relevance_floor(),
schema_min_score=sdk_relevance_floor(),
schema_limit=value.limit,
intention_limit=value.limit,
scene="normal",
reader=HY_MEMORY_READER,
)
hits = parse_sdk_search(raw, error_code="hy_memory_search_shape_unknown")
items: list[SdkMemoryContextItem] = []
for hit in hits:
record = await asyncio.to_thread(client.get, hit.memory_id)
memory = None if record is None else HySdkMemoryRecord.from_sdk(record)
if memory is None or memory.status != "active":
continue
items.append(
SdkMemoryContextItem(
memory_id=memory.memory_id,
content=(
hit.formatted_content
if hit.sdk_formatted
and hit.formatting_complete
and hit.formatted_content
else memory.content
),
layer=memory.layer,
status=memory.status,
source=memory.source,
updated_at=(
datetime.fromtimestamp(memory.gmt_created, tz=UTC)
if memory.gmt_created is not None
else None
),
score=hit.score,
)
)
return tuple(items)
lanes = (raw_lane(), memory_lane())
try:
raw_items, memory_items = await asyncio.wait_for(
asyncio.gather(*lanes, return_exceptions=True),
timeout=value.timeout_ms / 1000,
)
except TimeoutError:
return SdkContextSearchResponse(
request_id=str(uuid4()),
state="unavailable",
items=(),
used_characters=0,
truncated=True,
total_ms=(time.monotonic() - started) * 1000,
)
partial = isinstance(raw_items, Exception) or isinstance(memory_items, Exception)
raw_candidates = (
() if isinstance(raw_items, Exception) else cast(tuple[SdkContextItem, ...], raw_items)
)
memory_candidates = (
()
if isinstance(memory_items, Exception)
else cast(tuple[SdkContextItem, ...], memory_items)
)
candidates: list[SdkContextItem] = [
*raw_candidates,
*memory_candidates,
]
candidates.sort(key=lambda item: item.score, reverse=True)
selected: list[SdkContextItem] = []
used = 0
truncated = False
for item in candidates:
if len(selected) >= value.limit:
truncated = True
break
content = item.content
remaining = value.character_budget - used
if remaining <= 0:
truncated = True
break
if len(content) > remaining:
item = item.model_copy(update={"content": content[:remaining], "truncated": True})
truncated = True
selected.append(item)
used += len(item.content)
return SdkContextSearchResponse(
request_id=str(uuid4()),
state=("partial" if partial else "grounded" if selected else "empty"),
items=tuple(selected),
used_characters=used,
truncated=truncated,
total_ms=(time.monotonic() - started) * 1000,
)
return router
@@ -22,7 +22,7 @@ from dataclasses import dataclass
from datetime import UTC, datetime
from functools import partial
from pathlib import Path
from typing import Any, Literal, Protocol, cast
from typing import Any, Literal, cast
from one_memory.background_work import interactive_read_pool
from one_memory.context_expand import ExpansionAuthority, ExpansionRefSigner
@@ -36,23 +36,8 @@ from one_memory.retrieval.models import (
RawEvidence,
RetrievalPath,
RetrievalResponse,
TimeRange,
)
from one_memory.retrieval.query_plan import plan_local_query
from one_memory.retrieval.raw_candidates import RawCandidateBatch
from one_memory.retrieval.raw_evidence import materialize_raw_candidates
class RawIndexLookup(Protocol):
def lookup_raw(
self,
query: str,
*,
source_ids: frozenset[str],
deadline: float,
time_range: TimeRange | None = None,
) -> tuple[RawCandidateBatch, bool]: ...
ExpandRefs = tuple[ExpansionRefSigner, ExpansionAuthority]
@@ -106,11 +91,6 @@ class LaneResult:
coverage_limited: bool = False
def _semantic_only_raw(item: RawEvidence) -> bool:
"""Semantic overlap alone is a candidate, not a confirmed recall item."""
return set(item.matched_by) == {"semantic"}
@dataclass(frozen=True)
class StageTimings:
raw_ms: float = 0.0
@@ -191,12 +171,6 @@ def _managed(
return selected, truncated
def _group_missing_requirements(item: RawEvidence | GovernedEvidence) -> list[str]:
if isinstance(item, RawEvidence) and _semantic_only_raw(item):
return ["relevance_confirmation"]
return []
def _path(
status: str,
reason: str | None,
@@ -296,8 +270,7 @@ def read_lexical_raw_lane(
("lexical", "object") if plan.object_keys else ("lexical",),
truncated,
# Starvation means: this lane matched, then dropped the item whole. An
# ordinary no-match must stay empty, and an unconfigured semantic lane
# is not starvation.
# ordinary no-match must stay empty.
starved and not items,
probe_saturated,
)
@@ -345,7 +318,7 @@ def _lexical_raw_rows(
if context_raw._prefers_declared_facts(query.query)
else "1"
)
person_authored = "CASE WHEN e.written_by='person' THEN 1 ELSE 0 END"
person_authored = "CASE WHEN e.role='user' THEN 1 ELSE 0 END"
query_echo = (
"CASE WHEN trim(e.verbatim)=? OR trim(e.verbatim)=? THEN 0 ELSE 1 END"
if context_raw._prefers_declared_facts(query.query)
@@ -507,7 +480,7 @@ def _raw_item(row: sqlite3.Row, start1: int, matched_by: tuple[str, ...]) -> Raw
"source_id": row["source_id"],
"conversation_id": row["conversation_id"],
"role": row["role"],
"written_by": "person" if row["written_by"] == "person" else "agent",
"written_by": "person" if row["role"] == "user" else "agent",
"event_time": event_time.isoformat() if event_time else None,
"spans": [{"start_cp": start, "end_cp": start + len(text), "text": text}],
"matched_by": list(matched_by),
@@ -564,97 +537,6 @@ def warm_raw_read_path(
return False
def read_semantic_raw_lane(
index: RawIndexLookup | None,
database_path: Path,
query: CoordinatorQuery,
*,
source_ids: frozenset[str],
deadline: float,
) -> LaneResult:
if not source_ids:
return LaneResult((), "unavailable", "permission_required", (), False)
# No derived index is the no-model baseline, not a failure: the lexical lane
# must still answer. Semantic is genuinely unsearched in that state, so it
# must not claim a channel or a coverage result it never produced.
if index is None:
return LaneResult((), "not_searched", None, (), False)
try:
batch, unpublished = index.lookup_raw(
query.query,
source_ids=source_ids,
deadline=deadline,
time_range=plan_local_query(query.query).time_range,
)
except Exception:
return LaneResult((), "unavailable", "index_unavailable", ("semantic",), False)
if not isinstance(batch, RawCandidateBatch):
return LaneResult((), "unavailable", "index_unavailable", ("semantic",), False)
if batch.reason == "not_authorized":
return LaneResult((), "unavailable", "permission_required", ("semantic",), False)
if batch.reason == "deadline":
return LaneResult((), "unavailable", "timeout_budget", ("semantic",), True)
if batch.reason in {"vector_unavailable", "index_unavailable"}:
return LaneResult((), "unavailable", batch.reason, ("semantic",), False)
store, generation = _index_state(index, database_path)
from one_memory.retrieval.index_store import RetrievalIndexStore
store = cast("RetrievalIndexStore | None", store)
if store is None or generation is None:
return LaneResult((), "unavailable", "index_unavailable", ("semantic",), False)
try:
materialized = materialize_raw_candidates(
store,
batch,
generation_id=generation,
source_ids=source_ids,
deadline=deadline,
character_budget=query.character_budget,
)
except Exception:
return LaneResult((), "unavailable", "index_unavailable", ("semantic",), False)
if materialized.reason == "deadline":
return LaneResult((), "unavailable", "timeout_budget", ("semantic",), True)
if materialized.reason in {"index_unavailable", "not_authorized"}:
return LaneResult((), "unavailable", materialized.reason, ("semantic",), False)
complete = materialized.complete and not unpublished
if materialized.reason == "evidence_changed":
status: Literal["ok", "empty", "unavailable", "not_searched"] = "unavailable"
reason = "evidence_changed"
elif not materialized.items and not complete:
status, reason = "unavailable", "index_incomplete"
elif materialized.reason == "character_budget":
status, reason = "ok", None
else:
status, reason = ("ok" if materialized.items else "empty"), None
return LaneResult(
tuple(materialized.items),
status,
reason,
("semantic",),
materialized.reason == "character_budget",
)
def _index_state(index: RawIndexLookup, database_path: Path) -> tuple[object | None, str | None]:
store = getattr(index, "_store", None)
generation = None
snapshot = getattr(index, "snapshot", None)
if snapshot is not None:
try:
generation = snapshot().generation_id
except Exception:
generation = None
if store is None:
try:
from one_memory.retrieval.index_store import RetrievalIndexStore
store = RetrievalIndexStore(database_path)
except Exception:
store = None
return store, generation
def read_memory_lane(
database_path: Path,
query: CoordinatorQuery,
@@ -857,7 +739,6 @@ def coordinate_context_v2(
query: CoordinatorQuery,
*,
database_path: Path,
index: RawIndexLookup | None = None,
deadline: float,
expand_refs: ExpandRefs | None = None,
) -> RetrievalResponse:
@@ -871,62 +752,29 @@ def coordinate_context_v2(
lexical = read_lexical_raw_lane(
database_path, query, source_ids=authority.raw_sources, deadline=deadline
)
semantic = read_semantic_raw_lane(
index, database_path, query, source_ids=authority.raw_sources, deadline=deadline
)
timings = StageTimings(raw_ms=(time.monotonic() - raw_started) * 1000)
combined: dict[tuple[str, str], RawEvidence] = {}
for item in (*lexical.items, *semantic.items):
if not isinstance(item, RawEvidence):
continue
identity = _identity(item)
previous = combined.get(identity)
if previous is None or _semantic_only_raw(previous):
combined[identity] = item
# Semantic similarity is a candidate signal, not a verified recall
# result. Keep semantic-only candidates visible in coverage, but do not
# release their bodies for host injection unless the item is
# independently confirmed by the lexical/object lane. A global distance
# threshold is deliberately not used: the measured positive and
# negative distributions overlap.
semantic_only = {_identity(item) for item in combined.values() if _semantic_only_raw(item)}
confirmed = {_identity(item) for item in lexical.items if isinstance(item, RawEvidence)}
deferred_raw = semantic_only - confirmed
if deferred_raw:
combined = {
identity: item
for identity, item in combined.items()
if identity not in deferred_raw
}
channels = tuple(dict.fromkeys((*lexical.channels, *semantic.channels)))
for item in lexical.items:
if isinstance(item, RawEvidence):
combined.setdefault(_identity(item), item)
if lexical.status == "unavailable":
status: Literal["ok", "empty", "unavailable", "not_searched", "degraded"] = (
"unavailable"
)
reason = lexical.reason
elif semantic.status == "unavailable":
status = "unavailable"
reason = semantic.reason
elif combined:
status, reason = "ok", semantic.reason if semantic.status != "ok" else None
elif deferred_raw:
status, reason = "degraded", "relevance_confirmation"
elif lexical.status == "empty":
status, reason = ("empty" if semantic.status != "not_searched" else "ok"), None
elif combined or lexical.status == "empty":
status, reason = "ok", None
else:
status, reason = "empty", None
truncated = lexical.truncated or semantic.truncated
raw = LaneResult(
tuple(combined.values()),
status,
reason,
channels,
truncated,
lexical.channels,
lexical.truncated,
lexical.starved,
lexical.coverage_limited,
)
if deferred_raw:
object.__setattr__(raw, "coverage_limited", True)
elif "raw" in query.kinds and not authority.raw_allowed:
raw = LaneResult((), "unavailable", "permission_required", (), False)
if "memory" in query.kinds:
@@ -995,9 +843,7 @@ def coordinate_context_v2(
return _path("unavailable", raw.reason, raw.channels, "not_searched", False, 0)
if dropped and not final_raw:
return _path("unavailable", "permission_required", raw.channels, "unavailable", True, 0)
# Lexical-only is complete when the lexical lane actually answered. An
# unconfigured semantic lane is a capability absence, not proof that
# less than the authorized range was searched.
# The raw lane is complete when the lexical lane actually answered.
complete = (
raw.status in {"ok", "empty"}
and not dropped
@@ -1022,9 +868,7 @@ def coordinate_context_v2(
"count_budget"
if truncated
else "coverage_budget"
if raw.coverage_limited and not deferred_raw
else "relevance_confirmation"
if deferred_raw
if raw.coverage_limited
else "character_budget"
)
return _path(
@@ -1112,7 +956,7 @@ def coordinate_context_v2(
"group_id": f"group-{index}",
"answer_target": query.intent,
"decision_status": "missing_confirmation",
"missing_requirements": _group_missing_requirements(item),
"missing_requirements": [],
"object_refs": _object_refs(item, plan.object_keys),
"items": [group_item.model_dump(mode="json") for group_item in (item,)],
}
@@ -1185,7 +1029,6 @@ async def search_context_v2(
query: CoordinatorQuery,
*,
database_path: Path,
index: RawIndexLookup | None = None,
deadline: float,
expand_refs: ExpandRefs | None = None,
) -> RetrievalResponse:
@@ -1198,7 +1041,6 @@ async def search_context_v2(
authority,
query,
database_path=database_path,
index=index,
deadline=deadline,
expand_refs=expand_refs,
),
@@ -0,0 +1,277 @@
"""Pure conversation-window helpers shared by capture, retrieval, and writes."""
from __future__ import annotations
import os
import re
from one_memory.imports.models import EvidenceContentKind, EvidenceOrigin, EvidenceRecord
from one_memory.memory_tasks import segment_evidence_record
MEMORY_TASK_TIMEOUT_MARGIN_SECONDS = 60.0
MEMORY_TASK_TIMEOUT_MIN_SECONDS = 180.0
MEMHUB_DEFAULT_CODING_TOOL_RESULT_MAX_BYTES = 512
_HARNESS_PREFIXES = (
"<codex_internal_context",
"# agents.md instructions",
"<environment_context>",
"<permissions instructions>",
"<system-reminder>",
"<system_notification>",
"<instructions>",
)
_HOST_ENVELOPE = re.compile(
r"(?:"
r"^<timestamp>.*?<system_(?:notification|reminder)>|"
r"^<system_(?:notification|reminder)>|"
r'^\{\s*"request_id"\s*:.*?"steps"\s*:'
r")",
re.IGNORECASE | re.DOTALL,
)
_WHOLE_TURN_CHARACTERS = 60_000
_WINDOW_BYTE_CEILING = 2_000_000
_HISTORY_MERGE_TURNS = 8
_HISTORY_MERGE_CHARACTERS = 8_000
def memory_task_timeout_seconds(model_timeout_seconds: float) -> float:
"""Bound a whole write without treating one model request as its budget."""
return max(
MEMORY_TASK_TIMEOUT_MIN_SECONDS,
float(model_timeout_seconds) + MEMORY_TASK_TIMEOUT_MARGIN_SECONDS,
)
def _coding_tool_result_max_bytes() -> int:
raw = os.environ.get("MEMORY_CODING_TOOL_RESULT_MAX_BYTES")
if raw is None:
return MEMHUB_DEFAULT_CODING_TOOL_RESULT_MAX_BYTES
try:
value = int(raw)
except ValueError:
return MEMHUB_DEFAULT_CODING_TOOL_RESULT_MAX_BYTES
return value if value > 0 else MEMHUB_DEFAULT_CODING_TOOL_RESULT_MAX_BYTES
_HY_TOOL_CHARACTERS = _coding_tool_result_max_bytes()
def _conversation_chunks(
records: list[EvidenceRecord],
*,
max_characters: int | None = None,
max_turns: int | None = None,
completed_only: bool = False,
) -> list[tuple[EvidenceRecord, ...]]:
"""Build bounded, complete user/assistant/tool windows."""
turns: list[list[EvidenceRecord]] = []
for record in records:
if not _is_hy_turn_record(record):
continue
pending_proposal = bool(turns) and not _opens_turn(turns[-1][0])
if not turns or (_opens_turn(record) and not pending_proposal):
turns.append([record])
else:
turns[-1].append(record)
if completed_only and turns and _trailing_user_turn_is_open(turns[-1]):
turns.pop()
whole = _whole_turns() and max_characters is None
if whole:
size = _hy_read_length
max_characters = _WHOLE_TURN_CHARACTERS
max_turns = max_turns or 1_000_000
else:
size = lambda record: len(record.verbatim) # noqa: E731
max_characters = max_characters or 12_000
max_turns = max_turns or 24
chunks: list[tuple[EvidenceRecord, ...]] = []
for turn in turns:
original_question = turn[0] if _opens_turn(turn[0]) else None
expanded: list[EvidenceRecord] = []
for record in turn:
reserve = (
size(original_question)
if original_question is not None
and record is not original_question
and size(original_question) < max_characters
else 0
)
segment_limit = max(1, max_characters - reserve)
if size(record) <= segment_limit:
expanded.append(record)
continue
spans = _semantic_segment_spans(record.verbatim, segment_limit)
expanded.extend(
segment_evidence_record(record, index=index, start=start, end=end)
if len(spans) > 1
else record
for index, (start, end) in enumerate(spans)
)
question = expanded[0] if expanded and _opens_turn(expanded[0]) else None
current: list[EvidenceRecord] = []
for record in expanded:
if current and (
len(current) >= max_turns
or sum(size(item) for item in current) + size(record) > max_characters
or sum(_window_bytes(item) for item in current) + _window_bytes(record)
> _WINDOW_BYTE_CEILING
):
chunks.append(tuple(current))
current = (
[question]
if question is not None
and max_turns > 1
and size(question) + size(record) <= max_characters
else []
)
current.append(record)
chunks.append(tuple(current))
return _merge_tool_only_chunks(chunks)
def _semantic_segment_spans(text: str, limit: int) -> list[tuple[int, int]]:
if len(text) <= limit:
return [(0, len(text))]
spans: list[tuple[int, int]] = []
start = 0
separators = ("\n\n", "\n", "。", "!", "?", ". ", "! ", "? ")
while start < len(text):
hard_end = min(len(text), start + limit)
if hard_end == len(text):
end = hard_end
else:
floor = start + max(1, limit // 2)
candidates = [text.rfind(separator, floor, hard_end) for separator in separators]
boundary = max(candidates)
if boundary < floor:
end = hard_end
else:
matched = next(
separator for separator in separators if text.startswith(separator, boundary)
)
end = boundary + len(matched)
spans.append((start, end))
start = end
return spans
def _merge_tool_only_chunks(
chunks: list[tuple[EvidenceRecord, ...]],
) -> list[tuple[EvidenceRecord, ...]]:
if not any(chunk and all(record.role == "tool" for record in chunk) for chunk in chunks):
return chunks
merged: list[tuple[EvidenceRecord, ...]] = []
leading_tools: list[EvidenceRecord] = []
for chunk in chunks:
if not chunk:
continue
if all(record.role == "tool" for record in chunk):
if merged:
merged[-1] = (*merged[-1], *chunk)
else:
leading_tools.extend(chunk)
continue
if leading_tools:
chunk = (*leading_tools, *chunk)
leading_tools = []
merged.append(chunk)
return [] if leading_tools else merged
def _merge_historical_chunks(
chunks: list[tuple[EvidenceRecord, ...]],
*,
max_turns: int = _HISTORY_MERGE_TURNS,
max_characters: int = _HISTORY_MERGE_CHARACTERS,
) -> list[tuple[EvidenceRecord, ...]]:
if not chunks:
return []
merged: list[tuple[EvidenceRecord, ...]] = []
current: list[EvidenceRecord] = []
current_turns = 0
current_characters = 0
for chunk in chunks:
chunk_characters = sum(len(record.verbatim) for record in chunk)
if current and (
current_turns >= max_turns or current_characters + chunk_characters > max_characters
):
merged.append(tuple(current))
current = []
current_turns = 0
current_characters = 0
current.extend(chunk)
current_turns += 1
current_characters += chunk_characters
if current:
merged.append(tuple(current))
return merged
def _chunk_input_ref(chunk: tuple[EvidenceRecord, ...]) -> str:
user_records = tuple(item for item in chunk if item.role == "user")
return user_records[-1].evidence_id if user_records else chunk[-1].evidence_id
def _opens_turn(record: EvidenceRecord) -> bool:
return record.role == "user"
def _trailing_user_turn_is_open(turn: list[EvidenceRecord]) -> bool:
if len(turn) != 1:
return False
opener = turn[0]
return (
_opens_turn(opener)
and opener.content_kind is EvidenceContentKind.RAW_CONVERSATION
and not _is_memory_note(opener)
)
def _is_hy_turn_record(record: EvidenceRecord) -> bool:
if record.role == "tool":
return record.content_kind is EvidenceContentKind.RAW_CONVERSATION and bool(
record.verbatim.strip()
)
return _is_hy_input_turn(record)
def _is_hy_input_turn(record: EvidenceRecord) -> bool:
source = record.verbatim.strip()
if not source:
return False
if record.content_kind is EvidenceContentKind.MEMORY_CONTENT:
return True
if record.role == "assistant":
return True
if record.role != "user":
return False
if source.casefold().startswith(_HARNESS_PREFIXES):
return False
return _HOST_ENVELOPE.search(source[:2_000]) is None
def _is_memory_note(record: EvidenceRecord) -> bool:
meta = record.origin_meta.get(EvidenceOrigin.MANUAL_IMPORT)
return (
record.source_id == "one-memory-manual"
and meta is not None
and meta.raw_meta.get("input_mode") == "direct_memory_note"
)
def _window_bytes(record: EvidenceRecord) -> int:
return len(record.verbatim.encode("utf-8"))
def _whole_turns() -> bool:
return os.environ.get("ONE_MEMORY_SPLIT_TURNS", "").strip() != "1"
def _hy_read_length(record: EvidenceRecord) -> int:
if record.role == "tool":
return min(len(record.verbatim), _HY_TOOL_CHARACTERS)
return len(record.verbatim)
Loaded 100 of 772 files, more files were not shown because too many files have changed in this diff. Show more