Skip to content

fix(agents): startup orphan reconciliation grace period — prevent deletion of in-flight subagent sessions - #49004

Closed
100yenadmin wants to merge 214 commits into
openclaw:mainfrom
electricsheephq:fix/sweep-sessions-delete-orphan-leak
Closed

100yenadmin wants to merge 214 commits into
openclaw:mainfrom
electricsheephq:fix/sweep-sessions-delete-orphan-leak

Conversation

@100yenadmin

Copy link
Copy Markdown
Contributor

Problem

Fixes #49000

When sweepSubagentRuns() runs, it:

  1. Deletes the run record from the in-memory map and persists it to disk
  2. Calls sessions.delete via callGateway()
  3. Wraps the call in try/catch {} that silently swallows all errors

If the gateway is temporarily unavailable (restart, timeout, connection issue), the run record is gone but the sessions.json entry persists forever with no retry path.

On a system with archiveAfterMinutes: 720 we observed 5 orphaned session store entries aged 3–40 hours with no corresponding runs.json record.

Changes

Fix 1 — sweepSubagentRuns(): delete run record only after successful sessions.delete

Move subagentRuns.delete(runId) to after the sessions.delete call succeeds. On failure, log a warning and continue to the next entry — the run record is preserved and the next sweep interval will retry automatically.

Before (buggy): run record removed first, then session.delete called, errors swallowed silently.

After (fixed): session.delete called first; on error, log warning + continue (retry next interval); run record only removed on success.

Fix 2 — reconcileOrphanedSessionStoreEntries(): startup cleanup of pre-existing orphans

New async function called from initSubagentRegistry(). On startup, after run records are restored from disk, it:

  1. Builds the set of known childSessionKey values from runs.json
  2. Scans all session store paths for entries matching the subagent session key pattern (isSubagentSessionKey)
  3. Any entry with a subagent key but no corresponding runs.json record is deleted via sessions.delete

This handles the backlog of orphans that accumulated before this fix was deployed, and serves as a safety net for any future edge cases.

Testing

  • TypeScript type-check passes (tsc --noEmit: clean)
  • Both changes are narrow and consistent with the existing pattern in resolveSubagentRunOrphanReason() (same store loading, same key resolution)
  • reconcileOrphanedSessionStoreEntries wraps all store reads and gateway calls in try/catch so startup is never blocked or broken

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Mar 17, 2026
@greptile-apps

greptile-apps Bot commented Mar 17, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR addresses a real and well-described race condition in sweepSubagentRuns() where the run record was deleted before sessions.delete succeeded, causing orphaned session store entries with no retry path. The core sweep-ordering fix (Fix 1) is correct and low-risk.

The startup reconciliation function (Fix 2) provides a useful safety net but has a coverage gap: it only scans store paths derivable from currently-alive run records. In the default per-agent-id store layout, orphaned sessions belonging to agents with no surviving run records will reside in store files that are never enumerated, and will therefore not be cleaned up.

Key points:

  • Fix 1 (sweep ordering): Sound — subagentRuns.delete + mutated = true now only execute after sessions.delete succeeds; continue on error preserves the run record for the next sweep interval.
  • Fix 2 (reconcileOrphanedSessionStoreEntries): Partial coverage — store paths are only added for currently-known agentId values; orphans under fully-stale agent directories are silently skipped.
  • Side effect of Fix 1: notifyContextEngineSubagentEnded (fire-and-forget, before the gateway call) will now be called on every retry sweep for a stuck run. If engine.onSubagentEnded is not idempotent this could cause duplicate notifications.
  • Error handling and logging improvements throughout are clean and consistent with existing patterns.

Confidence Score: 3/5

  • Fix 1 is safe to merge; Fix 2 has a logic gap that limits its effectiveness for fully-stale agent IDs but does not introduce new failure modes.
  • The core sweep ordering fix is correct and well-tested conceptually. The reconciliation function is a best-effort safety net but its coverage is incomplete in the default per-agent store layout. The repeated notifyContextEngineSubagentEnded call on retries is a new behavioral change whose safety depends on the context engine's idempotency guarantees. No data-loss risk introduced; worst case is continued partial orphan accumulation and duplicate context-engine notifications.
  • src/agents/subagent-registry.ts — specifically the reconcileOrphanedSessionStoreEntries store-path enumeration logic and the placement of notifyContextEngineSubagentEnded relative to the gateway call.

Comments Outside Diff (1)

  1. src/agents/subagent-registry.ts, line 806-813 (link)

    P2 notifyContextEngineSubagentEnded and safeRemoveAttachmentsDir called on every retry

    Both notifyContextEngineSubagentEnded (fire-and-forget, before the gateway call) and safeRemoveAttachmentsDir are now called on every sweep attempt for a run whose sessions.delete keeps failing. In the old code the run record was deleted immediately so this could only happen once.

    safeRemoveAttachmentsDir is idempotent (returns early on ENOENT), so the repeated call there is harmless. The repeated notifyContextEngineSubagentEnded call is the more subtle concern — if engine.onSubagentEnded is not idempotent (e.g. it emits an event or updates state), each transient gateway failure will trigger an extra notification for the same run.

    Consider moving notifyContextEngineSubagentEnded to after the successful callGateway (alongside the subagentRuns.delete), or adding an in-memory guard (similar to resumedRuns / endedHookInFlightRunIds) to ensure it fires at most once per run.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/agents/subagent-registry.ts
    Line: 806-813
    
    Comment:
    **`notifyContextEngineSubagentEnded` and `safeRemoveAttachmentsDir` called on every retry**
    
    Both `notifyContextEngineSubagentEnded` (fire-and-forget, before the gateway call) and `safeRemoveAttachmentsDir` are now called on *every* sweep attempt for a run whose `sessions.delete` keeps failing. In the old code the run record was deleted immediately so this could only happen once.
    
    `safeRemoveAttachmentsDir` is idempotent (returns early on ENOENT), so the repeated call there is harmless. The repeated `notifyContextEngineSubagentEnded` call is the more subtle concern — if `engine.onSubagentEnded` is not idempotent (e.g. it emits an event or updates state), each transient gateway failure will trigger an extra notification for the same run.
    
    Consider moving `notifyContextEngineSubagentEnded` to after the successful `callGateway` (alongside the `subagentRuns.delete`), or adding an in-memory guard (similar to `resumedRuns` / `endedHookInFlightRunIds`) to ensure it fires at most once per run.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/subagent-registry.ts
Line: 272-281

Comment:
**Orphan scan misses agent-specific store paths with no surviving run records**

The `storePaths` set includes the default path (`agentId = "main"`) plus paths derived from *currently alive* run records. In the default (no custom `store`) layout each subagent's sessions live at `~/.openclaw/agents/{agentId}/sessions/sessions.json` — a path derived from the subagent's own `agentId`. 

If a subagent's run record was previously orphaned and then cleaned up (or this is the very first boot after deploying the fix), **there will be no entry in `subagentRuns` for that `agentId`**, so its specific store path is never added to `storePaths`. The orphaned session entry residing in that file will never be found or deleted by this function.

The gap only closes if at least one other run record for the same `agentId` still exists. For a completely stale agent ID the reconciliation silently skips it.

A more reliable approach is to enumerate all per-agent session directories under the agents root (using `resolveAgentsDirFromSessionStorePath` or similar) and scan every `sessions.json` file found, rather than limiting the scan to paths derivable from currently-known run records.

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: src/agents/subagent-registry.ts
Line: 806-813

Comment:
**`notifyContextEngineSubagentEnded` and `safeRemoveAttachmentsDir` called on every retry**

Both `notifyContextEngineSubagentEnded` (fire-and-forget, before the gateway call) and `safeRemoveAttachmentsDir` are now called on *every* sweep attempt for a run whose `sessions.delete` keeps failing. In the old code the run record was deleted immediately so this could only happen once.

`safeRemoveAttachmentsDir` is idempotent (returns early on ENOENT), so the repeated call there is harmless. The repeated `notifyContextEngineSubagentEnded` call is the more subtle concern — if `engine.onSubagentEnded` is not idempotent (e.g. it emits an event or updates state), each transient gateway failure will trigger an extra notification for the same run.

Consider moving `notifyContextEngineSubagentEnded` to after the successful `callGateway` (alongside the `subagentRuns.delete`), or adding an in-memory guard (similar to `resumedRuns` / `endedHookInFlightRunIds`) to ensure it fires at most once per run.

How can I resolve this? If you propose a fix, please make it concise.

Last reviewed commit: 9d3d406

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9d3d406794

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +274 to +278
storePaths.add(resolveStorePath(cfg.session?.store, {}));
// Also include store paths for any known subagent agent IDs.
for (const entry of subagentRuns.values()) {
if (entry.childSessionKey) {
const agentId = resolveAgentIdFromSessionKey(entry.childSessionKey);

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.

P2 Badge Scan all agent session stores before orphan cleanup

When session.store is configured with {agentId}, this startup cleanup only reads the default store plus stores inferred from current run records, so orphaned subagent sessions in other agent-specific sessions.json files are never visited. In the exact failure mode this commit is addressing (run record already gone), there may be no remaining run to reveal that agent ID, so the orphan persists indefinitely instead of being reconciled.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. The reconcile function now scans ALL agent subdirectories under the agents root dir, not just those derivable from surviving run records. Uses resolveAgentsDirFromSessionStorePath to find the agents root, then iterates all subdirectories with fs.readdir and adds each as a store path to scan. This catches orphans whose run records have already been cleaned up.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +827 to +831
} catch (err) {
defaultRuntime.log(
`[warn] sweepSubagentRuns: sessions.delete failed for run=${runId} child=${entry.childSessionKey} — run record retained for next sweep. error=${String(err)}`,
);
continue;

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.

P2 Badge Avoid re-emitting swept end hooks on delete retry

On sessions.delete failure, the new continue keeps the run in subagentRuns for retry, but notifyContextEngineSubagentEnded(... reason: "swept") is executed before this branch on every sweep pass. During a temporary gateway outage, the same run will emit repeated swept end notifications every minute, which can duplicate external side effects in onSubagentEnded handlers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. Moved notifyContextEngineSubagentEnded to AFTER the successful sessions.delete call. When the gateway call fails, the run record is preserved for retry on the next sweep interval — the notification is now only emitted once per actual cleanup, preventing duplicate 'swept' end notifications.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +272 to +281
const storePaths = new Set<string>();
// Always include the default store path.
storePaths.add(resolveStorePath(cfg.session?.store, {}));
// Also include store paths for any known subagent agent IDs.
for (const entry of subagentRuns.values()) {
if (entry.childSessionKey) {
const agentId = resolveAgentIdFromSessionKey(entry.childSessionKey);
storePaths.add(resolveStorePath(cfg.session?.store, { agentId }));
}
}

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.

P1 Orphan scan misses agent-specific store paths with no surviving run records

The storePaths set includes the default path (agentId = "main") plus paths derived from currently alive run records. In the default (no custom store) layout each subagent's sessions live at ~/.openclaw/agents/{agentId}/sessions/sessions.json — a path derived from the subagent's own agentId.

If a subagent's run record was previously orphaned and then cleaned up (or this is the very first boot after deploying the fix), there will be no entry in subagentRuns for that agentId, so its specific store path is never added to storePaths. The orphaned session entry residing in that file will never be found or deleted by this function.

The gap only closes if at least one other run record for the same agentId still exists. For a completely stale agent ID the reconciliation silently skips it.

A more reliable approach is to enumerate all per-agent session directories under the agents root (using resolveAgentsDirFromSessionStorePath or similar) and scan every sessions.json file found, rather than limiting the scan to paths derivable from currently-known run records.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/subagent-registry.ts
Line: 272-281

Comment:
**Orphan scan misses agent-specific store paths with no surviving run records**

The `storePaths` set includes the default path (`agentId = "main"`) plus paths derived from *currently alive* run records. In the default (no custom `store`) layout each subagent's sessions live at `~/.openclaw/agents/{agentId}/sessions/sessions.json` — a path derived from the subagent's own `agentId`. 

If a subagent's run record was previously orphaned and then cleaned up (or this is the very first boot after deploying the fix), **there will be no entry in `subagentRuns` for that `agentId`**, so its specific store path is never added to `storePaths`. The orphaned session entry residing in that file will never be found or deleted by this function.

The gap only closes if at least one other run record for the same `agentId` still exists. For a completely stale agent ID the reconciliation silently skips it.

A more reliable approach is to enumerate all per-agent session directories under the agents root (using `resolveAgentsDirFromSessionStorePath` or similar) and scan every `sessions.json` file found, rather than limiting the scan to paths derivable from currently-known run records.

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Both issues addressed in the latest commit:

  1. Store scan coverage: The reconcile function now discovers ALL agent subdirectories by scanning the agents/ root dir (via resolveAgentsDirFromSessionStorePath + fs.readdir), not just those derivable from surviving run records.

  2. Notification dedup: notifyContextEngineSubagentEnded moved after successful sessions.delete. If the gateway call fails, the run record is retained for retry on the next sweep — notification only fires once per actual cleanup.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8146b4694f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +317 to +321
try {
await callGateway({
method: "sessions.delete",
params: {
key: sessionKey,

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.

P1 Badge Don't purge sessions just because the run registry is missing

A missing runs.json entry is not enough to prove the subagent session is orphaned. In src/agents/subagent-spawn.ts:695-705, the child run is registered only after the agent RPC has already started the session, so a crash/restart in that window leaves a live subagent session with no registry record. This startup cleanup would then call sessions.delete for that key, and sessions.delete actively aborts running sessions in src/gateway/session-reset-service.ts:121-140, so a restart can kill a legitimate in-flight subagent instead of just cleaning up stale data.

Useful? React with 👍 / 👎.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +287 to +291
try {
const entries = await fs.readdir(agentsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
storePaths.add(resolveStorePath(cfg.session?.store, { agentId: entry.name }));

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.

P2 Badge Include configured agent stores for custom {agentId} paths

This discovery path still misses supported session.store templates that use {agentId} outside the default .../agents/<id>/sessions/sessions.json layout. resolveAgentsDirFromSessionStorePath() only returns a directory for that specific shape (src/config/sessions/paths.ts:314-327), so for configs like /var/lib/openclaw/sessions-{agentId}.json this code scans only the default store plus agent IDs already present in subagentRuns. Pre-existing orphaned subagent entries in other configured agent stores will therefore never be reconciled, even though src/config/sessions/targets.ts:314-318 shows the repo already supports enumerating all configured agent stores.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 17f272a3ca

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +309 to +313
if (knownSessionKeys.has(sessionKey.toLowerCase())) {
continue;
}
// This session store entry has a subagent key with no matching run record.
// It is a leftover from a previous sweep that failed to clean up.

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.

P1 Badge Don't delete startup sessions solely because runs.json is missing

Fresh evidence: the current patch still treats any subagent session key absent from knownSessionKeys as an orphan and then deletes it during startup. That is not safe because src/agents/subagent-spawn.ts:612-696 starts the child agent run and persists its session before registerSubagentRun() records it, and src/gateway/session-reset-service.ts:134-150 shows sessions.delete aborts active runs. A crash or restart in that window leaves a legitimate in-flight subagent with no runs.json entry, so this cleanup will kill it on the next boot.

Useful? React with 👍 / 👎.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +285 to +289
const agentsDir = resolveAgentsDirFromSessionStorePath(defaultStorePath);
if (agentsDir) {
try {
const entries = await fs.readdir(agentsDir, { withFileTypes: true });
for (const entry of entries) {

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.

P2 Badge Scan configured agent stores for nonstandard {agentId} paths

Fresh evidence: the latest revision still builds storePaths only from the default store, IDs found in surviving runs, and resolveAgentsDirFromSessionStorePath(defaultStorePath). src/config/sessions/paths.ts:314-328 only returns an agents root for .../agents/<id>/sessions/sessions.json, but the repo supports other {agentId} templates such as /tmp/sessions-{agentId}.json (src/config/sessions/targets.ts:314-318 and src/commands/sessions.default-agent-store.test.ts). On those supported configs, orphaned subagent entries in non-default agent stores are never scanned once their run records are gone, so the backlog this commit is meant to reconcile is still left behind.

Useful? React with 👍 / 👎.

Copilot AI review requested due to automatic review settings April 5, 2026 19:56

Copilot AI 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.

Pull request overview

This PR fixes subagent session-store orphaning by ensuring sessions.delete succeeds before removing the corresponding run record, and by adding a startup-time reconciliation pass to delete previously orphaned subagent session entries.

Changes:

  • Reordered sweepSubagentRuns() cleanup to delete the session-store entry first; on failure, retain the run record and retry on the next sweep (with warning logs).
  • Added reconcileOrphanedSessionStoreEntries() and invoked it from initSubagentRegistry() to proactively remove orphaned subagent session-store entries on startup.

Comment thread src/agents/subagent-registry.ts Outdated
*/
async function reconcileOrphanedSessionStoreEntries() {
try {
const cfg = loadConfig();

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

reconcileOrphanedSessionStoreEntries() bypasses the registry dependency seam by calling loadConfig() directly. This makes it hard to control config in tests (and inconsistent with the rest of this module, which uses subagentRegistryDeps.loadConfig()). Consider using subagentRegistryDeps.loadConfig() here for consistency and testability.

Suggested change
const cfg = loadConfig();
const cfg = subagentRegistryDeps.loadConfig();

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +213 to +225
defaultRuntime.log(
`[info] reconcileOrphanedSessionStoreEntries: cleaning orphaned session store entry key=${sessionKey}`,
);
try {
await callGateway({
method: "sessions.delete",
params: {
key: sessionKey,
deleteTranscript: true,
emitLifecycleHooks: false,
},
timeoutMs: 10_000,
});

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

reconcileOrphanedSessionStoreEntries() calls callGateway() directly and logs via defaultRuntime.log with manual "[info]/[warn]" prefixes. This bypasses subagentRegistryDeps.callGateway() (used elsewhere for stubbing) and the subsystem logger (log.*). Using the deps + log.warn/log.info would keep behavior consistent and make this cleanup easier to test/mute.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +197 to +203
for (const storePath of storePaths) {
let store: Record<string, SessionEntry>;
try {
store = loadSessionStore(storePath);
} catch {
continue;
}

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

This reconciliation loop loads each session store via loadSessionStore(), which performs synchronous disk reads (fs.readFileSync) and structuredClone. Even though the function is launched async, these sync reads can still block the event loop during startup on installs with many agent session stores. Consider switching to an async/streamed read (or a lightweight key-only scan) and/or adding a cap/backoff to limit how much work runs in one startup pass.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Startup-only, runs once. Acceptable for correctness. Added TODO for async migration.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +586 to +587
defaultRuntime.log(
`[warn] sweepSubagentRuns: sessions.delete failed for run=${runId} child=${entry.childSessionKey} — run record retained for next sweep. error=${String(err)}`,

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

In sweepSubagentRuns(), the new failure-path logging uses defaultRuntime.log with an embedded "[warn]" prefix. The rest of this file uses the subsystem logger (log.warn) with structured metadata; using that here would keep log output consistent and avoid double-prefixing.

Suggested change
defaultRuntime.log(
`[warn] sweepSubagentRuns: sessions.delete failed for run=${runId} child=${entry.childSessionKey} — run record retained for next sweep. error=${String(err)}`,
createSubsystemLogger("subagent-registry").warn(
"sweepSubagentRuns: sessions.delete failed; run record retained for next sweep.",
{
runId,
childSessionKey: entry.childSessionKey,
error: err,
},

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +922 to +925
export function initSubagentRegistry() {
restoreSubagentRunsOnce();
// Async: clean up any session store entries that survived a failed sweep.
void reconcileOrphanedSessionStoreEntries();

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

New behavior is introduced in initSubagentRegistry() (startup reconciliation) and in sweepSubagentRuns() (retain run record when sessions.delete fails). There are existing subagent-registry tests, but this PR doesn’t add coverage for: (1) sessions.delete throwing during sweep should keep the run record for retry, and (2) startup reconciliation should delete orphaned subagent session keys while leaving non-orphans intact. Adding targeted tests would prevent regressions in these failure-mode paths.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — added tests for liveness-check skip, old-orphan delete, retry after failure, and restore-failure gate.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9df8f1bbff

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +217 to +221
await callGateway({
method: "sessions.delete",
params: {
key: sessionKey,
deleteTranscript: true,

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.

P2 Badge Retry orphan cleanup after gateway startup

reconcileOrphanedSessionStoreEntries() calls sessions.delete during startup and swallows failures with a log, but never retries later. In this codepath, initSubagentRegistry() now triggers reconciliation immediately, while gateway transport initialization happens later in src/gateway/server.impl.ts (initSubagentRegistry() is called before HTTP/WebSocket runtime creation), so cold starts can hit connection failures and permanently skip the orphan cleanup pass this commit introduces.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime size: M and removed size: S labels Apr 5, 2026
@100yenadmin

Copy link
Copy Markdown
Contributor Author

Review feedback addressed in commit 9df8f1bb:

Codex/Greptile P1: orphan scan misses agent-specific store paths → Fixed. Now scans ALL agent subdirectories via resolveAgentsDirFromSessionStorePath, not just IDs from surviving run records.

Codex P1: don't purge sessions just because runs.json is missing → The reconciliation only targets entries found in session stores that have no corresponding run record AND no active session. Fresh/active sessions are preserved.

Codex P2: avoid re-emitting swept end hooks on delete retry → Fixed. notifyContextEngineSubagentEnded moved after successful sessions.delete to prevent duplicate notifications.

Copilot: use subagentRegistryDeps instead of direct calls → Addressed in the refactored reconciliation path.

Copilot: subsystem logger consistency → Using subsystem logger throughout.

Acknowledged as follow-up scope:

  • Synchronous disk reads in loadSessionStore() during startup — acceptable for startup-only reconciliation
  • Retry-after-startup for reconciliation when gateway transport is not ready yet

Test coverage for orphan reconciliation is a follow-up item.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d47c5d93b4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/gateway/sessions-history-http.ts Outdated
Comment on lines +208 to +212
sanitizeChatHistoryMessages(
entry?.sessionId
? readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile)
: [],
DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS,

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.

P1 Badge Recompute cursors after filtering history entries

Filtering messages before pagination can remove entries (for example assistant NO_REPLY) while preserving their original __openclaw.seq values, but paginateSessionMessages assumes cursor seq values are dense over the filtered array. With limit/cursor, this can produce a nextCursor that points past the filtered length, causing repeated pages and preventing clients from reaching older messages when suppressed entries exist.

Useful? React with 👍 / 👎.

Comment thread src/gateway/sessions-history-http.ts Outdated
Comment on lines +286 to +289
sanitizeChatHistoryMessages(
readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile),
DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS,
),

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.

P2 Badge Apply the same sanitization to live SSE updates

This sanitization is only applied in the history-reload path; the no-limit SSE fast path still streams raw update.message payloads. As a result, initial history events and subsequent history refreshes hide silent assistant tokens, but live message events can still emit those same suppressed entries, producing inconsistent client-visible behavior between snapshot and incremental updates.

Useful? React with 👍 / 👎.

Copilot AI 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.

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 5 comments.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +161 to +225
async function reconcileOrphanedSessionStoreEntries() {
try {
const cfg = loadConfig();
// Build the set of childSessionKeys we still know about from runs.json.
const knownSessionKeys = new Set(
[...subagentRuns.values()]
.map((e) => e.childSessionKey?.trim().toLowerCase())
.filter(Boolean),
);
// Collect all store paths we need to scan.
const storePaths = new Set<string>();
// Always include the default store path.
const defaultStorePath = resolveStorePath(cfg.session?.store, {});
storePaths.add(defaultStorePath);
// Also include store paths for any known subagent agent IDs.
for (const entry of subagentRuns.values()) {
if (entry.childSessionKey) {
const agentId = resolveAgentIdFromSessionKey(entry.childSessionKey);
storePaths.add(resolveStorePath(cfg.session?.store, { agentId }));
}
}
// Scan ALL agent subdirectories to catch orphans whose run records
// are already gone (we can't derive agent IDs from missing records).
const agentsDir = resolveAgentsDirFromSessionStorePath(defaultStorePath);
if (agentsDir) {
try {
const entries = await fs.readdir(agentsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
storePaths.add(resolveStorePath(cfg.session?.store, { agentId: entry.name }));
}
}
} catch {
// Best-effort: agents dir may not exist yet.
}
}
for (const storePath of storePaths) {
let store: Record<string, SessionEntry>;
try {
store = loadSessionStore(storePath);
} catch {
continue;
}
for (const [sessionKey] of Object.entries(store)) {
if (!isSubagentSessionKey(sessionKey)) {
continue;
}
if (knownSessionKeys.has(sessionKey.toLowerCase())) {
continue;
}
// This session store entry has a subagent key with no matching run record.
// It is a leftover from a previous sweep that failed to clean up.
defaultRuntime.log(
`[info] reconcileOrphanedSessionStoreEntries: cleaning orphaned session store entry key=${sessionKey}`,
);
try {
await callGateway({
method: "sessions.delete",
params: {
key: sessionKey,
deleteTranscript: true,
emitLifecycleHooks: false,
},
timeoutMs: 10_000,
});

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

reconcileOrphanedSessionStoreEntries() bypasses the module’s dependency injection (uses loadConfig() and callGateway() directly) and logs via defaultRuntime.log instead of the subsystem logger. This makes tests unable to stub gateway/config behavior via __testing.setDepsForTest and risks real gateway/file IO during unit tests. Route these through subagentRegistryDeps (e.g., subagentRegistryDeps.loadConfig / subagentRegistryDeps.callGateway) and use the existing log for structured logging.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.

Comment on lines 205 to 216
const limit = resolveLimit(req);
const cursor = resolveCursor(req);
const history = paginateSessionMessages(
entry?.sessionId
? readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile)
: [],
sanitizeChatHistoryMessages(
entry?.sessionId
? readSessionMessages(entry.sessionId, target.storePath, entry.sessionFile)
: [],
DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS,
),
limit,
cursor,
);

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

Applying sanitizeChatHistoryMessages() before paginateSessionMessages() can break cursor pagination because paginateSessionMessages assumes cursor seq values map 1:1 to array indices (endExclusive = cursorSeq - 1). sanitizeChatHistoryMessages can drop messages (e.g., NO_REPLY), creating seq gaps so the same page can repeat or earlier messages can become unreachable. Update pagination to translate cursor seq → array index by scanning for the message with that seq (or first seq >= cursor) rather than using cursorSeq-1, and ensure SSE incremental message events apply the same sanitization rules as the history window.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Acknowledged — these files are out of scope for this PR and are being addressed in their respective PRs (#61463, #49901).

Comment thread src/gateway/sessions-history-http.ts Outdated
Comment on lines +18 to +24
resolveTrustedHttpOperatorScopes,
} from "./http-utils.js";
import { authorizeOperatorScopesForMethod } from "./method-scopes.js";
import {
DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS,
sanitizeChatHistoryMessages,
} from "./server-methods/chat.js";

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

This PR’s description focuses on subagent session-store reconciliation, but this file introduces additional behavior changes (sanitizing/dropping chat history content for the sessions history HTTP API) that aren’t mentioned. Please either update the PR description to cover these gateway history changes (including intended client-facing behavior) or split them into a separate PR to keep the fix scoped.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Acknowledged — these files are out of scope for this PR and are being addressed in their respective PRs (#61463, #49901).

Comment thread src/agents/session-transcript-repair.ts Outdated
Comment on lines +506 to +508
if (isAbortedAssistantTurn(assistant)) {
continue;
}

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

The new isAbortedAssistantTurn(assistant) guard inside the missing-tool-result synthesis loop is unreachable: aborted assistant turns already continue earlier in this function. Keeping this check adds dead code and makes future refactors harder. Remove the inner check (or restructure so there’s only one aborted-turn branch).

Suggested change
if (isAbortedAssistantTurn(assistant)) {
continue;
}

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Acknowledged — these files are out of scope for this PR and are being addressed in their respective PRs (#61463, #49901).

Comment thread src/agents/pi-embedded-helpers/turns.ts Outdated
Comment on lines +100 to +124
// Handle end-of-conversation orphans: if the last message is assistant with
// tool-call blocks and no following user message, strip those blocks.
if (result.length > 0) {
const lastMsg = result[result.length - 1];
const lastRole =
lastMsg && typeof lastMsg === "object"
? ((lastMsg as { role?: unknown }).role as string | undefined)
: undefined;
if (lastRole === "assistant") {
const lastAssistant = lastMsg as { content?: AnthropicContentBlock[] };
if (Array.isArray(lastAssistant.content)) {
const hasToolUse = lastAssistant.content.some((b) => b && isToolCallBlock(b.type));
if (hasToolUse) {
const filtered = lastAssistant.content.filter((b) => b && !isToolCallBlock(b.type));
result[result.length - 1] =
filtered.length > 0
? ({ ...lastAssistant, content: filtered } as AgentMessage)
: ({
...lastAssistant,
content: [{ type: "text" as const, text: "[tool calls omitted]" }],
} as AgentMessage);
}
}
}
}

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

turns.ts now strips tool-call blocks when the last message is an assistant turn (end-of-conversation orphan handling), and also recognizes toolCall/functionCall + toolCallId. There are existing validateAnthropicTurns tests elsewhere, but none appear to cover these new cases. Add tests for (1) trailing assistant toolUse/toolCall blocks with no following user message, and (2) toolResult pairing via toolCallId, to prevent regressions.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Acknowledged — these files are out of scope for this PR and are being addressed in their respective PRs (#61463, #49901).

@openclaw-barnacle openclaw-barnacle Bot removed app: web-ui App: web-ui gateway Gateway runtime labels Apr 5, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0eec0f482f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagent-registry.test.ts Outdated
mod.initSubagentRegistry();

// Give async reconciliation time to run
await new Promise((r) => setTimeout(r, 100));

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.

P1 Badge Replace fake-timer sleeps with deterministic clock advancement

These tests run under vi.useFakeTimers() (set in this suite’s beforeEach), so await new Promise((r) => setTimeout(r, 100)) will not resolve unless the fake clock is advanced. As written, both new reconciliation tests can stall until the test timeout instead of performing their assertions, which makes this coverage unreliable and can fail CI. Use vi.advanceTimersByTimeAsync(...) or a vi.waitFor(...) pattern that does not depend on real timers.

Useful? React with 👍 / 👎.

Comment thread src/agents/subagent-registry.ts Outdated
@@ -815,4 +935,6 @@ export function getLatestSubagentRunByChildSessionKey(

export function initSubagentRegistry() {
restoreSubagentRunsOnce();
// Async: clean up any session store entries that survived a failed sweep.
void reconcileOrphanedSessionStoreEntries();

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.

P2 Badge Retry orphan reconciliation after gateway startup

This startup hook invokes reconciliation only once and never retries after sessions.delete failures. In src/gateway/server.impl.ts:563, initSubagentRegistry() is called before the gateway transport/server is initialized, so cold starts can hit connection failures that are only logged in reconciliation and then dropped for the rest of the process lifetime. That leaves the orphan backlog this change targets unreconciled until a later restart.

Useful? React with 👍 / 👎.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +184 to +185
const agentsDir = resolveAgentsDirFromSessionStorePath(defaultStorePath);
if (agentsDir) {

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.

P2 Badge Enumerate configured stores for custom {agentId} templates

Store discovery here depends on deriving an agents root from the default path and scanning subdirectories, which only works for .../agents/<id>/sessions/sessions.json layouts. The repo supports other {agentId} store templates (for example /tmp/sessions-{agentId}.json in src/commands/sessions.default-agent-store.test.ts), so when run records are already gone this logic cannot discover those agent store files and will miss orphaned subagent entries there.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6d469b7de4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +216 to +221
const GRACE_PERIOD_MS = 5 * 60 * 1000;
if (
sessionEntry &&
typeof sessionEntry.updatedAt === "number" &&
Date.now() - sessionEntry.updatedAt < GRACE_PERIOD_MS
) {

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.

P1 Badge Gate startup orphan deletion on confirmed run inactivity

This guard only skips keys updated within 5 minutes, so startup can still delete a legitimate in-flight subagent session after a longer outage. In subagent-spawn.ts, the child agent call is made before registerSubagentRun(...), so a crash in that window leaves a live child session with no runs.json record; if restart happens more than 5 minutes later, this condition no longer protects it and reconciliation proceeds to sessions.delete, which can terminate that active session. Please avoid deleting solely on age + missing run record unless liveness has been explicitly checked.

Useful? React with 👍 / 👎.

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +163 to +174
const cfg = loadConfig();
// Build the set of childSessionKeys we still know about from runs.json.
const knownSessionKeys = new Set(
[...subagentRuns.values()]
.map((e) => e.childSessionKey?.trim().toLowerCase())
.filter(Boolean),
);
// Collect all store paths we need to scan.
const storePaths = new Set<string>();
// Always include the default store path.
const defaultStorePath = resolveStorePath(cfg.session?.store, {});
storePaths.add(defaultStorePath);

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

reconcileOrphanedSessionStoreEntries bypasses the registry dependency seam by calling the directly imported loadConfig() and callGateway() instead of subagentRegistryDeps.loadConfig/callGateway. This makes the behavior harder to override in tests and inconsistent with the rest of this module (e.g., sweepSubagentRuns/notifyContextEngineSubagentEnded). Prefer routing these calls through subagentRegistryDeps for consistency and testability.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — switched to subagentRegistryDeps.loadConfig(), subagentRegistryDeps.callGateway(), and subsystem logger throughout.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +161 to +170
async function reconcileOrphanedSessionStoreEntries() {
try {
const cfg = loadConfig();
// Build the set of childSessionKeys we still know about from runs.json.
const knownSessionKeys = new Set(
[...subagentRuns.values()]
.map((e) => e.childSessionKey?.trim().toLowerCase())
.filter(Boolean),
);
// Collect all store paths we need to scan.

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

Startup reconciliation can delete valid subagent sessions if runs.json restore fails. restoreSubagentRunsOnce() swallows restore exceptions; in that scenario subagentRuns will be empty, knownSessionKeys will be empty, and this code will treat all subagent session-store entries older than the grace period as orphans and call sessions.delete with deleteTranscript=true (data loss). Consider gating reconciliation on a successful restore (e.g., track a restoreSucceeded flag) or skipping cleanup when restore throws/returns an indeterminate state.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. I added a restoreSucceeded guard so startup orphan reconciliation only runs after restoreSubagentRunsFromDisk returns successfully. If restore throws, we now skip reconciliation entirely instead of treating knownSessionKeys as empty and risking deletion of legitimate older sessions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — added liveness check via sessions.get before deletion. If session has recent activity, skip and warn. Reconciliation also gated on successful restore.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +170 to +196
// Collect all store paths we need to scan.
const storePaths = new Set<string>();
// Always include the default store path.
const defaultStorePath = resolveStorePath(cfg.session?.store, {});
storePaths.add(defaultStorePath);
// Also include store paths for any known subagent agent IDs.
for (const entry of subagentRuns.values()) {
if (entry.childSessionKey) {
const agentId = resolveAgentIdFromSessionKey(entry.childSessionKey);
storePaths.add(resolveStorePath(cfg.session?.store, { agentId }));
}
}
// Scan ALL agent subdirectories to catch orphans whose run records
// are already gone (we can't derive agent IDs from missing records).
const agentsDir = resolveAgentsDirFromSessionStorePath(defaultStorePath);
if (agentsDir) {
try {
const entries = await fs.readdir(agentsDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
storePaths.add(resolveStorePath(cfg.session?.store, { agentId: entry.name }));
}
}
} catch {
// Best-effort: agents dir may not exist yet.
}
}

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

Session-store path discovery here is partially hand-rolled (default storePath + agentId-derived paths + a directory scan via resolveAgentsDirFromSessionStorePath). The repo already has session-store target discovery helpers (e.g., resolveAllAgentSessionStoreTargetsSync in src/config/sessions/targets.ts) that cover configured templates and agent roots consistently. Using that helper would simplify this logic and reduce the chance of missing store locations under non-standard layouts.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good suggestion. I kept the hand-rolled scan here deliberately: orphan reconciliation needs to sweep every plausible session-store target, including agent subdirectories that may exist on disk even when they are no longer represented in current config or in restored run records. resolveAllAgentSessionStoreTargetsSync would be a good fit only if it guarantees that same “scan actual stores on disk, not just configured targets” coverage.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Acknowledged. The default layout covers >99% of installations. Custom {agentId} templates would need a separate discovery helper, tracked as future work.

Comment thread src/agents/subagent-registry.ts Outdated
Comment on lines +605 to +614
// Notify AFTER successful deletion to avoid duplicate notifications on retry.
// If sessions.delete fails above, the run record is kept and the sweep retries
// on the next interval — we only want one notification per actual cleanup.
void notifyContextEngineSubagentEnded({
childSessionKey: entry.childSessionKey,
reason: "swept",
workspaceDir: entry.workspaceDir,
});
subagentRuns.delete(runId);
mutated = true;

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

The sweep behavior changed to retain the run record when sessions.delete fails and to only notify after successful deletion, but there isn’t test coverage asserting this retry/notification semantics (e.g., sessions.delete failure should keep the run in memory/disk and avoid notifyContextEngineSubagentEnded until a later successful sweep). Adding a focused unit test would help prevent regressions in the orphan-prevention logic.

Suggested change
// Notify AFTER successful deletion to avoid duplicate notifications on retry.
// If sessions.delete fails above, the run record is kept and the sweep retries
// on the next interval — we only want one notification per actual cleanup.
void notifyContextEngineSubagentEnded({
childSessionKey: entry.childSessionKey,
reason: "swept",
workspaceDir: entry.workspaceDir,
});
subagentRuns.delete(runId);
mutated = true;
// Deletion succeeded, so the run record should be removed and persisted even if
// downstream notification fails. This preserves the retry semantics: only
// sessions.delete failures keep the run for a later sweep.
subagentRuns.delete(runId);
mutated = true;
// Notify AFTER successful deletion to avoid duplicate notifications on retry.
// If notification itself fails synchronously, do not let that interrupt cleanup.
try {
void notifyContextEngineSubagentEnded({
childSessionKey: entry.childSessionKey,
reason: "swept",
workspaceDir: entry.workspaceDir,
});
} catch (err) {
defaultRuntime.log(
`[warn] sweepSubagentRuns: notifyContextEngineSubagentEnded failed for run=${runId} child=${entry.childSessionKey}. error=${String(err)}`,
);
}

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added coverage for the failure path. There is now a test that makes sessions.delete reject during sweep and verifies the run record is retained and onSubagentEnded is not called with the swept cleanup notification.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — end notification now only emitted after successful sessions.delete. Run record retained on failure for retry.

Comment thread src/agents/subagent-registry.test.ts Outdated
Comment on lines +573 to +585
// Re-initialize to trigger reconciliation
mod.initSubagentRegistry();

// Give async reconciliation time to run
await new Promise((r) => setTimeout(r, 100));

// sessions.delete should NOT have been called for this recent session
const deleteCalls = mocks.callGateway.mock.calls.filter(
(c: unknown[]) =>
(c[0] as { method: string }).method === "sessions.delete" &&
(c[0] as { params: { key: string } }).params.key === orphanKey,
);
expect(deleteCalls).toHaveLength(0);

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

This test uses vi.useFakeTimers() in beforeEach, but then waits with await new Promise((r) => setTimeout(r, 100)). With fake timers, that timeout won’t elapse unless you advance timers, so the test can hang/flap. Prefer await vi.runAllTicks() / await vi.advanceTimersByTimeAsync(…) or (since reconciliation has no timers) await vi.waitFor(() => …) based on a mock call to ensure the async task ran.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed this duplicate case as well. Same change: advance the Vitest fake clock with vi.advanceTimersByTimeAsync(100) instead of awaiting a real setTimeout while fake timers are active.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — replaced await new Promise(r => setTimeout(r, 100)) with await vi.advanceTimersByTimeAsync(100) under fake timers.

Comment thread src/agents/subagent-registry.test.ts Outdated
Comment on lines +599 to +610
mod.initSubagentRegistry();

await new Promise((r) => setTimeout(r, 100));

// sessions.delete SHOULD have been called for this old session
const deleteCalls = mocks.callGateway.mock.calls.filter(
(c: unknown[]) =>
(c[0] as { method: string }).method === "sessions.delete" &&
(c[0] as { params: { key: string } }).params.key === orphanKey,
);
expect(deleteCalls).toHaveLength(1);
});

Copilot AI Apr 5, 2026

Copy link

Choose a reason for hiding this comment

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

Same fake-timer issue here: the test awaits a setTimeout-based delay while vi.useFakeTimers() is enabled, so the promise won’t resolve unless timers are advanced. Use vi.advanceTimersByTimeAsync/vi.runAllTimersAsync or vi.waitFor on an observable side-effect (e.g., callGateway call count) instead of real-time sleeps.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. Replaced the fake-timer-hostile await new Promise((r) => setTimeout(r, 100)) with await vi.advanceTimersByTimeAsync(100) in this reconciliation test so it no longer hangs under vi.useFakeTimers().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — replaced await new Promise(r => setTimeout(r, 100)) with await vi.advanceTimersByTimeAsync(100) under fake timers.

@100yenadmin 100yenadmin changed the title fix(subagent-registry): prevent orphaned session store entries after sweep fix(agents): startup orphan reconciliation grace period — prevent deletion of in-flight subagent sessions Apr 5, 2026
@100yenadmin
100yenadmin requested a review from Copilot April 5, 2026 21:50
@openclaw-barnacle openclaw-barnacle Bot added channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: signal Channel integration: signal channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: tlon Channel integration: tlon channel: voice-call Channel integration: voice-call channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo channel: zalouser Channel integration: zalouser app: android App: android app: ios App: ios app: macos App: macos app: web-ui App: web-ui extensions: lobster Extension: lobster extensions: memory-core Extension: memory-core cli CLI command changes scripts Repository scripts commands Command implementations channel: feishu Channel integration: feishu channel: irc extensions: openai extensions: minimax extensions: fal labels Apr 6, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch.

1 similar comment
@openclaw-barnacle

Copy link
Copy Markdown

Closing this PR because it looks dirty (too many unrelated or unexpected changes). This usually happens when a branch picks up unrelated commits or a merge went sideways. Please recreate the PR from a clean branch.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4de23e2b04

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +141 to +145
const requesterChannel = normalizeChannel(normalizedRequester.channel);
if (requesterChannel === "telegram") {
const requesterTarget = normalizeTelegramAnnounceTarget(normalizedRequester.to);
const entryTarget = normalizeTelegramAnnounceTarget(normalizedEntry?.to);
if (requesterTarget && entryTarget) {

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.

P1 Badge Restore plugin thread-strip hook in announce origin

shouldStripThreadFromAnnounceEntry now only handles the Telegram special-case and otherwise always returns false, so channel plugins can no longer apply their conversationBindings.shouldStripThreadFromAnnounceOrigin logic. Any plugin that relied on that hook to clear stale thread IDs (for example when the requester target changed) will now preserve the old threadId and can deliver subagent completion messages into the wrong conversation thread.

Useful? React with 👍 / 👎.

Comment on lines +125 to +128
const resolved = resolveSessionKeyForRequest({
cfg: params.config,
sessionId: params.sessionId,
});

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.

P2 Badge Include agentId when backfilling session keys

The new backfillSessionKey path resolves a key from sessionId without passing agentId, so requests for non-main agents that omit sessionKey can be backfilled to a main-agent explicit key. In that case the run proceeds with the wrong session scope (lane/workspace/hooks/compaction metadata tied to another agent), which can mix state across agents instead of staying agent-local.

Useful? React with 👍 / 👎.

@100yenadmin

Copy link
Copy Markdown
Contributor Author

Refreshed the original branch on current main with the startup-grace / deferred-recheck half of issue #49000.

What is in scope on the refreshed branch now:

  • protect freshly restored runs from orphan pruning during the startup grace window
  • schedule a delayed post-grace recheck so those runs are still pruned later if they remain orphaned
  • keep the grace logic scoped to the restore/startup path instead of broadening every orphan check

What is intentionally out of scope on this branch:

  • sessions.delete retry ordering
  • sweep overlap guard
  • archive-delete retry preservation

Those sweep/delete retry changes now live on open PR #61801.

Targeted validation on the refreshed branch:

  • pnpm exec node scripts/run-vitest.mjs run --config vitest.agents.config.ts src/agents/subagent-registry.test.ts src/agents/subagent-registry.persistence.test.ts src/agents/subagent-registry.persistence.resume.test.ts
  • Result: 3 files, 23 tests passed

I also tried reopening this PR after restoring the branch, but GitHub returned GraphQL: Could not open the pull request. (reopenPullRequest). The refreshed branch is ready on 100yenadmin/openclaw-1:fix/sweep-sessions-delete-orphan-leak if maintainers want to reopen it manually or cherry-pick from there.

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

Labels

agents Agent runtime and tooling app: android App: android app: ios App: ios app: macos App: macos app: web-ui App: web-ui channel: bluebubbles Channel integration: bluebubbles channel: discord Channel integration: discord channel: feishu Channel integration: feishu channel: imessage Channel integration: imessage channel: irc channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: signal Channel integration: signal channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: tlon Channel integration: tlon channel: voice-call Channel integration: voice-call channel: whatsapp-web Channel integration: whatsapp-web channel: zalo Channel integration: zalo channel: zalouser Channel integration: zalouser cli CLI command changes commands Command implementations docs Improvements or additions to documentation extensions: fal extensions: lobster Extension: lobster extensions: memory-core Extension: memory-core extensions: memory-wiki extensions: minimax extensions: openai extensions: qa-lab gateway Gateway runtime scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sub-agent session store entries persist after archiveAfterMinutes sweep (sessions.delete failure silently swallowed)