Skip to content

Release/memos local plugin v2.0.12 beta.1 - #2184

Merged
syzsunshine219 merged 9 commits into
mainfrom
release/memos-local-plugin-v2.0.12-beta.1
Jul 29, 2026
Merged

syzsunshine219 merged 9 commits into
mainfrom
release/memos-local-plugin-v2.0.12-beta.1

Conversation

@Hun-ger

@Hun-ger Hun-ger commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Description

This PR synchronizes the source tree with the published
@memtensor/memos-local-plugin@2.0.12-beta.1 release and includes the Hermes
reliability fixes validated in the Beta release.

Summary

  • Synchronizes the npm package version and Hermes plugin manifest during release.
  • Keeps Hermes compression turns read-only and prevents compression commands from
    creating unintended memory or reward records.
  • Reloads Hermes configuration when the plugin is restarted.
  • Shares the Hermes bridge runtime across provider instances while isolating
    runtimes by data home.
  • Hardens bridge startup, keepalive, reconnection, restart, shutdown, and recovery
    lifecycle handling.
  • Improves npm publishing validation and recovery behavior.
  • Adds unit, integration, and Python tests for the updated release and bridge
    lifecycle behavior.

Problem solved

Hermes could create multiple bridge runtimes for the same data home, retain stale
configuration after restart, or leave bridge resources in an inconsistent state
during recovery and shutdown. Compression commands could also enter normal
capture/reward processing even though they should be operational and read-only.

The release workflow additionally needed to keep npm package metadata and the
Hermes plugin manifest synchronized so that the installed plugin reports the same
version as the package published to npm.

Implementation approach

  • Introduced a shared Hermes bridge runtime with scoped ownership, reference
    counting, keepalive monitoring, and deterministic cleanup.
  • Scoped shared runtimes by MemOS data home to avoid cross-profile bridge reuse.
  • Updated restart handling to reload configuration and replace the appropriate
    runtime.
  • Separated compression control turns from normal memory capture and reward
    processing.
  • Added version synchronization and validation between package.json,
    package-lock.json, and the Hermes plugin.yaml.
  • Hardened the publish workflow with package verification, retry handling,
    idempotency checks, and release metadata synchronization.

Dependencies

No new runtime dependencies are required.

Known limitation

A pre-existing macOS/BSD compatibility issue remains in Hermes process-status
detection: the current pgrep -f expression uses non-POSIX regex syntax. On
affected macOS systems, the Viewer may display disconnected instead of
reconnecting while Hermes Chat is running. This does not affect memory storage,
retrieval, compression, or the actual bridge reconnection mechanism and will be
handled separately.

Related Issue (Required): N/A — release synchronization PR for the validated 2.0.12-beta.1 package.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Refactor (does not change functionality, e.g. code style improvements, linting)
  • Documentation update

How Has This Been Tested?

The Beta release workflow and local acceptance covered the following:

  • npm run lint
  • npm test
  • npm run check:hermes-version
  • npm package build and tarball validation
  • Native better-sqlite3 builds for:
    • macOS ARM64
    • macOS Intel
    • Linux x64
    • Windows x64
  • Installation of @memtensor/memos-local-plugin@2.0.12-beta.1 on macOS
  • Package, installed plugin, and Hermes manifest version consistency
  • Hermes provider loading and bridge connection
  • Viewer health endpoint
  • LLM and embedder availability
  • Real memory write and cross-session recall
  • /compress acceptance
  • SQLite quick_check
  • Configuration preservation across installation/restart
  • Log inspection for new warnings, errors, or fatal failures

Reproduction:

cd apps/memos-local-plugin
npm ci
npm run lint
npm test
npm run check:hermes-version
npm pack

bash install.sh --version 2.0.12-beta.1
  • Unit Test
  • Test Script Or Test Steps (provided above)
  • Pipeline Automated API Test (not applicable)

Checklist

  • I have performed a self-review of my own code | 我已自行检查了自己的代码
  • I have commented my code in hard-to-understand areas | 我已在难以理解的地方对代码进行了注释
  • I have added tests that prove my fix is effective or that my feature works | 我已添加测试以证明我的修复有效或功能正常
  • I have created related documentation issue/PR in MemOS-Docs (if applicable) | Not applicable; the repository-local Hermes documentation has been updated.
  • I have linked the issue to this PR (if applicable)
  • I have mentioned the person who will review this PR

Reviewer Checklist

  • closes #<PRIMARY_ISSUE_NUMBER>
  • Made sure Checks passed
  • Tests have been provided

@Memtensor-AI Memtensor-AI added area:plugin OpenClaw & Hermes status:in-progress Someone or AI is working on it | 人工或 AI 正在处理 labels Jul 29, 2026
@Memtensor-AI
Memtensor-AI requested review from hijzy and whipser030 July 29, 2026 06:32
@Memtensor-AI

Copy link
Copy Markdown
Collaborator

🤖 Open Code Review

Target: PR #2184
Task: 74c2430c2e6ab0ad
Base: main
Head: release/memos-local-plugin-v2.0.12-beta.1

🔍 OpenCodeReview found 30 issue(s) in this PR.

⚠️ 3 warning(s) occurred during review.


1. .github/workflows/memos-local-plugin-post-merge-dry-run.yml (L34-L39)

The run: block uses bash-specific syntax (command substitution $(...), single-quoted multi-line strings) but no shell: bash is declared. On ubuntu-latest the default is bash -e {0} so this works today, but it is implicitly relying on a platform default. Adding shell: bash makes the intent explicit and guards against any future runner image change.

Suggested fix: add shell: bash to this step.

💡 Suggested Change

Before:

      - name: Generate dry-run prerelease version
        id: version
        working-directory: apps/memos-local-plugin
        env:
          RUN_NUMBER: ${{ github.run_number }}
        run: |

After:

      - name: Generate dry-run prerelease version
        id: version
        shell: bash
        working-directory: apps/memos-local-plugin
        env:
          RUN_NUMBER: ${{ github.run_number }}
        run: |

2. .github/workflows/memos-local-plugin-post-merge-dry-run.yml (L26-L30)

The new prepare-version job has no timeout-minutes. If the runner stalls or node hangs (e.g. during a slow disk-backed checkout on a busy runner), the job will consume the runner indefinitely and block the downstream dry-run job from ever starting. A short timeout (e.g. 5 minutes) is sufficient for a checkout + inline node script.

Suggested fix: add timeout-minutes: 5.

💡 Suggested Change

Before:

  prepare-version:
    if: ${{ github.repository == 'MemTensor/MemOS' }}
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.version.outputs.version }}

After:

  prepare-version:
    if: ${{ github.repository == 'MemTensor/MemOS' }}
    runs-on: ubuntu-latest
    timeout-minutes: 5
    outputs:
      version: ${{ steps.version.outputs.version }}

3. .github/scripts/publish-local-plugin.sh (L136)

Bug: process.argv[1] is the wrong index when using node -e.

When Node.js is invoked as node -e 'script' arg, process.argv is:

  • [0] = node binary path
  • [1] = '' (empty string — no script file)
  • [2] = the first argument after the script ("${verify_json}" here)

So fs.readFileSync(process.argv[1], "utf8") tries to open an empty-string path and throws ENOENT. This breaks verify_published_package entirely at runtime.

Same bug applies to fs.writeFileSync(process.argv[1], ...) on the line further below.

Fix: change both process.argv[1] references to process.argv[2].

💡 Suggested Change

Before:

      const raw = fs.readFileSync(process.argv[1], "utf8");

After:

      const raw = fs.readFileSync(process.argv[2], "utf8");

4. .github/scripts/publish-local-plugin.sh (L145)

Bug: same process.argv[1] → process.argv[2] issue as above.

This writeFileSync will silently write to the wrong path (empty string) before throwing, leaving the verify_json file unmodified — so the CI log will contain the raw npm output instead of the cleaned-up JSON, making diagnosis harder.

Fix: change to process.argv[2].

💡 Suggested Change

Before:

      fs.writeFileSync(process.argv[1], `${JSON.stringify(report, null, 2)}\n`);

After:

      fs.writeFileSync(process.argv[2], `${JSON.stringify(report, null, 2)}\n`);

5. .github/scripts/publish-local-plugin.sh (L141)

Fragility: trailing non-JSON content after the array will cause a parse error.

raw.slice(jsonStart.index) finds the start of the JSON array but does not trim anything after it. If npm emits any text after the closing ] (registry-side notices can appear even with --silent), JSON.parse will throw a SyntaxError with no actionable message.

Consider extracting only the balanced array, or validate and strip trailing content:

const arrayEnd = raw.lastIndexOf(']');
const report = JSON.parse(raw.slice(jsonStart.index, arrayEnd + 1));

Or simply assert raw.trimEnd().endsWith(']') before parsing and surface a clear error if it doesn't.

💡 Suggested Change

Before:

      const report = JSON.parse(raw.slice(jsonStart.index));

After:

      const arrayEnd = raw.lastIndexOf(']');
      const report = JSON.parse(raw.slice(jsonStart.index, arrayEnd + 1));

6. .github/scripts/publish-local-plugin.sh (L151-L152)

Low: tar extraction failures produce no actionable error message.

If tar can't find package/package.json (e.g. a non-standard tarball layout or corruption), set -e will abort the script but the CI log will only show the tar error, with no context about which verification step failed.

Consider adding guards:

tar -xOf "${verify_tarball}" package/package.json 2>/dev/null \
  || { echo "::error::Failed to extract package/package.json from registry tarball."; exit 1; }
💡 Suggested Change

Before:

    tar -xOf "${verify_tarball}" package/package.json \
      | node -e '

After:

    tar -xOf "${verify_tarball}" package/package.json \
      2>/dev/null || { echo "::error::Failed to extract package/package.json from registry tarball."; exit 1; } \
      | node -e '

7. apps/memos-local-plugin/adapters/hermes/memos_provider/__init__.py (L101-L105)

json.loads can return any JSON value (list, string, number, None) — not just a dict. If the file's top-level content is anything other than a JSON object, payload.get("version") raises AttributeError, which is not caught, and the exception propagates to the module-level PLUGIN_VERSION = _read_plugin_version() assignment, crashing import.

Broaden the except clause to include AttributeError, or guard with an isinstance check before calling .get().

💡 Suggested Change

Before:

    try:
        payload = json.loads(package_json.read_text(encoding="utf-8"))
    except (OSError, ValueError, TypeError):
        return "dev"
    version = payload.get("version")

After:

    try:
        payload = json.loads(package_json.read_text(encoding="utf-8"))
    except (OSError, ValueError, TypeError):
        return "dev"
    if not isinstance(payload, dict):
        return "dev"
    version = payload.get("version")

8. apps/memos-local-plugin/adapters/hermes/install.hermes.sh (L33-L39)

The graceful fallback only covers the case where node is absent or the script file is missing. When node IS available and the sync script IS found, but sync-hermes-version.cjs exits non-zero (e.g., package.json has no version field), set -euo pipefail will abort the entire install immediately — without copying plugin.yaml or reaching any subsequent step. The warn / "as-is" path is never exercised for this failure mode.

Consider wrapping the node invocation with if ! ... ; then warn ...; fi so any sync failure degrades gracefully the same way a missing helper does:

if command -v node >/dev/null 2>&1 && [[ -f "$VERSION_SYNC_SCRIPT" ]]; then
  if ! node "$VERSION_SYNC_SCRIPT" "$PREFIX" >/dev/null; then
    warn "Hermes version sync failed; using packaged plugin.yaml as-is."
  fi
else
  warn "Hermes version sync helper unavailable; using packaged plugin.yaml as-is."
fi

9. apps/memos-local-plugin/adapters/hermes/install.hermes.sh (L34)

The sync script's stdout (e.g., "Synchronized Hermes manifest version to X.Y.Z") is silently discarded, while other install steps are announced via log. This makes it harder to audit which version was written during an install. Consider piping through log or at least removing the >/dev/null suppression so users can see the sync outcome:

  node "$VERSION_SYNC_SCRIPT" "$PREFIX" | while IFS= read -r line; do log "$line"; done

or simply:

  node "$VERSION_SYNC_SCRIPT" "$PREFIX"

10. .github/workflows/memos-local-plugin-publish.yml (L191-L194)

Missing shell: bash on the new multi-line run: block. The publish job runs on ubuntu-latest where the default shell is bash, so this is benign today. However, the review checklist calls out missing shell specification and if the runner ever changes (e.g. a self-hosted runner whose default is sh), the [[ … ]] bashism on line 183 and {…} >> "${GITHUB_ENV}" group redirect would silently break. Adding shell: bash makes the intent explicit and matches the explicit shell: bash already used on the build-prebuilds job's steps.

💡 Suggested Change

Before:

      - name: Validate and build package
        env:
          RELEASE_VERSION: ${{ inputs.version }}
        run: |

After:

      - name: Validate and build package
        shell: bash
        env:
          RELEASE_VERSION: ${{ inputs.version }}
        run: |

11. .github/workflows/memos-local-plugin-publish.yml (L244)

sha256sum writes the full absolute runner path into the .sha256 file (format: <hash> /home/runner/.../<tarball>). When this file is later uploaded to the inspection artifact and consumers try to verify it with sha256sum -c, the check will fail because the recorded path won't match the local relative path. Consider stripping the directory to store only the basename, e.g. sha256sum "${release_tarball}" | sed 's|.*/||' > "${release_tarball}.sha256", or document that verifiers must use --ignore-missing / manually edit the path.

💡 Suggested Change

Before:

          sha256sum "${release_tarball}" > "${release_tarball}.sha256"

After:

          ( cd "${release_dir}" && sha256sum "${pack_filename}" ) > "${release_tarball}.sha256"

12. apps/memos-local-plugin/core/capture/capture.ts (L440-L443)

The code field in the emit payload duplicates the ERROR_CODES.CONFLICT constant already passed to the MemosError constructor. If the error code changes, both sites must be updated in sync. Using error.code here removes that coupling and is more DRY.

💡 Suggested Change

Before:

        error: {
          code: ERROR_CODES.CONFLICT,
          message: error.message,
        },

After:

        error: {
          code: error.code,
          message: error.message,
        },

13. apps/memos-local-plugin/core/logger/index.ts (L422-L426)

Missing log flush on signal-triggered exit.

The hookProcessExit() function now registers only a process.once('beforeExit', ...) listener. The Node.js docs are clear: beforeExit is not emitted when process.exit() is called explicitly — and every signal handler in bridge.cts terminates with process.exit(0) (lines 505, 577, 597, 607). This means shutdownLogger() (which flushes and closes all file/SSE transports) is never called on the common SIGINT/SIGTERM path, potentially losing the last batch of log records to in-flight file rotate buffers.

Before removing the SIGINT/SIGTERM hooks the old code at least guaranteed a flush attempt on those signals, even if the exit code was wrong. The new code removes that guarantee without adding shutdownLogger() to the bridge's own shutdown helpers (shutdown(), shutdownDaemon(), waitForShutdown()).

Suggestion: Call shutdownLogger() (or await flushLogger()) explicitly inside bridge.cts's shutdown / shutdownDaemon closures before process.exit(), or have waitForShutdown() in bridge/stdio.ts call it. Example:

const shutdown = async (sig: string) => {
  ...
  await withShutdownTimeout(waitForShutdown(core, activeStdio));
  await shutdownLogger(); // flush file sinks before exit
  process.exit(0);
};

14. apps/memos-local-plugin/install.ps1 (L440-L449)

The Copy-Item for plugin.yaml runs unconditionally after the version-sync block, but the sync script modifies the source file (adapters/hermes/plugin.yaml) in-place. This ordering is correct — the copy reads the already-updated source.

However, there is an inconsistency with the shell counterpart (install.hermes.sh): the bash script suppresses stdout from the node call (>/dev/null) while this PS1 script does not. Any progress or diagnostic output from sync-hermes-version.cjs will be printed inline with the installer's own output, which may be intentional but is a divergence in behaviour worth confirming.

💡 Suggested Change

Before:

    $VersionSyncScript = Join-Path $Prefix "scripts\sync-hermes-version.cjs"
    if (Test-Path $VersionSyncScript) {
        & node $VersionSyncScript $Prefix
        if ($LASTEXITCODE -ne 0) {
            Stop-Die "Failed to synchronize Hermes plugin version metadata."
        }
    } else {
        Write-Warn "Hermes version sync helper missing; using packaged plugin.yaml as-is."
    }
    Copy-Item -Path (Join-Path $AdapterDir "plugin.yaml") -Destination (Join-Path $AdapterDir "memos_provider\plugin.yaml") -ErrorAction SilentlyContinue

After:

    $VersionSyncScript = Join-Path $Prefix "scripts\sync-hermes-version.cjs"
    if (Test-Path $VersionSyncScript) {
        & node $VersionSyncScript $Prefix | Out-Null
        if ($LASTEXITCODE -ne 0) {
            Stop-Die "Failed to synchronize Hermes plugin version metadata."
        }
    } else {
        Write-Warn "Hermes version sync helper missing; using packaged plugin.yaml as-is."
    }
    Copy-Item -Path (Join-Path $AdapterDir "plugin.yaml") -Destination (Join-Path $AdapterDir "memos_provider\plugin.yaml") -ErrorAction SilentlyContinue

15. apps/memos-local-plugin/install.ps1 (L449-L452)

Using -ErrorAction SilentlyContinue on Copy-Item silently swallows any copy error, leaving $Error populated but execution continuing. The subsequent existence check is a reasonable mitigation, but it only emits a Write-Warning (non-fatal). If plugin.yaml is absent at this point the junction created a few lines later will expose a provider directory without the manifest, likely causing a hard-to-diagnose Hermes plugin load failure at runtime. Consider making this a fatal error (Stop-Die) to fail fast, or at minimum surface the actual error message.

💡 Suggested Change

Before:

    Copy-Item -Path (Join-Path $AdapterDir "plugin.yaml") -Destination (Join-Path $AdapterDir "memos_provider\plugin.yaml") -ErrorAction SilentlyContinue
    if (-not (Test-Path (Join-Path $AdapterDir "memos_provider\plugin.yaml"))) {
        Write-Warning "plugin.yaml copy may have failed; verify $AdapterDir\memos_provider\plugin.yaml exists."
    }

After:

    try {
        Copy-Item -Path (Join-Path $AdapterDir "plugin.yaml") -Destination (Join-Path $AdapterDir "memos_provider\plugin.yaml") -ErrorAction Stop
    } catch {
        Stop-Die "Failed to copy plugin.yaml to memos_provider: $_"
    }

16. apps/memos-local-plugin/core/pipeline/memory-core.ts (L1775-L1778)

The fallback to tr.ts when tr.turnId is invalid silently discards the fact that the turn ID was missing or corrupted. A trace with a turnId of 0 or a non-finite number (e.g. NaN, Infinity) will silently fall back to tr.ts with no log warning. If tr.ts is also unreliable, the constructed turn will carry a wrong timestamp with no observable signal.

Consider logging a debug-level warning when the fallback is triggered so that data-quality issues can be detected in production.

💡 Suggested Change

Before:

      const turnId =
        typeof tr.turnId === "number" && Number.isFinite(tr.turnId)
          ? (tr.turnId as EpochMs)
          : tr.ts;

After:

      const turnIdRaw = tr.turnId;
      const turnIdValid = typeof turnIdRaw === "number" && Number.isFinite(turnIdRaw) && turnIdRaw > 0;
      if (!turnIdValid && turnIdRaw != null) {
        log.debug("snapshot.turn_id_invalid_fallback", { traceId: tr.id, turnId: turnIdRaw });
      }
      const turnId = turnIdValid ? (turnIdRaw as EpochMs) : tr.ts;

17. apps/memos-local-plugin/core/pipeline/memory-core.ts (L1448-L1455)

The evt.kind === "capture.failed" check is redundant. The listener is already subscribed to the "capture.failed" event topic on the bus, so the runtime will only deliver events of that kind here. The duplicate check adds noise without adding safety.

💡 Suggested Change

Before:

    const unsubscribeCaptureFailed = handle.buses.capture.on("capture.failed", (evt) => {
      if (
        evt.kind === "capture.failed" &&
        recoveryEpisodeIds.has(evt.episodeId)
      ) {
        captureFailedInBatch.add(evt.episodeId);
      }
    });

After:

    const unsubscribeCaptureFailed = handle.buses.capture.on("capture.failed", (evt) => {
      if (recoveryEpisodeIds.has(evt.episodeId)) {
        captureFailedInBatch.add(evt.episodeId);
      }
    });

18. apps/memos-local-plugin/core/pipeline/memory-core.ts (L1652)

Setting rewardDirty: undefined in a spread object does not actually remove the key — the key will still be present on the resulting object with value undefined. This means hasRewardDirtyMarker will subsequently read ep.meta.rewardDirty as undefined, which is falsy and will pass the check, so the in-memory guard works. However, the intent expressed by the comment is to "clean the contradictory marker", and retaining the key with undefined is semantically different from deleting it. A reader relying on Object.keys(ep.meta) or serialisation (e.g. JSON — undefined values are dropped) could see inconsistent state. Prefer delete ep.meta.rewardDirty for clarity and correctness.

💡 Suggested Change

Before:

        ep.meta = { ...(ep.meta ?? {}), rewardDirty: undefined };

After:

        if (ep.meta) {
          delete ep.meta.rewardDirty;
        } else {
          ep.meta = {};
        }

19. apps/memos-local-plugin/install.sh (L737-L743)

node is invoked without verifying it is available on PATH. If Node.js is not installed, the shell will emit an opaque "command not found" error and the || die branch will fire with a misleading message ("Failed to synchronize Hermes plugin version metadata") instead of something actionable.

Consider checking for node before calling it, similar to how the script likely gates other tools (Python, etc.):

if command -v node >/dev/null 2>&1; then
  node "${version_sync}" "${prefix}" >/dev/null \
    || die "Failed to synchronize Hermes plugin version metadata."
else
  warn "node not found; skipping Hermes version sync — plugin.yaml used as-is."
fi

This also keeps the behaviour consistent with the else branch that already degrades gracefully when the script file is missing.


20. apps/memos-local-plugin/scripts/sync-hermes-version.cjs (L39)

This read is not wrapped in a try/catch, unlike the package.json read above. If plugin.yaml exists but is unreadable (e.g., permission denied, I/O error), the script will throw an unhandled exception with a raw Node.js stack trace instead of the consistent fail() message used everywhere else. Wrap it for consistency:

let manifest;
try {
  manifest = fs.readFileSync(manifestPath, "utf8");
} catch (error) {
  fail(`cannot read ${manifestPath}: ${error.message}`);
}

21. apps/memos-local-plugin/scripts/sync-hermes-version.cjs (L45)

The version string from package.json is interpolated directly into the YAML file without any validation or sanitization. If version contains YAML-significant characters (:, #, {, }, newlines, or leading/trailing whitespace beyond what .trim() catches), the resulting plugin.yaml could be unparseable or semantically wrong — silently, since no YAML parse is done after writing.

At minimum, validate that the version is a safe semver-like string before writing:

if (!/^[\w.+\-]+$/.test(version)) {
  fail(`version string contains unsafe characters: ${version}`);
}

22. apps/memos-local-plugin/scripts/sync-hermes-version.cjs (L57-L59)

The script falls off the end without an explicit process.exit(0). While Node.js exits with code 0 by default when the event loop drains, relying on this is fragile — if any async work were ever added, the exit code could be non-deterministic. Adding an explicit process.exit(0) at the end (or after both branches) makes the intent clear and mirrors the style already used in the --check path at line 51.


23. apps/memos-local-plugin/server/routes/admin.ts (L125)

The agent value is interpolated without quoting into the shell command string. Although agent is currently typed as "openclaw" | "hermes" | undefined in ServerOptions — making this safe today — the lack of quoting is a latent shell injection hazard. If the type constraint is ever relaxed or bypassed, a value containing shell metacharacters (;, &&, $(...)) would be executed verbatim by bash -c.

Quote the argument to close the gap:

--agent="${agent}"

Alternatively, pass the agent as a separate argv element to avoid the shell entirely, though that requires restructuring the sleep delay.

💡 Suggested Change

Before:

  const cmd = `sleep 3 && "${process.execPath}" "${tsxBin}" "${bridgeScript}" --agent=${agent} --daemon`;

After:

  const cmd = `sleep 3 && "${process.execPath}" "${tsxBin}" "${bridgeScript}" --agent="${agent}" --daemon`;

24. apps/memos-local-plugin/server/routes/admin.ts (L47-L55)

spawnReplacementDaemon is awaited without any error handling. If it throws — for example because tsxBin or bridgeScript does not exist at the resolved path — the rejected promise propagates up through the route handler. The outer try/catch on line 38 only covers the bridge-status.json deletion, so this path is unhandled. The result: the server shuts down (via the immediately-following scheduleHermesShutdown) with no replacement daemon and no useful error surfaced to the caller.

Wrap the call in its own try/catch and log or return a meaningful error before proceeding to shutdown.

💡 Suggested Change

Before:

    if (agent !== "openclaw" && !isSupervisorManaged(options)) {
      // Portable Hermes: there is no supervisor to replace this process.
      await spawnReplacementDaemon(agent);
    }
    if (agent === "hermes") {
      scheduleHermesShutdown(options, 200);
    } else {
      setTimeout(() => process.exit(0), 200);
    }

After:

    if (agent !== "openclaw" && !isSupervisorManaged(options)) {
      // Portable Hermes: there is no supervisor to replace this process.
      try {
        await spawnReplacementDaemon(agent);
      } catch (err) {
        // Do not shut down if we failed to spawn a replacement; the
        // process would exit with nothing to take over.
        return { ok: false, error: `failed to spawn replacement daemon: ${err}` };
      }
    }
    if (agent === "hermes") {
      scheduleHermesShutdown(options, 200);
    } else {
      setTimeout(() => process.exit(0), 200);
    }

25. apps/memos-local-plugin/server/routes/admin.ts (L68-L72)

Same missing error handling on spawnReplacementDaemon as in the clear-data route. An exception here would propagate as an unhandled rejection after terminateHermesChat has already killed the chat process, leaving the system in a half-restarted state with no replacement spawned and no error response returned.

💡 Suggested Change

Before:

      if (!isSupervisorManaged(options)) {
        await spawnReplacementDaemon(agent);
      }
      scheduleHermesShutdown(options, 200);
      return { ok: true, restarting: true, killed };

After:

      if (!isSupervisorManaged(options)) {
        try {
          await spawnReplacementDaemon(agent);
        } catch (err) {
          return { ok: false, error: `failed to spawn replacement daemon: ${err}` };
        }
      }
      scheduleHermesShutdown(options, 200);
      return { ok: true, restarting: true, killed };

26. apps/memos-local-plugin/server/routes/admin.ts (L99-L110)

There is no guard against concurrent calls. If both /restart and /clear-data are invoked in quick succession, scheduleHermesShutdown is called twice, scheduling two SIGTERMs (or two requestShutdown() calls). The comment in the function body explicitly depends on graceful single-path draining of SQLite/telemetry — a double signal defeats that.

A simple module-level flag is enough to make this idempotent:

💡 Suggested Change

Before:

function scheduleHermesShutdown(options: ServerOptions, delayMs: number): void {
  setTimeout(() => {
    if (options.lifecycle?.requestShutdown) {
      options.lifecycle.requestShutdown();
      return;
    }
    // The bridge entry owns SIGINT/SIGTERM and drains the HTTP server,
    // MemoryCore, telemetry and SQLite before exiting. Do not call
    // process.exit() here: that bypasses the bridge's graceful path.
    process.kill(process.pid, "SIGTERM");
  }, delayMs);
}

After:

let shutdownScheduled = false;

function scheduleHermesShutdown(options: ServerOptions, delayMs: number): void {
  if (shutdownScheduled) return;
  shutdownScheduled = true;
  setTimeout(() => {
    if (options.lifecycle?.requestShutdown) {
      options.lifecycle.requestShutdown();
      return;
    }
    process.kill(process.pid, "SIGTERM");
  }, delayMs);
}

27. apps/memos-local-plugin/server/routes/admin.ts (L91)

The launchd label prefix is an inline magic string. This string gates whether the process expects a supervisor to respawn it — getting it wrong silently causes a restart to leave the process dead on macOS supervised installs. Extract it to a named constant so any future label rename is a single-point change and the intent is self-documenting.

💡 Suggested Change

Before:

  if (xpcService?.startsWith("ai.memtensor.memos-local-hermes")) return true;

After:

const LAUNCHD_SERVICE_PREFIX = "ai.memtensor.memos-local-hermes";

// …inside isSupervisorManagedProcess:
  if (xpcService?.startsWith(LAUNCHD_SERVICE_PREFIX)) return true;

28. apps/memos-local-plugin/server/routes/admin.ts (L112-L115)

node:fs, node:path, and node:url are re-imported dynamically on every call, while node:child_process (spawn) is already a static import at the top of the file. Node's module cache makes this functionally harmless, but it's inconsistent with the file's own import style and makes the function harder to test in isolation (no way to inject mocks without dynamic import interception). Move these to static top-level imports alongside the existing ones.

💡 Suggested Change

Before:

async function spawnReplacementDaemon(agent: string): Promise<void> {
  const fs = await import("node:fs");
  const nodePath = await import("node:path");
  const { fileURLToPath } = await import("node:url");

After:

import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { resolve, dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

29. apps/memos-local-plugin/viewer/src/stores/restart.ts (L92-L100)

The pollHealthUntilUp(60) + redirect/fail block is now duplicated identically in both the Hermes branch (lines 92–99) and the OpenClaw branch (lines 109–116). The two branches only differ in how they handle the api.post call (Hermes throws, OpenClaw swallows). The shared tail logic could be extracted by removing the early return and letting both branches fall through to a single polling block, or by extracting a helper like awaitHealthAndRedirect(). As-is, any future change to the post-restart behaviour must be applied in two places.

💡 Suggested Change

Before:

    const ok = await pollHealthUntilUp(60);
    if (ok) {
      window.location.href =
        window.location.pathname + "?_t=" + Date.now();
    } else {
      restartState.value = { phase: "restartFailed" };
      throw new Error("restart did not complete");
    }
    return;

After:

    // Remove the `return` here and let both branches fall through:
    // const ok = await pollHealthUntilUp(60);
    // if (ok) { ... } else { ... }
    //
    // Refactored shape:
    //
    // if (!isOpenClaw()) {
    //   try { await api.post("/api/v1/admin/restart"); }
    //   catch { restartState.value = { phase: "restartFailed" }; throw new Error("restart failed"); }
    // } else {
    //   try { await api.post("/api/v1/admin/restart"); } catch { /* going down */ }
    // }
    // // shared tail
    // const ok = await pollHealthUntilUp(60);
    // if (ok) {
    //   window.location.href = window.location.pathname + "?_t=" + Date.now();
    // } else {
    //   restartState.value = { phase: "restartFailed" };
    //   throw new Error("restart did not complete");
    // }

30. apps/memos-local-plugin/tests/python/test_hermes_provider_pipeline.py (L457)

Bare next() on an exhausted generator raises StopIteration, which unittest surfaces as a test error rather than a failure, producing a confusing traceback with no message about what was expected. If the production code ever stops emitting turn.start during prefetch(), the diagnosis becomes harder than it needs to be.

Use next(..., None) and follow it with an explicit assertion:

💡 Suggested Change

Before:

        turn_start = next(params for method, params in bridge.calls if method == "turn.start")

After:

        turn_start = next(
            (params for method, params in bridge.calls if method == "turn.start"),
            None,
        )
        self.assertIsNotNone(turn_start, "expected a turn.start call during prefetch")

Generated by cloud-assistant via Open Code Review.

@Memtensor-AI

Copy link
Copy Markdown
Collaborator

✅ Automated Test Results: PASSED

All tests passed (90/90 executed). memos_github_open_source/smoke: 1/1, memos_local_plugin/changed-repo-python: 89/89. Duration: 5s [advisory, non-gating] AI-generated tests on branch test/auto-gen-74c2430c2e6ab0ad-20260729153513: 95/97 passed, 2 failed — these do NOT affect the PR verdict; review the branch manually.

Branch: release/memos-local-plugin-v2.0.12-beta.1

@Memtensor-AI Memtensor-AI added status:ready Ready for implementation; waiting for assignee or AI dispatch | 可进入实现,等待认领或派发 and removed status:in-progress Someone or AI is working on it | 人工或 AI 正在处理 labels Jul 29, 2026
@syzsunshine219
syzsunshine219 merged commit 92653cd into main Jul 29, 2026
18 checks passed
@syzsunshine219
syzsunshine219 deleted the release/memos-local-plugin-v2.0.12-beta.1 branch July 29, 2026 07:52
steven-stack-s pushed a commit to steven-stack-s/dsh-memos-local that referenced this pull request Sep 18, 2026
* fix(plugin): synchronize Hermes release version metadata

* fix(plugin): keep Hermes compression turn read-only

* fix(plugin): reload Hermes config on restart

* fix(plugin): share Hermes bridge across providers

* fix(plugin): isolate Hermes bridges by data home

* fix(plugin): harden Hermes recovery lifecycle

* release: @memtensor/memos-local-plugin v2.0.12-beta.1

* fix(plugin): satisfy Python lint checks

---------

Co-authored-by: 谁在吵着吃糖 <gyunhang@qq.com>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:plugin OpenClaw & Hermes status:ready Ready for implementation; waiting for assignee or AI dispatch | 可进入实现,等待认领或派发

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants