Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## 0.7.1 — in development

- Background jobs: after a restart, a slow recovery reply for one job no longer delays monitoring
the other running jobs. Container jobs that finished while the daemon was down retain their
recorded success or failure instead of being reported as an unknown result.

- Audit: saving a changed new-channel, user DM or admin DM default under Conversations →
Templates now records the template, changed field names and signed-in administrator. Restores
are recorded too; unchanged or refused saves do not create a change event. Template values and
Expand Down
10 changes: 7 additions & 3 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -7688,9 +7688,13 @@ A categorized catalog of what's shipped. Cross-linked to `TEST-PLAN.md` checks.
command to the daemon (which outlives the one-shot `claude -p` subprocess); on completion the
daemon re-injects a turn into the same thread (same session resumes with full context) and posts
the continuation — no lost work, no "I'll continue automatically" dead-ends. → TEST-PLAN: Automation.
- Background jobs survive a daemon restart: each job is persisted in SQLite's `bg_jobs` table; on boot
a still-running job is watched to completion, and one that exited while the daemon was down gets a
forced "interrupted by restart" continuation — a thread never silently stalls.
- Background jobs survive a daemon restart: each job is persisted in SQLite's `bg_jobs` table. On
boot, every still-running job is watched before recovery waits for a completion reply or model
continuation from another job. A container job that already exited keeps its recorded success
or failure from its wrapper's durable exit marker. Without that evidence, recovery reports an
unknown result; it never assumes success or reruns the job. Recovery deliveries retain their
ordering for already-finished jobs; live-job completion proceeds independently.
→ TEST-PLAN: Background recovery ordering.
- **Container-only runtime settings.** Settings expose the CLI, image, idle/container limits,
resource caps and optional Full-access home mount. There is no host runtime switch or Claude
subscription-token field. Boundary validation rejects invalid CLI argument values before save.
Expand Down
15 changes: 15 additions & 0 deletions TEST-PLAN.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
# ChannelGate — Test Plan

## Background recovery ordering (0.7.1, 2026-12-05)

- [x] `test/background-recovery-order.test.js`: a blocked continuation for an earlier interrupted
agent does not delay a later live container job's watcher or durable completion outcome. The
later job completes with its actual recorded exit code, delivers once, and is never rerun or
signalled after completion. Already-finished container jobs preserve exit 0 and nonzero exits;
a missing marker remains unknown. The regression failed against the preceding implementation.
- [ ] Live, both Claude and Codex: before an authorized daemon restart, prepare an earlier job
whose recovery continuation takes longer than a later finite container shell. After restart,
verify the later shell is supervised and its completion is recorded while that continuation
is still running; confirm its original process, successful native completion, unchanged
container, no rerun, and cleanup. Also finish a container shell while the daemon is down and
verify its known outcome is preserved after boot. Ordinary restart-survival evidence alone
does not establish this ordering case.

## Protocol hardening from the 2026-12-05 security review (0.7.1, 2026-12-05)

Automated:
Expand Down
25 changes: 17 additions & 8 deletions src/gateway/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -1024,8 +1024,8 @@ export class BackgroundJobs {
// Boot recovery: read the persisted job list and reconcile each against reality.
// - Pending delivery → it finished before the restart but its thread was never told; redeliver.
// - PID still alive AND still ours → the job outlived the restart; watch it, then continue.
// - PID gone (or recycled onto a stranger) → it finished (or died) while the daemon was down;
// force the continuation now with an "interrupted by restart" note so the thread never stalls.
// - PID gone (or recycled onto a stranger) → preserve a verified container exit marker when
// available; otherwise continue with an unknown outcome so the thread never stalls.
async recover() {
try {
await this._recoverJobs();
Expand Down Expand Up @@ -1072,6 +1072,10 @@ export class BackgroundJobs {
try { rec.lease = rec.target.runtime.acquireLease(rec.target, { kind: "job", id: rec.runtime.runId || rec.id }); } catch { /* the watch still runs */ }
}
}
// Establish supervision for every live job before a delivery can await a whole model turn.
// Keep recovery deliveries ordered, but never let an earlier continuation hide later work
// until it exits (or exceeds its cap) without a watcher.
const deliveries = [];
for (const rec of recs) {
// A row that recorded a non-host runtime needs its target rebuilt before anything can be
// asked about it: its pid belonged to a client process that died with the old daemon, and
Expand All @@ -1098,26 +1102,31 @@ export class BackgroundJobs {
}
// The job already ran to completion; only its notice/continuation is outstanding.
await logEvent("bg_recover_redeliver", { id: rec.id, slug: rec.slug, attempts: rec.deliveryAttempts || 0 });
await this._deliver(rec);
deliveries.push(() => this._deliver(rec));
} else if (await this._jobAlive(rec)) {
await logEvent("bg_recover_watch", { id: rec.id, slug: rec.slug, pid: rec.pid, runtime: rec.runtime?.backend || "host" });
// Still running after a restart: live work again, for the egress proxy's swap gate.
rec.releaseLive = markLive({ channelId: rec.channelId, ownerId: rec.authorId, kind: "job", id: rec.runtime?.runId || rec.id, threadKey: rec.settingsThreadKey || rec.threadKey });
// It keeps the lease taken before this loop (the pre-pass above) until _finish.
this._watchByProbe(rec, { recovered: true });
} else {
// Already tracked above, so _finish's guard passes → force the continuation.
await logEvent("bg_recover_interrupted", { id: rec.id, slug: rec.slug });
// A container wrapper may already have completed while the daemon was down. Its
// durable exit marker is the same evidence the live poller uses; a missing marker or
// an unresolvable runtime stays unknown, never an inferred success from a dead pid.
const exitCode = rec.runtimeChild ? parseContainerJobExit(await this._tailFromLog(rec.logFile)) : null;
await logEvent(exitCode == null ? "bg_recover_interrupted" : "bg_recover_finished", { id: rec.id, slug: rec.slug });
const durMs = Date.now() - (rec.startedAt || Date.now());
await this._finish(rec, {
outcome: {
deliveries.push(() => this._finish(rec, {
code: exitCode,
outcome: exitCode != null ? describeProcessOutcome({ code: exitCode }) : {
ok: null,
kind: "restart_unknown",
summary: `was no longer running after the gateway restart, so its result could not be confirmed after ${fmtDur(durMs)}`,
},
});
}));
}
}
for (const deliver of deliveries) await deliver();
}

// Rebuild the runtime target a recovered row was spawned into, so its process group can be
Expand Down
109 changes: 109 additions & 0 deletions test/background-recovery-order.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import test from "node:test";
import assert from "node:assert/strict";
import path from "node:path";
import { mkdirSync, writeFileSync } from "node:fs";
import { ensureTestEnv } from "./helpers.js";

const scratch = ensureTestEnv();
process.env.CG_WORKSPACE_DIR = path.join(scratch, "workspace");
const { BackgroundJobs } = await import("../src/gateway/background.js");
const { getDb } = await import("../src/db/index.js");
const { upsertChannelEntry, saveChannelMeta, setUser } = await import("../src/config/store.js");
const { createFakeRuntimeBackend, fakeTarget, FAKE_CONTAINER } = await import("./runtime-fake.js");

const settle = () => new Promise((resolve) => setTimeout(resolve, 5));
async function waitFor(check, label) {
for (let i = 0; i < 400 && !check(); i++) await settle();
assert.ok(check(), label);
}
function finishEvent(id) {
return getDb().prepare("SELECT data FROM events WHERE event = 'bg_finish' ORDER BY id DESC").all()
.map(({ data }) => JSON.parse(data)).find((event) => event.id === id);
}
async function fixture(suffix) {
getDb().exec("DELETE FROM bg_jobs");
await setUser("U_RECOVERY_JOB", { name: "Recovery user", approved: true, isAdmin: true });
const channelId = "C_RECOVERY_" + suffix;
const entry = await upsertChannelEntry(channelId, { name: "recovery-" + suffix, type: "channel", isDM: false });
const meta = { channelId, autoMode: true, allowBash: true, platform: "slack" };
await saveChannelMeta(entry.slug, meta);
const backend = createFakeRuntimeBackend();
const target = fakeTarget(backend, entry.slug, meta);
mkdirSync(path.join(target.artifactDir, "jobs"), { recursive: true });
const row = (id, runtime = true) => ({
id, kind: "shell", channelId, slug: entry.slug, authorId: "U_RECOVERY_JOB", threadKey: id,
label: id, command: "true", startedAt: Date.now() - 1000, pid: null, maxMs: 60_000,
logFile: path.join(target.artifactDir, "jobs", id + ".log"),
...(runtime ? { runtime: { backend: "container", runId: "job-" + id, container: FAKE_CONTAINER } } : {}),
});
const persist = (rec) => getDb().prepare("INSERT INTO bg_jobs(id, data) VALUES(?, ?)").run(rec.id, JSON.stringify(rec));
return { backend, target, row, persist };
}

test("recovery watches a later live job before waiting for an earlier continuation", async (t) => {
const { backend, target, row, persist } = await fixture("ordering");
const earlier = { ...row("earlier", false), kind: "agent" };
const later = row("later");
writeFileSync(earlier.logFile, "interrupted agent\n");
writeFileSync(later.logFile, "working\n");
persist(earlier); persist(later);
let releaseEarlier, earlierEntered = false;
const held = new Promise((resolve) => { releaseEarlier = resolve; });
const delivered = [];
const jobs = new BackgroundJobs({ resolveTarget: () => target,
runner: async ({ threadKey }) => {
if (threadKey === earlier.threadKey) { earlierEntered = true; await held; }
return { content: "Recovery result", engine: "claude" };
},
deliver: async (_client, payload) => { delivered.push(payload.threadKey); },
});
jobs._client = () => ({ platform: "slack", post: async () => ({ ok: true }) });
t.mock.timers.enable({ apis: ["setInterval"] });
const recovery = jobs.recover();
try {
await waitFor(() => earlierEntered, "earlier continuation entered");
const watchedBeforeRelease = backend.calls.probe.includes("job-later") && Boolean(jobs.jobs.get("later")?.watchTimer);
// The later shell exits while the earlier model turn is still held. Its actual wrapper
// marker is available, so neither its supervision nor its outcome may depend on that turn.
backend.alive = false;
writeFileSync(later.logFile, "completed\n[cg-exit:0]\n");
t.mock.timers.tick(5000);
for (let i = 0; i < 20 && !finishEvent("later"); i++) await settle();
const finishedBeforeRelease = Boolean(finishEvent("later"));
releaseEarlier();
await recovery;
await waitFor(() => finishEvent("later"), "later outcome recorded");
await waitFor(() => delivered.includes("later"), "later result delivered");
assert.equal(finishEvent("later").ok, true, "a completed container job retains its known success");
assert.equal(finishEvent("later").exitCode, 0);
assert.equal(watchedBeforeRelease, true, "live jobs are supervised before a continuation can block recovery");
assert.equal(finishedBeforeRelease, true, "the later result is checkpointed while the earlier continuation is blocked");
assert.equal(delivered.filter((key) => key === "later").length, 1);
assert.equal(backend.calls.spawn.length, 0, "recovery never reruns a job");
assert.deepEqual(backend.calls.signal, [], "a completed job is never signalled");
} finally {
releaseEarlier();
await recovery;
for (const rec of jobs.jobs.values()) { clearInterval(rec.watchTimer); clearInterval(rec.tailTimer); rec.lease?.release(); }
}
});

for (const expected of [0, 23, null]) {
test(`recovery preserves a finished container job's ${expected === null ? "unknown" : expected} exit`, async () => {
const suffix = expected === null ? "missing" : String(expected);
const { backend, target, row, persist } = await fixture(suffix);
const rec = row("finished-" + suffix);
writeFileSync(rec.logFile, "completed\n" + (expected === null ? "" : `[cg-exit:${expected}]\n`));
persist(rec); backend.alive = false;
const jobs = new BackgroundJobs({ resolveTarget: () => target });
jobs._client = () => null; // Keep the durable outcome available until its transport reconnects.
await jobs.recover();
const event = finishEvent(rec.id);
assert.equal(event.exitCode, expected);
assert.equal(event.ok, expected === null ? null : expected === 0);
assert.equal(jobs.jobs.get(rec.id).pendingDelivery.outcome.ok, event.ok);
assert.deepEqual(backend.calls.signal, []);
assert.equal(backend.calls.spawn.length, 0);
assert.ok(backend.calls.leases.every((lease) => lease.released));
});
}
Loading