From 38fbcfc8ee8739b95bc5da253fea264d584e00ae Mon Sep 17 00:00:00 2001 From: Memtensor-AI Date: Sun, 14 Jun 2026 17:24:41 +0800 Subject: [PATCH 1/5] Fix #1540: fix: (#1824) docs(memos-local-plugin): clarify install path and stale dir names (#1540) The README's 'Quick start' section told users to use install.sh instead of npm install, but the warning was buried and users still tried 'npm install -g @memtensor/memos-local-plugin' first. The reporter in #1540 encountered this on a Hermes deployment. This change: - Promotes the 'do not run npm install -g' notice to a prominent IMPORTANT callout explaining why global install is wrong (no agent-home deploy, no config.yaml, no bridge/viewer) and that the tarball intentionally ships built artifacts only. - Adds a Troubleshooting subsection covering the two specific symptoms in the bug report: the 'package not found' misread, and the stale web/ and site/ directory names (web/ is now viewer/, site/ was removed by commit 26e7e3db). - Mentions install.ps1 for Windows alongside install.sh. - CHANGELOG: record the docs fix and reference #1540. Documentation-only change; no code or runtime behavior touched. Co-authored-by: MemOS AutoDev Co-authored-by: Matthew From 576b408154523eba2765f9ee7226f12cd4a6141f Mon Sep 17 00:00:00 2001 From: Memtensor-AI Date: Sun, 14 Jun 2026 17:54:02 +0800 Subject: [PATCH 2/5] Fix #1888: [Bug] test_system_parser.py: SystemParser.__init__() got an unexpected keyword a (#1889) fix: remove invalid chunker parameter from SystemParser test instantiation - SystemParser.__init__() signature changed to (embedder, llm=None) - Test was still passing chunker=None causing TypeError - Fixes all 5 failing tests in test_system_parser.py Fixes #1888 Co-authored-by: MemOS AutoDev Co-authored-by: Matthew From 968930faf0210a50e91a0de42677777ea77f0e40 Mon Sep 17 00:00:00 2001 From: Memtensor-AI Date: Sun, 14 Jun 2026 22:29:42 +0800 Subject: [PATCH 3/5] Fix #1525: [Bug] clean_json_response crashes with cryptic AttributeError when given None (#1884) * test: add comprehensive tests for clean_json_response (issue #1525) - Add test suite in tests/mem_os/test_format_utils.py - Cover None input ValueError with diagnostic message - Cover markdown removal, whitespace stripping, edge cases - Verify fix for AttributeError when LLM returns None * style: format clean_json_response tests --------- Co-authored-by: MemOS AutoDev Co-authored-by: Matthew --- tests/mem_os/test_format_utils.py | 75 +++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 tests/mem_os/test_format_utils.py diff --git a/tests/mem_os/test_format_utils.py b/tests/mem_os/test_format_utils.py new file mode 100644 index 000000000..b97178784 --- /dev/null +++ b/tests/mem_os/test_format_utils.py @@ -0,0 +1,75 @@ +""" +Test suite for src/memos/mem_os/utils/format_utils.py + +Focus: clean_json_response function defensive behavior +Related issue: #1525 +""" + +import pytest + +from memos.mem_os.utils.format_utils import clean_json_response + + +class TestCleanJsonResponse: + """Test clean_json_response function with various inputs.""" + + def test_clean_json_response_with_none_raises_value_error(self): + """Test that passing None raises ValueError with diagnostic message.""" + with pytest.raises(ValueError) as exc_info: + clean_json_response(None) + + error_message = str(exc_info.value) + assert "clean_json_response received None" in error_message + assert "upstream LLM call" in error_message + assert "timed_with_status" in error_message or "generate()" in error_message + + def test_clean_json_response_removes_json_code_block(self): + """Test removal of ```json markers.""" + input_str = '```json\n{"key": "value"}\n```' + expected = '{"key": "value"}' + assert clean_json_response(input_str) == expected + + def test_clean_json_response_removes_plain_code_block(self): + """Test removal of ``` markers without json keyword.""" + input_str = '```\n{"key": "value"}\n```' + expected = '{"key": "value"}' + assert clean_json_response(input_str) == expected + + def test_clean_json_response_strips_whitespace(self): + """Test that leading/trailing whitespace is stripped.""" + input_str = ' \n {"key": "value"} \n ' + expected = '{"key": "value"}' + assert clean_json_response(input_str) == expected + + def test_clean_json_response_handles_plain_json(self): + """Test that plain JSON without markdown is unchanged (except strip).""" + input_str = '{"key": "value"}' + expected = '{"key": "value"}' + assert clean_json_response(input_str) == expected + + def test_clean_json_response_handles_empty_string(self): + """Test that empty string is handled correctly.""" + assert clean_json_response("") == "" + + def test_clean_json_response_with_complex_json(self): + """Test with realistic LLM response containing nested JSON.""" + input_str = """```json +{ + "queries": [ + {"query": "test", "weight": 1.0}, + {"query": "example", "weight": 0.5} + ] +} +```""" + result = clean_json_response(input_str) + assert "```json" not in result + assert "```" not in result + assert '"queries"' in result + assert result.strip() == result # No leading/trailing whitespace + + def test_clean_json_response_preserves_internal_backticks(self): + """Test that backticks inside JSON content are preserved.""" + input_str = '```json\n{"code": "`example`"}\n```' + result = clean_json_response(input_str) + assert "`example`" in result + assert result.count("`") == 2 # Only internal backticks remain From 8bfef2597f6913541e72eccae42998ca2e254f0f Mon Sep 17 00:00:00 2001 From: Memtensor-AI Date: Mon, 15 Jun 2026 00:10:23 +0800 Subject: [PATCH 4/5] =?UTF-8?q?Fix=20#1901:=20share=5Fcube=5Fwith=5Fuser?= =?UTF-8?q?=20passes=20swapped=20args=20to=20=5Fvalidate=5Fcube=5Faccess?= =?UTF-8?q?=20=E2=80=94=20fails=20for=20ev=20(#1903)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix: validate current user not target in share_cube_with_user (#1901) share_cube_with_user(cube_id, target_user_id) called _validate_cube_access(cube_id, target_user_id), but the validator signature is (user_id, cube_id). The cube_id therefore landed in the user_id slot and _validate_user_exists raised "User '' does not exist or is inactive" for every well-formed call, making the API unusable. The in-code comment "Validate current user has access to this cube" already documented the correct intent: the sharing user (self.user_id) must have access to the cube being shared, not the target. Switch the call to self._validate_cube_access(self.user_id, cube_id). The target user's existence is independently checked on the next line via validate_user(target_user_id), so that path is unchanged. Add regression tests in tests/mem_os/test_memos_core.py that pin down: - validate_user_cube_access is consulted with (self.user_id, cube_id), - add_user_to_cube is called with (target_user_id, cube_id) on success, - a missing target raises "Target user '' does not exist". Closes #1901 Co-authored-by: MemOS AutoDev Bot Co-authored-by: Matthew --- src/memos/mem_os/core.py | 2 +- tests/mem_os/test_memos_core.py | 143 ++++++++++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 1 deletion(-) diff --git a/src/memos/mem_os/core.py b/src/memos/mem_os/core.py index 54f8f01e0..3ede965d3 100644 --- a/src/memos/mem_os/core.py +++ b/src/memos/mem_os/core.py @@ -1170,7 +1170,7 @@ def share_cube_with_user(self, cube_id: str, target_user_id: str) -> bool: bool: True if successful, False otherwise. """ # Validate current user has access to this cube - self._validate_cube_access(cube_id, target_user_id) + self._validate_cube_access(self.user_id, cube_id) # Validate target user exists if not self.user_manager.validate_user(target_user_id): diff --git a/tests/mem_os/test_memos_core.py b/tests/mem_os/test_memos_core.py index 6d2408d05..b57b0b254 100644 --- a/tests/mem_os/test_memos_core.py +++ b/tests/mem_os/test_memos_core.py @@ -795,3 +795,146 @@ def test_search_nonexistent_cube( assert result["text_mem"] == [] assert result["act_mem"] == [] assert result["para_mem"] == [] + + +class TestShareCubeWithUser: + """Regression tests for share_cube_with_user (issue #1901). + + The original implementation called ``_validate_cube_access(cube_id, + target_user_id)``, which both (a) swapped the positional arguments and + (b) validated the wrong user. Every well-formed call therefore failed + with ``ValueError: User '' does not exist or is inactive`` even + though the calling user owned the cube. These tests pin down the correct + semantics: validate the *current* user against the cube being shared, + then delegate the share to ``user_manager.add_user_to_cube``. + """ + + def _build_mos( + self, + mock_llm_factory, + mock_reader_factory, + mock_user_manager_class, + mock_config, + mock_llm, + mock_mem_reader, + mock_user_manager, + ): + mock_llm_factory.from_config.return_value = mock_llm + mock_reader_factory.from_config.return_value = mock_mem_reader + mock_user_manager_class.return_value = mock_user_manager + return MOSCore(MOSConfig(**mock_config)) + + @patch("memos.mem_os.core.UserManager") + @patch("memos.mem_os.core.MemReaderFactory") + @patch("memos.mem_os.core.LLMFactory") + def test_share_cube_validates_current_user_not_target( + self, + mock_llm_factory, + mock_reader_factory, + mock_user_manager_class, + mock_config, + mock_llm, + mock_mem_reader, + mock_user_manager, + ): + """Cube access must be validated against the *current* user. + + Regression for #1901: previously the cube_id was passed where the + user_id was expected, causing ``_validate_user_exists`` to reject + every call because the cube UUID is obviously not a registered user. + """ + mock_user_manager.validate_user.return_value = True + mock_user_manager.validate_user_cube_access.return_value = True + mock_user_manager.add_user_to_cube.return_value = True + + mos = self._build_mos( + mock_llm_factory, + mock_reader_factory, + mock_user_manager_class, + mock_config, + mock_llm, + mock_mem_reader, + mock_user_manager, + ) + + cube_id = "cube-uuid-1234" + target_user_id = "target_user" + + result = mos.share_cube_with_user(cube_id=cube_id, target_user_id=target_user_id) + + assert result is True + # The cube-access check must be made against the *current* user, + # not the cube_id and not the target user. + mock_user_manager.validate_user_cube_access.assert_called_once_with(mos.user_id, cube_id) + # And the actual sharing must add the *target* user to the cube. + mock_user_manager.add_user_to_cube.assert_called_once_with(target_user_id, cube_id) + + @patch("memos.mem_os.core.UserManager") + @patch("memos.mem_os.core.MemReaderFactory") + @patch("memos.mem_os.core.LLMFactory") + def test_share_cube_raises_when_current_user_lacks_access( + self, + mock_llm_factory, + mock_reader_factory, + mock_user_manager_class, + mock_config, + mock_llm, + mock_mem_reader, + mock_user_manager, + ): + """If the current user doesn't have access to the cube, refuse to share. + + The error message must reference the current user, not the cube_id + (which was the misleading symptom in #1901). + """ + mock_user_manager.validate_user.return_value = True + mock_user_manager.validate_user_cube_access.return_value = False + + mos = self._build_mos( + mock_llm_factory, + mock_reader_factory, + mock_user_manager_class, + mock_config, + mock_llm, + mock_mem_reader, + mock_user_manager, + ) + + with pytest.raises(ValueError, match="test_user"): + mos.share_cube_with_user(cube_id="cube-uuid-1234", target_user_id="target_user") + + mock_user_manager.add_user_to_cube.assert_not_called() + + @patch("memos.mem_os.core.UserManager") + @patch("memos.mem_os.core.MemReaderFactory") + @patch("memos.mem_os.core.LLMFactory") + def test_share_cube_raises_when_target_user_missing( + self, + mock_llm_factory, + mock_reader_factory, + mock_user_manager_class, + mock_config, + mock_llm, + mock_mem_reader, + mock_user_manager, + ): + """Target user must exist; ``validate_user`` is consulted independently.""" + # validate_user is used twice: once during MOSCore.__init__ for + # ``self.user_id`` (must succeed) and once for the target user (fail). + mock_user_manager.validate_user.side_effect = lambda uid: uid == "test_user" + mock_user_manager.validate_user_cube_access.return_value = True + + mos = self._build_mos( + mock_llm_factory, + mock_reader_factory, + mock_user_manager_class, + mock_config, + mock_llm, + mock_mem_reader, + mock_user_manager, + ) + + with pytest.raises(ValueError, match="Target user 'missing_user'"): + mos.share_cube_with_user(cube_id="cube-uuid-1234", target_user_id="missing_user") + + mock_user_manager.add_user_to_cube.assert_not_called() From fafad68f8d01527ae949df1372b7f04c704b56e2 Mon Sep 17 00:00:00 2001 From: Fayenix Date: Sun, 21 Jun 2026 12:45:08 -0700 Subject: [PATCH 5/5] feat(2c): add log timezone support --- .../agent-contract/log-record.ts | 2 + .../core/config/defaults.ts | 1 + apps/memos-local-plugin/core/config/index.ts | 6 +++ apps/memos-local-plugin/core/config/schema.ts | 2 + .../core/logger/format/compact.ts | 2 +- .../core/logger/format/pretty.ts | 2 +- apps/memos-local-plugin/core/logger/index.ts | 6 +++ apps/memos-local-plugin/core/time.ts | 45 +++++++++++++++-- .../tests/unit/config/load.test.ts | 21 ++++++++ .../tests/unit/id-time.test.ts | 18 +++++++ .../tests/unit/logger/dispatch.test.ts | 48 +++++++++++++++++++ .../tests/unit/logger/format.test.ts | 30 ++++++++++++ 12 files changed, 178 insertions(+), 5 deletions(-) create mode 100644 apps/memos-local-plugin/tests/unit/logger/format.test.ts diff --git a/apps/memos-local-plugin/agent-contract/log-record.ts b/apps/memos-local-plugin/agent-contract/log-record.ts index 81e87c072..59a35454b 100644 --- a/apps/memos-local-plugin/agent-contract/log-record.ts +++ b/apps/memos-local-plugin/agent-contract/log-record.ts @@ -56,6 +56,8 @@ export interface SerializedLogError { export interface LogRecord { /** Unix epoch milliseconds (UTC). */ ts: number; + /** IANA timezone used for display formatting. Canonical event time remains `ts`. */ + tz?: string; level: LogLevel; kind: LogKind; channel: string; diff --git a/apps/memos-local-plugin/core/config/defaults.ts b/apps/memos-local-plugin/core/config/defaults.ts index 1cf2d2cf6..01fe0b711 100644 --- a/apps/memos-local-plugin/core/config/defaults.ts +++ b/apps/memos-local-plugin/core/config/defaults.ts @@ -277,6 +277,7 @@ export const DEFAULT_CONFIG: ResolvedConfig = { logging: { level: "info", detailedView: false, + timezone: "UTC", console: { enabled: true, pretty: true, channels: ["*"] }, file: { enabled: true, diff --git a/apps/memos-local-plugin/core/config/index.ts b/apps/memos-local-plugin/core/config/index.ts index 1466c27ef..d7cb6638d 100644 --- a/apps/memos-local-plugin/core/config/index.ts +++ b/apps/memos-local-plugin/core/config/index.ts @@ -86,6 +86,12 @@ export function resolveConfig(raw: unknown, warnings?: string[]): ResolvedConfig }); } + try { + new Intl.DateTimeFormat("en-US", { timeZone: completed.logging.timezone }).format(0); + } catch { + throw new MemosError("config_invalid", `invalid logging.timezone: ${completed.logging.timezone}`); + } + return Object.freeze(completed) as ResolvedConfig; } diff --git a/apps/memos-local-plugin/core/config/schema.ts b/apps/memos-local-plugin/core/config/schema.ts index 7c9ff193b..bce3e6bcb 100644 --- a/apps/memos-local-plugin/core/config/schema.ts +++ b/apps/memos-local-plugin/core/config/schema.ts @@ -505,6 +505,8 @@ const LoggingSchema = Type.Object({ ], { default: "info" }), /** Viewer-only switch: expose detailed logs, lifecycle tags and chain view. */ detailedView: Bool(false), + /** IANA timezone for log timestamp display. */ + timezone: StringWithDefault("UTC"), console: Type.Object({ enabled: Bool(true), pretty: Bool(true), diff --git a/apps/memos-local-plugin/core/logger/format/compact.ts b/apps/memos-local-plugin/core/logger/format/compact.ts index 4058a45b5..1d1fd0521 100644 --- a/apps/memos-local-plugin/core/logger/format/compact.ts +++ b/apps/memos-local-plugin/core/logger/format/compact.ts @@ -8,7 +8,7 @@ import type { LogRecord } from "../types.js"; export function formatCompact(record: LogRecord): string { const parts: string[] = []; - parts.push(isoFromEpochMs(record.ts)); + parts.push(isoFromEpochMs(record.ts, record.tz, { offset: true })); parts.push(record.level); parts.push(record.kind); parts.push(`channel=${record.channel}`); diff --git a/apps/memos-local-plugin/core/logger/format/pretty.ts b/apps/memos-local-plugin/core/logger/format/pretty.ts index 66da5052b..d4f225e25 100644 --- a/apps/memos-local-plugin/core/logger/format/pretty.ts +++ b/apps/memos-local-plugin/core/logger/format/pretty.ts @@ -30,7 +30,7 @@ const KIND_TAG: Record = { }; export function formatPretty(record: LogRecord, opts: { color: boolean }): string { - const ts = isoFromEpochMs(record.ts).slice(11, 23); // HH:mm:ss.SSS + const ts = isoFromEpochMs(record.ts, record.tz).slice(11, 23); // HH:mm:ss.SSS const lvl = record.level.toUpperCase().padEnd(5); const kind = KIND_TAG[record.kind] ?? ""; const channel = record.channel ?? "?"; diff --git a/apps/memos-local-plugin/core/logger/index.ts b/apps/memos-local-plugin/core/logger/index.ts index 6c4f4087c..d9ac5afb0 100644 --- a/apps/memos-local-plugin/core/logger/index.ts +++ b/apps/memos-local-plugin/core/logger/index.ts @@ -62,6 +62,8 @@ interface LoggerCore { pid: number; host: string; seq: number; + /** IANA timezone used by display formatters. */ + tz: string; /** Whether file sinks are wired up (false in pre-init / null mode). */ filesActive: boolean; } @@ -90,6 +92,7 @@ function bootstrapConsoleOnly(): LoggerCore { pid: process.pid, host: hostname(), seq: 0, + tz: "UTC", filesActive: false, }; } @@ -199,6 +202,7 @@ export function initLogger( pid: process.pid, host: hostname(), seq: 0, + tz: logging.timezone, filesActive: filesEnabled, }; @@ -229,6 +233,7 @@ export function initTestLogger(): void { pid: process.pid, host: hostname(), seq: 0, + tz: "UTC", filesActive: false, }; } @@ -360,6 +365,7 @@ function emitToCore(record: LogRecord, skipLevelGate = false): void { host: core.host, src: "ts", seq: ++core.seq, + tz: core.tz, ...record, }; const safe = core.redactor.redact(enriched); diff --git a/apps/memos-local-plugin/core/time.ts b/apps/memos-local-plugin/core/time.ts index 84830c526..7437c48d9 100644 --- a/apps/memos-local-plugin/core/time.ts +++ b/apps/memos-local-plugin/core/time.ts @@ -44,7 +44,46 @@ export function formatDurationMs(ms: number): string { return seconds === 0 ? `${minutes}m` : `${minutes}m${seconds}s`; } -/** Convenience: ISO 8601 string for a given epoch ms (UTC). */ -export function isoFromEpochMs(ms: EpochMs): string { - return new Date(ms).toISOString(); +export interface IsoFromEpochOptions { + /** Include numeric UTC offset for localized timestamps. UTC fast path stays unchanged. */ + offset?: boolean; +} + +/** Convenience: ISO 8601 string for a given epoch ms. Defaults to UTC. */ +export function isoFromEpochMs(ms: EpochMs, tz?: string, opts: IsoFromEpochOptions = {}): string { + if (!tz || tz === "UTC") return new Date(ms).toISOString(); + const d = new Date(ms); + const parts = dateTimeParts(d, tz); + const base = `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}.${parts.fractionalSecond ?? "000"}`; + return opts.offset ? base + offsetForTimeZone(d, tz) : base; +} + +function dateTimeParts(d: Date, tz: string): Record { + const fmt = new Intl.DateTimeFormat("en-CA", { + timeZone: tz, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + fractionalSecondDigits: 3, + hour12: false, + }); + const out: Record = {}; + for (const part of fmt.formatToParts(d)) { + if (part.type !== "literal") out[part.type] = part.value; + } + return out; +} + +function offsetForTimeZone(d: Date, tz: string): string { + const fmt = new Intl.DateTimeFormat("en-US", { + timeZone: tz, + timeZoneName: "longOffset", + hour: "2-digit", + }); + const zone = fmt.formatToParts(d).find((part) => part.type === "timeZoneName")?.value; + if (!zone || zone === "GMT" || zone === "UTC") return "+00:00"; + return zone.replace(/^GMT/, ""); } diff --git a/apps/memos-local-plugin/tests/unit/config/load.test.ts b/apps/memos-local-plugin/tests/unit/config/load.test.ts index 77f2f6b3f..b25ba4832 100644 --- a/apps/memos-local-plugin/tests/unit/config/load.test.ts +++ b/apps/memos-local-plugin/tests/unit/config/load.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { promises as fs } from "node:fs"; import { join } from "node:path"; +import { MemosError } from "../../../agent-contract/errors.js"; import { DEFAULT_CONFIG, loadConfig, resolveConfig, resolveHome } from "../../../core/config/index.js"; import { makeTmpHome } from "../../helpers/tmp-home.js"; @@ -21,6 +22,26 @@ describe("config/loadConfig", () => { expect(result.config.embedding.provider).toBe(DEFAULT_CONFIG.embedding.provider); }); + + it("defaults logging.timezone to UTC and accepts custom IANA zones", () => { + expect(resolveConfig({}).logging.timezone).toBe("UTC"); + const cfg = resolveConfig({ logging: { timezone: "America/Los_Angeles" } }); + expect(cfg.logging.timezone).toBe("America/Los_Angeles"); + }); + + it("rejects invalid logging.timezone with config_invalid", () => { + expect(() => resolveConfig({ logging: { timezone: "Not/AZone" } })).toThrow(MemosError); + try { + resolveConfig({ logging: { timezone: "Not/AZone" } }); + throw new Error("expected resolveConfig to reject invalid timezone"); + } catch (err) { + expect(MemosError.is(err)).toBe(true); + expect((err as MemosError).code).toBe("config_invalid"); + expect((err as MemosError).message).toContain("invalid logging.timezone"); + } + }); + + it("merges YAML over defaults and preserves unspecified branches", async () => { const yaml = ` viewer: diff --git a/apps/memos-local-plugin/tests/unit/id-time.test.ts b/apps/memos-local-plugin/tests/unit/id-time.test.ts index 5f277640d..5b3f4dabc 100644 --- a/apps/memos-local-plugin/tests/unit/id-time.test.ts +++ b/apps/memos-local-plugin/tests/unit/id-time.test.ts @@ -56,4 +56,22 @@ describe("core/time", () => { const t = 1_700_000_000_000; expect(isoFromEpochMs(t)).toBe(new Date(t).toISOString()); }); + + it("isoFromEpochMs stays byte-identical to Date.toISOString by default and for UTC", () => { + const t = Date.UTC(2026, 5, 21, 21, 30, 45, 123); + expect(isoFromEpochMs(t)).toBe(new Date(t).toISOString()); + expect(isoFromEpochMs(t, "UTC")).toBe(new Date(t).toISOString()); + }); + + it("isoFromEpochMs formats local wall time for a configured timezone", () => { + const t = Date.UTC(2026, 5, 21, 21, 30, 45, 123); + expect(isoFromEpochMs(t, "America/Los_Angeles")).toBe("2026-06-21T14:30:45.123"); + }); + + it("isoFromEpochMs can include numeric UTC offset for compact logs", () => { + const summer = Date.UTC(2026, 5, 21, 21, 30, 45, 123); + const winter = Date.UTC(2026, 11, 21, 21, 30, 45, 123); + expect(isoFromEpochMs(summer, "America/Los_Angeles", { offset: true })).toBe("2026-06-21T14:30:45.123-07:00"); + expect(isoFromEpochMs(winter, "America/Los_Angeles", { offset: true })).toBe("2026-12-21T13:30:45.123-08:00"); + }); }); diff --git a/apps/memos-local-plugin/tests/unit/logger/dispatch.test.ts b/apps/memos-local-plugin/tests/unit/logger/dispatch.test.ts index ee3297761..93b8712f5 100644 --- a/apps/memos-local-plugin/tests/unit/logger/dispatch.test.ts +++ b/apps/memos-local-plugin/tests/unit/logger/dispatch.test.ts @@ -155,4 +155,52 @@ logging: await rootLogger.flush(); expect(memoryBuffer().tail({ limit: 1 }).at(0)?.msg).toBe("py.heartbeat"); }); + + it("attaches configured timezone to locally-created records", async () => { + const yaml = ` +logging: + timezone: America/Los_Angeles +`; + const ctx = await makeTmpHome({ agent: "openclaw", configYaml: yaml }); + cleanup = ctx.cleanup; + initLogger(ctx.config, ctx.home); + + rootLogger.child({ channel: "core.session" }).info("timezone.local"); + await rootLogger.flush(); + + expect(memoryBuffer().tail({ limit: 1 }).at(0)?.tz).toBe("America/Los_Angeles"); + }); + + it("forward preserves explicit timezone and defaults missing timezone", async () => { + const yaml = ` +logging: + timezone: America/Los_Angeles +`; + const ctx = await makeTmpHome({ agent: "openclaw", configYaml: yaml }); + cleanup = ctx.cleanup; + initLogger(ctx.config, ctx.home); + + const log = rootLogger.child({ channel: "adapter.hermes" }); + log.forward({ + ts: Date.UTC(2026, 5, 21, 21, 30, 45, 123), + level: "info", + kind: "app", + channel: "adapter.hermes", + msg: "py.explicit", + src: "py", + tz: "Europe/London", + }); + log.forward({ + ts: Date.UTC(2026, 5, 21, 21, 30, 45, 123), + level: "info", + kind: "app", + channel: "adapter.hermes", + msg: "py.defaulted", + src: "py", + }); + + const tail = memoryBuffer().tail({ limit: 2 }); + expect(tail.find((r) => r.msg === "py.explicit")?.tz).toBe("Europe/London"); + expect(tail.find((r) => r.msg === "py.defaulted")?.tz).toBe("America/Los_Angeles"); + }); }); diff --git a/apps/memos-local-plugin/tests/unit/logger/format.test.ts b/apps/memos-local-plugin/tests/unit/logger/format.test.ts new file mode 100644 index 000000000..2d631d64e --- /dev/null +++ b/apps/memos-local-plugin/tests/unit/logger/format.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; + +import type { LogRecord } from "../../../agent-contract/log-record.js"; +import { formatCompact } from "../../../core/logger/format/compact.js"; +import { formatPretty } from "../../../core/logger/format/pretty.js"; + +const base: LogRecord = { + ts: Date.UTC(2026, 5, 21, 21, 30, 45, 123), + level: "info", + kind: "app", + channel: "core.session", + msg: "session.opened", +}; + +describe("logger/format", () => { + it("pretty formatter displays configured local time", () => { + const out = formatPretty({ ...base, tz: "America/Los_Angeles" }, { color: false }); + expect(out.startsWith("14:30:45.123 INFO [core.session] session.opened")).toBe(true); + }); + + it("compact formatter preserves UTC default output", () => { + const out = formatCompact(base); + expect(out.startsWith("2026-06-21T21:30:45.123Z info app ")).toBe(true); + }); + + it("compact formatter emits offset-bearing local timestamp", () => { + const out = formatCompact({ ...base, tz: "America/Los_Angeles" }); + expect(out.startsWith("2026-06-21T14:30:45.123-07:00 info app ")).toBe(true); + }); +});