Repository navigation
Conversation
…upted turns on restart Adds a pending-inbound store and active-turn tracking to support lossless gateway restarts and crash recovery. Key changes: - src/infra/pending-inbound-store.ts: file-backed store for pending inbound messages (written by channel plugins before processing, cleared on delivery) and active-turn records (written at turn start, cleared on completion) - src/gateway/server-startup.ts: on startup, read pending-inbound store and deliver any unprocessed messages queued before restart; read active-turn records to recover interrupted turns - src/infra/system-events.ts: ActiveTurnState events for turn lifecycle tracking - src/process/command-queue.ts: integrate with drain lifecycle - src/infra/json-files.ts: atomic JSON file helpers used by pending-inbound store - src/agents/pi-embedded-runner/run/attempt.ts: write active-turn record before run starts; clear on completion (for crash recovery) Note: Channel-specific drain routing (telegram topic/thread replyThreadId passthrough) will be applied separately as it requires porting to the current extensions/telegram/ layout.
🔒 Aisle Security AnalysisWe found 2 potential security issue(s) in this PR:
1. 🔵 Symlink-following chmod in atomic writer can change permissions of attacker-chosen directory
Description
On POSIX platforms, Impact depends on deployment, but can include:
Vulnerable code (new behavior): await fs.mkdir(path.dirname(filePath), mkdirOptions);
if (typeof options?.ensureDirMode === "number") {
try {
await fs.chmod(path.dirname(filePath), options.ensureDirMode);
} catch {
// ignore
}
}This is a classic link-following / TOCTOU class issue when directory paths are not guaranteed to be trusted and immutable. RecommendationAvoid chmod’ing a path that could be a symlink, and (where possible) constrain writes to a trusted root. Minimum hardening:
const dir = path.dirname(filePath);
const st = await fs.lstat(dir);
if (st.isSymbolicLink()) {
throw new Error(`Refusing to chmod symlink directory: ${dir}`);
}
if (!st.isDirectory()) {
throw new Error(`Expected directory for atomic write: ${dir}`);
}
await fs.chmod(dir, options.ensureDirMode);
const root = await fs.realpath(trustedRoot);
const dirReal = await fs.realpath(path.dirname(filePath));
if (!dirReal.startsWith(root + path.sep)) {
throw new Error("Refusing to chmod/write outside trusted root");
}
These changes reduce symlink/hardlink and TOCTOU risk around permission-setting operations. 2. 🔵 Prototype pollution via attacker-controlled sessionId in active-turn on-disk store
DescriptionThe active-turn tracking store uses a plain object (
Vulnerable code: if (!existing.activeTurns) {
existing.activeTurns = {};
}
existing.activeTurns[entry.sessionId] = entry;RecommendationPrevent prototype pollution by not using plain objects with untrusted keys. Recommended fixes (pick one):
const FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);
function assertSafeKey(key: string) {
if (FORBIDDEN_KEYS.has(key)) {
throw new Error(`invalid sessionId key`);
}
}
// When creating:
existing.activeTurns = Object.create(null) as Record<string, ActiveTurnEntry>;
// Before setting:
assertSafeKey(entry.sessionId);
existing.activeTurns[entry.sessionId] = entry;
Also consider applying the same protection to any other record-like objects keyed by identifiers coming from requests or external systems. Analyzed PR: #49407 at commit Last updated on: 2026-03-18T04:21:22Z |
|
Closing this PR because the author has more than 10 active PRs in this repo. Please reduce the active PR queue and reopen or resubmit once it is back under the limit. You can close your own PRs to get back under the limit. |
There was a problem hiding this comment.
Pull request overview
Adds crash/restart resilience by persisting (a) inbound messages captured during gateway drain and (b) in-flight “active turns”, then replaying/notifying on startup.
Changes:
- Export gateway draining state and system event queue cap (
MAX_EVENTS) for reuse. - Introduce
pending-inbound-store(disk-backed pending inbound + active turn tracking) with extensive tests. - Harden atomic JSON/text writes (directory/file permissions) and add startup replay + stale-turn recovery flows.
Reviewed changes
Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
| src/process/command-queue.ts | Exposes isGatewayDraining() to query restart-drain state. |
| src/infra/system-events.ts | Exports MAX_EVENTS so other modules can cap per-session queues consistently. |
| src/infra/system-events.test.ts | Updates tests to align with MAX_EVENTS export and dedupe/cap behavior. |
| src/infra/pending-inbound-store.ts | New disk-backed store for drain-captured inbound messages + active turn crash recovery. |
| src/infra/pending-inbound-store.test.ts | Adds coverage for persistence, dedupe, pruning, concurrency, and permissions. |
| src/infra/json-files.ts | Improves permission enforcement for atomic writes (dir chmod + temp-file mode). |
| src/gateway/server-startup.ts | Replays pending inbound system events before channels start; recovers stale active turns after startup. |
| src/agents/pi-embedded-runner/run/attempt.ts | Persists/clears active turn records around embedded runs for crash recovery. |
| const rawSenderLabel = | ||
| payload.senderName ?? payload.senderUsername ?? payload.senderId ?? "unknown"; | ||
| const senderLabel = sanitizeInboundSystemTags(String(rawSenderLabel)); | ||
| const rawPreview = (payload.text ?? "").slice(0, 200).replace(/\n/g, "\\n"); |
|
|
||
| /** | ||
| * Remove the pending inbound file entirely. | ||
| * @deprecated Use `clearPendingInboundEntries` or `clearActiveTurns` to avoid |
| it("pending-inbound.json is written with mode 0o600", async () => { | ||
| await writePendingInbound(stateDir, { | ||
| channel: "telegram", | ||
| id: "perm-test-1", | ||
| payload: { text: "secret" }, | ||
| capturedAt: Date.now(), | ||
| }); | ||
|
|
||
| const filePath = path.join(stateDir, "pending-inbound.json"); | ||
| const stat = await fsp.stat(filePath); | ||
| // Mask to the low 9 permission bits (strip file type bits) | ||
| const mode = stat.mode & 0o777; | ||
| expect(mode).toBe(0o600); | ||
| }); | ||
|
|
||
| it("state dir is created with mode 0o700", async () => { | ||
| // Use a sub-directory that does not yet exist | ||
| const subDir = path.join(stateDir, "sub-state-dir"); | ||
|
|
||
| await writePendingInbound(subDir, { | ||
| channel: "telegram", | ||
| id: "perm-test-2", | ||
| payload: { text: "secret" }, | ||
| capturedAt: Date.now(), | ||
| }); | ||
|
|
||
| const stat = await fsp.stat(subDir); | ||
| const mode = stat.mode & 0o777; | ||
| expect(mode).toBe(0o700); | ||
| }); |
Greptile SummaryThis PR introduces a lossless gateway restart mechanism by adding a file-backed The core infrastructure (store design, atomic writes, file-lock + in-process queue composition, pruning, and the
Confidence Score: 3/5
Prompt To Fix All With AIThis is a comment left during a code review.
Path: src/infra/pending-inbound-store.ts
Line: 247-260
Comment:
**Unnecessary file write when entry is absent**
`clearActiveTurn` takes out a file lock, reads the file, performs a no-op `delete`, and writes the file back unchanged whenever `activeTurns` exists but doesn't contain the target `sessionId`. This shows up on every normal turn completion path (the `finally` block in `attempt.ts`) if `writeActiveTurn` previously failed and never persisted an entry.
Adding an early-return guard avoids the wasted I/O:
```suggestion
const existing = await readPendingInboundFile(filePath);
if (!existing.activeTurns || !(entry.sessionId in existing.activeTurns)) {
return; // nothing to clear
}
delete existing.activeTurns[sessionId];
```
Actually, since the parameter name is `sessionId` not `entry.sessionId`, the fix should be:
```
if (!existing.activeTurns || !(sessionId in existing.activeTurns)) {
return; // nothing to clear
}
```
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/infra/system-events.test.ts
Line: 4-11
Comment:
**Test coverage regression for retained exports**
This PR removes tests for `isSystemEventContextChanged`, `drainSystemEventEntries`, `hasSystemEvents`, and `peekSystemEventEntries`. All four functions are still exported from `system-events.ts` and remain part of the public API used by the rest of the codebase.
The deleted test cases covered meaningful behaviour: context-key normalisation (`isSystemEventContextChanged`), clone-on-drain and duplicate-reset semantics (`drainSystemEventEntries`), and event presence (`hasSystemEvents` / `peekSystemEventEntries`). Removing them leaves a gap that makes it easier for regressions in those functions to go undetected.
Consider keeping the existing tests alongside the new ones, or migrating them to a dedicated `system-events-legacy.test.ts` if the file felt too large.
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/gateway/server-startup.ts
Line: 264-361
Comment:
**Stale-turn recovery runs after `startChannels()`, creating a narrow TOCTOU window**
The pending-inbound replay block correctly runs *before* `startChannels()`, but the stale active-turn recovery block runs *after* channels are already live. Once `startChannels()` returns, a fast inbound message could trigger `writeActiveTurn` for a session whose stale record is still being processed by the recovery loop. The re-validation (`readActiveTurn`) and the subsequent `clearActiveTurn` are not atomic — if a fresh `writeActiveTurn` from the new channel handler completes between those two calls (both async awaits), the recovery loop will delete the new, live entry.
The `processStartedAt` guard at the top of the loop handles the most common case (turns where `startedAt >= processStartedAt`), but is not a complete fence: `writeActiveTurn` uses `Date.now()` at call time, which must be called *after* `processStartedAt` was captured for the guard to fire. If a very fast channel handler writes its turn before the loop reaches that `sessionId`, and the clock hasn't advanced enough, both `turn.startedAt` (stale snapshot) and the fresh entry's `startedAt` could compare equal, causing the guard to pass and the live entry to be silently cleared.
Moving the entire stale-turn recovery block to *before* `startChannels()` — similar to the pending-inbound replay — would eliminate the race entirely without requiring any logic changes.
How can I resolve this? If you propose a fix, please make it concise.Last reviewed commit: "feat(gateway): queue..." |
| for (let i = 0; i < pruneCount; i++) { | ||
| delete existing.activeTurns[sorted[i]]; | ||
| } | ||
| } | ||
| await writeJsonAtomic(filePath, existing, { | ||
| mode: 0o600, | ||
| trailingNewline: true, | ||
| ensureDirMode: 0o700, | ||
| }); | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| /** |
There was a problem hiding this comment.
Unnecessary file write when entry is absent
clearActiveTurn takes out a file lock, reads the file, performs a no-op delete, and writes the file back unchanged whenever activeTurns exists but doesn't contain the target sessionId. This shows up on every normal turn completion path (the finally block in attempt.ts) if writeActiveTurn previously failed and never persisted an entry.
Adding an early-return guard avoids the wasted I/O:
| for (let i = 0; i < pruneCount; i++) { | |
| delete existing.activeTurns[sorted[i]]; | |
| } | |
| } | |
| await writeJsonAtomic(filePath, existing, { | |
| mode: 0o600, | |
| trailingNewline: true, | |
| ensureDirMode: 0o700, | |
| }); | |
| }), | |
| ); | |
| } | |
| /** | |
| const existing = await readPendingInboundFile(filePath); | |
| if (!existing.activeTurns || !(entry.sessionId in existing.activeTurns)) { | |
| return; // nothing to clear | |
| } | |
| delete existing.activeTurns[sessionId]; |
Actually, since the parameter name is sessionId not entry.sessionId, the fix should be:
if (!existing.activeTurns || !(sessionId in existing.activeTurns)) {
return; // nothing to clear
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/pending-inbound-store.ts
Line: 247-260
Comment:
**Unnecessary file write when entry is absent**
`clearActiveTurn` takes out a file lock, reads the file, performs a no-op `delete`, and writes the file back unchanged whenever `activeTurns` exists but doesn't contain the target `sessionId`. This shows up on every normal turn completion path (the `finally` block in `attempt.ts`) if `writeActiveTurn` previously failed and never persisted an entry.
Adding an early-return guard avoids the wasted I/O:
```suggestion
const existing = await readPendingInboundFile(filePath);
if (!existing.activeTurns || !(entry.sessionId in existing.activeTurns)) {
return; // nothing to clear
}
delete existing.activeTurns[sessionId];
```
Actually, since the parameter name is `sessionId` not `entry.sessionId`, the fix should be:
```
if (!existing.activeTurns || !(sessionId in existing.activeTurns)) {
return; // nothing to clear
}
```
How can I resolve this? If you propose a fix, please make it concise.| import { resolveMainSessionKey } from "../config/sessions.js"; | ||
| import { isCronSystemEvent } from "./heartbeat-runner.js"; | ||
| import { | ||
| drainSystemEventEntries, | ||
| enqueueSystemEvent, | ||
| hasSystemEvents, | ||
| isSystemEventContextChanged, | ||
| peekSystemEventEntries, | ||
| MAX_EVENTS, | ||
| peekSystemEvents, | ||
| resetSystemEventsForTest, | ||
| } from "./system-events.js"; |
There was a problem hiding this comment.
Test coverage regression for retained exports
This PR removes tests for isSystemEventContextChanged, drainSystemEventEntries, hasSystemEvents, and peekSystemEventEntries. All four functions are still exported from system-events.ts and remain part of the public API used by the rest of the codebase.
The deleted test cases covered meaningful behaviour: context-key normalisation (isSystemEventContextChanged), clone-on-drain and duplicate-reset semantics (drainSystemEventEntries), and event presence (hasSystemEvents / peekSystemEventEntries). Removing them leaves a gap that makes it easier for regressions in those functions to go undetected.
Consider keeping the existing tests alongside the new ones, or migrating them to a dedicated system-events-legacy.test.ts if the file felt too large.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/system-events.test.ts
Line: 4-11
Comment:
**Test coverage regression for retained exports**
This PR removes tests for `isSystemEventContextChanged`, `drainSystemEventEntries`, `hasSystemEvents`, and `peekSystemEventEntries`. All four functions are still exported from `system-events.ts` and remain part of the public API used by the rest of the codebase.
The deleted test cases covered meaningful behaviour: context-key normalisation (`isSystemEventContextChanged`), clone-on-drain and duplicate-reset semantics (`drainSystemEventEntries`), and event presence (`hasSystemEvents` / `peekSystemEventEntries`). Removing them leaves a gap that makes it easier for regressions in those functions to go undetected.
Consider keeping the existing tests alongside the new ones, or migrating them to a dedicated `system-events-legacy.test.ts` if the file felt too large.
How can I resolve this? If you propose a fix, please make it concise.| ); | ||
| } | ||
|
|
||
| // Recover stale active turns — runs that were in-flight when the process died. | ||
| // Notify the originating session so the user knows to resend. | ||
| try { | ||
| const stateDir = resolveStateDir(process.env); | ||
| const staleTurns = await readStaleActiveTurns(stateDir); | ||
| if (staleTurns.length > 0) { | ||
| params.log.warn( | ||
| `active-turn recovery: found ${staleTurns.length} stale turn(s) from previous process`, | ||
| ); | ||
| for (const turn of staleTurns) { | ||
| // Skip turns started by THIS process — they raced ahead of the | ||
| // recovery loop (channel startup created a new turn before we got | ||
| // here). Only turns from the PREVIOUS process are truly stale. | ||
| if (turn.startedAt >= processStartedAt) { | ||
| params.log.warn( | ||
| `active-turn recovery: skipping live turn ${turn.sessionId} (startedAt=${turn.startedAt} >= processStartedAt=${processStartedAt})`, | ||
| ); | ||
| continue; | ||
| } | ||
|
|
||
| // Re-validate the current store entry before clearing. Between the | ||
| // snapshot (readStaleActiveTurns) and now, a fresh turn could have | ||
| // been written under the same sessionId — e.g. if a channel handler | ||
| // started a new turn whose sessionId collides with a stale one. | ||
| // Only clear if the on-disk entry still has the same startedAt we | ||
| // saw in the snapshot (i.e. it has NOT been refreshed by this process). | ||
| const currentEntry = await readActiveTurn(stateDir, turn.sessionId); | ||
| if (!currentEntry) { | ||
| // Already cleared by something else — nothing to do. | ||
| continue; | ||
| } | ||
| if (currentEntry.startedAt !== turn.startedAt) { | ||
| // A fresh turn was written under the same sessionId after our snapshot. | ||
| // The startedAt guard above already protects against this case when the | ||
| // new turn's startedAt >= processStartedAt, but a recycled sessionId | ||
| // whose new startedAt still happens to be < processStartedAt (due to | ||
| // clock imprecision or test-injected timestamps) would slip through. | ||
| // Comparing startedAt values is the most reliable way to detect staleness. | ||
| params.log.warn( | ||
| `active-turn recovery: skipping refreshed turn ${turn.sessionId} (snapshot startedAt=${turn.startedAt}, current startedAt=${currentEntry.startedAt})`, | ||
| ); | ||
| continue; | ||
| } | ||
|
|
||
| // Consume first to prevent infinite retry on crash. | ||
| await clearActiveTurn(stateDir, turn.sessionId); | ||
|
|
||
| // Skip probe sessions — they are synthetic health-check runs. | ||
| if (turn.sessionId.startsWith("probe-")) { | ||
| continue; | ||
| } | ||
|
|
||
| // Attempt to resolve a delivery target for the session. Sessions without | ||
| // a resolvable channel target (isolated scheduler sessions, orphaned sessions, | ||
| // or any session with no channel mapping) are skipped — the originating system | ||
| // (e.g. a scheduler's drain-retry) handles recovery for those. | ||
| const { baseSessionKey } = parseSessionThreadInfo(turn.sessionKey); | ||
| const parsedTarget = resolveAnnounceTargetFromKey(baseSessionKey ?? turn.sessionKey ?? ""); | ||
| const { entry: turnEntry } = loadSessionEntry(turn.sessionKey ?? ""); | ||
| let deliveryCtx = deliveryContextFromSession(turnEntry); | ||
| if (!deliveryCtx && baseSessionKey && baseSessionKey !== turn.sessionKey) { | ||
| const { entry: baseEntry } = loadSessionEntry(baseSessionKey); | ||
| deliveryCtx = deliveryContextFromSession(baseEntry); | ||
| } | ||
| const origin = mergeDeliveryContext(deliveryCtx, parsedTarget ?? undefined); | ||
| const resolvedChannel = origin?.channel ? normalizeChannelId(origin.channel) : null; | ||
| const resolvedTo = origin?.to; | ||
| if (!resolvedChannel || !resolvedTo) { | ||
| continue; | ||
| } | ||
|
|
||
| try { | ||
| const recoveryMessage = | ||
| "⚠️ I was restarted mid-conversation. Please resend your last message."; | ||
| enqueueSystemEvent(`[active-turn-recovery] ${recoveryMessage}`, { | ||
| sessionKey: turn.sessionKey, | ||
| contextKey: `active-turn-recovery:${turn.sessionId}`, | ||
| }); | ||
| params.log.warn( | ||
| `active-turn recovery: notified session ${turn.sessionKey} (sessionId=${turn.sessionId}, channel=${turn.channel})`, | ||
| ); | ||
| } catch (err) { | ||
| params.log.warn( | ||
| `active-turn recovery: notify failed for session ${turn.sessionKey}: ${String(err)}`, | ||
| ); | ||
| } | ||
| } | ||
| } | ||
| } catch (err) { | ||
| params.log.warn(`active-turn recovery: startup failed: ${String(err)}`); | ||
| } | ||
|
|
||
| if (params.cfg.hooks?.internal?.enabled) { | ||
| setTimeout(() => { | ||
| const hookEvent = createInternalHookEvent("gateway", "startup", "gateway:startup", { |
There was a problem hiding this comment.
Stale-turn recovery runs after
startChannels(), creating a narrow TOCTOU window
The pending-inbound replay block correctly runs before startChannels(), but the stale active-turn recovery block runs after channels are already live. Once startChannels() returns, a fast inbound message could trigger writeActiveTurn for a session whose stale record is still being processed by the recovery loop. The re-validation (readActiveTurn) and the subsequent clearActiveTurn are not atomic — if a fresh writeActiveTurn from the new channel handler completes between those two calls (both async awaits), the recovery loop will delete the new, live entry.
The processStartedAt guard at the top of the loop handles the most common case (turns where startedAt >= processStartedAt), but is not a complete fence: writeActiveTurn uses Date.now() at call time, which must be called after processStartedAt was captured for the guard to fire. If a very fast channel handler writes its turn before the loop reaches that sessionId, and the clock hasn't advanced enough, both turn.startedAt (stale snapshot) and the fresh entry's startedAt could compare equal, causing the guard to pass and the live entry to be silently cleared.
Moving the entire stale-turn recovery block to before startChannels() — similar to the pending-inbound replay — would eliminate the race entirely without requiring any logic changes.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/server-startup.ts
Line: 264-361
Comment:
**Stale-turn recovery runs after `startChannels()`, creating a narrow TOCTOU window**
The pending-inbound replay block correctly runs *before* `startChannels()`, but the stale active-turn recovery block runs *after* channels are already live. Once `startChannels()` returns, a fast inbound message could trigger `writeActiveTurn` for a session whose stale record is still being processed by the recovery loop. The re-validation (`readActiveTurn`) and the subsequent `clearActiveTurn` are not atomic — if a fresh `writeActiveTurn` from the new channel handler completes between those two calls (both async awaits), the recovery loop will delete the new, live entry.
The `processStartedAt` guard at the top of the loop handles the most common case (turns where `startedAt >= processStartedAt`), but is not a complete fence: `writeActiveTurn` uses `Date.now()` at call time, which must be called *after* `processStartedAt` was captured for the guard to fire. If a very fast channel handler writes its turn before the loop reaches that `sessionId`, and the clock hasn't advanced enough, both `turn.startedAt` (stale snapshot) and the fresh entry's `startedAt` could compare equal, causing the guard to pass and the live entry to be silently cleared.
Moving the entire stale-turn recovery block to *before* `startChannels()` — similar to the pending-inbound replay — would eliminate the race entirely without requiring any logic changes.
How can I resolve this? If you propose a fix, please make it concise.There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c4b49d2521
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| // is required at this point. | ||
| try { | ||
| const stateDir = resolveStateDir(process.env); | ||
| const pending = await readPendingInbound(stateDir); |
There was a problem hiding this comment.
Wire pending-inbound writes into the drain path
This startup replay path assumes inbound messages were persisted during shutdown drain, but in this commit there is still no production caller of writePendingInbound (repo-wide search in src/ and extensions/ only finds the declaration/tests). As a result, pending will remain empty here and messages arriving after markGatewayDraining() are still lost across restarts, so the new lossless-drain behavior does not actually activate.
Useful? React with 👍 / 👎.
| // Consume first to prevent infinite retry on crash. | ||
| await clearActiveTurn(stateDir, turn.sessionId); |
There was a problem hiding this comment.
Atomically verify-and-clear stale active turns
The stale-turn check is not atomic: readActiveTurn and clearActiveTurn happen in separate awaited operations, so a new run can write a fresh record for the same sessionId in between (see writeActiveTurn usage in src/agents/pi-embedded-runner/run/attempt.ts). In that interleaving this code can delete the live record after passing the earlier startedAt comparison, which removes crash-recovery coverage for the active turn and can lead to incorrect recovery behavior.
Useful? React with 👍 / 👎.
Summary
Closes and supersedes #41597 (rebased onto current upstream/main).
Adds a pending-inbound store and active-turn tracking to support lossless gateway restarts and crash recovery. When the gateway restarts, messages that were queued before the shutdown are re-delivered, and interrupted turns can be recovered.
Changes
Core infrastructure
src/infra/pending-inbound-store.ts(new): File-backed store with two tables:src/infra/pending-inbound-store.test.ts(new): Full test coverageGateway startup recovery
src/gateway/server-startup.ts: On startup, read pending-inbound store and re-deliver any messages queued before the shutdown; read active-turn records to recover interrupted session stateSupporting changes
src/infra/system-events.ts:ActiveTurnStateevents for turn lifecyclesrc/process/command-queue.ts: Drain lifecycle integrationsrc/infra/json-files.ts: Atomic JSON file helperssrc/agents/pi-embedded-runner/run/attempt.ts: Write active-turn record before run; clear on completionNote
Channel-specific drain routing (telegram topic/replyThreadId passthrough) will follow as a separate commit once ported to the current
extensions/telegram/layout.