Python
fix(memhub): experiences show their conversation time
alvinfeic8b660651e70
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1e29f07..055f081 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,14 @@ Hy Memory and MemHub are versioned and released independently.## Unreleased+- MemHub shows when working and coding experiences were talked about. After+ the SDK upgrade every one of them read "时间未知" (time unknown) because the+ SDK never stored their conversation time; hy-memory 2.0.7 stores it and+ Core now passes it through the memory list, detail, search and home+ summary. An experience stored before 2.0.7 shows its write time, labelled+ "写入于" / "写入时间", instead of "时间未知". Metadata repair also writes+ the conversation time it recovers from the migration bundle into the SDK's+ coding/working stores when they already have the column.- The SDK migration no longer fails its first run on a home with legacyvectors: reattaching them left a Chroma instance open with its own settings,and the readback that followed could not open the same storediff --git a/memhub/apps/core/src/one_memory/hy_sdk_migration.py b/memhub/apps/core/src/one_memory/hy_sdk_migration.pyindex cf43a29..b4bd56b 100644--- a/memhub/apps/core/src/one_memory/hy_sdk_migration.py+++ b/memhub/apps/core/src/one_memory/hy_sdk_migration.py@@ -437,10 +437,13 @@ def _repair_coding():if table not in tables:continue+ # hy-memory 2.0.7 added the conversation time; older stores lack it.+ has_memory_at = "memory_at" in _columns(database, table)rows = database.execute(- f"SELECT {identifier},source,created_at FROM {table}"+ f"SELECT {identifier},source,created_at,"+ f"{'memory_at' if has_memory_at else 'NULL'} FROM {table}").fetchall()- for memory_id, source, created_at in rows:+ for memory_id, source, created_at, memory_at in rows:desired = mapping.get(str(memory_id))if desired is None:continue@@ -449,6 +452,13 @@ def _repair_coding(if desired.source and source in {None, "", "default"}:updates.append("source=?")values.append(desired.source)+ if (+ has_memory_at+ and desired.memory_at is not None+ and memory_at != desired.memory_at+ ):+ updates.append("memory_at=?")+ values.append(desired.memory_at)if desired.created_at is not None:desired_created_at = (datetime.fromtimestamp(desired.created_at, tz=UTC)diff --git a/memhub/apps/core/src/one_memory/hy_sdk_types.py b/memhub/apps/core/src/one_memory/hy_sdk_types.pyindex 52fd381..d510a79 100644--- a/memhub/apps/core/src/one_memory/hy_sdk_types.py+++ b/memhub/apps/core/src/one_memory/hy_sdk_types.py@@ -151,6 +151,7 @@ class HySdkMemoryRecord(BaseModel):if not content.strip():raise HySdkReadError("hy_memory_record_shape_unknown")status = str(raw.get("status") or "active")+ memory_at = raw.get("memory_at")created_at = _epoch(raw.get("created_at"))updated_at = _epoch(raw.get("updated_at"))try:@@ -167,6 +168,9 @@ class HySdkMemoryRecord(BaseModel):str(raw["session_id"]) if isinstance(raw.get("session_id"), str) else None),source=str(raw["source"]) if isinstance(raw.get("source"), str) else None,+ # Conversation time; hy-memory 2.0.7 stores it for experiences+ # and facts. Older stores leave it unknown.+ memory_at=memory_at if isinstance(memory_at, int) else None,gmt_created=created_at,scene=cast(MemoryScene, variant),kind=cast(MemoryKindName, kind),diff --git a/memhub/apps/core/tests/test_memory_library_all_scenes.py b/memhub/apps/core/tests/test_memory_library_all_scenes.pyindex 439aa18..1d07cb4 100644--- a/memhub/apps/core/tests/test_memory_library_all_scenes.py+++ b/memhub/apps/core/tests/test_memory_library_all_scenes.py@@ -55,6 +55,9 @@ def chat_row(memory_id, content, *, source="cursor"):}+EXPERIENCE_MEMORY_AT = 1_789_990_000++def experience_row(memory_id, task, solution, *, variant="working", source="codebuddy"):return {"experience_id": memory_id,@@ -63,6 +66,8 @@ def experience_row(memory_id, task, solution, *, variant="working", source="code"task": task,"solution": solution,"source": source,+ # Conversation time, epoch seconds like chat (hy-memory 2.0.7).+ "memory_at": EXPERIENCE_MEMORY_AT,"created_at": "2026-10-01T08:00:00","updated_at": "2026-10-02T08:00:00","_variant": variant,@@ -446,6 +451,7 @@ def test_keyword_filter_reads_experience_and_fact_text(tmp_path, monkeypatch):assert experience["content"] == "Fix flaky tests\nPin the pytest seed"assert experience["status"] == "active"assert experience["updated_at"] > experience["created_at"]+ assert experience["memory_at"] == EXPERIENCE_MEMORY_ATfact = by_id["fact-1"]assert (fact["scene"], fact["kind"], fact["variant"]) == ("coding", "fact", "coding")assert fact["content"] == "The pytest suite runs in CI"@@ -488,6 +494,10 @@ def test_empty_query_lists_all_scenes_with_source_filter_and_totals(tmp_path, mo"chat","chat",]+ assert [item["memory_at"] for item in body["memories"][:2]] == [+ EXPERIENCE_MEMORY_AT,+ EXPERIENCE_MEMORY_AT,+ ]call = sdk.list_calls[0]assert call["scene"] == "all"assert call["include_sources"] is None@@ -527,6 +537,7 @@ def test_detail_edit_delete_pass_kind_and_variant(tmp_path, monkeypatch):assert record["task"] == "Old task"assert record["solution"] == "Old solution"assert record["content"] == "Old task\nOld solution"+ assert record["memory_at"] == EXPERIENCE_MEMORY_ATassert sdk.get_calls[-1] == ("exp-1", "experience", "working")# Chat detail with no namespace keeps the plain SDK call.@@ -692,5 +703,6 @@ def test_home_summary_counts_what_the_memory_page_lists(tmp_path, monkeypatch):assert (home_list["offset"], home_list["limit"], home_list["order"]) == (0, 1, "desc")assert body["latest"]["memory_id"] == "exp-w"assert body["latest"]["scene"] == "working"+ assert body["latest"]["memory_at"] == EXPERIENCE_MEMORY_ATrun_with_sdk(tmp_path, monkeypatch, scenario)diff --git a/memhub/apps/core/tests/test_sdk_data_plane_migration.py b/memhub/apps/core/tests/test_sdk_data_plane_migration.pyindex 31d41f7..bdf9cf8 100644--- a/memhub/apps/core/tests/test_sdk_data_plane_migration.py+++ b/memhub/apps/core/tests/test_sdk_data_plane_migration.py@@ -137,10 +137,12 @@ def test_post_cutover_metadata_repair_restores_source_and_original_times(store):)coding = data_dir / "hy-memory" / "governed-v2" / "coding_cv.sqlite3"with sqlite3.connect(coding) as database:+ # hy-memory 2.0.7 stores the conversation time; working_fact below is+ # left without it, as a store not yet opened by 2.0.7.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)"+ "source TEXT,memory_at INTEGER,created_at TEXT,updated_at TEXT)")database.execute("CREATE TABLE working_fact ("@@ -149,7 +151,7 @@ def test_post_cutover_metadata_repair_restores_source_and_original_times(store):)database.execute("INSERT INTO coding_memory_meta VALUES "- "('sdk-1','local','scope','remember','default','now','now')"+ "('sdk-1','local','scope','remember','default',NULL,'now','now')")result = repair_sdk_metadata_from_bundle(@@ -168,10 +170,11 @@ def test_post_cutover_metadata_repair_restores_source_and_original_times(store):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'"+ source, memory_at, created_at = database.execute(+ "SELECT source,memory_at,created_at FROM coding_memory_meta WHERE experience_id='sdk-1'").fetchone()assert source == "workbuddy"+ assert datetime.fromtimestamp(memory_at, tz=UTC) == datetime(2026, 10, 17, tzinfo=UTC)assert created_at.startswith("2026-10-18T00:00:00")repeated = repair_sdk_metadata_from_bundle(diff --git a/memhub/apps/web/src/MemoryMap.test.tsx b/memhub/apps/web/src/MemoryMap.test.tsxindex beec1a5..dfbafd2 100644--- a/memhub/apps/web/src/MemoryMap.test.tsx+++ b/memhub/apps/web/src/MemoryMap.test.tsx@@ -517,7 +517,7 @@ it("D96: the memory page has no raw-dialogue tab and never loads the dialogue liit("D96: lists a memory by when its conversation happened, not when it was generated", () => {const today = new Date().toISOString();const thisYear = new Date().getFullYear();- const items = ["第一条", "第二条", "第三条"].map((content, i) => ({+ const items = ["第一条", "第二条", "第三条", "第四条"].map((content, i) => ({...memories[0],memory_id: `t${i}`,content,@@ -532,10 +532,11 @@ it("D96: lists a memory by when its conversation happened, not when it was genertotal: 519,offset: 100,limit: 100,- source_ids_by_memory: { t0: [], t1: [], t2: [] },+ source_ids_by_memory: { t0: [], t1: [], t2: [], t3: [] },source_time_by_memory: {t0: { at: `${thisYear}-10-02T10:54:00`, basis: "conversation" },t1: { at: `${thisYear}-09-30T08:00:00`, basis: "import" },+ t3: { at: `${thisYear}-09-29T08:00:00`, basis: "write" },},})}/>,@@ -547,6 +548,10 @@ it("D96: lists a memory by when its conversation happened, not when it was generexpect(within(list).getByRole("button", { name: /第二条/ }).textContent,).toContain("导入于 9月30日");+ // An experience stored without a conversation time names its write time.+ expect(+ within(list).getByRole("button", { name: /第四条/ }).textContent,+ ).toContain("写入于 9月29日");// D99: the generated day keeps its own line, so a memory made today from an// old conversation still reads as new rather than looking misplaced.expect(diff --git a/memhub/apps/web/src/MemoryMap.tsx b/memhub/apps/web/src/MemoryMap.tsxindex b1fc273..7852c4c 100644--- a/memhub/apps/web/src/MemoryMap.tsx+++ b/memhub/apps/web/src/MemoryMap.tsx@@ -139,7 +139,7 @@ function monthDay(value: string, locale: GuiLocale): string | null {/** D96: when the cited conversation happened, not when the memory was generated. */function sourceStamp(- time: { at: string; basis: "conversation" | "import" } | undefined,+ time: { at: string; basis: "conversation" | "import" | "write" } | undefined,fallback: string | null | undefined,locale: GuiLocale = "zh-CN",): string {@@ -147,7 +147,11 @@ function sourceStamp(if (time && day)return memoryText(locale,- time.basis === "conversation" ? "对话于 {day}" : "导入于 {day}",+ time.basis === "conversation"+ ? "对话于 {day}"+ : time.basis === "write"+ ? "写入于 {day}"+ : "导入于 {day}",{ day },);return dayStamp(fallback, locale);diff --git a/memhub/apps/web/src/SelectedMemoryDetail.test.tsx b/memhub/apps/web/src/SelectedMemoryDetail.test.tsxindex 3964c72..4409ff5 100644--- a/memhub/apps/web/src/SelectedMemoryDetail.test.tsx+++ b/memhub/apps/web/src/SelectedMemoryDetail.test.tsx@@ -176,3 +176,41 @@ it("stamps today's source and conversation time without an evidence page", () =>expect(screen.getByText(/对话时间 今天 /)).toBeTruthy();expect(screen.queryByRole("button", { name: "查看原文" })).toBeNull();});+it("shows an experience's conversation time when the SDK stored one", () => {+ const today = new Date().toISOString();+ render(+ <SelectedMemoryDetail+ detail={{+ ...detail,+ evidence: [],+ sdk_status: "active",+ source_id: "codebuddy",+ sdk_memory_at: today,+ sdk_created_at: today,+ sdk_ref: { scene: "coding", kind: "experience", variant: "coding" },+ }}+ sources={[]}+ />,+ );+ expect(screen.getByText(/对话时间 今天 /)).toBeTruthy();+ expect(screen.queryByText(/时间未知/)).toBeNull();+});+it("labels an experience without a conversation time by its write time", () => {+ render(+ <SelectedMemoryDetail+ detail={{+ ...detail,+ evidence: [],+ sdk_status: "active",+ source_id: "codebuddy",+ sdk_memory_at: null,+ sdk_created_at: new Date().toISOString(),+ sdk_ref: { scene: "working", kind: "experience", variant: "working" },+ }}+ sources={[]}+ />,+ );+ expect(screen.getByText(/来源 codebuddy · 写入时间 今天 /)).toBeTruthy();+ expect(screen.queryByText(/对话时间/)).toBeNull();+ expect(screen.queryByText(/时间未知/)).toBeNull();+});diff --git a/memhub/apps/web/src/SelectedMemoryDetail.tsx b/memhub/apps/web/src/SelectedMemoryDetail.tsxindex 6b32b32..10d2ace 100644--- a/memhub/apps/web/src/SelectedMemoryDetail.tsx+++ b/memhub/apps/web/src/SelectedMemoryDetail.tsx@@ -19,7 +19,10 @@ export function SelectedMemoryDetail({detail: MemoryDetail;sources: SourceResponse[];/** D99: when the cited conversation happened, in the list's own terms. */- conversationAt?: { at: string; basis: "conversation" | "import" } | null;+ conversationAt?: {+ at: string;+ basis: "conversation" | "import" | "write";+ } | null;}) {const { locale, t } = useGuiLanguage();const memory = detail.memory;@@ -42,6 +45,17 @@ export function SelectedMemoryDetail({? t("selectedMemory.status.superseded"): t("selectedMemory.status.unknown");const sourceId = detail.source_id ?? evidence?.source_id;+ const created = clockStamp(+ detail.sdk_created_at ?? memory.updated_at,+ locale,+ );+ // An SDK experience or fact stored before hy-memory 2.0.7 has no+ // conversation time. It shows when it was written, named as such, instead+ // of "时间未知".+ const writtenOnly =+ detail.sdk_ref !== undefined &&+ detail.sdk_ref.kind !== "chat" &&+ !detail.sdk_memory_at;const source =detail.sdk_status && sourceId === UNATTRIBUTED_SOURCE_ID? t("selectedMemory.sourceUnattributed")@@ -77,25 +91,28 @@ export function SelectedMemoryDetail({<p className="selected-memory-source">{t("selectedMemory.sourceLine", {source,- time: clockStamp(- detail.sdk_memory_at ?? evidence?.created_at,+ time: writtenOnly+ ? t("selectedMemory.writeTime", { created })+ : clockStamp(+ detail.sdk_memory_at ?? evidence?.created_at,+ locale,+ ),+ })}+ </p>+ ) : null}+ {writtenOnly ? null : (+ <p className="selected-memory-times">+ {t("selectedMemory.timestamps", {+ conversation: clockStamp(+ conversationAt?.at ??+ detail.sdk_memory_at ??+ evidence?.created_at,locale,),+ created,})}</p>- ) : null}- <p className="selected-memory-times">- {t("selectedMemory.timestamps", {- conversation: clockStamp(- conversationAt?.at ?? detail.sdk_memory_at ?? evidence?.created_at,- locale,- ),- created: clockStamp(- detail.sdk_created_at ?? memory.updated_at,- locale,- ),- })}- </p>+ )}</article>);}diff --git a/memhub/apps/web/src/sdk-memory-map.test.ts b/memhub/apps/web/src/sdk-memory-map.test.tsindex 55d8667..0b18c92 100644--- a/memhub/apps/web/src/sdk-memory-map.test.ts+++ b/memhub/apps/web/src/sdk-memory-map.test.ts@@ -119,8 +119,12 @@ it("carries each memory's scene and namespace, and edits an experience's solutio});expect(page.window_id).toBe("w1");expect(page.window_reset).toBe(true);- // An experience has no conversation time to show as "imported".- expect(page.source_time_by_memory?.e).toBeUndefined();+ // Stored without a conversation time: it shows when it was written, not+ // an "import".+ expect(page.source_time_by_memory?.e).toEqual({+ at: new Date((NOW - 86_400) * 1_000).toISOString(),+ basis: "write",+ });expect(page.items[1]).toMatchObject({kind: "working",updated_at: new Date((NOW - 3_600) * 1_000).toISOString(),@@ -140,3 +144,29 @@ it("carries each memory's scene and namespace, and edits an experience's solutioexpect(sdkEditableText(experience)).toBe("Pin seed");expect(sdkEditableText(record({}))).toBe("memory");});++it("shows an experience's conversation time when the SDK stored one", () => {+ const at = NOW - 2 * 86_400;+ const experience = record({+ memory_id: "e",+ layer: "experience",+ scene: "coding",+ kind: "experience",+ variant: "coding",+ memory_at: at,+ created_at: NOW - 3_600,+ });+ const page = sdkLibraryPage({+ memories: [experience],+ total: 1,+ limit: 20,+ offset: 0,+ });+ expect(page.source_time_by_memory?.e).toEqual({+ at: new Date(at * 1_000).toISOString(),+ basis: "conversation",+ });+ expect(sdkDetail(experience).sdk_memory_at).toBe(+ new Date(at * 1_000).toISOString(),+ );+});diff --git a/memhub/apps/web/src/sdk-memory-map.ts b/memhub/apps/web/src/sdk-memory-map.tsindex 8e48829..ba13781 100644--- a/memhub/apps/web/src/sdk-memory-map.ts+++ b/memhub/apps/web/src/sdk-memory-map.ts@@ -154,22 +154,24 @@ export function sdkDetail(record: SdkMemoryRecord): MemoryDetail {export function sdkLibraryPage(page: SdkMemoryPage): MemoryLibraryPage {const sourceTime: Record<string,- { at: string; basis: "conversation" | "import" }+ { at: string; basis: "conversation" | "import" | "write" }> = {};const sourceIds: Record<string, string[]> = {};const refs: Record<string, SdkMemoryRef> = {};for (const record of page.memories) {sourceIds[record.memory_id] = [sourceOf(record)];refs[record.memory_id] = sdkMemoryRef(record);- // An experience or fact has no conversation time; the list shows when it- // was last updated instead of calling its creation an import.- if (refs[record.memory_id].kind !== "chat") continue;+ // An experience or fact stored before hy-memory 2.0.7 has no+ // conversation time. It shows when it was written, labelled as such,+ // rather than calling its creation an import.+ const chat = refs[record.memory_id].kind === "chat";const conversation = plausible(record.memory_at);- const at = conversation ?? plausible(record.gmt_created);+ const at =+ conversation ?? plausible(chat ? record.gmt_created : record.created_at);if (at === null) continue;sourceTime[record.memory_id] = {at: new Date(at * 1_000).toISOString(),- basis: conversation !== null ? "conversation" : "import",+ basis: conversation !== null ? "conversation" : chat ? "import" : "write",};}return {diff --git a/memhub/packages/contracts/src/index.ts b/memhub/packages/contracts/src/index.tsindex 2ca034a..1d443ba 100644--- a/memhub/packages/contracts/src/index.ts+++ b/memhub/packages/contracts/src/index.ts@@ -468,10 +468,12 @@ export interface MemoryLibraryPage {limit: number;/** Active evidence sources for each returned memory, from the same authorized page snapshot. */source_ids_by_memory?: Record<string, string[]>;- /** When each returned memory's cited conversation happened (D96). `import` when only the import time is known. */+ /** When each returned memory's cited conversation happened (D96). `import`+ * when only the import time is known; `write` for an SDK experience or fact+ * stored without a conversation time, which shows when it was written. */source_time_by_memory?: Record<string,- { at: string; basis: "conversation" | "import" }+ { at: string; basis: "conversation" | "import" | "write" }>;/** True when the read budget ran out mid-page (typically during a history* import): a partial snapshot, not an authoritative view. Show "importing"diff --git a/memhub/packages/i18n/src/gui-i18n-current.ts b/memhub/packages/i18n/src/gui-i18n-current.tsindex 489a093..6eea397 100644--- a/memhub/packages/i18n/src/gui-i18n-current.ts+++ b/memhub/packages/i18n/src/gui-i18n-current.ts@@ -108,6 +108,7 @@ export const currentChineseMessages = {"selectedMemory.version": "第 {revision} 版","selectedMemory.sourceLine": "来源 {source} · {time}","selectedMemory.timestamps": "对话时间 {conversation} · 沉淀时间 {created}",+ "selectedMemory.writeTime": "写入时间 {created}","selectedMemory.edit": "编辑","selectedMemory.evidence": "原始依据","selectedMemory.evidenceLine": "{author} · 原对话 {time}:",@@ -258,6 +259,7 @@ export const currentEnglishMessages: Record<"selectedMemory.sourceLine": "Source {source} · {time}","selectedMemory.timestamps":"Conversation time {conversation} · Created {created}",+ "selectedMemory.writeTime": "Written {created}","selectedMemory.edit": "Edit","selectedMemory.evidence": "Original evidence","selectedMemory.evidenceLine": "{author} · Original conversation {time}:",@@ -418,6 +420,7 @@ export const currentSpanishMessages: Record<"selectedMemory.sourceLine": "Origen {source} · {time}","selectedMemory.timestamps":"Conversación {conversation} · Guardada {created}",+ "selectedMemory.writeTime": "Escrita {created}","selectedMemory.edit": "Editar","selectedMemory.evidence": "Evidencia original","selectedMemory.evidenceLine": "{author} · Conversación original {time}:",diff --git a/memhub/packages/i18n/src/gui-i18n-english.ts b/memhub/packages/i18n/src/gui-i18n-english.tsindex 8cd10e6..e5952ef 100644--- a/memhub/packages/i18n/src/gui-i18n-english.ts+++ b/memhub/packages/i18n/src/gui-i18n-english.ts@@ -1774,6 +1774,7 @@ const baseEnglishMessages = {" · Import count is still updating; refresh to check","memory:对话于 {day}": "Conversation on {day}","memory:导入于 {day}": "Imported on {day}",+ "memory:写入于 {day}": "Written on {day}","memory:已开始处理所选对话": "Processing selected conversations","memory:处理请求已受理": "Processing request received","memory:模型连接已通过。首批记忆生成后,会逐步出现在记忆列表里。":diff --git a/memhub/packages/i18n/src/gui-i18n-memory.ts b/memhub/packages/i18n/src/gui-i18n-memory.tsindex d27ee09..9db1fb3 100644--- a/memhub/packages/i18n/src/gui-i18n-memory.ts+++ b/memhub/packages/i18n/src/gui-i18n-memory.ts@@ -336,6 +336,7 @@ export const memoryChineseMessages = {"memory: · 导入数量仍在更新,可刷新核对": " · 导入数量仍在更新,可刷新核对","memory:对话于 {day}": "对话于 {day}","memory:导入于 {day}": "导入于 {day}",+ "memory:写入于 {day}": "写入于 {day}","memory:已开始处理所选对话": "已开始处理所选对话","memory:处理请求已受理": "处理请求已受理","memory:模型连接已通过。首批记忆生成后,会逐步出现在记忆列表里。":@@ -750,6 +751,7 @@ export const memorySpanishMessages: Record<" · La importación continúa; actualiza para verificar","memory:对话于 {day}": "Conversación del {day}","memory:导入于 {day}": "Importada el {day}",+ "memory:写入于 {day}": "Escrita el {day}","memory:已开始处理所选对话": "Procesamiento de conversaciones iniciado","memory:处理请求已受理": "Solicitud de procesamiento aceptada","memory:模型连接已通过。首批记忆生成后,会逐步出现在记忆列表里。":