Skip to content

fix(gateway): make doctor dreaming timestamp comparators NaN-safe - #118749

Merged
Patrick-Erichsen merged 6 commits into
openclaw:mainfrom
tzy-17:fix/doctor-timestamp-nan-comparator
Aug 7, 2026
Merged

Patrick-Erichsen merged 6 commits into
openclaw:mainfrom
tzy-17:fix/doctor-timestamp-nan-comparator

Conversation

@tzy-17

@tzy-17 tzy-17 commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The gateway doctor's dreaming statistics comparators (compareDreamingEntryByRecency and compareDreamingEntryByPromotion in doctor.ts) use Date.parse + bMs - aMs subtraction. When one entry has a valid timestamp and the other has a malformed lastRecalledAt (e.g., "not-a-valid-date"), Date.parse returns NaN, and bMs - aMs returns NaN. Array.sort with a NaN comparator produces undefined ordering, so the operator may see malformed entries ranked ahead of valid recent ones.

The same mixed-NaN comparator exists in Memory Core's short-term-promotion-stats.ts (compareDreamingStatsEntryByRecency and compareDreamingStatsEntryByPromotion). Memory Core caps each workspace list at 8 entries BEFORE the gateway merges them, so a NaN-discarded valid entry cannot be recovered at the gateway boundary.

Why This Change Was Made

This PR now fixes both boundaries to be self-contained:

  1. Gateway (doctor.ts): new parseDreamingTimestampMs coerces invalid timestamps to -Infinity, comparators return finite -1/0/1
  2. Memory Core producer (short-term-promotion-stats.ts): replaces the buggy raw Date.parse pattern with the existing compareStoreTimestampDesc helper (already NaN-safe in short-term-promotion-utils.ts)

The companion PR #118750 now only covers the recency ranking fix (ageDays/recency calculation in short-term-promotion.ts), which is a separate concern from the comparators.

User Impact

Operators running openclaw doctor memory status with malformed persisted timestamps see deterministic ordering: valid recent entries always rank ahead of entries with invalid timestamps. Previously, NaN comparators could place malformed entries (with more signals) ahead of valid recent entries, or cause Memory Core to discard valid entries during its 8-entry cap before the gateway ever saw them.

Evidence

Real gateway doctor response proof

Actual doctor.memory.status response with malformed timestamps: https://gist.github.com/tzy-17/b8e0d53f7f3644a90720fa57f2814769

=== Ordering proof (after fix) ===
  1. memory/recent.md (signals=1, lastRecalledAt=2026-04-04T00:00:00.000Z)
  2. memory/malformed.md (signals=5, lastRecalledAt=not-a-valid-date)

  Valid entry (1 signal, recent) ranks AHEAD of malformed entry (5 signals, invalid date).
  On main: NaN comparator → undefined order (malformed could appear first despite more signals).
  On fix: malformed → -Infinity → valid entry sorts first deterministically.

The response payload is captured from the actual invokeDoctorMemory("doctor.memory.status") call, not a mocked comparator script. Both boundaries (gateway + memory-core) use the NaN-safe comparator.

Before/after comparator behavior

// Main (buggy): NaN when one timestamp is malformed
const aMs = Date.parse("not-a-valid-date"); // NaN
const bMs = Date.parse("2026-04-04T00:00:00.000Z"); // valid
return bMs - aMs; // NaN → Array.sort undefined order

// Fix (both boundaries): -Infinity coercion → finite comparison
const aMs = parseDreamingTimestampMs("not-a-valid-date"); // -Infinity
const bMs = parseDreamingTimestampMs("2026-04-04T00:00:00.000Z"); // valid
return bMs > aMs ? 1 : -1; // 1 (always finite, never NaN)

Tests

  • doctor.test.ts: 46 tests pass (includes regression test for malformed ordering)
  • short-term-promotion.test.ts: 85 tests pass
  • dreaming-phases.test.ts: 56 tests pass
  • Total: 187 tests pass

Companion PR

#118750 covers the separate recency ranking fix (ageDays/recency in short-term-promotion.ts). It is no longer a merge dependency since the comparator fix is now self-contained in this PR.

compareDreamingEntryByRecency and compareDreamingEntryByPromotion used
`Number.isFinite(aMs) || Number.isFinite(bMs)` then `return bMs - aMs`.
When exactly one side parsed to NaN (non-empty malformed timestamp), the
guard still entered the branch and returned NaN - bMs, producing NaN and
leaving Array.sort order undefined for the doctor.memory.status dreaming
entry list. Coerce unparseable timestamps to -Infinity via a shared
parseDreamingTimestampMs helper and return a finite -1/0/1 from the
timestamp branch so the sort stays deterministic.
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Aug 3, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Aug 3, 2026
@clawsweeper

clawsweeper Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 6, 2026, 8:37 PM ET / August 7, 2026, 00:37 UTC.

ClawSweeper review

What this changes

The branch makes malformed dreaming timestamps rank as oldest in capped Memory Core statistics and gateway doctor output, with regression tests.

Merge readiness

⚠️ Needs maintainer review before merge

This PR remains necessary: current main can return NaN from timestamp comparators at both the Memory Core cap and gateway merge boundaries. The patch uses the existing canonical comparator upstream and downstream; no code finding was identified, but required exact-head checks are failing and must be resolved before merge.

Priority: P2
Reviewed head: e945866b139aef8083b15241e4b2e6991c324d37

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The root-cause repair and real behavior proof are strong, but failing required exact-head checks prevent merge readiness.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (linked_artifact): The PR body links a redacted captured gateway doctor response that directly demonstrates the corrected ordering; the added consolidation preserves the same established helper semantics.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): The PR body links a redacted captured gateway doctor response that directly demonstrates the corrected ordering; the added consolidation preserves the same established helper semantics.
Evidence reviewed 5 items Current-main defect: Current main subtracts parsed timestamps after an OR finite-value guard; one malformed and one valid timestamp produces NaN at both the producer and gateway boundaries.
Canonical owner-boundary repair: The PR reuses Memory Core's existing NaN-safe descending timestamp helper before the eight-entry cap, while the gateway returns finite ordering results when merging diagnostics.
Regression coverage: The head adds a producer-cap regression and a gateway doctor-response ordering regression for valid and malformed timestamps.
Findings None None.
Security None None.

How this fits together

Memory Core turns persisted recall entries into capped dreaming diagnostics, and the gateway doctor method merges those diagnostics for operators. Ordering at either boundary controls whether valid entries survive and appear in memory-status output.

flowchart LR
  A[Persisted recall entries] --> B[Memory Core statistics]
  B --> C[Eight-entry cap]
  C --> D[Gateway doctor method]
  D --> E[Cross-workspace ordering]
  E --> F[Operator memory status]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -10, Tests +101. Total +91 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 32 42 -10
Tests 2 101 0 +101
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 133 42 +91

Review metrics

Metric Value Why it matters
Production vs test delta production +32/-42 (net -10); tests +101/-0 Production code is net smaller while the added tests cover the capped producer and gateway response boundaries.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/gateway/server-methods/doctor.test.ts, migration/backfill/repair: src/gateway/server-methods/doctor.ts, unknown-data-model-change: extensions/memory-core/src/dreaming-phases.ts, unknown-data-model-change: extensions/memory-core/src/short-term-promotion.test.ts, vector/embedding metadata: extensions/memory-core/src/dreaming-phases.ts, vector/embedding metadata: extensions/memory-core/src/short-term-promotion-utils.ts, and 1 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

  • Required exact-head CI checks are failing; their causes must be identified and repaired or shown unrelated before merge.

Maintainer options:

  1. Decide the mitigation before merge
    Keep the canonical producer-and-consumer comparator repair, then resolve the failing required checks and rerun them on the current head before landing.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep the canonical producer-and-consumer comparator repair, then resolve the failing required checks and rerun them on the current head before landing.

Do we have a high-confidence way to reproduce the issue?

Yes, source-reproducible: one valid and one malformed timestamp makes current-main subtraction return NaN at both sorting boundaries; the added fixtures encode that path, though no local execution was performed in this read-only review.

Is this the best way to solve the issue?

Yes. Reusing the existing Memory Core timestamp comparator at the capped producer boundary and making the gateway merge finite fixes the complete observable path without adding competing policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against ec023a433614.

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P2: This is a bounded repair for deterministic Memory Core and diagnostics ordering without evidence of an urgent outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The PR body links a redacted captured gateway doctor response that directly demonstrates the corrected ordering; the added consolidation preserves the same established helper semantics.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body links a redacted captured gateway doctor response that directly demonstrates the corrected ordering; the added consolidation preserves the same established helper semantics.

Evidence

What I checked:

Likely related people:

  • Patrick-Erichsen: Authored the exact-head consolidation that moves Dreaming phases onto the existing canonical timestamp comparator. (role: recent area contributor; confidence: high; commits: fcec33f828f7, cf5fe82ffcb0; files: extensions/memory-core/src/dreaming-phases.ts, extensions/memory-core/src/short-term-promotion-utils.ts)
  • Peter Steinberger: The available shallow history attributes the surrounding current-main timestamp modules to this source snapshot, though the original introduction could not be traced further. (role: current-main history attribution; confidence: low; commits: 4d91d44d; files: src/gateway/server-methods/doctor.ts, extensions/memory-core/src/short-term-promotion-stats.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Identify and resolve or verify the cause of the failed required checks, then rerun them on the exact current head.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-08-03T16:15:19.969Z sha ea4bbab :: needs real behavior proof before merge. :: [P1] Repair malformed timestamp ordering in Memory Core
  • reviewed 2026-08-04T03:24:54.316Z sha ea4bbab :: needs real behavior proof before merge. :: [P1] Land the producer-side timestamp repair with this change
  • reviewed 2026-08-04T08:04:45.023Z sha ddeb30d :: needs maintainer review before merge. :: none
  • reviewed 2026-08-05T10:47:44.588Z sha ddeb30d :: needs maintainer review before merge. :: none
  • reviewed 2026-08-06T11:14:57.922Z sha ddeb30d :: needs maintainer review before merge. :: none

@tzy-17

tzy-17 commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Added real behavior proof per ClawSweeper review:

  • Allocation/comparator/recency comparison (main vs fix) via public Gist
  • Focused test captures showing all tests pass
  • Updated PR body with evidence links

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Aug 4, 2026
…ator

ClawSweeper [P1] finding: gateway-only fix is incomplete because Memory Core
has the same mixed-NaN comparator BEFORE the gateway merges lists. A valid
entry discarded upstream cannot be recovered at the gateway boundary.

Incorporate the producer-side fix:
- Export compareStoreTimestampDesc from short-term-promotion-utils.ts
- Replace the buggy raw Date.parse + bMs-aMs pattern in
  short-term-promotion-stats.ts with the NaN-safe compareStoreTimestampDesc

This makes openclaw#118749 self-contained: both gateway doctor.ts AND memory-core
stats.ts comparators are NaN-safe. The companion openclaw#118750 now only needs to
cover the recency ranking fix (ageDays/recency calculation).
@openclaw-barnacle openclaw-barnacle Bot added the extensions: memory-core Extension: memory-core label Aug 4, 2026
@tzy-17

tzy-17 commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Resolved both `merge-risk: 🚨 other` and `status: 📣 needs proof`:

merge-risk: 🚨 other → resolved

Incorporated the producer-side NaN-safe timestamp comparator from #118750 into this PR, making it self-contained:

  • Gateway (doctor.ts): `parseDreamingTimestampMs` → -Infinity → finite comparison
  • Memory Core producer (short-term-promotion-stats.ts): replaced buggy raw `Date.parse` + `bMs-aMs` with existing `compareStoreTimestampDesc` (already NaN-safe)
  • Exported `compareStoreTimestampDesc` from `short-term-promotion-utils.ts`

Both boundaries now use NaN-safe comparators. A valid entry can no longer be discarded by Memory Core's 8-entry cap before the gateway sees it. #118750 now only covers the separate recency ranking fix.

status: 📣 needs proof → resolved

Added real gateway doctor response proof: https://gist.github.com/tzy-17/b8e0d53f7f3644a90720fa57f2814769

Captured from actual `invokeDoctorMemory("doctor.memory.status")` call (not a mocked comparator script). Shows the full response payload with valid entry ranking ahead of malformed entry.

Tests

  • `doctor.test.ts`: 46 pass
  • `short-term-promotion.test.ts`: 85 pass
  • `dreaming-phases.test.ts`: 56 pass
  • Total: 187 pass

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Aug 4, 2026

@Patrick-Erichsen Patrick-Erichsen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved for landing at exact head ddeb30d30ba5d9153a2a19686a4b1e930450b239.

The mixed-NaN defect exists at both the Memory Core top-eight producer cap and the gateway merge boundary; this patch fixes both at their owners and preserves the existing signal/path tie-breakers. Exact-head CI is green and the real doctor.memory.status regression covers the malformed/valid ordering.

ClawSweeper's optional refresh move is intentionally skipped: all four touched current-main blobs remain byte-identical to the reviewed base, GitHub reports a clean merge, exact-head CI is green, and the repository-native merge gate will verify the current merge result. After landing, #118750 needs to rebase/drop its duplicate comparator hunks before separate consideration.

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Aug 6, 2026
tzy-17 added a commit to tzy-17/openclaw that referenced this pull request Aug 6, 2026
…overlap

Revert ageDays from `number | null` back to `number` to preserve the
Gateway doctor payload contract. The actual bug (max recency boost for
malformed timestamps) is fixed in the recency calculation, not in the
ageDays representation: invalid timestamps get `ageDays = 0` (same as
main) but `recency = 0` instead of `calculateRecencyComponent(0, ...)`
which returns the maximum.

This resolves three ClawSweeper merge-risk labels:
- compatibility: ageDays stays numeric across the Gateway boundary
- session-state: malformed-timestamp candidates are no longer excluded
  from the maxAgeDays gate (they pass with ageDays=0, same as main)
- other: drop comparator + helper-export changes owned by PR openclaw#118749
@vincentkoc vincentkoc self-assigned this Aug 6, 2026
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Aug 7, 2026
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@Patrick-Erichsen Patrick-Erichsen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved for landing at exact head 4881823894aed1c8727b74ec8bba93d4b7a2b035.

Remaining mechanical gate: the queued ClawSweeper refresh must finish on this exact head, then the repository-native prepare/merge guards will run.

@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@Patrick-Erichsen
Patrick-Erichsen merged commit e0ec136 into openclaw:main Aug 7, 2026
120 checks passed
@Patrick-Erichsen

Copy link
Copy Markdown
Contributor

Merged via squash.

vincentkoc added a commit to VACInc/openclaw that referenced this pull request Aug 7, 2026
* origin/main: (58 commits)
  fix(test): restart shared gateway after migration convergence (openclaw#120089)
  fix(ui): make active-run steering reliable (openclaw#120083)
  fix(telegram): preserve voice fallback text
  test(swift): preserve queued websocket frames (openclaw#120106)
  fix: reject missing oxlint shard selectors (openclaw#120096)
  test(channels): align prerelease fallback catalog spec (openclaw#120092)
  fix(node-cli): warn when systemd user lingering is disabled after install (openclaw#118430)
  fix(diagnostics): preserve CLI turn usage totals (openclaw#120100)
  fix(gateway): derive lock and coordinator paths from the resolved state dir (openclaw#120110)
  fix(release): isolate private Telegram QA harness (openclaw#120088)
  test(agents): exercise execution attribution ingress guard
  fix(gateway): defer attribution until admission succeeds
  refactor(agents): centralize exact execution attribution
  fix(google): accept base64url provider media (openclaw#116204)
  fix(plugins): warn when registerHook uses a typed hook event name (openclaw#118601)
  fix(canvas): serve Content-Length on A2UI HEAD responses (openclaw#117961)
  fix(gateway): make doctor dreaming timestamp comparators NaN-safe (openclaw#118749)
  fix(heartbeat): explain target-none skips (openclaw#119689)
  fix(security): stop recommending retired install-policy bypasses (openclaw#120011)
  fix(plugins): preserve startup release during repair (openclaw#120085)
  ...

# Conflicts:
#	CHANGELOG.md
#	src/config/sessions/session-accessor.sqlite-transcript-write.ts
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 7, 2026
…enclaw#118749)

* fix(gateway): make doctor dreaming timestamp comparators NaN-safe

compareDreamingEntryByRecency and compareDreamingEntryByPromotion used
`Number.isFinite(aMs) || Number.isFinite(bMs)` then `return bMs - aMs`.
When exactly one side parsed to NaN (non-empty malformed timestamp), the
guard still entered the branch and returned NaN - bMs, producing NaN and
leaving Array.sort order undefined for the doctor.memory.status dreaming
entry list. Coerce unparseable timestamps to -Infinity via a shared
parseDreamingTimestampMs helper and return a finite -1/0/1 from the
timestamp branch so the sort stays deterministic.

* fix(memory-core): incorporate producer-side NaN-safe timestamp comparator

ClawSweeper [P1] finding: gateway-only fix is incomplete because Memory Core
has the same mixed-NaN comparator BEFORE the gateway merges lists. A valid
entry discarded upstream cannot be recovered at the gateway boundary.

Incorporate the producer-side fix:
- Export compareStoreTimestampDesc from short-term-promotion-utils.ts
- Replace the buggy raw Date.parse + bMs-aMs pattern in
  short-term-promotion-stats.ts with the NaN-safe compareStoreTimestampDesc

This makes openclaw#118749 self-contained: both gateway doctor.ts AND memory-core
stats.ts comparators are NaN-safe. The companion openclaw#118750 now only needs to
cover the recency ranking fix (ageDays/recency calculation).

* fix(memory): preserve valid dreaming diagnostics

* style(memory): format dreaming imports

---------

Co-authored-by: Patrick Erichsen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: memory-core Extension: memory-core gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants