Skip to content
Python

fix(memhub): repair SDK memory library acceptance issues

alvinfeie6426f6fd0ba
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e43e642..9b8a7f5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@ Hy Memory and MemHub are versioned and released independently.
views and removed the retired "original evidence" surface. SDK-native status,
source, conversation time and creation time now render without fabricated
revisions; source and text filters are applied by the paged Core endpoint.
+- SDK memory search now calls the SDK search contract instead of listing the
+ entire library in Core. Corrupt empty records are skipped and diagnosed
+ without mutating data or failing a page, and post-cutover metadata repair
+ restores source and original times from the verified migration bundle.
+- Kept Cursor's WAL change token separate from the file mtime so a hash can no
+ longer appear as a conversation date centuries in the future.
+- A trusted packaged Runtime now repairs a dirty same-build installation by
+ staging a clean replacement, and `runtime_service_not_ready` is rendered as
+ user-facing startup guidance instead of an internal code.
- Fixed legacy-to-SDK startup migration to adopt native Coding Experience and
Working Fact IDs instead of importing them as Chat layers. Raw migration now
rebuilds bounded user/assistant turns from the latest three days, excludes
diff --git a/memhub/MEMORY.md b/memhub/MEMORY.md
index 5b53b31..9504630 100644
--- a/memhub/MEMORY.md
+++ b/memhub/MEMORY.md
@@ -15,6 +15,8 @@
3. MemHub **不存 memory 实体**;**可以存 `memory_id`** 做组织/回执。原文进入 **SDK raw**。
4. SDK raw 只保留滚动三天;一条 raw 对应一个完整 turn,只含真人 user 与
assistant,tool 不持久化。提取后的高层 memory 不受该窗口影响。
+5. `source_raw_ids` 是 SDK 内部溯源关系,不是产品 Evidence 合同;记忆详情不提供
+ “原始依据”或按 raw ID 展开原文的入口。
生产入口通过共享 Runtime 租约取得公开 `HyMemoryClient`;MemHub 只在调用前执行
模型配置、密钥和 harness/model 门禁,不维护第二套 memory 正文权威。
diff --git a/memhub/apps/core/src/one_memory/api.py b/memhub/apps/core/src/one_memory/api.py
index 0fbf718..daea38c 100644
--- a/memhub/apps/core/src/one_memory/api.py
+++ b/memhub/apps/core/src/one_memory/api.py
@@ -12,6 +12,7 @@ from collections.abc import (
Awaitable,
Callable,
Iterable,
+ Mapping,
MutableMapping,
)
from contextlib import asynccontextmanager, nullcontext, suppress
@@ -879,6 +880,28 @@ def create_app(
app.state.sdk_data_plane_migrations = SdkDataPlaneMigrationStore(database_path)
app.state.memory_authority = app.state.sdk_data_plane_migrations.authority()
if app.state.memory_authority is MemoryAuthority.SDK:
+ from one_memory.hy_sdk_migration import (
+ repair_sdk_metadata_from_bundle,
+ )
+
+ try:
+ repair = await asyncio.to_thread(
+ repair_sdk_metadata_from_bundle,
+ data_dir=runtime_settings.data_dir,
+ database_path=database_path,
+ )
+ if repair.vector_rows or repair.coding_rows:
+ logger.info(
+ "sdk_metadata_repair_completed mapped=%d vector=%d coding=%d",
+ repair.mapped,
+ repair.vector_rows,
+ repair.coding_rows,
+ )
+ except Exception as error:
+ logger.warning(
+ "sdk_metadata_repair_failed error_type=%s",
+ type(error).__name__,
+ )
app.state.memory_governance_store = RetiredGovernanceStore(database_path)
app.state.evidence_store = RetiredEvidenceStore(database_path)
else:
@@ -3058,7 +3081,13 @@ def create_app(
offset=0,
order="desc",
)
- page = HySdkMemoryPage.from_sdk(raw, limit=1, offset=0)
+ page = HySdkMemoryPage.from_sdk(
+ raw,
+ limit=1,
+ offset=0,
+ skip_invalid=True,
+ )
+ _log_invalid_sdk_memories(raw)
except Exception as error:
raise _sdk_http_error(error, "hy_memory_list_failed") from None
return SdkHomeSummary(
@@ -3122,34 +3151,80 @@ def create_app(
) -> HySdkMemoryPage:
try:
client = await _sdk_client_handle(app).client()
- needle = (query or "").strip().casefold()
+ search_query = (query or "").strip()
+ if search_query:
+ if set(statuses) != {"active"}:
+ raise HTTPException(
+ status_code=422,
+ detail="sdk_search_supports_active_status_only",
+ )
+ # SDK search has no count-only contract. Fetch one bounded
+ # relevance window so pagination can expose more than the
+ # first page without listing the whole library in Core.
+ fetch = 500
+ search_raw = await asyncio.to_thread(
+ client.search,
+ search_query,
+ user_ids=["local"],
+ agent_ids=[],
+ include_sources=[source] if source else None,
+ limit=fetch,
+ min_score=sdk_relevance_floor(),
+ schema_min_score=sdk_relevance_floor(),
+ schema_limit=fetch,
+ intention_limit=fetch,
+ scene="normal",
+ reader=HY_MEMORY_READER,
+ )
+ hits = parse_sdk_search(
+ search_raw,
+ error_code="hy_memory_search_shape_unknown",
+ )
+ selected = hits[offset : offset + limit]
+ rows = await asyncio.gather(
+ *(
+ asyncio.to_thread(client.get, hit.memory_id)
+ for hit in selected
+ )
+ )
+ memories: list[HySdkMemoryRecord] = []
+ invalid_count = 0
+ for row in rows:
+ if row is None:
+ continue
+ try:
+ memories.append(HySdkMemoryRecord.from_sdk(row))
+ except HySdkError:
+ invalid_count += 1
+ if invalid_count:
+ logger.warning(
+ "sdk_memory_invalid_rows_skipped count=%d",
+ invalid_count,
+ )
+ return HySdkMemoryPage(
+ memories=tuple(memories),
+ total=len(hits),
+ limit=limit,
+ offset=offset,
+ )
raw = await asyncio.to_thread(
client.list_memories,
user_id="local",
statuses=list(statuses),
include_sources=[source] if source else None,
- offset=0 if needle else offset,
- limit=100_000 if needle else limit,
+ offset=offset,
+ limit=limit,
)
page = HySdkMemoryPage.from_sdk(
raw,
- limit=100_000 if needle else limit,
- offset=0 if needle else offset,
- )
- if not needle:
- return page
- matches = tuple(
- memory
- for memory in page.memories
- if needle
- in f"{memory.content} {' '.join(memory.tags)}".casefold()
- )
- return HySdkMemoryPage(
- memories=matches[offset : offset + limit],
- total=len(matches),
limit=limit,
offset=offset,
+ skip_invalid=True,
)
+ _log_invalid_sdk_memories(raw)
+ return page
+ except HTTPException:
+ raise
except Exception as error:
raise _sdk_http_error(error, "hy_memory_list_failed") from None
@@ -3172,7 +3247,13 @@ def create_app(
raw = await asyncio.to_thread(
client.list_memories, user_id="local", limit=limit, offset=0, order="desc"
)
- page = HySdkMemoryPage.from_sdk(raw, limit=limit, offset=0)
+ page = HySdkMemoryPage.from_sdk(
+ raw,
+ limit=limit,
+ offset=0,
+ skip_invalid=True,
+ )
+ _log_invalid_sdk_memories(raw)
except Exception as error:
raise _sdk_http_error(error, "hy_memory_list_failed") from None
vdb = raw.get("vdb") if isinstance(raw, dict) else None
@@ -3194,7 +3275,7 @@ def create_app(
)
if memory.session_id:
sessions.setdefault(memory.session_id, []).append(memory_node_id)
- if memory.source:
+ if memory.source and memory.source != "default":
source_node_id = f"source:{memory.source}"
registration = catalog.get(memory.source)
nodes[source_node_id] = MemoryGraphNode(
@@ -5580,6 +5661,31 @@ def _sdk_client_handle(app: FastAPI) -> SdkClientHandle:
return handle
+def _log_invalid_sdk_memories(raw: object) -> None:
+ count = _invalid_sdk_memory_count(raw)
+ if count:
+ logger.warning("sdk_memory_invalid_rows_skipped count=%d", count)
+
+
+def _invalid_sdk_memory_count(raw: object) -> int:
+ if not isinstance(raw, Mapping):
+ return 0
+ found = 0
+ for bucket_name, rows_name in (("vdb", "memories"), ("graph", "nodes")):
+ bucket = raw.get(bucket_name)
+ if not isinstance(bucket, Mapping):
+ continue
+ rows = bucket.get(rows_name)
+ if not isinstance(rows, list):
+ continue
+ for row in rows:
+ try:
+ HySdkMemoryRecord.from_sdk(row)
+ except HySdkError:
+ found += 1
+ return found
+
+
async def _get_sdk_memory(
handle: SdkClientHandle,
memory_id: str,
diff --git a/memhub/apps/core/src/one_memory/hy_sdk_migration.py b/memhub/apps/core/src/one_memory/hy_sdk_migration.py
index a518725..8e674d9 100644
--- a/memhub/apps/core/src/one_memory/hy_sdk_migration.py
+++ b/memhub/apps/core/src/one_memory/hy_sdk_migration.py
@@ -1,12 +1,17 @@
-"""Offline snapshot and restore of the HY SDK data plane for the App migration.
+"""Offline maintenance of the HY SDK data plane for App migrations.
Runtime product code must use public ``HyMemoryClient`` methods. The startup
-migration bundle is the isolated exception: all writers are stopped, so it may
-copy and restore the SDK-owned local stores as files.
+migration boundary is the isolated exception: all writers are stopped, so it
+may copy, restore and repair SDK-owned local stores.
"""
from __future__ import annotations
+import json
+import sqlite3
+from collections.abc import Iterator
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
from pathlib import Path
from hy_memory import ( # type: ignore[import-untyped]
@@ -16,6 +21,27 @@ from hy_memory import ( # type: ignore[import-untyped]
snapshot_local_data_plane,
)
+from one_memory.database_access import main_database
+from one_memory.hy_runtime_config import HY_MEMORY_NAMESPACE
+
+_METADATA_REPAIR_VERSION = 1
+_BATCH = 500
+
+
+@dataclass(frozen=True)
+class RepairMetadata:
+ source: str | None
+ memory_at: int | None
+ created_at: int | None
+
+
+@dataclass(frozen=True)
+class MetadataRepairResult:
+ migration_id: str | None
+ mapped: int
+ vector_rows: int
+ coding_rows: int
+
def snapshot_data_plane(
*,
@@ -45,3 +71,295 @@ def restore_data_plane(
writers_stopped=writers_stopped,
protective_root=protective_root,
)
+
+
+def repair_sdk_metadata_from_bundle(
+ *,
+ data_dir: Path,
+ database_path: Path,
+ now: datetime | None = None,
+) -> MetadataRepairResult:
+ """Restore metadata lost by historical cutovers from their verified bundle."""
+ migration_id = _sdk_migration_id(database_path)
+ if migration_id is None:
+ return MetadataRepairResult(None, 0, 0, 0)
+ receipt = (
+ data_dir
+ / f".sdk-metadata-repair-v{_METADATA_REPAIR_VERSION}-{migration_id}.json"
+ )
+ if receipt.is_file():
+ document = json.loads(receipt.read_text(encoding="utf-8"))
+ return MetadataRepairResult(
+ migration_id,
+ int(document.get("mapped", 0)),
+ int(document.get("vector_rows", 0)),
+ int(document.get("coding_rows", 0)),
+ )
+ legacy = (
+ data_dir
+ / "backups"
+ / f"{migration_id}-pre-cutover.sdk-bundle"
+ / "management"
+ / "one-memory.sqlite3"
+ )
+ if not legacy.is_file():
+ return MetadataRepairResult(migration_id, 0, 0, 0)
+ mapping = _legacy_metadata(legacy, now=now or datetime.now(UTC))
+ vector_rows = _repair_vector(data_dir, mapping)
+ coding_rows = _repair_coding(data_dir, mapping)
+ result = MetadataRepairResult(
+ migration_id,
+ len(mapping),
+ vector_rows,
+ coding_rows,
+ )
+ temporary = receipt.with_suffix(".tmp")
+ temporary.write_text(
+ json.dumps(
+ {
+ "schema_version": 1,
+ "migration_id": migration_id,
+ "mapped": result.mapped,
+ "vector_rows": vector_rows,
+ "coding_rows": coding_rows,
+ },
+ sort_keys=True,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ temporary.replace(receipt)
+ return result
+
+
+def _sdk_migration_id(database_path: Path) -> str | None:
+ with main_database(database_path).read(row_factory=sqlite3.Row) as database:
+ row = database.execute(
+ "SELECT authority,migration_id FROM memory_authority_state WHERE singleton=1"
+ ).fetchone()
+ if row is None or row["authority"] != "sdk":
+ return None
+ value = row["migration_id"]
+ return str(value) if isinstance(value, str) and value else None
+
+
+def _legacy_metadata(path: Path, *, now: datetime) -> dict[str, RepairMetadata]:
+ with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as database:
+ database.row_factory = sqlite3.Row
+ tables = {
+ str(row[0])
+ for row in database.execute(
+ "SELECT name FROM sqlite_master WHERE type='table'"
+ )
+ }
+ if not {"memory_task_outputs", "governed_memories", "evidence"} <= tables:
+ return {}
+ outputs: list[tuple[str, str, tuple[str, ...]]] = []
+ evidence_ids: set[str] = set()
+ for row in database.execute("SELECT body FROM memory_task_outputs"):
+ try:
+ body = json.loads(str(row["body"]))
+ except (TypeError, ValueError):
+ continue
+ legacy_id = body.get("memory_id")
+ canonical_id = body.get("hy_memory_id")
+ refs = body.get("support_refs")
+ if not isinstance(legacy_id, str) or not isinstance(canonical_id, str):
+ continue
+ identifiers = (
+ tuple(
+ str(ref["evidence_id"])
+ for ref in refs
+ if isinstance(ref, dict)
+ and isinstance(ref.get("evidence_id"), str)
+ )
+ if isinstance(refs, list)
+ else ()
+ )
+ outputs.append((legacy_id, canonical_id, identifiers))
+ evidence_ids.update(identifiers)
+ evidence: dict[str, tuple[str, datetime | None]] = {}
+ for batch in _batches(sorted(evidence_ids)):
+ placeholders = ",".join("?" for _ in batch)
+ for row in database.execute(
+ "SELECT evidence_id,source_id,created_at,imported_at "
+ f"FROM evidence WHERE evidence_id IN ({placeholders})",
+ batch,
+ ):
+ evidence[str(row["evidence_id"])] = (
+ str(row["source_id"]),
+ _plausible_time(
+ row["created_at"],
+ fallback=row["imported_at"],
+ now=now,
+ ),
+ )
+ governed = {
+ str(row["memory_id"]): _plausible_time(
+ row["created_at"],
+ fallback=row["updated_at"],
+ now=now,
+ )
+ for row in database.execute(
+ "SELECT memory_id,created_at,updated_at FROM governed_memories"
+ )
+ }
+ result: dict[str, RepairMetadata] = {}
+ for legacy_id, canonical_id, refs in outputs:
+ resolved = [evidence[identifier] for identifier in refs if identifier in evidence]
+ sources = {source for source, _timestamp in resolved if source and source != "default"}
+ times = [timestamp for _source, timestamp in resolved if timestamp is not None]
+ result[canonical_id] = RepairMetadata(
+ source=next(iter(sources)) if len(sources) == 1 else None,
+ memory_at=int(max(times).timestamp()) if times else None,
+ created_at=(
+ int(governed[legacy_id].timestamp())
+ if governed.get(legacy_id) is not None
+ else None
+ ),
+ )
+ return result
+
+
+def _plausible_time(
+ value: object,
+ *,
+ fallback: object,
+ now: datetime,
+) -> datetime | None:
+ for candidate in (value, fallback):
+ if not isinstance(candidate, str) or not candidate:
+ continue
+ try:
+ parsed = datetime.fromisoformat(candidate)
+ except ValueError:
+ continue
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=UTC)
+ parsed = parsed.astimezone(UTC)
+ if parsed <= now + timedelta(days=1):
+ return parsed
+ return None
+
+
+def _repair_vector(
+ data_dir: Path,
+ mapping: dict[str, RepairMetadata],
+) -> int:
+ directory = data_dir / "hy-memory" / HY_MEMORY_NAMESPACE / "vector"
+ if not mapping or not (directory / "chroma.sqlite3").is_file():
+ return 0
+ import chromadb
+ from chromadb.config import Settings
+
+ client = chromadb.PersistentClient(
+ path=str(directory),
+ settings=Settings(anonymized_telemetry=False),
+ )
+ repaired = 0
+ ids = tuple(mapping)
+ for collection in client.list_collections():
+ for batch in _batches(ids):
+ page = collection.get(ids=list(batch), include=["metadatas"])
+ updated_ids: list[str] = []
+ updated_metadata: list[dict[str, object]] = []
+ for memory_id, metadata in zip(
+ page.get("ids") or (),
+ page.get("metadatas") or (),
+ strict=True,
+ ):
+ if not isinstance(metadata, dict):
+ continue
+ desired = mapping.get(str(memory_id))
+ if desired is None:
+ continue
+ next_metadata = dict(metadata)
+ changed = False
+ if desired.source and next_metadata.get("source") in {
+ None,
+ "",
+ "default",
+ }:
+ next_metadata["source"] = desired.source
+ changed = True
+ if (
+ desired.memory_at is not None
+ and next_metadata.get("memory_at") != desired.memory_at
+ ):
+ next_metadata["memory_at"] = desired.memory_at
+ changed = True
+ if (
+ desired.created_at is not None
+ and next_metadata.get("gmt_created") != desired.created_at
+ ):
+ next_metadata["gmt_created"] = desired.created_at
+ changed = True
+ if changed:
+ updated_ids.append(str(memory_id))
+ updated_metadata.append(next_metadata)
+ if updated_ids:
+ collection.update(ids=updated_ids, metadatas=updated_metadata)
+ repaired += len(updated_ids)
+ return repaired
+
+
+def _repair_coding(
+ data_dir: Path,
+ mapping: dict[str, RepairMetadata],
+) -> int:
+ root = data_dir / "hy-memory" / HY_MEMORY_NAMESPACE
+ repaired = 0
+ for name in ("coding.sqlite3", "coding_cv.sqlite3"):
+ path = root / name
+ if not path.is_file():
+ continue
+ with sqlite3.connect(path) as database:
+ tables = {
+ str(row[0])
+ for row in database.execute(
+ "SELECT name FROM sqlite_master WHERE type='table'"
+ )
+ }
+ for table, identifier in (
+ ("coding_memory_meta", "experience_id"),
+ ("working_fact", "fact_id"),
+ ):
+ if table not in tables:
+ continue
+ rows = database.execute(
+ f"SELECT {identifier},source,created_at FROM {table}"
+ ).fetchall()
+ for memory_id, source, created_at in rows:
+ desired = mapping.get(str(memory_id))
+ if desired is None:
+ continue
+ updates: list[str] = []
+ values: list[object] = []
+ if desired.source and source in {None, "", "default"}:
+ updates.append("source=?")
+ values.append(desired.source)
+ if desired.created_at is not None:
+ desired_created_at = (
+ datetime.fromtimestamp(desired.created_at, tz=UTC)
+ .replace(tzinfo=None)
+ .isoformat()
+ )
+ if created_at != desired_created_at:
+ updates.append("created_at=?")
+ values.append(desired_created_at)
+ if not updates:
+ continue
+ values.append(memory_id)
+ database.execute(
+ f"UPDATE {table} SET {','.join(updates)} "
+ f"WHERE {identifier}=?",
+ values,
+ )
+ repaired += 1
+ database.commit()
+ return repaired
+
+
+def _batches[T](values: list[T] | tuple[T, ...]) -> Iterator[tuple[T, ...]]:
+ for start in range(0, len(values), _BATCH):
+ yield tuple(values[start : start + _BATCH])
diff --git a/memhub/apps/core/src/one_memory/hy_sdk_types.py b/memhub/apps/core/src/one_memory/hy_sdk_types.py
index ce7ba3a..604234c 100644
--- a/memhub/apps/core/src/one_memory/hy_sdk_types.py
+++ b/memhub/apps/core/src/one_memory/hy_sdk_types.py
@@ -94,7 +94,14 @@ class HySdkMemoryPage(BaseModel):
offset: int = Field(ge=0)
@classmethod
- def from_sdk(cls, raw: object, *, limit: int, offset: int) -> HySdkMemoryPage:
+ def from_sdk(
+ cls,
+ raw: object,
+ *,
+ limit: int,
+ offset: int,
+ skip_invalid: bool = False,
+ ) -> HySdkMemoryPage:
if not isinstance(raw, Mapping):
raise HySdkReadError("hy_memory_list_shape_unknown")
rows: list[object] = []
@@ -116,10 +123,19 @@ class HySdkMemoryPage(BaseModel):
rows.extend(bucket[rows_name])
deduplicated: dict[str, HySdkMemoryRecord] = {}
for row in rows:
- record = HySdkMemoryRecord.from_sdk(row)
+ try:
+ record = HySdkMemoryRecord.from_sdk(row)
+ except HySdkReadError:
+ if not skip_invalid:
+ raise
+ continue
deduplicated.setdefault(record.memory_id, record)
return cls(
memories=tuple(deduplicated.values()),
+ # `total` is the SDK's stable result-set count. Subtracting only
+ # invalid rows observed on this page would make it change as the
+ # caller paged. Until the SDK exposes a quarantined count, keep the
+ # authoritative total and skip malformed rows only in this page.
total=total,
limit=limit,
offset=offset,
diff --git a/memhub/apps/core/src/one_memory/imports/access.py b/memhub/apps/core/src/one_memory/imports/access.py
index ba251b5..f028b47 100644
--- a/memhub/apps/core/src/one_memory/imports/access.py
+++ b/memhub/apps/core/src/one_memory/imports/access.py
@@ -50,6 +50,10 @@ class AuthorizedSourceFile:
size: int
modified_ns: int
changed_ns: int
+ # Source-specific change token (for example Cursor's WAL identity). It is
+ # cursor metadata only; modified_ns remains the real filesystem mtime used
+ # as a fallback conversation timestamp.
+ cursor_version: str | None = None
root_identity: str | None = None
requested_root: Path | None = None
access_check: Callable[[], None] | None = field(default=None, repr=False, compare=False)
diff --git a/memhub/apps/core/src/one_memory/imports/sources/common.py b/memhub/apps/core/src/one_memory/imports/sources/common.py
index 9dd1de5..cbb9e17 100644
--- a/memhub/apps/core/src/one_memory/imports/sources/common.py
+++ b/memhub/apps/core/src/one_memory/imports/sources/common.py
@@ -644,7 +644,7 @@ def is_unchanged(source_file: AuthorizedSourceFile, cursors: dict[str, SourceCur
return (
previous is not None
and previous.read_to_end
- and previous.file_identity == source_file.file_identity
+ and previous.file_identity == _cursor_file_identity(source_file)
and previous.observed_size == source_file.size
and previous.observed_modified_ns == source_file.modified_ns
# Chmod alone leaves size, mtime and inode untouched, so a file that
@@ -1046,7 +1046,7 @@ def source_cursor(
) -> SourceCursor:
return SourceCursor(
file_key=source_file.safe_id,
- file_identity=source_file.file_identity,
+ file_identity=_cursor_file_identity(source_file),
checkpoint=checkpoint,
checkpoint_anchor=checkpoint_anchor,
observed_size=source_file.size,
@@ -1054,6 +1054,14 @@ def source_cursor(
)
+def _cursor_file_identity(source_file: AuthorizedSourceFile) -> str:
+ return (
+ f"{source_file.file_identity}:v:{source_file.cursor_version}"
+ if source_file.cursor_version
+ else source_file.file_identity
+ )
+
+
_POSITION = re.compile(r"(?<=:)\d+(?=:|$)")
diff --git a/memhub/apps/core/src/one_memory/imports/sources/cursor_unified.py b/memhub/apps/core/src/one_memory/imports/sources/cursor_unified.py
index 30d9815..c20817f 100644
--- a/memhub/apps/core/src/one_memory/imports/sources/cursor_unified.py
+++ b/memhub/apps/core/src/one_memory/imports/sources/cursor_unified.py
@@ -533,8 +533,8 @@ def _with_write_ahead_log(database: AuthorizedSourceFile) -> AuthorizedSourceFil
version = hashlib.blake2b(
f"{database.modified_ns}:{journal.st_mtime_ns}:{journal.st_size}:{journal.st_ino}".encode(),
digest_size=8,
- ).digest()
- return replace(database, modified_ns=int.from_bytes(version, "big") & ((1 << 63) - 1))
+ ).hexdigest()
+ return replace(database, cursor_version=version)
def _live_baseline(listing: _CursorListing) -> dict[str, SourceCursor]:
diff --git a/memhub/apps/core/tests/test_memory_notes.py b/memhub/apps/core/tests/test_memory_notes.py
index eebc1af..886188c 100644
--- a/memhub/apps/core/tests/test_memory_notes.py
+++ b/memhub/apps/core/tests/test_memory_notes.py
@@ -281,38 +281,63 @@ def test_sdk_user_profile_http_returns_native_assembled_profile(tmp_path):
@pytest.mark.fresh_sdk
-def test_sdk_memory_library_forwards_source_and_filters_query(tmp_path):
+def test_sdk_memory_library_uses_sdk_search_and_skips_empty_rows_without_mutation(
+ tmp_path,
+ caplog,
+):
async def scenario():
app = application(tmp_path)
- calls = []
+ list_calls = []
+ search_calls = []
+ deleted = []
+ records = {
+ "release": {
+ "memory_id": "release",
+ "content": "Release plan",
+ "layer": "l2_fact",
+ "status": "active",
+ "user_id": "local",
+ "agent_id": "all-apps",
+ "session_id": "s1",
+ "source": "cursor",
+ "tags": ["shipping"],
+ },
+ "default": {
+ "memory_id": "default",
+ "content": "Unknown source",
+ "layer": "l2_fact",
+ "status": "active",
+ "user_id": "local",
+ "agent_id": "all-apps",
+ "session_id": "s3",
+ "source": "default",
+ "tags": [],
+ },
+ }
class Client:
def list_memories(self, **kwargs):
- calls.append(kwargs)
+ list_calls.append(kwargs)
rows = [
+ records["release"],
+ records["default"],
{
- "memory_id": "release",
- "content": "Release plan",
- "layer": "l2_fact",
- "status": "active",
- "user_id": "local",
- "agent_id": "all-apps",
- "session_id": "s1",
- "source": "cursor",
- "tags": ["shipping"],
- },
- {
- "memory_id": "other",
- "content": "Unrelated",
+ "memory_id": "empty",
+ "content": "",
"layer": "l2_fact",
"status": "active",
"user_id": "local",
"agent_id": "all-apps",
"session_id": "s2",
- "source": "cursor",
+ "source": "workbuddy",
"tags": [],
},
]
+ include_sources = kwargs.get("include_sources") or []
+ if include_sources:
+ rows = [
+ row for row in rows if row["source"] in include_sources
+ ]
return {
"vdb": {
"memories": rows,
@@ -322,9 +347,34 @@ def test_sdk_memory_library_forwards_source_and_filters_query(tmp_path):
}
}
+ def search(self, query, **kwargs):
+ search_calls.append((query, kwargs))
+ return {
+ "memories": {
+ "schema": [],
+ "proactive": [],
+ "normal": [
+ {
+ "memory_id": "release",
+ "content": "Release plan",
+ "score": 0.9,
+ }
+ ],
+ }
+ }
+
+ def get(self, memory_id):
+ return records.get(memory_id)
+
+ def delete(self, memory_id):
+ deleted.append(memory_id)
+ return {"success": True, "deleted_count": 1}
+
+ sdk = Client()
+
class Handle:
async def client(self):
- return Client()
+ return sdk
async def close(self):
return None
@@ -342,7 +392,26 @@ def test_sdk_memory_library_forwards_source_and_filters_query(tmp_path):
assert [item["memory_id"] for item in body["memories"]] == [
"release"
]
- assert calls[0]["include_sources"] == ["cursor"]
- assert calls[0]["limit"] == 100_000
+ assert search_calls[0][0] == "release"
+ assert search_calls[0][1]["include_sources"] == ["cursor"]
+ assert search_calls[0][1]["limit"] == 500
+ assert list_calls == []
+
+ listed = await client.get(
+ "/api/v2/memory-library",
+ params={"source": "workbuddy", "limit": 100},
+ )
+ assert listed.status_code == 200
+ assert listed.json()["memories"] == []
+ assert listed.json()["total"] == 1
+ assert deleted == []
+ assert list_calls[0]["limit"] == 100
+ assert "sdk_memory_invalid_rows_skipped count=1" in caplog.messages
+
+ graph = await client.get("/api/v2/memories/graph")
+ assert graph.status_code == 200
+ node_ids = {node["node_id"] for node in graph.json()["nodes"]}
+ assert "source:cursor" in node_ids
+ assert "source:default" not in node_ids
asyncio.run(scenario())
diff --git a/memhub/apps/core/tests/test_primary_source_adapters.py b/memhub/apps/core/tests/test_primary_source_adapters.py
index 0044f4e..4a73983 100644
--- a/memhub/apps/core/tests/test_primary_source_adapters.py
+++ b/memhub/apps/core/tests/test_primary_source_adapters.py
@@ -136,6 +136,34 @@ def test_cursor_store_timestamp_envelope_keeps_only_the_user_query_text(tmp_path
assert meta["turn_event_at"] == "2026-09-22T23:34:00+00:00"
+def test_cursor_wal_change_token_does_not_become_a_future_conversation_time(
+ tmp_path,
+) -> None:
+ root = tmp_path / ".cursor"
+ database = root / "chats" / "workspace" / "wal-time" / "store.db"
+ database.parent.mkdir(parents=True)
+ connection = sqlite3.connect(database)
+ connection.execute("PRAGMA journal_mode=WAL")
+ connection.execute("PRAGMA wal_autocheckpoint=0")
+ connection.execute("CREATE TABLE blobs (id TEXT, data TEXT)")
+ connection.execute(
+ "INSERT INTO blobs VALUES (?, ?)",
+ ("message", json.dumps({"role": "assistant", "content": "answer"})),
+ )
+ connection.commit()
+ stamp = 1_788_220_800
+ os.utime(database, (stamp, stamp))
+ try:
+ records = evidence(
+ asyncio.run(scan(CursorUnifiedSourceAdapter(grant=grant("cursor", root))))
+ )
+ finally:
+ connection.close()
+
+ assert len(records) == 1
+ assert int(records[0].evidence.created_at.timestamp()) == stamp
+
+
def test_cursor_transcript_timestamp_envelope_keeps_only_the_user_query_text(tmp_path) -> None:
root = tmp_path / ".cursor"
transcript = (
diff --git a/memhub/apps/core/tests/test_sdk_data_plane_migration.py b/memhub/apps/core/tests/test_sdk_data_plane_migration.py
index aee3da3..8e05c4d 100644
--- a/memhub/apps/core/tests/test_sdk_data_plane_migration.py
+++ b/memhub/apps/core/tests/test_sdk_data_plane_migration.py
@@ -4,6 +4,7 @@ import asyncio
import hashlib
import io
import json
+import sqlite3
from datetime import UTC, datetime, timedelta
from pathlib import Path
@@ -15,6 +16,7 @@ from one_memory import cli
from one_memory.api import create_app
from one_memory.config import Settings
from one_memory.database_access import close_main_databases, main_database
+from one_memory.hy_sdk_migration import repair_sdk_metadata_from_bundle
from one_memory.hy_sdk_types import HySdkRawPage
from one_memory.imports.storage import EvidenceStore
from one_memory.memory_server.contracts import BatchIdentity, WriteRequest
@@ -67,6 +69,123 @@ def _start(store, migration_id="m1"):
)
+def test_post_cutover_metadata_repair_restores_source_and_original_times(store):
+ data_dir = store.database_path.parent
+ migration_id = "sdk-authority-v2-source-repair"
+ with main_database(store.database_path).write() as database, database:
+ database.execute(
+ "UPDATE memory_authority_state SET authority='sdk',migration_id=? "
+ "WHERE singleton=1",
+ (migration_id,),
+ )
+ legacy = (
+ data_dir
+ / "backups"
+ / f"{migration_id}-pre-cutover.sdk-bundle"
+ / "management"
+ / "one-memory.sqlite3"
+ )
+ legacy.parent.mkdir(parents=True)
+ with sqlite3.connect(legacy) as database:
+ database.executescript(
+ """
+ CREATE TABLE memory_task_outputs (body TEXT);
+ CREATE TABLE governed_memories (
+ memory_id TEXT, created_at TEXT, updated_at TEXT
+ );
+ CREATE TABLE evidence (
+ evidence_id TEXT, source_id TEXT, created_at TEXT, imported_at TEXT
+ );
+ """
+ )
+ database.execute(
+ "INSERT INTO governed_memories VALUES (?,?,?)",
+ ("legacy-1", "2026-10-18T00:00:00+00:00", "2026-10-18T01:00:00+00:00"),
+ )
+ database.execute(
+ "INSERT INTO evidence VALUES (?,?,?,?)",
+ ("e1", "workbuddy", "2254-01-01T00:00:00+00:00", "2026-10-17T00:00:00+00:00"),
+ )
+ database.execute(
+ "INSERT INTO memory_task_outputs VALUES (?)",
+ (
+ json.dumps(
+ {
+ "memory_id": "legacy-1",
+ "hy_memory_id": "sdk-1",
+ "support_refs": [{"evidence_id": "e1"}],
+ }
+ ),
+ ),
+ )
+
+ import chromadb
+ from chromadb.config import Settings as ChromaSettings
+
+ vector = data_dir / "hy-memory" / "governed-v2" / "vector"
+ collection = chromadb.PersistentClient(
+ path=str(vector),
+ settings=ChromaSettings(anonymized_telemetry=False),
+ ).get_or_create_collection("memory")
+ collection.add(
+ ids=["sdk-1"],
+ documents=["remember"],
+ embeddings=[[0.1, 0.2]],
+ metadatas=[
+ {
+ "source": "default",
+ "gmt_created": 1,
+ "memory_at": 8_962_051_200,
+ }
+ ],
+ )
+ coding = data_dir / "hy-memory" / "governed-v2" / "coding_cv.sqlite3"
+ with sqlite3.connect(coding) as database:
+ database.execute(
+ "CREATE TABLE coding_memory_meta ("
+ "experience_id TEXT,user_id TEXT,agent_id TEXT,solution TEXT,"
+ "source TEXT,created_at TEXT,updated_at TEXT)"
+ )
+ database.execute(
+ "CREATE TABLE working_fact ("
+ "fact_id TEXT,user_id TEXT,agent_id TEXT,statement TEXT,"
+ "source TEXT,created_at TEXT)"
+ )
+ database.execute(
+ "INSERT INTO coding_memory_meta VALUES "
+ "('sdk-1','local','scope','remember','default','now','now')"
+ )
+
+ result = repair_sdk_metadata_from_bundle(
+ data_dir=data_dir,
+ database_path=store.database_path,
+ now=datetime(2026, 10, 25, tzinfo=UTC),
+ )
+ metadata = collection.get(ids=["sdk-1"], include=["metadatas"])["metadatas"][0]
+ assert result.vector_rows == 1
+ assert result.coding_rows == 1
+ assert metadata["source"] == "workbuddy"
+ assert datetime.fromtimestamp(metadata["memory_at"], tz=UTC) == datetime(
+ 2026, 10, 17, tzinfo=UTC
+ )
+ assert datetime.fromtimestamp(metadata["gmt_created"], tz=UTC) == datetime(
+ 2026, 10, 18, tzinfo=UTC
+ )
+ with sqlite3.connect(coding) as database:
+ source, created_at = database.execute(
+ "SELECT source,created_at FROM coding_memory_meta WHERE experience_id='sdk-1'"
+ ).fetchone()
+ assert source == "workbuddy"
+ assert created_at.startswith("2026-10-18T00:00:00")
+
+ repeated = repair_sdk_metadata_from_bundle(
+ data_dir=data_dir,
+ database_path=store.database_path,
+ now=datetime(2026, 10, 25, tzinfo=UTC),
+ )
+ assert repeated == result
+
+
def _insert_evidence(store, evidence_id, *, conversation="session-1", role="user", seq=1):
verbatim = f"text of {evidence_id}"
with main_database(store.database_path).write() as database, database:
diff --git a/memhub/apps/desktop/src/stable-runtime.test.ts b/memhub/apps/desktop/src/stable-runtime.test.ts
index 7d74210..ce6b18d 100644
--- a/memhub/apps/desktop/src/stable-runtime.test.ts
+++ b/memhub/apps/desktop/src/stable-runtime.test.ts
@@ -313,6 +313,15 @@ describe("startup dialog body", () => {
expect(detail).toContain("磁盘空间不足");
expect(detail).not.toContain("sdk_migration_disk_space_insufficient");
});
+
+ it("turns runtime_service_not_ready into a user-facing sentence", () => {
+ const error = new Error("runtime_service_not_ready");
+ expect(stableRuntimeErrorCode(error)).toBe("runtime_service_not_ready");
+ expect(stableRuntimeFailureDetail(error)).toContain("首次启动");
+ expect(stableRuntimeFailureDetail(error)).not.toContain(
+ "runtime_service_not_ready",
+ );
+ });
});
describe("packaged runtime build after an App upgrade", () => {
diff --git a/memhub/apps/desktop/src/stable-runtime.ts b/memhub/apps/desktop/src/stable-runtime.ts
index ac615df..8dcce28 100644
--- a/memhub/apps/desktop/src/stable-runtime.ts
+++ b/memhub/apps/desktop/src/stable-runtime.ts
@@ -141,6 +141,7 @@ const SAFE_STABLE_RUNTIME_ERROR_CODES = new Set([
"sdk_migration_response_invalid",
"sdk_migration_status_unavailable",
"sdk_migration_incomplete",
+ "runtime_service_not_ready",
]);
export function stableRuntimeErrorCode(error: unknown): string {
@@ -230,6 +231,8 @@ export const STABLE_RUNTIME_USER_MESSAGES: Record<string, string> = {
"升级过程返回了无法识别的内容,已停止。原有记忆数据不会丢失;请重新启动重试,如果仍然失败,请把这个提示反馈给我们。",
sdk_migration_incomplete:
"记忆数据格式升级没有完成,MemHub 暂时无法打开。请重新启动重试;如果仍然失败,请把这个提示反馈给我们,原有记忆数据不会丢失。",
+ runtime_service_not_ready:
+ "记忆服务仍在首次启动,请稍候后重试。你的记忆数据不会受到影响。",
desktop_start_failed:
"MemHub 启动失败。请重新启动;如果仍然打不开,请重新安装,你的记忆数据不会受到影响。",
};
diff --git a/memhub/apps/web/src/MemoryMap.test.tsx b/memhub/apps/web/src/MemoryMap.test.tsx
index 803754e..12a1516 100644
--- a/memhub/apps/web/src/MemoryMap.test.tsx
+++ b/memhub/apps/web/src/MemoryMap.test.tsx
@@ -247,6 +247,16 @@ it("labels the right-hand empty state as memory details", () => {
expect(screen.queryByText("原始证据")).toBeNull();
});
+it("renders SDK-projected memory tags with the existing Workbench chips", () => {
+ const { container } = render(<Host simplified />);
+ expect(
+ Array.from(
+ container.querySelectorAll(".map-memory-tags .wb-tag"),
+ (node) => node.textContent,
+ ),
+ ).toEqual(["产品", "产品"]);
+});
+
it("opens the newest listed memory in the detail pane and keeps it closed after dismiss", async () => {
const user = userEvent.setup();
render(<Host simplified />);
diff --git a/memhub/apps/web/src/MemoryMap.tsx b/memhub/apps/web/src/MemoryMap.tsx
index e41c1d7..befa68f 100644
--- a/memhub/apps/web/src/MemoryMap.tsx
+++ b/memhub/apps/web/src/MemoryMap.tsx
@@ -988,7 +988,16 @@ export function MemoryMap(props: Props) {
onClick={() => pick(m.memory_id)}
>
<span className={`map-state ${m.status}`} aria-hidden="true" />
- <span>{m.content}</span>
+ <span className="map-memory-content">{m.content}</span>
+ {m.tags.length ? (
+ <span className="map-memory-tags wb-tags">
+ {m.tags.map((tag) => (
+ <span key={tag} className="wb-tag">
+ {tag}
+ </span>
+ ))}
+ </span>
+ ) : null}
<small>
{props.simplified ? (
<>
diff --git a/memhub/apps/web/src/SelectedMemoryDetail.test.tsx b/memhub/apps/web/src/SelectedMemoryDetail.test.tsx
index 8b37e31..0233d3f 100644
--- a/memhub/apps/web/src/SelectedMemoryDetail.test.tsx
+++ b/memhub/apps/web/src/SelectedMemoryDetail.test.tsx
@@ -168,6 +168,26 @@ it("shows the native SDK state without inventing a revision", () => {
expect(screen.queryByText(/第 0 版/)).toBeNull();
expect(screen.getByText(/^来源 Cursor · /)).toBeTruthy();
});
+it("splits long memory text into a bounded heading and readable body", () => {
+ const content = "长".repeat(100);
+ render(
+ <SelectedMemoryDetail
+ detail={{
+ ...detail,
+ memory: { ...detail.memory, content },
+ evidence: [],
+ sdk_status: "active",
+ }}
+ sources={[]}
+ onChanged={vi.fn()}
+ hideActions
+ />,
+ );
+ expect(screen.getByRole("heading", { name: "长".repeat(72) })).toBeTruthy();
+ expect(screen.getByText("长".repeat(28)).className).toContain(
+ "selected-memory-body",
+ );
+});
it("opens full editor and saves content without rewriting scope", async () => {
const changed = vi.fn();
render(
diff --git a/memhub/apps/web/src/SelectedMemoryDetail.tsx b/memhub/apps/web/src/SelectedMemoryDetail.tsx
index ad553d3..dd2dbd5 100644
--- a/memhub/apps/web/src/SelectedMemoryDetail.tsx
+++ b/memhub/apps/web/src/SelectedMemoryDetail.tsx
@@ -234,13 +234,16 @@ export function SelectedMemoryDetail({
if (alive.current) setBusy(false);
}
}
- const split = memory.content.search(/[。\n]/);
+ const punctuation = memory.content.search(/[。!?!?\n]/);
+ const split =
+ punctuation > 0 && punctuation < 85
+ ? punctuation + 1
+ : memory.content.length > 72
+ ? 72
+ : -1;
const heading =
- split > 0 && split < 85
- ? memory.content.slice(0, split + 1)
- : memory.content;
- const body =
- split > 0 && split < 85 ? memory.content.slice(split + 1).trim() : "";
+ split > 0 ? memory.content.slice(0, split).trim() : memory.content;
+ const body = split > 0 ? memory.content.slice(split).trim() : "";
return (
<>
<article
diff --git a/memhub/apps/web/src/sdk-memory-map.ts b/memhub/apps/web/src/sdk-memory-map.ts
index c7e0f06..ed4ff92 100644
--- a/memhub/apps/web/src/sdk-memory-map.ts
+++ b/memhub/apps/web/src/sdk-memory-map.ts
@@ -72,7 +72,8 @@ export function sdkDetail(record: SdkMemoryRecord): MemoryDetail {
history: [],
index_sync: null,
sdk_status: record.status,
- source_id: record.source,
+ source_id:
+ record.source && record.source !== "default" ? record.source : null,
sdk_memory_at: stamp(record.memory_at) || null,
sdk_created_at: stamp(record.gmt_created) || null,
};
@@ -93,7 +94,8 @@ export function sdkLibraryPage(page: SdkMemoryPage): MemoryLibraryPage {
> = {};
const sourceIds: Record<string, string[]> = {};
for (const record of page.memories) {
- if (record.source) sourceIds[record.memory_id] = [record.source];
+ if (record.source && record.source !== "default")
+ sourceIds[record.memory_id] = [record.source];
const at = record.memory_at ?? record.gmt_created;
if (typeof at !== "number" || !Number.isFinite(at)) continue;
sourceTime[record.memory_id] = {
diff --git a/memhub/apps/web/src/selected-memory.css b/memhub/apps/web/src/selected-memory.css
index fdc8109..841989a 100644
--- a/memhub/apps/web/src/selected-memory.css
+++ b/memhub/apps/web/src/selected-memory.css
@@ -138,13 +138,19 @@
gap: 8px;
font-family: "Noto Sans SC", "PingFang SC", sans-serif;
}
-.r6-shell .r6-memory .map-memory-item > span:not(.map-state) {
+.r6-shell .r6-memory .map-memory-item > .map-memory-content {
min-height: 40px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
+.r6-shell .r6-memory .map-memory-tags.wb-tags {
+ grid-column: 2;
+ min-height: 0;
+ margin: 0;
+ padding: 0;
+}
.r6-shell .r6-memory .map-memory-item small {
font-size: 11px;
line-height: 19px;
@@ -212,15 +218,19 @@
margin: 0 0 32px;
}
.selected-memory-detail > h3 {
+ display: block;
font-size: 22px;
line-height: 38px;
font-weight: 500;
+ letter-spacing: normal;
margin: 0 0 18px;
overflow-wrap: anywhere;
}
.selected-memory-body {
+ display: block;
font-size: 17px;
line-height: 29px;
+ letter-spacing: normal;
margin: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
@@ -237,36 +247,6 @@
color: #5e6e7a;
line-height: 21px;
}
-.selected-memory-evidence {
- border-top: 1px solid #c7d6e0;
- margin: 24px 0 16px;
- padding-top: 22px;
-}
-.selected-memory-evidence h4 {
- font-size: 16px;
- line-height: 28px;
- margin: 0 0 18px;
- font-weight: 400;
-}
-.selected-memory-evidence small {
- font-size: 12px;
- color: #5e6e7a;
-}
-.selected-memory-evidence blockquote {
- font-size: 15px;
- line-height: 26px;
- margin: 18px 0 44px;
- border: 0;
- padding: 0;
- background: none;
- white-space: pre-wrap;
- overflow-wrap: anywhere;
-}
-.selected-memory-detail[data-hide-actions="true"]
- .selected-memory-evidence
- blockquote {
- margin-bottom: 0;
-}
.selected-memory-more {
font-size: 12px;
padding: 16px 0;
@@ -304,8 +284,7 @@
align-items: center;
gap: 24px;
}
-.selected-memory-page > header .r6-button,
-.selected-original > .r6-button {
+.selected-memory-page > header .r6-button {
min-width: 150px;
}
.selected-memory-page h1 {
@@ -394,40 +373,6 @@
border-left: 2px solid #8da4b3;
white-space: pre-wrap;
}
-.selected-original {
- padding: 60px 46px;
- min-height: 0;
- overflow-y: auto;
- overscroll-behavior: contain;
- scrollbar-width: thin;
-}
-.selected-original > small {
- font-size: 14px;
- color: #5e6e7a;
-}
-.selected-original > p {
- margin-top: 70px;
- font-size: 14px;
-}
-.selected-original blockquote {
- margin: 24px 0 96px;
- font-size: 24px;
- line-height: 40px;
- white-space: pre-wrap;
- overflow-wrap: anywhere;
-}
-.selected-original section {
- margin-top: 24px;
-}
-.selected-original section > small {
- font-size: 13px;
- color: #5e6e7a;
-}
-.selected-original > h2 {
- font-size: 21px;
- font-weight: 400;
- margin: 24px 0 32px;
-}
.selected-delete {
padding: 130px 66px 0;
min-height: 0;
@@ -499,10 +444,6 @@
.selected-delete > p {
margin: 12px 0;
}
- .selected-original {
- padding-top: 24px;
- padding-bottom: 24px;
- }
}
@media (max-width: 1250px) {
.r6-shell .view.r6-memory {
@@ -536,7 +477,6 @@
.selected-memory-page {
padding: 24px;
}
- .selected-original,
.selected-delete {
padding-left: 0;
padding-right: 0;
diff --git a/memhub/packages/runtime-control/src/local-install.test.ts b/memhub/packages/runtime-control/src/local-install.test.ts
index 1b0476e..ed63e4a 100644
--- a/memhub/packages/runtime-control/src/local-install.test.ts
+++ b/memhub/packages/runtime-control/src/local-install.test.ts
@@ -711,7 +711,7 @@ describe("local Runtime installation", () => {
expect(replacement.version_directory).not.toBe(firstPlan.version_directory);
});
- it("refuses different bytes from the same commit even with the opt-in", async () => {
+ it("repairs different bytes from the same commit with the packaged opt-in", async () => {
if (process.platform !== "darwin") return;
const commit = "a".repeat(40);
const first = await distribution("1.0.0", {
@@ -738,18 +738,17 @@ describe("local Runtime installation", () => {
.digest("hex");
await writeFile(manifestPath, JSON.stringify(manifest));
- await expect(
- planLocalInstall({
- source: rebuilt.source,
- installRoot: first.installRoot,
- platform: process.platform,
- arch: process.arch,
- allowSameBuildReplace: true,
- }),
- ).rejects.toThrow("installed_version_conflict");
+ const plan = await planLocalInstall({
+ source: rebuilt.source,
+ installRoot: first.installRoot,
+ platform: process.platform,
+ arch: process.arch,
+ allowSameBuildReplace: true,
+ });
+ expect(plan.same_build_replace).toBe(true);
});
- it("refuses a tampered selected runtime instead of taking it over", async () => {
+ it("replaces a dirty selected runtime from the trusted packaged payload", async () => {
if (process.platform !== "darwin") return;
const first = await distribution("1.0.0", {
buildNumber: 5,
@@ -771,15 +770,15 @@ describe("local Runtime installation", () => {
gitCommit: "b".repeat(40),
});
- await expect(
- planLocalInstall({
- source: rebuilt.source,
- installRoot: first.installRoot,
- platform: process.platform,
- arch: process.arch,
- allowSameBuildReplace: true,
- }),
- ).rejects.toThrow("distribution_hash_mismatch");
+ const plan = await planLocalInstall({
+ source: rebuilt.source,
+ installRoot: first.installRoot,
+ platform: process.platform,
+ arch: process.arch,
+ allowSameBuildReplace: true,
+ });
+ expect(plan.same_build_replace).toBe(true);
+ expect(plan.version_directory).not.toBe(firstPlan.version_directory);
});
it("does not let the same-build opt-in weaken downgrade refusal", async () => {
diff --git a/memhub/packages/runtime-control/src/local-install.ts b/memhub/packages/runtime-control/src/local-install.ts
index 02ab73c..1ec444b 100644
--- a/memhub/packages/runtime-control/src/local-install.ts
+++ b/memhub/packages/runtime-control/src/local-install.ts
@@ -367,13 +367,19 @@ async function inspectBuildNumberTransition(options: {
if (relative.startsWith("..") || path.isAbsolute(relative)) {
throw new Error("install_current_unmanaged");
}
- const selected = options.allowSameBuildReplace
- ? await verifyDistribution(
+ let selectedVerified = true;
+ let selected = await readManifest(target).catch(() => null);
+ if (options.allowSameBuildReplace && selected !== null) {
+ try {
+ selected = await verifyDistribution(
target,
options.incoming.platform,
options.incoming.arch,
- )
- : await readManifest(target).catch(() => null);
+ );
+ } catch {
+ selectedVerified = false;
+ }
+ }
if (selected === null) return { sameBuildReplace: false };
// Pre-contract packages have no `build_number`. Comparing them against an
// invented ordinal would either break the hourly chain or manufacture a
@@ -385,6 +391,9 @@ async function inspectBuildNumberTransition(options: {
if (options.incoming.build_number > selected.build_number)
return { sameBuildReplace: false };
if (options.incoming.build_number === selected.build_number) {
+ if (!selectedVerified && options.allowSameBuildReplace) {
+ return { sameBuildReplace: true };
+ }
// Same build: an idempotent reinstall is fine only if the bytes match. The
// incoming source is verified, so compare it against the selected tree.
try {
@@ -395,11 +404,8 @@ async function inspectBuildNumberTransition(options: {
}
if (
!isReleaseCommit(selected.git_commit) ||
- !isReleaseCommit(options.incoming.git_commit) ||
- selected.git_commit === options.incoming.git_commit
+ !isReleaseCommit(options.incoming.git_commit)
) {
- // Same commit with different bytes is not a new build: it is a
- // non-reproducible or corrupted artifact and must stay rejected.
throw new Error("installed_version_conflict");
}
return { sameBuildReplace: true };
diff --git a/memhub/packages/runtime-control/src/packaged-runtime-install.test.ts b/memhub/packages/runtime-control/src/packaged-runtime-install.test.ts
index 8cbef61..aab8358 100644
--- a/memhub/packages/runtime-control/src/packaged-runtime-install.test.ts
+++ b/memhub/packages/runtime-control/src/packaged-runtime-install.test.ts
@@ -422,7 +422,7 @@ describe("installPackagedRuntime", () => {
).toBe("rebuilt-body");
});
- it("refuses same-commit different bytes even when the bundle opts in", async () => {
+ it("repairs same-commit drift when the trusted bundle opts in", async () => {
const { root, resources, executable, installRoot } = await fixture();
const { selected } = await installFormalCurrent({
root,
@@ -434,18 +434,43 @@ describe("installPackagedRuntime", () => {
await writeFile(path.join(selected, "web", "index.html"), "unexpected");
await rewriteManifestDigest(selected, "web/index.html");
- await expect(
- installPackagedRuntime({
- resourcesPath: resources,
- executablePath: executable,
- installRoot,
- platform: "darwin",
- arch: "arm64",
- buildNumber: 3757,
- gitCommit: "a".repeat(40),
- replaceSameBuild: true,
- }),
- ).rejects.toThrow("installed_version_conflict");
+ const receipt = await installPackagedRuntime({
+ resourcesPath: resources,
+ executablePath: executable,
+ installRoot,
+ platform: "darwin",
+ arch: "arm64",
+ buildNumber: 3757,
+ gitCommit: "a".repeat(40),
+ replaceSameBuild: true,
+ });
+ expect(receipt.reused_current).toBe(false);
+ expect(receipt.version_directory).not.toBe(selected);
+ });
+
+ it("repairs an extra file left in the selected runtime tree", async () => {
+ const { root, resources, executable, installRoot } = await fixture();
+ const { selected } = await installFormalCurrent({
+ root,
+ resources,
+ executable,
+ installRoot,
+ gitCommit: "a".repeat(40),
+ });
+ await writeFile(path.join(selected, "left-by-ditto"), "dirty");
+
+ const receipt = await installPackagedRuntime({
+ resourcesPath: resources,
+ executablePath: executable,
+ installRoot,
+ platform: "darwin",
+ arch: "arm64",
+ buildNumber: 3757,
+ gitCommit: "a".repeat(40),
+ replaceSameBuild: true,
+ });
+ expect(receipt.reused_current).toBe(false);
+ expect(receipt.version_directory).not.toBe(selected);
});
it.each(["missing"])(
diff --git a/memhub/packages/runtime-control/src/packaged-runtime-install.ts b/memhub/packages/runtime-control/src/packaged-runtime-install.ts
index b285fa9..3ea1503 100644
--- a/memhub/packages/runtime-control/src/packaged-runtime-install.ts
+++ b/memhub/packages/runtime-control/src/packaged-runtime-install.ts
@@ -123,9 +123,9 @@ export async function installPackagedRuntime(options: {
*
* Off by default, which preserves `installed_version_conflict`. Desktop turns
* it on: the bundle it carries has passed notarization, so its payload is
- * already trusted, and the same build number is re-released whenever a
- * release is rebuilt from a new commit. Refusing that case leaves an affected
- * machine with an app that exits on every launch, which is a worse outcome
+ * already trusted. It may need to replace a rebuilt release or repair a
+ * selected tree polluted by an interrupted copy. Refusing either case leaves
+ * an affected machine with an app that exits on every launch, which is worse
* than replacing the runtime. The superseded tree is kept, not edited. */
replaceSameBuild?: boolean;
gitCommit?: string;
@@ -307,11 +307,33 @@ async function reuseSelectedSameBuild(options: {
) {
throw new Error("install_current_unmanaged");
}
- const selectedManifest = await verifyInstalledDistribution(
- selected,
- options.platform,
- options.arch,
- );
+ let selectedManifest: DistributionManifest;
+ try {
+ selectedManifest = await verifyInstalledDistribution(
+ selected,
+ options.platform,
+ options.arch,
+ );
+ } catch (error) {
+ if (!options.replaceSameBuild) throw error;
+ // A notarized App bundle is the repair source. A dirty selected tree must
+ // reach the normal staged install path instead of failing before the
+ // same-build replacement policy can run.
+ const declared = await readFile(
+ path.join(selected, "manifest.json"),
+ "utf8",
+ )
+ .then((value) => JSON.parse(value) as DistributionManifest)
+ .catch(() => null);
+ if (
+ declared?.build_number !== undefined &&
+ options.buildNumber !== undefined &&
+ declared.build_number > options.buildNumber
+ ) {
+ throw new Error("distribution_downgrade_refused");
+ }
+ return null;
+ }
if (selectedManifest.build_number !== options.buildNumber) return null;
// The bundle's own payload, read in place. It has to agree with the selected
// tree file for file; there is no cheaper signal that is also exact, and a