Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Fix dev idle retirement and slot cleanup (#1079)

Regan Bellb3544a14f12b
diff --git a/.codex/skills/dev-instance/SKILL.md b/.codex/skills/dev-instance/SKILL.md
index 6bfa4332e..fb6d90cf1 100644
--- a/.codex/skills/dev-instance/SKILL.md
+++ b/.codex/skills/dev-instance/SKILL.md
@@ -109,10 +109,12 @@ canary message is deleted right after it round-trips. `CANARY_CHANNEL=<channel i
slot env overrides. With no eligible channel at all, `up` prints `delivery unverified` (or
fails under `--strict`).
-A forgotten instance cleans itself up: after 24 hours with no Slack activity and no CLI control
-actions the supervisor tears itself down and frees the slot
-on its next idle check (every 10 minutes). Health checks, status reads, and automatic
-canaries do not reset the timer. `DEV_INSTANCE_IDLE_HOURS` overrides the timeout; `0` disables it.
+A forgotten instance cleans itself up: after 24 hours with no handled Slack turns,
+interactions, reloads, or restarts, the supervisor tears itself down and frees the slot
+on its next idle check (every 10 minutes). Ambient workspace events, health checks,
+status reads, and canaries (including `dev doctor`) do not reset the timer. This is
+an idle timeout, not a fixed 24-hour lifetime. It only retires instances running this
+supervisor; extra connections on another host must be stopped on that host. `DEV_INSTANCE_IDLE_HOURS` overrides the timeout; `0` disables it.
## Real by Default
diff --git a/scripts/dev/cli.ts b/scripts/dev/cli.ts
index db4474850..9c4e5ae5f 100644
--- a/scripts/dev/cli.ts
+++ b/scripts/dev/cli.ts
@@ -358,7 +358,8 @@ async function cmdUp(): Promise<number> {
const excluded = new Set<string>();
const waitMax = Number(process.env.DEV_INSTANCE_WAIT || 120);
const claim = (): string | null => (withSlack ? claimNext(excluded) : claimPortSlot(excluded));
- for (let attempt = 1; attempt <= 3; attempt++) {
+ const maxAttempts = withSlack ? Math.max(1, listSlots(store).length) : 1;
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
let slot = claim();
if (!slot && (await reclaimReclaimable())) slot = claim();
if (!slot && waitMax > 0 && attempt === 1) {
diff --git a/scripts/dev/lib/proc.ts b/scripts/dev/lib/proc.ts
index d8f3afd9f..e50817227 100644
--- a/scripts/dev/lib/proc.ts
+++ b/scripts/dev/lib/proc.ts
@@ -101,7 +101,7 @@ export function tcpPortOpen(port: number, host = "127.0.0.1", timeoutMs = 500):
}
export function portHolders(port: number): number[] {
- const res = spawnSync("lsof", ["-ti", `tcp:${port}`], { encoding: "utf8" });
+ const res = spawnSync("lsof", ["-nP", "-a", "-ti", `tcp:${port}`, "-sTCP:LISTEN"], { encoding: "utf8" });
if (res.status !== 0 || !res.stdout) return [];
return res.stdout
.split("\n")
diff --git a/scripts/dev/supervisor/main.ts b/scripts/dev/supervisor/main.ts
index 3155378d6..cb36a74d0 100644
--- a/scripts/dev/supervisor/main.ts
+++ b/scripts/dev/supervisor/main.ts
@@ -621,12 +621,13 @@ function serveApi(): Server {
return;
}
const body = await readBody(req);
- if (req.method === "POST") lastControlAt = nowEpoch();
if (req.method === "POST" && req.url === "/reload") {
+ lastControlAt = nowEpoch();
respond(200, await reload(body));
return;
}
if (req.method === "POST" && req.url === "/restart") {
+ lastControlAt = nowEpoch();
const names = (body.children as ChildName[] | undefined) ?? [...children.keys()];
const results: Record<string, unknown> = {};
for (const name of CHILD_ORDER.filter((n) => names.includes(n))) {
diff --git a/src/slack/dev-introspection.ts b/src/slack/dev-introspection.ts
index 8e91f83c3..453f3231c 100644
--- a/src/slack/dev-introspection.ts
+++ b/src/slack/dev-introspection.ts
@@ -96,6 +96,7 @@ export function installDevIntrospection(app: any, opts: DevIntrospectionOptions
state,
markEvent: () => {
state.lastEventAt = now();
+ state.lastActivityAt = state.lastEventAt;
},
ready: (info) => {
state.connectedAs = info.connectedAs;
@@ -142,7 +143,7 @@ function attachRawFrameTap(
const event = frame?.type === "events_api" ? frame.payload?.event : undefined;
const text = event?.subtype === "message_deleted" ? event.previous_message?.text : event?.text;
const isCanary = typeof text === "string" && text.includes(CANARY_PREFIX);
- const isActivity = ["events_api", "interactive", "slash_commands"].includes(frame?.type);
+ const isActivity = ["interactive", "slash_commands"].includes(frame?.type);
if (isActivity && !isCanary) state.lastActivityAt = now();
if (frame?.type !== "events_api" || !isCanary || event?.subtype === "message_deleted") return;
const nonce = text.slice(text.indexOf(CANARY_PREFIX) + CANARY_PREFIX.length).trim();
diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.ts
index ea886de9f..40471c6fe 100644
--- a/src/slack/turn-handler.ts
+++ b/src/slack/turn-handler.ts
@@ -181,6 +181,7 @@ export function createTurnHandler(deps: {
}
async function handleIncoming(inc: Incoming, client: any): Promise<void> {
+ deps.markEvent?.();
const t0 = inc.recvAt ?? performance.now();
const slackInflightMs =
inc.recvWall !== undefined && inc.eventTs !== undefined
@@ -763,7 +764,6 @@ export function createTurnHandler(deps: {
}
: {}),
};
- deps.markEvent?.();
const ran = await dedupedRun(
deduper,
key,
diff --git a/test/dev-supervisor-child.test.ts b/test/dev-supervisor-child.test.ts
index 5f7c9c5cd..d70ed35fa 100644
--- a/test/dev-supervisor-child.test.ts
+++ b/test/dev-supervisor-child.test.ts
@@ -1,11 +1,11 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
-import { createServer } from "node:net";
+import { connect, createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Child } from "../scripts/dev/supervisor/children.ts";
-import { tcpPortOpen } from "../scripts/dev/lib/proc.ts";
+import { portHolders, tcpPortOpen } from "../scripts/dev/lib/proc.ts";
import { sleep } from "../scripts/dev/lib/util.ts";
import type { ChildSpec } from "../scripts/dev/lib/types.ts";
@@ -117,3 +117,30 @@ test("stop escalates to SIGKILL for a TERM-ignoring child", async () => {
assert.ok(Date.now() - before < 8000);
rmSync(lock, { recursive: true, force: true });
});
+
+test("port ownership excludes clients connected to the listener", async () => {
+ const lock = mkdtempSync(join(tmpdir(), "qm-child-"));
+ const port = await freeTcpPort();
+ const child = new Child(
+ spec(lock, port),
+ lock,
+ () => {},
+ () => {},
+ );
+ let client: ReturnType<typeof connect> | undefined;
+ try {
+ assert.equal((await child.start()).ok, true);
+ client = connect(port, "127.0.0.1");
+ await new Promise<void>((resolve, reject) => {
+ client!.once("connect", resolve);
+ client!.once("error", reject);
+ });
+ const holders = portHolders(port);
+ assert.ok(holders.includes(child.proc!.pid!));
+ assert.ok(!holders.includes(process.pid), "the connected client must never be a cleanup target");
+ } finally {
+ client?.destroy();
+ await child.stop();
+ rmSync(lock, { recursive: true, force: true });
+ }
+});
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index 66ebbe751..823733f48 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -104,7 +104,8 @@ test("the persisted assistant entry carries authoritative turn timing for transc
assert.ok(p.workStartedAt! >= before && p.workFinishedAt! >= p.workStartedAt!);
});
-test("org turn wall-clock governance reaches the harness and a per-turn cap only tightens", async () => {
+test("org turn wall-clock governance reaches the harness and a per-turn cap only tightens", async (t) => {
+ t.mock.timers.enable({ apis: ["Date"], now: Date.now() });
const { app, config } = freshApp();
await config.setTurnWallClockSec(scopeId("org", "default-org"), 120);
assert.equal((await app.turn(dm("!wallclock"))).reply, "wallclock:120000");
diff --git a/test/slack-dev-introspection.test.ts b/test/slack-dev-introspection.test.ts
index 88c2123e1..3f1d35564 100644
--- a/test/slack-dev-introspection.test.ts
+++ b/test/slack-dev-introspection.test.ts
@@ -167,13 +167,13 @@ test("canary deletes its posted message after the round trip (and after a timeou
});
});
-test("lastActivityAt tracks real inbound frames but never canary traffic", async () => {
+test("lastActivityAt tracks dispatched turns and interactions but never canary traffic", async () => {
const app = makeApp(async ({ text }) => {
setTimeout(() => emitFrame(app, { type: "events_api", payload: { event: { type: "message", text } } }), 10);
return { ok: true, ts: "1.2" };
});
await withIntrospection(app, async (dev) => {
- emitFrame(app, { type: "events_api", payload: { event: { type: "reaction_added" } } });
+ dev.markEvent();
const afterReaction = dev.state.lastActivityAt;
assert.ok(afterReaction);
emitFrame(app, { type: "interactive", payload: { actions: [{ action_id: "agent_request_approve" }] } });
@@ -192,7 +192,7 @@ test("canary deletion and connection maintenance do not keep an idle slot alive"
const dev = installDevIntrospection(app, { enabled: true, now: () => clock });
assert.ok(dev);
try {
- emitFrame(app, { type: "events_api", payload: { event: { type: "message", text: "hello" } } });
+ dev.markEvent();
assert.equal(dev.state.lastActivityAt, 1000);
clock = 2000;
emitFrame(app, {
@@ -210,7 +210,7 @@ test("canary deletion and connection maintenance do not keep an idle slot alive"
type: "events_api",
payload: { event: { type: "message", subtype: "message_deleted", previous_message: { text: "hello" } } },
});
- assert.equal(dev.state.lastActivityAt, 3000);
+ assert.equal(dev.state.lastActivityAt, 1000);
clock = 4000;
emitFrame(app, { type: "slash_commands", payload: { command: "/qm" } });
assert.equal(dev.state.lastActivityAt, 4000);
@@ -218,3 +218,32 @@ test("canary deletion and connection maintenance do not keep an idle slot alive"
await dev.close();
}
});
+
+test("ambient workspace traffic cannot extend the idle lease", async () => {
+ const app = makeApp();
+ let clock = 1000;
+ const dev = installDevIntrospection(app, { enabled: true, now: () => clock });
+ assert.ok(dev);
+ try {
+ dev.ready({ connectedAs: "qa", botUserId: "BQA", teamId: "TQA" });
+ dev.markEvent();
+ clock += 25 * 60 * 60 * 1000;
+ for (const event of [
+ { type: "message", user: "UHUMAN", text: "unrelated channel chatter" },
+ { type: "message", bot_id: "OTHER", text: "background bot update" },
+ { type: "reaction_added", user: "UHUMAN", item_user: "OTHER" },
+ { type: "user_change", user: { id: "UHUMAN" } },
+ { type: "member_joined_channel", user: "UHUMAN" },
+ ])
+ emitFrame(app, { type: "events_api", payload: { event } });
+ assert.equal(dev.state.lastActivityAt, 1000);
+ assert.equal(dev.state.lastEventAtRaw, clock);
+ emitFrame(app, { type: "events_api", payload: { event: { type: "reaction_added", item_user: "BQA" } } });
+ assert.equal(dev.state.lastActivityAt, 1000);
+ clock += 1000;
+ dev.markEvent();
+ assert.equal(dev.state.lastActivityAt, clock);
+ } finally {
+ await dev.close();
+ }
+});