Compare commits

..
Author SHA1 Message Date
db6fd1b8e3 chore(memhub): bump release build number to 13 (#53)
Co-authored-by: alvinfei <alvinfei@tencent.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 18:04:18 +08:00
kristinhe1111 5176683937 fix(web): sync sedimentation switch status to home (#51) 2026-10-18 17:42:54 +08:00
alvinfeiandCursor 6150ceb9cc fix(security): parse diagnostic stack paths linearly
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 17:00:27 +08:00
alvinfei 6054f9921a Merge remote-tracking branch 'github/main' into dev 2026-10-18 16:53:45 +08:00
alvinfeiandCursor ba70b84b00 chore(memhub): bump release build number to 12
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:12:48 +08:00
alvinfeiandCursor fb71eafa35 refactor(memhub): simplify durable memory scheduling
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 16:11:02 +08:00
kristinhe cdd549fdd1 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.
2026-10-18 13:41:48 +08:00
kristinhe 0df84c086c 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.
2026-10-18 12:44:01 +08:00
kristinhe dc0ba49fbe 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.
2026-10-18 12:33:02 +08:00
kristinhe ce705e9e4a 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.
2026-10-18 10:41:58 +08:00
kristinhe 334b14472b 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.
2026-10-18 10:37:09 +08:00
kristinhe 38baa9eebf 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.
2026-10-18 10:30:43 +08:00
kristinhe 0083a355a5 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.
2026-10-18 10:17:15 +08:00
kristinhe c049facb70 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.
2026-10-18 10:15:36 +08:00
alvinfeiandCursor c681fdcf24 feat(memhub): schedule memory writes by event time
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 08:43:58 +08:00
alvinfeiandCursor d0a52c9863 fix(memhub): make sedimentation pause stop model dispatch
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-18 07:54:13 +08:00
kristinhe 01259d01f5 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.
2026-10-18 02:07:37 +08:00
kristinhe 0e436e9b70 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.
2026-10-18 02:07:26 +08:00
kristinhe ec99618e1f 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.
2026-10-18 01:36:53 +08:00
kristinhe c53c874c21 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.
2026-10-18 01:36:33 +08:00
kristinhe 80f21d29a7 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.
2026-10-18 00:58:42 +08:00
kristinhe 2cc2f02450 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
2026-10-18 00:16:03 +08:00
kristinhe 5be27fd87f merge: issue 29 source authorization state and registry ownership into dev 2026-10-17 23:55:28 +08:00
kristinhe 7aaf0f8557 merge: model sedimentation switch into dev 2026-10-17 23:54:23 +08:00
kristinhe 887583b858 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.
2026-10-17 23:45:55 +08:00
alvinfeiandCursor fcdb2307e2 release: prepare MemHub 1.0.4 build 8
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 23:41:13 +08:00
alvinfeiandCursor 9ed744b455 fix(settings): align help controls and tighten spacing
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 23:35:58 +08:00
alvinfeiandCursor 1b90f04a50 feat(diagnostics): expose build info and fullscreen logs
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 23:34:04 +08:00
kristinhe 0822e7137e 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.
2026-10-17 23:31:42 +08:00
alvinfeiandCursor bcc0751060 fix(logging): keep info diagnostics actionable
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 23:25:44 +08:00
kristinhe 183b61e736 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.
2026-10-17 23:22:48 +08:00
kristinhe e038006c7f 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.
2026-10-17 23:00:44 +08:00
kristinhe 16953ed49e 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).
2026-10-17 22:52:22 +08:00
alvinfei 4ff948c7e1 Merge remote-tracking branch 'github/main' into fix/cost-control-audit 2026-10-17 22:15:07 +08:00
alvinfeiandCursor 346f2653f2 feat(memhub): add model usage audit and cost controls
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-17 22:02:52 +08:00
33 changed files with 311 additions and 1215 deletions

No files matched your search

-11
View File
@@ -14,17 +14,6 @@ Hy Memory and MemHub are versioned and released independently.
## Unreleased
- 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.
- Serialized each SDK SQLite store's shared connection lifecycle so concurrent
history/cache operations cannot race with `close()` and crash the process.
- Clarified that `add(metadata=...)` carries legacy SDK processing options,
while persistent caller business context belongs in `meta`.
- Added an opt-in `get(..., include_raw=True)` path for reading `L1_RAW`
memories, including memories written in lite mode. The default remains
hidden for backward compatibility.
- 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.
+1 -2
View File
@@ -32,8 +32,7 @@ English | [中文](README.zh.md)
## Latest News
* *<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]**: 🚀 **Released** **Hy Memory 2.0 (`hy-memory==2.0.3`)** on [PyPI](https://pypi.org/project/hy-memory/2.0.3/) 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)**!
+1 -2
View File
@@ -32,8 +32,7 @@
## 最新动态
* *<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]**: 🚀 **正式发布** **Hy Memory 2.0 (`hy-memory==2.0.3`)**(已上线 [PyPI](https://pypi.org/project/hy-memory/2.0.3/)),并开源 **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** 接收!
-15
View File
@@ -106,15 +106,6 @@ result = client.add(
)
```
`metadata` 与 `meta` 不是同一字段:
- `metadata` 是兼容旧调用方保留的 SDK 处理选项,会进入内部
`WriteRequest.extra`,不保证持久化或随查询结果返回。
- `meta` 是调用方的业务上下文,会持久化并在 `search()`、`get()` 等结果中返回。
同一记忆被多次合并时,各次 `meta` 会按写入顺序保存在列表中。
需要以后读回的数据必须放在 `meta`,不要放在 `metadata`。
`scene` 的公开取值:
- `None`:普通文本直接走 chat;messages 含 tool 时执行快速场景判断。
@@ -272,8 +263,6 @@ catalog 也可以在没有基础 L0 时形成只读的合成画像。
```python
memory = client.get("memory_id")
# lite 模式写入的是 L1_RAW;按 ID 读取时必须显式选择返回原文。
raw_memory = client.get("memory_id", include_raw=True)
result = client.update("memory_id", "更新后的内容")
result = client.delete("memory_id")
result = client.delete_all(user_id="user_001")
@@ -293,10 +282,6 @@ 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()` 默认继续隐藏 `L1_RAW`,因此不会改变现有调用方的原文访问
边界。只有显式传入 `include_raw=True` 才返回该层;这也是 lite 模式按 ID 读取
写入内容及其 `meta` 的方式。MemHub 的 HTTP 读取接口不开放此参数。
普通 `list_memories()` 返回 `vdb` 桶,并在 Graph 有结果时附带 `graph`;传入
`workspace_id` 时返回生产力记忆的 `scene="productivity"` 和 `experiences`。
+12 -39
View File
@@ -1597,9 +1597,7 @@ class HyMemoryClient:
session_id: Session ID(三级隔离 key)
source: 调用来源,例如 openclaw / cursor / codex;与 agent_id 正交。
写入前执行 strip().lower(),默认 "default"。
metadata: 旧版 SDK 处理选项,会并入内部 WriteRequest.extra。
不保证持久化或随查询返回;调用方需要保存并读回的业务字段
请使用 meta。
metadata: 自定义元数据
memory_at: 记忆时间戳(不传则用当前时间),用于导入历史记忆
scene: 显式指定写入路由,跳过 LLM 自动判定。
- None(默认):含 tool 时 LLM 判 chat/working/coding;
@@ -1625,8 +1623,8 @@ class HyMemoryClient:
branch: Coding memory 路径专用。分支名。同 workspace_id。chat 路径忽略。
meta: 调用方自定义业务 meta,随本次产出的记忆存储、查询时原样返回。
不 embed、不参与召回、不作过滤条件。
与 metadata 不同:metadata 是旧版内部处理选项,
meta 独立持久化,只做业务透传。
与 metadata 不同:metadata 会并入 extra(含 SDK 内部控制键),
meta 独立存放,只做透传。
语义为「该次 write 时刻的上下文」,故存为 list——同一节点被
多次写入合并时会追加而非覆盖,详见 get() 返回的 meta 字段。
@@ -1793,26 +1791,17 @@ class HyMemoryClient:
query_embedding=query_embedding,
))
def get(
self,
memory_id: str,
*,
include_raw: bool = False,
) -> Optional[Dict[str, Any]]:
def get(self, memory_id: str) -> Optional[Dict[str, Any]]:
"""
获取单条记忆。
Args:
memory_id: 记忆 ID
include_raw: 是否允许返回 L1_RAW 原始记忆。默认 False,保持原有隐藏行为;
lite 模式的记忆均为 L1_RAW,需显式设为 True 才能按 ID 读取。
Returns:
{"memory_id", "content", "layer", "request_id", "elapsed_ms"} 或 None(不存在时)
"""
return self._loop_thread.run(
self.async_get(memory_id, include_raw=include_raw)
)
return self._loop_thread.run(self.async_get(memory_id))
def update(
self,
@@ -3661,21 +3650,12 @@ class HyMemoryClient:
# ================================================================
@_ensure_internal_loop
async def async_get(
self,
memory_id: str,
*,
include_raw: bool = False,
) -> Optional[Dict[str, Any]]:
async def async_get(self, memory_id: str) -> Optional[Dict[str, Any]]:
"""
获取单条记忆(异步)。
VDB + Graph 双路并行查询,哪个有结果返回哪个。
Args:
memory_id: 记忆 ID
include_raw: 是否允许返回 L1_RAW 原始记忆,默认 False。
Returns:
{"memory_id", "content", "layer", "source", "request_id", "elapsed_ms"} 或 None
"""
@@ -3703,24 +3683,17 @@ class HyMemoryClient:
vdb_node, graph_node = await _asyncio_get.gather(_get_vdb(), _get_graph())
# L1_RAW 默认不对外可见:按 ID 直取走主键查询、绕过向量库的 layer
# filter,故在此统一挡掉。SDK 调用方可通过 include_raw=True 显式读取;
# HTTP 接口不传该参数,继续保持隐藏。内部写链路不经过此方法。
# L1_RAW 不对外可见:按 ID 直取走主键查询、绕过向量库的 layer filter,
# 故在此统一挡掉。async_get 是 GET /v1/memories/{id} 与
# /v1/memories/batch 两个对外接口的共同必经处,而内部写链路不经过它
# (writer 写后校验直接调 vector_store.get_by_id),挡在此处不影响内部。
#
# 置于 gather 之后、埋点之前:命中 raw 仍照常落 GET 埋点(保留可观测性,
# 便于发现有调用方拿 raw id 试探),只是不把内容返回给调用方。
# 对调用方的表现与"该 id 不存在"完全一致,不额外暴露"存在但被挡"的信息。
if (
not include_raw
and vdb_node is not None
and vdb_node.layer == MemoryLayer.L1_RAW
):
if vdb_node is not None and vdb_node.layer == MemoryLayer.L1_RAW:
vdb_node = None
if (
not include_raw
and graph_node is not None
and getattr(graph_node, "layer", None) == MemoryLayer.L1_RAW
):
if graph_node is not None and getattr(graph_node, "layer", None) == MemoryLayer.L1_RAW:
graph_node = None
elapsed = round((time.perf_counter() - t0) * 1000, 2)
+125 -136
View File
@@ -7,7 +7,7 @@ Agent Memory V2 - SqliteCache
设计模式跟随 history_store.py:
- 标准库 sqlite3 + _run_in_sqlite_pool()
- WAL 模式 + check_same_thread=False
- 每实例 threading.RLock 保护共享连接的全部操作与关闭
- threading.Lock 保护写操作
三张表:
- memory_operations / pipeline_logs / system_metrics: 审计与观测
@@ -122,10 +122,7 @@ class SqliteCache(CacheBase):
def __init__(self, config: MemoryConfig):
self.config = config
self._conn: Optional[sqlite3.Connection] = None
# 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()
self._lock = threading.Lock()
# 读取 db_path
cache_cfg = getattr(config, "cache", None)
@@ -147,37 +144,35 @@ class SqliteCache(CacheBase):
logger.debug(f"SqliteCache initialized: {self._db_path}")
def _init_sync(self) -> None:
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()
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 列。"""
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:
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(
"ALTER TABLE pipeline_logs_v2 ADD COLUMN event_at_ms INTEGER NOT NULL DEFAULT 0"
f"ALTER TABLE pipeline_logs_v2 ADD COLUMN {col} TEXT NOT NULL DEFAULT ''"
)
except Exception as e:
logger.debug(f"[sqlite] pipeline_logs_v2 column migration skipped: {e}")
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}")
async def close(self) -> None:
if self._conn is not None:
@@ -185,10 +180,9 @@ class SqliteCache(CacheBase):
logger.info("SqliteCache closed")
def _close_sync(self) -> None:
with self._lock:
if self._conn:
self._conn.close()
self._conn = None
if self._conn:
self._conn.close()
self._conn = None
# ================================================================
# 统计
@@ -261,40 +255,39 @@ class SqliteCache(CacheBase):
"""
try:
def _query():
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)
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:
@@ -376,38 +369,37 @@ class SqliteCache(CacheBase):
"""
try:
def _query():
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)
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:
@@ -422,27 +414,26 @@ class SqliteCache(CacheBase):
"""存储一个分钟桶的增量指标数据(UPSERT: 同一分钟多次写入会合并)"""
try:
def _store():
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()
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}")
@@ -451,18 +442,17 @@ class SqliteCache(CacheBase):
"""读取指定时间范围内的分钟指标数据"""
try:
def _load():
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
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}")
@@ -472,12 +462,11 @@ class SqliteCache(CacheBase):
"""删除指定时间之前的 metrics 数据"""
try:
def _cleanup():
with self._lock:
self._conn.execute(
"DELETE FROM system_metrics WHERE minute_ts < ?",
(before_ts,),
)
self._conn.commit()
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}")
+70 -81
View File
@@ -16,7 +16,6 @@ import json
import logging
import os
import sqlite3
import threading
from datetime import datetime, timezone
from typing import Dict, List, Any, Optional
@@ -90,10 +89,6 @@ 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:
"""创建表和索引(如果不存在)"""
@@ -102,21 +97,20 @@ class HistoryStore:
def _init_sync(self) -> None:
"""同步初始化:创建目录、连接数据库、建表建索引"""
with self._conn_lock:
# 确保目录存在
db_dir = os.path.dirname(self._db_path)
if db_dir:
os.makedirs(db_dir, exist_ok=True)
# 确保目录存在
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()
# ================================================================
# 记录操作
@@ -224,14 +218,13 @@ 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]]:
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()]
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,
@@ -251,15 +244,14 @@ 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]]:
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()]
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 count(self, isolation_key: str = "") -> int:
"""
@@ -274,17 +266,16 @@ class HistoryStore:
return await _run_in_sqlite_pool(self._count_sync, isolation_key)
def _count_sync(self, isolation_key: str) -> int:
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]
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:
"""关闭数据库连接"""
@@ -293,10 +284,9 @@ class HistoryStore:
logger.info("[HistoryStore] closed")
def _close_sync(self) -> None:
with self._conn_lock:
if self._conn:
self._conn.close()
self._conn = None
if self._conn:
self._conn.close()
self._conn = None
# ================================================================
# 内部
@@ -349,34 +339,33 @@ class HistoryStore:
role: str = "",
extra: Optional[Dict[str, Any]] = None,
) -> int:
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
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
@@ -12,6 +12,7 @@
* 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";
@@ -19,14 +20,12 @@ 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 { assertSemver } = require("../../../scripts/release-version.cjs");
const { resolveBuildVersion } = require("../../../scripts/release-version.cjs");
const releaseVersion = resolveBuildVersion(process.env, repositoryRoot);
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(
@@ -54,7 +53,7 @@ mkdirSync(outDir, { recursive: true });
const published = { ...pkg };
published.name = publishName;
published.version = publishVersion;
published.version = releaseVersion;
for (const section of ["dependencies", "devDependencies", "peerDependencies"]) {
if (!published[section]) continue;
published[section] = Object.fromEntries(
+5 -6
View File
@@ -331,7 +331,7 @@ import {
renderVersion,
renderVersionDocument,
} from "./usage.js";
import { CLI_VERSION, PRODUCT, RUNTIME_RELEASE_VERSION } from "./version.js";
import { CLI_VERSION, PRODUCT } from "./version.js";
import { runWatchLoop, type WatchEvent, type WatchRead } from "./watch-loop.js";
export interface RunControls {
@@ -417,8 +417,7 @@ async function selectInstallSource(
throw new Error("release_manifest_url_unavailable");
}
const manifestUrl =
explicitManifestUrl ??
template.replaceAll("{version}", RUNTIME_RELEASE_VERSION);
explicitManifestUrl ?? template.replaceAll("{version}", CLI_VERSION);
const allowedHosts = parseAllowedReleaseHosts(
environment.MEMHUB_RELEASE_ALLOWED_HOSTS,
);
@@ -463,7 +462,7 @@ async function resolveRemoteInstallPreview(
): Promise<ResolvedRuntimeRelease> {
return (controls.resolveRuntimeRelease ?? resolveRuntimeRelease)({
manifestUrl: selection.manifestUrl,
expectedVersion: RUNTIME_RELEASE_VERSION,
expectedVersion: CLI_VERSION,
channel: selection.channel,
platform: process.platform,
arch: process.arch,
@@ -477,7 +476,7 @@ async function acquireRemoteInstallSource(
): Promise<AcquiredRuntimeDistribution> {
return (controls.acquireRuntimeDistribution ?? acquireRuntimeDistribution)({
manifestUrl: selection.manifestUrl,
expectedVersion: RUNTIME_RELEASE_VERSION,
expectedVersion: CLI_VERSION,
channel: selection.channel,
platform: process.platform,
arch: process.arch,
@@ -6521,7 +6520,7 @@ function parseInstallOptions(
...(releaseManifestUrl ? { releaseManifestUrl } : {}),
releaseChannel:
releaseChannel ??
(RUNTIME_RELEASE_VERSION.includes("-") ? "prerelease" : "stable"),
(CLI_VERSION.includes("-") ? "prerelease" : "stable"),
installRoot: resolvedInstallRoot,
home: resolvedHome,
uid: uid ?? process.getuid?.(),
+1 -6
View File
@@ -48,11 +48,7 @@ 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",
MEMHUB_NPM_VERSION: "1.0.5",
},
env: { ...process.env, MEMHUB_NPM_PACKAGE: "@example/memhub-cli" },
});
const published = JSON.parse(
readFileSync(path.join(root, "dist-publish", "package.json"), "utf8"),
@@ -60,7 +56,6 @@ 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",
+6 -15
View File
@@ -1,9 +1,5 @@
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"
@@ -13,18 +9,13 @@ 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 = SEMVER.test(embeddedVersion)
? embeddedVersion
: "development";
export const RUNTIME_RELEASE_VERSION = SEMVER.test(embeddedRuntimeVersion)
? embeddedRuntimeVersion
: CLI_VERSION;
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_BUILD_NUMBER = /^\d+$/.test(embeddedBuildNumber)
? Number(embeddedBuildNumber)
+2 -14
View File
@@ -2,22 +2,11 @@ import { createRequire } from "node:module";
import { defineConfig } from "tsup";
const require = createRequire(import.meta.url);
const { assertSemver, resolveBuildVersion } =
const { 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" },
@@ -26,7 +15,7 @@ export default defineConfig({
outDir: "dist",
clean: true,
define: {
__ONE_MEMORY_VERSION__: JSON.stringify(cliVersion),
__ONE_MEMORY_VERSION__: JSON.stringify(releaseVersion),
__ONE_MEMORY_BUILD_NUMBER__: JSON.stringify(
process.env.ONE_MEMORY_BUILD_NUMBER ?? "unknown",
),
@@ -36,7 +25,6 @@ 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
-1
View File
@@ -11,7 +11,6 @@ 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 -8
View File
@@ -2793,12 +2793,6 @@ def create_app(
# D75: work queued for the previous model continues with this one.
# Only tasks that never reached the model are re-bound.
await asyncio.to_thread(app.state.memory_task_store.rebind_unstarted_profile, profile)
# A missing profile is an event-driven wait, not a provider outage.
# Release those durable rows only now that activation has changed the
# condition; the ordinary drain poll will claim them without a restart.
await asyncio.to_thread(
app.state.memory_write_queue.readmit_model_profile_waiters
)
# Not awaited: the catch-up reads every conversation ever imported, and
# the answer to "which profile is active" does not depend on it.
_start_backfill(app)
@@ -5068,11 +5062,10 @@ def _source_writes_on(app: FastAPI, source_id: str) -> bool:
def _sedimentation_claim_enabled(app: FastAPI, source_id: str) -> bool:
"""Claim queued model work only when policy, source and model all admit it."""
"""Claim queued model work only while both global and source gates allow it."""
return (
_config_store(app).sedimentation_enabled()
and _model_profile_store(app).active_identity() is not None
and _history_import_gate_released(app)
and _source_writes_on(app, source_id)
)
@@ -282,24 +282,11 @@ class PollingLiveSyncSupervisor:
and job.status
in {ImportStatus.PENDING, ImportStatus.RUNNING, ImportStatus.INTERRUPTED}
]
bounded_history_incomplete = any(
job.source_id == source_id
and job.operation == "history"
and job.history_after is not None
and job.status is not ImportStatus.COMPLETED
for job in source_jobs
)
# Establish the realtime EOF independently even while history owns
# this source. Otherwise the P1 job starts from the P2 checkpoint
# (or from zero) and becomes a second full-history scan.
adapter = self.import_supervisor.adapters[source_id]
live_cursors = await self._live_cursors(source_id, adapter)
# A bounded onboarding history is the authority for everything up
# to its EOF. An adapter without a native live baseline has no safe
# realtime cursor until that history finishes; starting a sync from
# zero here would bypass `history_after` and import the old corpus.
if bounded_history_incomplete and not live_cursors:
return None
await self._live_cursors(source_id, adapter)
# Only one scan of a source may be in flight: they share the
# cursor, and two readers means every file read twice. With a
# catch-up still holding the source there is no free moment to ask
@@ -1404,12 +1404,11 @@ class DurableWriteQueue:
) -> int:
"""Re-admit `waiting_for_model` jobs whose wait has elapsed.
A model outage clears on its own, so transient waiters retry on a timer
A model outage clears on its own, so this state is retried on a timer
rather than waiting for a grant event like `waiting_for_permission`.
`model_profile_not_active` is excluded: only explicit activation can
change that condition. Keyed on `updated_at` so repeated calls while a
job is still parked do not reset its own clock; the attempt consumed by
the parking claim is returned, the same way `readmit_parked` does.
Keyed on `updated_at` so repeated calls while a job is still parked do
not reset its own clock; the attempt consumed by the parking claim is
returned, the same way `readmit_parked` does.
"""
now = now or datetime.now(UTC)
threshold = (now - after).isoformat()
@@ -1418,33 +1417,8 @@ class DurableWriteQueue:
"UPDATE memory_write_jobs SET state=?, lease_owner=NULL, "
"lease_expires_at=NULL, attempts=CASE WHEN attempts>0 "
"THEN attempts-1 ELSE 0 END, last_error=NULL, updated_at=? "
"WHERE state=? AND updated_at <= ? AND hy_invoked=0 "
"AND (last_error IS NULL OR last_error<>?)",
(
PENDING,
now.isoformat(),
WAITING_FOR_MODEL,
threshold,
"model_profile_not_active",
),
)
return changed.rowcount
def readmit_model_profile_waiters(self) -> int:
"""Re-admit no-profile work only after model activation changes the condition."""
now = datetime.now(UTC).isoformat()
with main_database(self.database_path).write() as connection, connection:
changed = connection.execute(
"UPDATE memory_write_jobs SET state=?, lease_owner=NULL, "
"lease_expires_at=NULL, attempts=CASE WHEN attempts>0 "
"THEN attempts-1 ELSE 0 END, last_error=NULL, updated_at=? "
"WHERE state=? AND last_error=? AND hy_invoked=0",
(
PENDING,
now,
WAITING_FOR_MODEL,
"model_profile_not_active",
),
"WHERE state=? AND updated_at <= ? AND hy_invoked=0",
(PENDING, now.isoformat(), WAITING_FOR_MODEL, threshold),
)
return changed.rowcount
@@ -2097,12 +2071,7 @@ async def execute_job(
# Never `logger.exception` here: it prints the exception's message,
# which may be a provider response or the user's own text. Log the
# already-sanitised code instead, matching `hy-failure-classification`.
if code == "model_profile_not_active":
logger.debug("durable_write_job_parked job_id=%s error_code=%s", job_id, code)
elif state in PARKED_STATES:
logger.info("durable_write_job_parked job_id=%s error_code=%s", job_id, code)
else:
logger.error("durable_write_job_failed job_id=%s error_code=%s", job_id, code)
logger.error("durable_write_job_failed job_id=%s error_code=%s", job_id, code)
return
await in_the_background(queue.settle, job_id, state=COMPLETED, owner=owner)
@@ -200,12 +200,10 @@ def _trigger_sql() -> list[tuple[str, str]]:
CREATE TRIGGER IF NOT EXISTS memory_visibility_dirty_on_link_update
AFTER UPDATE ON governed_memory_evidence
BEGIN
INSERT INTO memory_visibility_dirty (memory_id)
VALUES (NEW.memory_id)
ON CONFLICT(memory_id) DO NOTHING;
INSERT INTO memory_visibility_dirty (memory_id)
VALUES (OLD.memory_id)
ON CONFLICT(memory_id) DO NOTHING;
INSERT OR IGNORE INTO memory_visibility_dirty (memory_id)
VALUES (NEW.memory_id);
INSERT OR IGNORE INTO memory_visibility_dirty (memory_id)
VALUES (OLD.memory_id);
END;""",
),
(
@@ -296,10 +294,6 @@ def install_triggers(db: sqlite3.Connection) -> None:
str(row["name"])
for row in cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
}
# CREATE TRIGGER IF NOT EXISTS cannot repair the legacy definition. Replace
# this derived-cache trigger transactionally on every startup so old
# libraries get the row-level conflict handling without a schema migration.
cursor.execute("DROP TRIGGER IF EXISTS memory_visibility_dirty_on_link_update")
for table, statement in _trigger_sql():
if table not in present:
continue
@@ -309,15 +303,11 @@ def install_triggers(db: sqlite3.Connection) -> None:
def startup(database_path: Path) -> None:
"""Idempotent: create the derived tables and triggers. No version change.
Runs through the write connection because the triggers are schema. The
trigger replacement is one short transaction and happens once per start.
Runs through the write connection because the triggers are schema. It is
one short transaction and happens once per start.
"""
with main_database(database_path).write() as db, db:
with main_database(database_path).write() as db:
ensure_tables(db)
# ensure_tables uses executescript(), which commits any pending legacy
# transaction. Begin only afterward so replacing the installed trigger
# is one atomic schema change and a failed CREATE restores the old one.
db.execute("BEGIN IMMEDIATE")
install_triggers(db)
-111
View File
@@ -94,67 +94,6 @@ class SettledFixtureAdapter(IncrementalFixtureAdapter):
}
class BoundedOnboardingAdapter:
"""No native baseline: bounded history must establish the live cursor."""
descriptor = IncrementalFixtureAdapter.descriptor
def __init__(self) -> None:
self.include_new = False
async def detect(self) -> bool:
return True
async def scan(self, options: ScanOptions):
current = options.cursors.get("e" * 64)
checkpoint = current.checkpoint if current is not None else None
if checkpoint not in {"byte:10", "byte:20"}:
yield ScannedEvidence(
evidence=EvidenceInput(
source_id="fixture",
conversation_id="old-conversation",
message_id="old-message",
role="user",
written_by=WrittenBy.PERSON,
created_at=datetime(2020, 1, 1, tzinfo=UTC),
verbatim="old history",
origin_meta={EvidenceOrigin.FILE: OriginMetadata()},
),
cursor=SourceCursor(
file_key="e" * 64,
file_identity="bounded",
checkpoint="byte:10",
checkpoint_anchor="f" * 64,
observed_size=20,
observed_modified_ns=1,
),
)
checkpoint = "byte:10"
if self.include_new and checkpoint != "byte:20":
yield ScannedEvidence(
evidence=EvidenceInput(
source_id="fixture",
conversation_id="new-conversation",
message_id="new-message",
role="user",
written_by=WrittenBy.PERSON,
created_at=datetime(2026, 10, 18, tzinfo=UTC),
verbatim="new append",
origin_meta={EvidenceOrigin.FILE: OriginMetadata()},
),
cursor=SourceCursor(
file_key="e" * 64,
file_identity="bounded",
checkpoint="byte:20",
checkpoint_anchor="1" * 64,
observed_size=20,
observed_modified_ns=2,
read_to_end=True,
),
)
yield ScanProgressEvent(phase=ScanPhase.DONE)
class HoldingHistoryAdapter:
"""First scan blocks until cancelled; later scans yield one new record."""
@@ -389,56 +328,6 @@ def test_live_sync_does_not_resume_a_history_import_the_user_paused(tmp_path) ->
asyncio.run(scenario())
def test_bounded_onboarding_history_establishes_cursor_before_first_sync(tmp_path) -> None:
async def scenario() -> None:
database = tmp_path / "one-memory.sqlite3"
evidence = EvidenceStore(database)
jobs = ImportJobStore(database)
adapter = BoundedOnboardingAdapter()
imports = ImportSupervisor(
adapters={"fixture": adapter},
evidence_store=evidence,
job_store=jobs,
)
live_sync = PollingLiveSyncSupervisor(
source_ids=("fixture",),
import_supervisor=imports,
job_store=jobs,
)
history = imports.create_job("fixture", operation="history")
with sqlite3.connect(database) as connection, connection:
connection.execute(
"UPDATE import_jobs SET history_after=? WHERE job_id=?",
(datetime(2026, 10, 15, tzinfo=UTC).isoformat(), history.job_id),
)
# With no native baseline, sync must wait instead of scanning from zero
# and bypassing the onboarding history window.
assert await live_sync.trigger("fixture") is None
assert not [job for job in jobs.list_jobs() if job.operation == "sync"]
imports.enqueue(history.job_id)
completed = await imports.wait(history.job_id)
assert completed.status is ImportStatus.COMPLETED
assert completed.stored == 0
assert completed.skipped == 1
assert evidence.count() == 0
# Once bounded history has advanced the cursor to EOF, normal realtime
# appends are admitted without retaining the three-day cutoff forever.
adapter.include_new = True
synced = await live_sync.trigger("fixture")
assert synced is not None
assert synced.status is ImportStatus.COMPLETED
assert synced.stored == 1
records = evidence.list_extractable()
assert [record.verbatim for record in records] == ["new append"]
await live_sync.shutdown()
await imports.shutdown()
asyncio.run(scenario())
def test_a_sync_left_running_after_its_worker_died_is_started_again(tmp_path) -> None:
"""A running row with no live worker used to be returned as 'already syncing'.
@@ -5,7 +5,6 @@ from __future__ import annotations
import asyncio
import contextlib
import json
import logging
import sqlite3
import threading
import time
@@ -1370,30 +1369,24 @@ def test_a_machine_error_code_is_preserved(tmp_path) -> None:
assert safe_error_code(ValueError("some sentence with spaces")) == "ValueError"
def test_an_inactive_profile_parks_without_error_logging(tmp_path, caplog) -> None:
def test_an_inactive_profile_parks_for_model_before_any_send(tmp_path) -> None:
"""A pre-bridge model-not-ready code parks and keeps the intent."""
path = tmp_path / "one-memory.sqlite3"
queue = DurableWriteQueue(path)
record = queue.submit(_request())
_claim_through_drain(queue, record.job_id)
with caplog.at_level(
logging.DEBUG,
logger="one_memory.memory_server.durable_queue",
):
asyncio.run(
execute_job(
record.job_id,
queue=queue,
supervisor=_Recorder(error=RuntimeError("model_profile_not_active")),
evidence=_EvidenceStore({"e1"}),
)
asyncio.run(
execute_job(
record.job_id,
queue=queue,
supervisor=_Recorder(error=RuntimeError("model_profile_not_active")),
evidence=_EvidenceStore({"e1"}),
)
)
assert _state(path, record.job_id) == WAITING_FOR_MODEL
assert _rows(path)[0]["hy_invoked"] == 0
assert "durable_write_job_failed" not in caplog.text
assert "durable_write_job_parked" in caplog.text
def test_an_authorization_stop_cancels_instead_of_failing(tmp_path) -> None:
@@ -1553,7 +1546,7 @@ def test_parking_does_not_burn_the_retry_budget(tmp_path) -> None:
assert queue.get("idem-1").state == PENDING
def test_a_transient_model_waiter_is_readmitted_once_its_wait_elapses(tmp_path) -> None:
def test_a_model_waiter_is_readmitted_once_its_wait_elapses(tmp_path) -> None:
"""A model outage clears on its own; nothing re-admits it otherwise.
`waiting_for_permission` needs a grant event, but `waiting_for_model` is
@@ -1571,7 +1564,7 @@ def test_a_transient_model_waiter_is_readmitted_once_its_wait_elapses(tmp_path)
queue.settle(
record.job_id,
state=WAITING_FOR_MODEL,
error_code="model_secret_unavailable",
error_code="model_profile_not_active",
hy_invoked=False,
)
@@ -1588,8 +1581,8 @@ def test_a_transient_model_waiter_is_readmitted_once_its_wait_elapses(tmp_path)
assert _rows(path)[0]["attempts"] == 0
def test_no_profile_waiter_is_readmitted_only_after_activation(tmp_path) -> None:
"""No timer can create a model profile; activation owns this transition."""
def test_readmitting_a_model_waiter_clears_its_stale_detail(tmp_path) -> None:
"""The timer readmission path must clear the old blocking reason too."""
path = tmp_path / "one-memory.sqlite3"
queue = DurableWriteQueue(path)
record = queue.submit(_request())
@@ -1601,50 +1594,13 @@ def test_no_profile_waiter_is_readmitted_only_after_activation(tmp_path) -> None
)
now = datetime.now(UTC)
assert queue.readmit_model_waiters(now=now + timedelta(minutes=2)) == 0
parked = queue.get("idem-1")
assert parked.state == WAITING_FOR_MODEL
assert parked.detail == "model_profile_not_active"
assert queue.readmit_model_waiters(now=now + timedelta(minutes=2)) == 1
assert queue.readmit_model_profile_waiters() == 1
readmitted = queue.get("idem-1")
assert readmitted.state == PENDING
assert readmitted.detail == ""
def test_no_profile_backlog_stays_parked_across_maintenance_cycles(tmp_path) -> None:
path = tmp_path / "one-memory.sqlite3"
queue = DurableWriteQueue(path)
for index in range(100):
record = queue.submit(_request(key=f"no-profile-{index}"))
queue.settle(
record.job_id,
state=WAITING_FOR_MODEL,
error_code="model_profile_not_active",
hy_invoked=False,
)
with sqlite3.connect(path) as connection, connection:
connection.execute(
"UPDATE memory_write_jobs SET attempts=1,"
"updated_at='2000-01-01T00:00:00+00:00'"
)
first = datetime.now(UTC)
assert queue.readmit_model_waiters(now=first, after=timedelta(0)) == 0
assert (
queue.readmit_model_waiters(
now=first + timedelta(minutes=2),
after=timedelta(0),
)
== 0
)
with sqlite3.connect(path) as connection:
assert connection.execute(
"SELECT state,attempts,COUNT(*) FROM memory_write_jobs "
"GROUP BY state,attempts"
).fetchall() == [(WAITING_FOR_MODEL, 1, 100)]
def test_readmit_parked_cannot_resurrect_a_terminal_row(tmp_path) -> None:
"""Only parked states may be re-admitted, never a finished write.
@@ -8,14 +8,7 @@ import pytest
from one_memory.imports.grants import GRANT_SCHEMA
from one_memory.imports.models import EvidenceInput, EvidenceOrigin, OriginMetadata, WrittenBy
from one_memory.imports.storage import EvidenceStore
from one_memory.memory_governance import (
HyCreate,
HyLink,
HyRevise,
MemoryDraft,
MemoryGovernanceStore,
MemoryKind,
)
from one_memory.memory_governance import MemoryDraft, MemoryGovernanceStore, MemoryKind
from one_memory.memory_tasks import (
MemoryTaskOutput,
MemoryTaskStore,
@@ -26,7 +19,6 @@ from one_memory.memory_visibility import (
install_triggers,
pending,
recompute,
startup,
)
from one_memory.model_profiles import (
ModelCapabilities,
@@ -344,197 +336,6 @@ def test_starting_the_app_creates_the_derived_tables(tmp_path):
asyncio.run(scenario())
@pytest.mark.parametrize("visibility_mode", ["exact", "derived"])
def test_hy_revise_and_repeated_link_reuse_the_same_evidence(library, monkeypatch, visibility_mode):
"""The outer evidence UPSERT must not override the trigger's duplicate handling."""
database, evidence, _tasks, governance, _profile = library
monkeypatch.setenv("ONE_MEMORY_READ_VISIBILITY", visibility_mode)
startup(database)
record = evidence.put(
EvidenceInput(
source_id="cursor",
conversation_id="trigger-regression",
message_id="trigger-regression",
correlation_id="trigger-regression",
role="user",
written_by=WrittenBy.PERSON,
verbatim="用户住在杭州。",
origin_meta={EvidenceOrigin.FILE: OriginMetadata()},
)
).record
created = governance.write_from_hy(
HyCreate(
draft=MemoryDraft(
user_id="local",
kind=MemoryKind.CHAT,
content="用户住在杭州。",
scopes=("all-apps",),
evidence_ids=(record.evidence_id,),
),
request_id="trigger-create",
memory_id="trigger-memory",
),
user_id="local",
derivation=governance.hy_derivation((record.evidence_id,)),
)
revision = HyRevise(
memory_id=created.memory_id,
request_id="trigger-revise",
expected_revision=created.revision,
content="用户住在杭州并在那里工作。",
evidence_ids=(record.evidence_id,),
)
revised = governance.write_from_hy(
revision,
user_id="local",
derivation=governance.hy_derivation((record.evidence_id,)),
)
replayed = governance.write_from_hy(
revision,
user_id="local",
derivation=governance.hy_derivation((record.evidence_id,)),
)
assert replayed == revised
link = HyLink(memory_id=created.memory_id, evidence_id=record.evidence_id)
for _ in range(2):
governance.write_from_hy(
link,
user_id="local",
derivation=governance.hy_derivation((record.evidence_id,)),
)
current = governance.get(created.memory_id, user_id="local")
assert current is not None
assert current.content == "用户住在杭州并在那里工作。"
assert current.revision == created.revision + 1
with main_database_read(database) as db:
assert db.execute(
"SELECT memory_id, COUNT(*) FROM memory_visibility_dirty GROUP BY memory_id"
).fetchall() == [(created.memory_id, 1)]
if visibility_mode == "derived":
monkeypatch.setenv("ONE_MEMORY_READ_VISIBILITY", "exact")
exact = {memory.memory_id for memory in SourceReadAccess(database).filter([current])}
with main_database_write(database) as db:
assert recompute(db, [created.memory_id], readable_sql=_MEMORY_READABLE) == 1
db.commit()
monkeypatch.setenv("ONE_MEMORY_READ_VISIBILITY", "derived")
derived = {memory.memory_id for memory in SourceReadAccess(database).filter([current])}
assert derived == exact
with main_database_read(database) as db:
assert created.memory_id not in pending(db)
def test_startup_atomically_replaces_the_legacy_link_update_trigger(tmp_path, monkeypatch):
import one_memory.memory_visibility as visibility_module
from one_memory.schema_gate import guard_schema_version
database = tmp_path / "one-memory.sqlite3"
expected_version = guard_schema_version(database)
evidence = EvidenceStore(database)
governance = MemoryGovernanceStore(database)
record = evidence.put(
EvidenceInput(
source_id="cursor",
conversation_id="legacy-trigger",
message_id="legacy-trigger",
correlation_id="legacy-trigger",
role="user",
written_by=WrittenBy.PERSON,
verbatim="升级失败不能改变这条原文。",
origin_meta={EvidenceOrigin.FILE: OriginMetadata()},
)
).record
memory = as_person(governance).create(
MemoryDraft(
user_id="local",
kind=MemoryKind.CHAT,
content="升级失败不能改变这条记忆。",
scopes=("all-apps",),
evidence_ids=(record.evidence_id,),
),
request_id="legacy-trigger-memory",
)
startup(database)
with sqlite3.connect(database) as db:
db.execute("DROP TRIGGER memory_visibility_dirty_on_link_update")
db.executescript(
"""
CREATE TRIGGER memory_visibility_dirty_on_link_update
AFTER UPDATE ON governed_memory_evidence
BEGIN
INSERT OR IGNORE INTO memory_visibility_dirty (memory_id)
VALUES (NEW.memory_id);
INSERT OR IGNORE INTO memory_visibility_dirty (memory_id)
VALUES (OLD.memory_id);
END;
"""
)
db.execute(
"INSERT INTO memory_visibility (memory_id, visible, reason, computed_at) "
"VALUES (?, 1, 'ok', '2026-10-19T00:00:00+00:00')",
(memory.memory_id,),
)
db.execute(
"INSERT INTO memory_visibility_dirty (memory_id) VALUES (?)",
(memory.memory_id,),
)
legacy_trigger = db.execute(
"SELECT sql FROM sqlite_master "
"WHERE type='trigger' AND name='memory_visibility_dirty_on_link_update'"
).fetchone()[0]
before = tuple(db.iterdump())
real_trigger_sql = visibility_module._trigger_sql
def fail_after_drop() -> list[tuple[str, str]]:
statements = real_trigger_sql()
return [
(table, "CREATE TRIGGER")
if "CREATE TRIGGER IF NOT EXISTS memory_visibility_dirty_on_link_update" in statement
else (table, statement)
for table, statement in statements
]
with monkeypatch.context() as failure:
failure.setattr(visibility_module, "_trigger_sql", fail_after_drop)
with pytest.raises(sqlite3.OperationalError):
startup(database)
with sqlite3.connect(database) as db:
assert tuple(db.iterdump()) == before
assert (
db.execute(
"SELECT sql FROM sqlite_master "
"WHERE type='trigger' AND name='memory_visibility_dirty_on_link_update'"
).fetchone()[0]
== legacy_trigger
)
assert db.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] == (
expected_version
)
startup(database)
startup(database)
with sqlite3.connect(database) as db:
trigger_sql = db.execute(
"SELECT sql FROM sqlite_master "
"WHERE type='trigger' AND name='memory_visibility_dirty_on_link_update'"
).fetchone()[0]
assert trigger_sql.count("ON CONFLICT(memory_id) DO NOTHING") == 2
assert "INSERT OR IGNORE" not in trigger_sql
assert db.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] == (
expected_version
)
assert db.execute("SELECT * FROM memory_visibility").fetchall() == [
(memory.memory_id, 1, "ok", "2026-10-19T00:00:00+00:00")
]
assert db.execute("SELECT * FROM memory_visibility_dirty").fetchall() == [
(memory.memory_id,)
]
def test_the_audit_notices_a_conclusion_that_no_longer_holds(library):
"""The ongoing proof: recompute a slice and compare with what is stored.
@@ -259,17 +259,12 @@ def test_activation_survives_a_corpus_already_imported(tmp_path) -> None:
),
secrets=secrets,
)
readmissions: list[bool] = []
app.state.memory_write_queue.readmit_model_profile_waiters = (
lambda: readmissions.append(True) or 0
)
activated = await client.post(f"/api/v1/model-profiles/{profile_id}/activate")
assert activated.status_code == 200
assert activated.json()["is_active"] is True
assert API_KEY not in activated.text
assert readmissions == [True]
# Started, not waited for: the walk reads every conversation.
assert not app.state.memory_backfill.done()
@@ -111,9 +111,6 @@ def test_the_manual_source_is_admitted_by_grant_without_a_toggle(tmp_path) -> No
app = SimpleNamespace(
state=SimpleNamespace(
config_store=config,
model_profile_store=SimpleNamespace(
active_identity=lambda: ("profile", 1)
),
source_grant_store=SimpleNamespace(
receipt=lambda **_kwargs: SimpleNamespace(revoked_at=None)
),
@@ -128,21 +125,6 @@ def test_the_manual_source_is_admitted_by_grant_without_a_toggle(tmp_path) -> No
assert _sedimentation_claim_enabled(app, "one-memory-manual") is False
def test_claim_gate_waits_without_polling_when_no_model_is_active(tmp_path) -> None:
config = ConfigStore(tmp_path)
app = SimpleNamespace(
state=SimpleNamespace(
config_store=config,
model_profile_store=SimpleNamespace(active_identity=lambda: None),
source_grant_store=SimpleNamespace(
receipt=lambda **_kwargs: SimpleNamespace(revoked_at=None)
),
)
)
assert _sedimentation_claim_enabled(app, "one-memory-manual") is False
def test_first_import_gate_waits_for_every_selected_history_job() -> None:
state = SimpleNamespace(
status="importing",
@@ -174,20 +174,20 @@ it("continues to step3 while sample GET is pending without calling completion AP
expect(screen.queryByText(/^已生成.*记忆/)).toBeNull();
});
it.each([
["pending", "已扫描 100 条,正在筛选"],
["paused", "已扫描 100 条,尚未保存"],
["interrupted", "已扫描 100 条,尚未保存"],
["failed", "已扫描 100 条,尚未保存"],
["cancelled", "已扫描 100 条,尚未保存"],
["completed", "已扫描 100 条,本次没有可保存的对话"],
"pending",
"paused",
"interrupted",
"failed",
"cancelled",
"completed",
] as const)(
"shows %s without mutating jobs or fetching missing content",
(status, expected) => {
(status) => {
setup({
jobs: [{ ...job, status, stored: 0 }],
sources: [{ ...source, imported_messages: 0 }],
});
expect(screen.getByText(expected)).toBeTruthy();
expect(screen.getByText("已扫描 100 条,正在保存")).toBeTruthy();
expect(api.receipt).not.toHaveBeenCalled();
},
);
@@ -38,71 +38,6 @@ it("uses the selected job's message count, never the source total or fake percen
expect(container.textContent).not.toContain("%");
expect(container.textContent).not.toContain("持续导入中");
});
it("does not describe scanned-but-skipped history as saved", () => {
const { container } = render(
<R6ImportProgress
sourceIds={["cursor"]}
sources={[source]}
jobs={[
{
...job,
status: "completed",
discovered: 12_375,
stored: 0,
skipped: 12_375,
history_after: "2026-10-15T00:00:00Z",
},
]}
/>,
);
expect(
screen.getByText("已扫描 12,375 条,本次没有符合时间范围的对话"),
).toBeTruthy();
expect(screen.getByText("导入完成")).toBeTruthy();
expect(container.textContent).not.toContain("正在保存");
expect(container.textContent).not.toContain("已保存 12,375");
});
it("calls an active bounded scan filtering rather than saving", () => {
render(
<R6ImportProgress
sourceIds={["cursor"]}
sources={[source]}
jobs={[
{
...job,
discovered: 3_522,
stored: 0,
history_after: "2026-10-15T00:00:00Z",
},
]}
/>,
);
expect(screen.getByText("已扫描 3,522 条,正在筛选最近 3 天")).toBeTruthy();
});
it("reports only stored rows as saved after a completed partial import", () => {
const { container } = render(
<R6ImportProgress
sourceIds={["cursor"]}
sources={[source]}
jobs={[
{
...job,
status: "completed",
discovered: 25_177,
stored: 20_826,
skipped: 4_351,
},
]}
/>,
);
expect(screen.getByText("已保存 20,826 条消息")).toBeTruthy();
expect(screen.getByText("导入完成")).toBeTruthy();
expect(container.textContent).not.toContain("25,177");
});
it.each(["paused", "interrupted", "failed", "completed", "cancelled"] as const)(
"does not animate %s as active work",
(status) => {
+5 -19
View File
@@ -3,21 +3,6 @@ import { useEffect, useLayoutEffect, useRef } from "react";
import { AppMark } from "./app-mark";
import "./r6-import-progress.css";
function progressText(job: ImportJob): string | null {
if (job.stored > 0) return `已保存 ${job.stored.toLocaleString()} 条消息`;
if (job.discovered <= 0) return null;
const scanned = `已扫描 ${job.discovered.toLocaleString()} 条`;
if (job.status === "completed")
return job.history_after
? `${scanned},本次没有符合时间范围的对话`
: `${scanned},本次没有可保存的对话`;
if (job.status === "pending" || job.status === "running")
return job.history_after
? `${scanned},正在筛选最近 3 天`
: `${scanned},正在筛选`;
return `${scanned},尚未保存`;
}
export function R6ImportProgress({
sourceIds,
sources,
@@ -101,9 +86,8 @@ export function R6ImportProgress({
interrupted: "已中断",
failed: "导入遇到问题",
cancelled: "已取消",
completed: "导入完成",
completed: "已保存",
};
const progress = job ? progressText(job) : null;
return (
<article
className="r6-import-progress-card"
@@ -118,8 +102,10 @@ export function R6ImportProgress({
</div>
</div>
<h2>{source?.display_name ?? id}</h2>
{progress ? (
<p>{progress}</p>
{job && job.stored > 0 ? (
<p>{`已保存 ${job.stored.toLocaleString()} 条消息`}</p>
) : job && job.discovered > 0 ? (
<p>{`已扫描 ${job.discovered.toLocaleString()} 条,正在保存`}</p>
) : noImportedHistory ? (
<p>没有可保存的历史对话</p>
) : null}
@@ -312,48 +312,6 @@ describe("remote Runtime acquisition", () => {
});
});
it("allows the exact GitHub Release asset redirect hosts by default", async () => {
const value = await fixture();
const manifestUrl =
"https://github.com/example/project/releases/download/v1.2.3/release-manifest.json";
const artifactUrl =
"https://github.com/example/project/releases/download/v1.2.3/runtime.tar.gz";
const manifestAssetUrl =
"https://release-assets.githubusercontent.com/manifest-download";
const runtimeAssetUrl =
"https://release-assets.githubusercontent.com/runtime-download";
const release = {
...value.release,
artifacts: [{ ...value.artifact, url: artifactUrl }],
};
const temporaryParent = await mkdtemp(
path.join(os.tmpdir(), "memhub-github-release-parent-"),
);
roots.push(temporaryParent);
const acquired = await acquireRuntimeDistribution({
manifestUrl,
expectedVersion: "1.2.3",
channel: "stable",
platform: "linux",
arch: "x64",
temporaryParent,
httpGet: httpFixture({
[manifestUrl]: response(new Uint8Array(), 302, {
location: manifestAssetUrl,
}),
[manifestAssetUrl]: response(Buffer.from(JSON.stringify(release))),
[artifactUrl]: response(new Uint8Array(), 302, {
location: runtimeAssetUrl,
}),
[runtimeAssetUrl]: response(value.archiveBytes),
}),
});
expect(acquired.release.version).toBe("1.2.3");
await acquired.cleanup();
});
it("rejects an archive whose internal commit drifts from the Release", async () => {
const value = await fixture();
const release = { ...value.release, git_commit: "b".repeat(40) };
@@ -410,6 +368,7 @@ describe("remote Runtime acquisition", () => {
);
it("rejects a redirect to an untrusted host", async () => {
const value = await fixture();
await expect(
acquireRuntimeDistribution({
manifestUrl: "https://downloads.example.test/release-manifest.json",
@@ -38,10 +38,6 @@ const SHA256 = /^[a-f0-9]{64}$/;
const COMMIT = /^[0-9a-f]{40}$/;
const SAFE_FILE_NAME = /^[0-9A-Za-z][0-9A-Za-z._-]{0,255}$/;
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
const GITHUB_RELEASE_REDIRECT_HOSTS = [
"release-assets.githubusercontent.com",
"objects.githubusercontent.com",
] as const;
export type ReleaseChannel = "stable" | "prerelease";
export type RuntimeReleasePlatform = "darwin" | "linux";
@@ -334,12 +330,8 @@ export async function resolveRuntimeRelease(options: {
maxRedirects?: number;
}): Promise<ResolvedRuntimeRelease> {
const manifestUrl = trustedUrl(options.manifestUrl);
const defaultHosts =
normalizedHost(manifestUrl.hostname) === "github.com"
? [manifestUrl.hostname, ...GITHUB_RELEASE_REDIRECT_HOSTS]
: [manifestUrl.hostname];
const allowedHosts = new Set(
(options.allowedHosts ?? defaultHosts).map(normalizedHost),
(options.allowedHosts ?? [manifestUrl.hostname]).map(normalizedHost),
);
if (!allowedHosts.has(normalizedHost(manifestUrl.hostname))) {
throw new Error("release_url_untrusted");
-7
View File
@@ -8,7 +8,6 @@ import {
mkdir,
readdir,
readFile,
readlink,
realpath,
rm,
stat,
@@ -321,12 +320,6 @@ async function distributionBytes(source) {
async function sha256File(file) {
const digest = createHash("sha256");
const info = await lstat(file);
if (info.isSymbolicLink()) {
digest.update("symlink\0");
digest.update(await readlink(file));
return digest.digest("hex");
}
for await (const chunk of createReadStream(file)) digest.update(chunk);
return digest.digest("hex");
}
@@ -6,7 +6,6 @@ import {
readdir,
readFile,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import os from "node:os";
@@ -122,35 +121,6 @@ test("builds versioned Runtime archives, checksums and a downloader-compatible m
}
});
test("verifies Runtime symlinks with the same identity rule as the installer", async (t) => {
const root = await mkdtemp(path.join(os.tmpdir(), "memhub-release-assets-"));
t.after(() => rm(root, { recursive: true, force: true }));
const source = await distribution(root, "linux", "x64");
const link = "memhub";
await symlink(link, path.join(source, "bin", "node"));
const manifestPath = path.join(source, "manifest.json");
const manifest = JSON.parse(await readFile(manifestPath, "utf8"));
manifest.files["bin/node"] = sha256(`symlink\0${link}`);
await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
const release = await buildReleaseAssets({
output: path.join(root, "release"),
version: "0.1.0-internal.1",
channel: "prerelease",
assetBaseUrl: "https://git.example.test/release/downloads/",
distributions: [source],
});
assert.ok(
release.artifacts.some(
(artifact) =>
artifact.kind === "runtime" &&
artifact.platform === "linux" &&
artifact.arch === "x64",
),
);
});
test("refuses version, build and duplicate target drift", async (t) => {
const root = await mkdtemp(path.join(os.tmpdir(), "memhub-release-assets-"));
t.after(() => rm(root, { recursive: true, force: true }));
+5 -13
View File
@@ -23,8 +23,7 @@ export async function publishCliAfterRelease(options, dependencies = {}) {
const statImpl = dependencies.statImpl ?? stat;
const buildEnvironment = {
...environment,
MEMHUB_NPM_VERSION: options.version,
MEMHUB_DEFAULT_RUNTIME_VERSION: options.runtimeVersion,
ONE_MEMORY_VERSION: options.version,
ONE_MEMORY_BUILD_NUMBER: String(options.buildNumber),
ONE_MEMORY_COMMIT: options.gitCommit,
};
@@ -32,7 +31,7 @@ export async function publishCliAfterRelease(options, dependencies = {}) {
const versionReceipt = await verifyVersion(
[
"--version",
options.runtimeVersion,
options.version,
"--channel",
options.channel,
"--tag",
@@ -44,7 +43,7 @@ export async function publishCliAfterRelease(options, dependencies = {}) {
);
const releaseReceipt = await verifyRelease({
manifestUrl: options.manifestUrl,
version: options.runtimeVersion,
version: options.version,
gitCommit: options.gitCommit,
channel: options.channel,
platform: options.platform,
@@ -107,8 +106,7 @@ export async function publishCliAfterRelease(options, dependencies = {}) {
return {
schema_version: 1,
product: "memhub-cli-publication",
version: options.version,
runtime_version: releaseReceipt.version,
version: versionReceipt.version,
build_number: versionReceipt.build_number,
tag: versionReceipt.tag,
release: releaseReceipt,
@@ -198,11 +196,6 @@ function parseArgs(arguments_) {
options.manifestUrl = value;
else if (flag === "--version" && options.version === undefined)
options.version = value;
else if (
flag === "--runtime-version" &&
options.runtimeVersion === undefined
)
options.runtimeVersion = value;
else if (flag === "--git-commit" && options.gitCommit === undefined)
options.gitCommit = value;
else if (flag === "--channel" && options.channel === undefined)
@@ -226,7 +219,6 @@ function parseArgs(arguments_) {
if (
!options.manifestUrl ||
!options.version ||
!options.runtimeVersion ||
!options.gitCommit ||
!options.channel ||
!options.tag ||
@@ -238,7 +230,7 @@ function parseArgs(arguments_) {
!options.npmTag
) {
throw new Error(
"usage: publish-cli-after-release.mjs --manifest-url <https-url> --version <CLI SemVer> --runtime-version <Runtime SemVer> --git-commit <sha> --channel <stable|prerelease> --tag <vSemVer> --build-number <integer> --platform <darwin|linux> --arch <x64|arm64> --registry <https-url> --npm-tag <tag> [--access <public|restricted>] [--provenance] [--allowed-host <hostname>] [--dry-run]",
"usage: publish-cli-after-release.mjs --manifest-url <https-url> --version <SemVer> --git-commit <sha> --channel <stable|prerelease> --tag <vSemVer> --build-number <integer> --platform <darwin|linux> --arch <x64|arm64> --registry <https-url> --npm-tag <tag> [--access <public|restricted>] [--provenance] [--allowed-host <hostname>] [--dry-run]",
);
}
return options;
@@ -6,9 +6,6 @@ import test from "node:test";
import { publishCliAfterRelease } from "./publish-cli-after-release.mjs";
const CLI_VERSION = "0.1.1";
const RUNTIME_VERSION = "0.1.0-internal.1";
async function fixture(t) {
const root = await mkdtemp(path.join(os.tmpdir(), "memhub-publish-gate-"));
t.after(() => rm(root, { recursive: true, force: true }));
@@ -18,10 +15,10 @@ async function fixture(t) {
await mkdir(output, { recursive: true });
await writeFile(
path.join(publish, "package.json"),
`${JSON.stringify({ name: "@example/memhub-cli", version: CLI_VERSION, private: false })}\n`,
`${JSON.stringify({ name: "@example/memhub-cli", version: "0.1.0-internal.1", private: false })}\n`,
);
await writeFile(
path.join(output, `example-memhub-cli-${CLI_VERSION}.tgz`),
path.join(output, "example-memhub-cli-0.1.0-internal.1.tgz"),
"tarball",
);
return root;
@@ -29,11 +26,10 @@ async function fixture(t) {
const options = {
manifestUrl: "https://releases.example.test/release-manifest.json",
version: CLI_VERSION,
runtimeVersion: RUNTIME_VERSION,
version: "0.1.0-internal.1",
gitCommit: "a".repeat(40),
channel: "prerelease",
tag: `v${RUNTIME_VERSION}`,
tag: "v0.1.0-internal.1",
buildNumber: 1,
platform: "linux",
arch: "x64",
@@ -53,24 +49,15 @@ test("verifies the Runtime before building and publishing the CLI", async (t) =>
{
verifyVersion: async () => {
events.push("version");
return {
version: options.runtimeVersion,
build_number: 1,
tag: options.tag,
};
return { version: options.version, build_number: 1, tag: options.tag };
},
verifyRelease: async (verifyOptions) => {
events.push("release");
assert.equal(verifyOptions.gitCommit, options.gitCommit);
assert.equal(verifyOptions.version, options.runtimeVersion);
return { version: options.runtimeVersion, sha256: "a".repeat(64) };
return { version: options.version, sha256: "a".repeat(64) };
},
runCommand: (command, arguments_, commandOptions) => {
assert.equal(commandOptions.env.MEMHUB_NPM_VERSION, options.version);
assert.equal(
commandOptions.env.MEMHUB_DEFAULT_RUNTIME_VERSION,
options.runtimeVersion,
);
assert.equal(commandOptions.env.ONE_MEMORY_VERSION, options.version);
assert.equal(
commandOptions.env.ONE_MEMORY_BUILD_NUMBER,
String(options.buildNumber),
@@ -87,8 +74,6 @@ test("verifies the Runtime before building and publishing the CLI", async (t) =>
assert.match(events[3], /--access public/);
assert.match(events[3], /--provenance/);
assert.equal(receipt.npm_package, "@example/memhub-cli");
assert.equal(receipt.version, CLI_VERSION);
assert.equal(receipt.runtime_version, RUNTIME_VERSION);
assert.equal(receipt.dry_run, true);
assert.equal(receipt.npm_access, "public");
assert.equal(receipt.provenance, true);
@@ -102,7 +87,7 @@ test("never builds or invokes npm when the Runtime release is unavailable", asyn
{ ...options, root },
{
verifyVersion: async () => ({
version: options.runtimeVersion,
version: options.version,
build_number: 1,
tag: options.tag,
}),
@@ -130,11 +115,11 @@ test("rejects a package identity that differs from the configured publish name",
},
{
verifyVersion: async () => ({
version: options.runtimeVersion,
version: options.version,
build_number: 1,
tag: options.tag,
}),
verifyRelease: async () => ({ version: options.runtimeVersion }),
verifyRelease: async () => ({ version: options.version }),
runCommand: () => undefined,
},
),
+23 -59
View File
@@ -12,9 +12,8 @@ L1_RAW 对外读路径不可见:闸门焊在向量库唯一查询入口。
hybrid_search_native / list_by_user 四个查询方法的共同必经处,
上层无法绕开,新增接口自动受保护。
按 ID 直取走主键查询、不经过 filter,故在 `client.async_get` 处默认挡住。
Python SDK 调用方可显式传 `include_raw=True` 读取;HTTP 接口不传该参数,
继续保持原有隐藏行为。
按 ID 直取走主键查询、不经过 filter,故在 `client.async_get` 处单独挡
(GET /v1/memories/{id} 与 /v1/memories/batch 的共同必经处)。
内部管线需读原始对话时显式 allow_raw_layer=True 放行:
- `writer._get_recent_dialogue_history`:提取前拼多轮对话历史喂 LLM
@@ -125,63 +124,28 @@ class TestListNoLongerFiltersInProcess:
"list 又出现进程内过滤 raw 的写法,应交由 vdb 侧 filter 完成"
class TestGetByIdRawOptIn:
"""按 ID 直取默认隐藏 raw,只有 SDK 显式选择时才返回。"""
class TestGetByIdPathBlocksRaw:
"""按 ID 直取:走主键查询不经 filter,须在 async_get 处挡住。"""
@staticmethod
def _client(node):
from hy_memory.client import HyMemoryClient
class Store:
async def get_by_id(self, memory_id):
return node if memory_id == node.node_id else None
async def no_op_log(**kwargs):
return None
client = HyMemoryClient.__new__(HyMemoryClient)
client._vector_store = Store()
client._graph_store = None
client._backend_identity = lambda: {}
client._maybe_store_op_log = no_op_log
return client
@staticmethod
def _raw_node():
return MemoryNode(
node_id="raw-1",
user_id="u1",
agent_id="a1",
session_id="s1",
content="原始对话",
layer=MemoryLayer.L1_RAW,
status=MemoryStatus.ACTIVE,
custom={"meta": [{"source": "test"}]},
)
def test_default_still_hides_raw(self):
from hy_memory.client import HyMemoryClient
client = self._client(self._raw_node())
raw_get = HyMemoryClient.async_get.__wrapped__
assert run(raw_get(client, "raw-1")) is None
def test_explicit_include_raw_returns_lite_memory(self):
from hy_memory.client import HyMemoryClient
client = self._client(self._raw_node())
raw_get = HyMemoryClient.async_get.__wrapped__
result = run(raw_get(client, "raw-1", include_raw=True))
assert result["memory_id"] == "raw-1"
assert result["content"] == "原始对话"
assert result["layer"] == MemoryLayer.L1_RAW.value
assert result["meta"] == [{"source": "test"}]
def test_public_get_exposes_keyword_only_opt_in(self):
def test_async_get_drops_raw_node(self):
import inspect
from hy_memory.client import HyMemoryClient
src = inspect.getsource(HyMemoryClient.async_get)
assert "MemoryLayer.L1_RAW" in src, \
"async_get 未挡 raw,batch 与按 ID 单取会漏出原始对话"
param = inspect.signature(HyMemoryClient.get).parameters["include_raw"]
assert param.default is False
assert param.kind is inspect.Parameter.KEYWORD_ONLY
def test_block_happens_before_return(self):
"""挡的位置必须在两处 return 之前,否则等于没挡。"""
import inspect
from hy_memory.client import HyMemoryClient
lines = inspect.getsource(HyMemoryClient.async_get).splitlines()
block_at = next(
i for i, l in enumerate(lines)
if "MemoryLayer.L1_RAW" in l and "vdb_node" in l
)
first_return_at = next(
i for i, l in enumerate(lines)
if l.strip().startswith("return {")
)
assert block_at < first_return_at, \
f"挡 raw 在第 {block_at} 行、首个 return 在第 {first_return_at} 行,顺序错了"
-136
View File
@@ -1,136 +0,0 @@
import asyncio
import threading
import pytest
from hy_memory.config import MemoryConfig
from hy_memory.data.cache_sqlite import SqliteCache
from hy_memory.data.history_store import HistoryStore
class _BlockingCursor:
def fetchone(self):
return (1,)
def fetchall(self):
return []
class _BlockingConnection:
"""Hold execute() open so a concurrent close() can be observed."""
def __init__(self):
self.entered = threading.Event()
self.release = threading.Event()
self.closed = threading.Event()
def execute(self, *_args, **_kwargs):
self.entered.set()
if not self.release.wait(timeout=2):
raise TimeoutError("test did not release the blocking query")
if self.closed.is_set():
raise AssertionError("connection was closed while execute() was active")
return _BlockingCursor()
def close(self):
self.closed.set()
def _config(tmp_path) -> MemoryConfig:
config = MemoryConfig()
config.history.db_path = str(tmp_path / "history.db")
config.cache.db_path = str(tmp_path / "cache.db")
return config
async def _wait_for(event: threading.Event) -> None:
assert await asyncio.wait_for(asyncio.to_thread(event.wait, 1), timeout=2)
@pytest.mark.asyncio
async def test_history_close_waits_for_active_query(tmp_path):
store = HistoryStore(_config(tmp_path))
connection = _BlockingConnection()
store._conn = connection
query = asyncio.create_task(store.count())
await _wait_for(connection.entered)
closing = asyncio.create_task(store.close())
await asyncio.sleep(0.05)
assert not connection.closed.is_set()
connection.release.set()
assert await query == 1
await closing
assert connection.closed.is_set()
@pytest.mark.asyncio
async def test_cache_close_waits_for_active_query(tmp_path):
store = SqliteCache(_config(tmp_path))
connection = _BlockingConnection()
store._conn = connection
query = asyncio.create_task(store.load_metrics_range("0", "9"))
await _wait_for(connection.entered)
closing = asyncio.create_task(store.close())
await asyncio.sleep(0.05)
assert not connection.closed.is_set()
connection.release.set()
assert await query == []
await closing
assert connection.closed.is_set()
@pytest.mark.asyncio
async def test_history_concurrent_reads_and_writes_are_serialized(tmp_path):
store = HistoryStore(_config(tmp_path))
await store.initialize()
try:
inserted = await asyncio.gather(
*(
store.record_add(
memory_id=f"memory-{index}",
content="content",
layer="l2_fact",
isolation_key="user",
)
for index in range(200)
)
)
assert all(row_id > 0 for row_id in inserted)
assert len(set(inserted)) == 200
counts = await asyncio.gather(*(store.count() for _ in range(100)))
assert counts == [200] * 100
finally:
await store.close()
@pytest.mark.asyncio
async def test_cache_concurrent_pipeline_log_reads_and_writes_are_serialized(tmp_path):
store = SqliteCache(_config(tmp_path))
await store.initialize()
try:
written = await asyncio.gather(
*(
store.store_pipeline_log(
request_id="request",
user_id="user",
agent_id="agent",
step="EXTRACT",
prompt=f"prompt-{index}",
response="response",
)
for index in range(200)
)
)
assert written == [True] * 200
pages = await asyncio.gather(
*(store.get_pipeline_logs(request_id="request", limit=200) for _ in range(50))
)
assert all(len(page) == 200 for page in pages)
finally:
await store.close()