Skip to content

feat(plugins): session idle auto-commit across harnesses, plus close-path fixes - #4062

Draft
t0saki wants to merge 5 commits into
volcengine:mainfrom
t0saki:feat/session-idle-auto-commit
Draft

t0saki wants to merge 5 commits into
volcengine:mainfrom
t0saki:feat/session-idle-auto-commit

Conversation

@t0saki

@t0saki t0saki commented Aug 17, 2026

Copy link
Copy Markdown
Collaborator

Description

Harness memory plugins commit an OV session at end-of-conversation, but several
harnesses never fire a usable hook when the user simply closes them. Codex fires
nothing at all on SIGTERM/Ctrl+C//exit (upstream declined a SessionEnd
hook), so its plugin emulates one with local state files, a 2-minute
active-window heuristic and a 30-minute idle-TTL sweep — and its own design doc
accepts that if the user never relaunches Codex, the session stays open forever.

The server already has the right mechanism (auto_commit_policy.idle_timeout_seconds
plus SessionAutoCommitScheduler, #3736/#3850), but nothing used it: the .mjs
plugins never create sessions at all (they rely on auto_create inside
POST /messages, which takes no options), and the sweeper is gated by
memory.session_auto_commit.idle_enabled, which is not reachable over HTTP.

This PR makes every harness plugin request a per-session idle policy, lets
plugins detect whether the server will actually act on it, retires Codex's local
sweep on servers that do, and fixes each harness's real close path.

Upstream close behavior was verified against source/docs per harness before
writing any of it; the findings changed the plan (Cursor and pi turned out to be
in the "does not commit on close" group, DSH turned out to be better than
assumed), and the docs now describe what remains uncovered rather than a guess.

Human Involvement

  • A human participated in the implementation or review loop
  • This PR was generated entirely by AI agents without human participation in the loop

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement
  • Test update

Changes Made

Server — capability detection only, defaults unchanged

  • POST /api/v1/sessions, GET /api/v1/sessions/{id} and
    PATCH /api/v1/sessions/{id}/config now return auto_commit_idle_enabled.
    It gives clients a tri-state: field absent means an old server, false means
    a server that stored the policy but will not sweep, true means it will.
    The policy echo alone cannot express that difference, which is why the field
    exists.
  • memory.session_auto_commit defaults are deliberately untouched
    (default_enabled=false, idle_enabled=false); a unit test pins both so a
    future accidental flip fails CI. examples/ov.conf.example documents the
    block at its shipped values.

Plugins — one shared, idempotent policy path

  • New examples/memory-plugin-shared/lib/session-policy.mjs: normalize/build
    the policy, then POST /sessions with it and fall back to
    PATCH /{id}/config on ALREADY_EXISTS. Old servers ignore the unknown
    create field, so they are detected by the missing echo and negative-cached for
    6h; transient failures never write that cache.
  • Payload is {idle_timeout_seconds, pending_token_threshold: 0, message_count_threshold: 0}. The two zeros matter: they disable the
    server-side threshold triggers so they cannot race the plugins' own
    client-side threshold commits, which use different keep-recent semantics.
  • Wired into claude-code, codex, cursor, zcode, trae, opencode, pi, dsh and
    openclaw, once per session start, best-effort, never blocking the hook.
    Knob: OPENVIKING_COMMIT_IDLE_TIMEOUT_SECONDS / commitIdleTimeoutSeconds,
    default 3600, 0/off to disable.

Codex — the local sweep now retires itself

  • The state file records serverIdleCommit only when the server reported
    auto_commit_idle_enabled: true. Both the active-window heuristic and the
    idle-TTL sweep skip marked sessions, and a marked file is garbage-collected
    (never committed) once it is past the server's own timeout plus a margin.
  • Everything else keeps today's behavior: an old server, idle_enabled=false,
    a failed apply or the knob turned off all leave the marker absent, so on stock
    servers the sweep stays fully active. Zero regression by construction.
  • Fixes a real bug on that path: the swept commit sent the new session's peer
    as X-OpenViking-Actor-Peer instead of the swept session's stored
    workspacePeerId, misattributing extracted memories.

Close-path fixes, per harness

  • openclaw — upstream emits an awaited session_end(reason=shutdown|restart)
    per active session during shutdown drain, plus an awaited gateway_stop; the
    plugin received the first and discarded it and never registered the second.
    Both now commit, bounded to fit the 2s drain and 5s per-hook budgets.
  • pi — session_shutdown fires on every close mode and is fully awaited,
    but in the default takeover config the handler only persisted local state.
    It now commits, ordered commit-before-watermark and refusing to advance on
    failure so a delayed commit can never move the local context boundary.
  • cursor — upstream sessionEnd fires only on window_close, where the
    shell-exec host is already torn down, so the hook command never spawns
    (Cursor-staff-confirmed, no ETA). Commit-turn threshold now defaults to 1,
    adopting the zcode/trae per-turn model that already ships.
  • dsh — the shutdown commit no longer queues behind an in-flight
    addMessage (10s) or threshold commit (30s), a SIGHUP listener covers
    terminal close, and dispose no longer re-runs full initialization on the
    teardown path.
  • opencode — the dispose commit now fits the 5s shutdown budget so the
    pending-queue fallback can still enqueue, and startup flushes and commits
    rehydrated entries that a dead process left behind.

Docs (EN + ZH)

  • Per-integration pages state the real remaining gap after these fixes and how
    to enable the server backstop, explicitly in the server's ov.conf — the
    earlier draft showed the snippet with no file named, right after plugin-config
    commands, where setting it does nothing.
  • Codex DESIGN.md/VERIFICATION.md cover the new marker, the gating decision
    tree and the manual runbook.

Testing

  • I have added tests that prove my fix is effective or that my feature works

  • New and existing unit tests pass locally with my changes

  • I have tested this on the following platforms:

    • Linux
    • macOS
    • Windows
  • pytest tests/server/test_api_sessions.py tests/server/test_api_sessions_event_tags.py tests/unit/service/test_session_auto_commit.py tests/unit/session/test_auto_commit_policy.py
    → 90 passed.

  • node --test across memory-plugin-shared, codex, claude-code, cursor, zcode,
    trae, opencode, pi and dsh → 183 passed.

  • examples/openclaw-plugin: npm run typecheck clean, npm run test → 751
    passed. The 4 failures in tests/ut/architecture-boundaries.test.ts are
    pre-existing and fail identically on main (verified in a clean worktree);
    they are unrelated to this branch.

  • The gating logic carries an explicit mutation guard: a test asserts that stale
    state the server does not cover is still swept locally, for both an unmarked
    file and a marked file missing its timeout. Without it, relaxing the predicate
    from === true to !== false left the whole suite green while silently
    disabling commits on every stock server.

Checklist

  • My code follows the project's coding style
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

Additional Notes

Rollout is order-independent. Plugins against an old server negative-cache and
keep today's behavior; the server field against old plugins is inert because no
policy is sent. Codex's sweep only retires where an operator has enabled
idle_enabled — intentionally, since that is the only state in which the server
actually sweeps.

Draft while a review pass finishes. Known follow-ups, deliberately not in scope:

  • openviking-session-state.json in the OpenCode plugin is one global file
    rewritten wholesale from a single process's in-memory map, so concurrent
    OpenCode servers clobber each other's entries. Needs a layout change.
  • The claude-code capture watermark lives in os.tmpdir() and its
    writePathAsync default detaches the SessionEnd write.
  • Codex skips the whole sweep when /health fails at that instant — the same
    outage that stranded the session disables its recovery.
  • examples/ov.conf.example cannot be loaded by the server's strict
    json.loads because of pre-existing trailing commas; now that docs point
    users at it to find this knob, that is worth fixing separately.
  • A dedicated DSH integration doc page still does not exist.

t0saki and others added 5 commits August 17, 2026 19:05
Add a response field that lets clients distinguish stored session policies
from an actively running idle scheduler, while keeping server defaults off.

Co-authored-by: TRAE CLI <noreply@bytedance.com>
Apply idle auto-commit policies across harness integrations, gate Codex local
recovery on server capability, and make close paths commit within host budgets.

Co-authored-by: TRAE CLI <noreply@bytedance.com>
Document server capability detection, per-harness idle policy knobs, fixed
close behavior, and the remaining lifecycle gaps across integrations.

Co-authored-by: TRAE CLI <noreply@bytedance.com>
Startup recovery in the OpenCode plugin ran unguarded, so a single state entry
whose OV session no longer exists rejected init() and took the plugin down on
every launch. Its flushSession also grew an uncaptured-message branch that
preempted both the queue fallback and the direct commit, silently dropping the
final commit on a non-retryable send or an exhausted dispose deadline.

The pi extension stopped queueing a failed non-takeover shutdown commit; that
rule only applies to takeover mode, where a delayed commit must not advance the
local context boundary, so non-takeover lost its only recovery path.

OpenClaw sent the raw hook agent id as the actor peer while its messages are
recorded under a prefixed and sanitized peer, scoping the shutdown commit to a
peer the session never used; ids containing ':' were rejected outright.

DSH re-ran full initialization from dispose when a session was never ready,
which cannot fit the host process grace, and returned without committing or
queueing when it still failed.

Codex created an "unknown" state file and a bogus cx-unknown session when the
hook payload carried no session id, and a covered marker without a usable
timeout was neither committed nor garbage-collected.

The shared helper cached a server as legacy on any ok-but-no-echo create, and
plugin fetch helpers turn an unparseable 200 into an empty result, so one
garbled response disabled the backstop for the whole TTL. Session-start policy
application in the thin hook harnesses also had no request timeout and logged
nothing when it did not apply.

Co-authored-by: TRAE CLI <noreply@bytedance.com>
The OpenClaw and Codex pages presented the session_auto_commit snippet without
saying where it goes, and on the OpenClaw page it followed plugin-config
commands, inviting users to set a server-only option in the plugin config where
it is silently ignored. Both now name the server's ov.conf, in English and
Chinese.

The Cursor hook list still credited sessionEnd with committing pending
messages, contradicting the paragraph below it that explains the hook command
cannot execute. Also drop the mirrorMemoryWrites key from the pi design doc:
it matches no config field and its only flow step was already removed.

Co-authored-by: TRAE CLI <noreply@bytedance.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Backlog

Development

Successfully merging this pull request may close these issues.

1 participant