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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"start": "node --env-file-if-exists=.env src/index.ts",
"dev": "SHUTDOWN_DRAIN_MS=2000 node --env-file-if-exists=.env --watch src/index.ts",
"dev-instance": "bash scripts/dev-instance.sh up",
"dev-instance:no-slack": "bash scripts/dev-instance.sh up --no-slack",
"dev-instance:status": "bash scripts/dev-instance.sh status",
"dev-instance:down": "bash scripts/dev-instance.sh down",
"worker": "node --env-file-if-exists=.env src/runs/worker-main.ts",
Expand Down
88 changes: 66 additions & 22 deletions scripts/dev/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ function parseCli() {
follow: { type: "boolean", short: "f", default: false },
fix: { type: "boolean", default: false },
sandbox: { type: "string", default: "auto" },
"no-slack": { type: "boolean", default: false },
"no-watch": { type: "boolean", default: false },
org: { type: "string" },
},
Expand All @@ -74,13 +75,13 @@ const command = positionals[0] ?? "up";
const store = poolStore();

const commandOptions: Record<string, readonly string[]> = {
up: ["json", "force", "strict", "rotate", "sandbox", "no-watch", "org"],
up: ["json", "force", "strict", "rotate", "sandbox", "no-slack", "no-watch", "org"],
down: ["json"],
status: ["json"],
restart: ["json"],
canary: ["json"],
logs: ["follow"],
doctor: ["json", "fix"],
doctor: ["json", "fix", "no-slack"],
};

const devServiceNames = [...CHILD_ORDER, "web-ui"];
Expand Down Expand Up @@ -115,6 +116,7 @@ function emitJson(payload: unknown): void {
}

const orgId = opts.org ?? process.env.DEV_INSTANCE_ORG_ID ?? "acme";
const withSlack = !opts["no-slack"] && process.env.DEV_INSTANCE_NO_SLACK !== "1";
const devCallerEnv = (): Record<string, string> => ({ ...callerEnvSnapshot(), DEV_INSTANCE_ORG_ID: orgId });

async function legacyTeardown(lease: LeaseInfo): Promise<void> {
Expand Down Expand Up @@ -175,6 +177,22 @@ function claimNext(exclude: Set<string>): string | null {
return null;
}

// Slackless instances need only a port/lock slot, not a provisioned Slack app.
// Prefer slot numbers with no poolN.env so a browser-only instance never squats
// a slot a Slack-enabled worktree could use; fall back to configured ones.
const MAX_PORT_SLOTS = 16; // slotPorts spaces port families 16 apart

function claimPortSlot(exclude: Set<string>): string | null {
const configured = new Set(listSlots(store));
const all = Array.from({ length: MAX_PORT_SLOTS }, (_, i) => `pool${i + 1}`);
const ordered = [...all.filter((s) => !configured.has(s)), ...all.filter((s) => configured.has(s))];
for (const slot of ordered) {
if (exclude.has(slot)) continue;
if (claimSlotLock(slot, store)) return slot;
}
return null;
}

function renderPhase(e: BootPhaseEvent): void {
if (opts.json || e.event !== "phase") return;
let mark = "…";
Expand All @@ -188,7 +206,7 @@ function renderPhase(e: BootPhaseEvent): void {
async function bootOnSlot(slot: string, worktree: string, branch: string): Promise<BootResult> {
const ports = slotPorts(slot);
const lock = lockDir(slot, store);
const tokens = slotTokens(slot, store);
const tokens = withSlack ? slotTokens(slot, store) : null;

writeFileSync(
join(lock, "meta"),
Expand All @@ -200,6 +218,7 @@ async function bootOnSlot(slot: string, worktree: string, branch: string): Promi
`web_port=${ports.web}`,
`admin_port=${ports.admin}`,
`portal_port=${ports.portal}`,
`slack=${withSlack ? "1" : "0"}`,
"booting=1",
`owner_pid=${process.pid}`,
`created_epoch=${nowEpoch()}`,
Expand All @@ -208,11 +227,15 @@ async function bootOnSlot(slot: string, worktree: string, branch: string): Promi
].join("\n"),
);

const swept = await sweepSlackTokenOrphans(tokens.appToken, new Set(), (m) => out(m));
if (swept.swept.length) out(`swept ${swept.swept.length} orphaned process(es) holding ${slot}'s Slack app token`);
if (tokens) {
const swept = tokens?.appToken
? await sweepSlackTokenOrphans(tokens.appToken, new Set(), (m) => out(m))
: { swept: [] as string[] };
if (swept.swept.length) out(`swept ${swept.swept.length} orphaned process(es) holding ${slot}'s Slack app token`);
}

const callerEnv = devCallerEnv();
const canaryChannel = tokens.canaryChannel || callerEnv.DEV_INSTANCE_CANARY_CHANNEL || "";
const canaryChannel = (tokens?.canaryChannel ?? "") || callerEnv.DEV_INSTANCE_CANARY_CHANNEL || "";
writeFileSync(
join(lock, "boot-spec.json"),
JSON.stringify(
Expand All @@ -225,6 +248,7 @@ async function bootOnSlot(slot: string, worktree: string, branch: string): Promi
sandbox: opts.sandbox as "local" | "sprites" | "auto",
canaryChannel,
strict: opts.strict,
slack: withSlack,
},
null,
2,
Expand Down Expand Up @@ -256,7 +280,11 @@ async function bootOnSlot(slot: string, worktree: string, branch: string): Promi
};
}

out(`booting on slot ${slot} (@${tokens.handle || `agent-${slot}`})...`);
out(
tokens
? `booting on slot ${slot} (@${tokens.handle || `agent-${slot}`})...`
: `booting on slot ${slot} (Slack off -- browser only)...`,
);
let result: BootResult | null = null;
await streamBootEvents(sock, (e) => {
renderPhase(e);
Expand All @@ -270,15 +298,18 @@ function printSuccess(result: BootResult, branch: string): void {
const lock = lockDir(result.slot, store);
const meta = readMeta(lock);
out("");
const slackLive = result.slackEnabled !== false;
out(
`[ok] dev instance up -- slot ${result.slot} (VERIFIED: socket exclusive${result.canary ? `, canary ${result.canary.rttMs}ms round trip` : ", delivery unverified -- no canary channel"})`,
slackLive
? `[ok] dev instance up -- slot ${result.slot} (VERIFIED: socket exclusive${result.canary ? `, canary ${result.canary.rttMs}ms round trip` : ", delivery unverified -- no canary channel"})`
: `[ok] dev instance up -- slot ${result.slot} (browser only -- Slack off)`,
);
out(` branch : ${branch}`);
out(` portal : http://localhost:${ports.portal} -> prod-style front door: the assistant at / and /admin`);
out(
` core : http://localhost:${ports.core} (org=${orgId}, session_store=${meta.session_store}, run_store=${meta.run_store})`,
);
out(` slack : @${result.handle} -> mention it in example.slack.com to test`);
if (slackLive) out(` slack : @${result.handle} -> mention it in example.slack.com to test`);
out(` web : http://localhost:${ports.portal}/ (direct: http://localhost:${ports.web})`);
out(` admin : http://localhost:${ports.portal}/admin/ (direct: http://localhost:${ports.admin})`);
out(` logs : ${lock}/{core,web,admin,portal,supervisor}.log`);
Expand Down Expand Up @@ -326,26 +357,33 @@ 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++) {
let slot = claimNext(excluded);
if (!slot && (await reclaimReclaimable())) slot = claimNext(excluded);
let slot = claim();
if (!slot && (await reclaimReclaimable())) slot = claim();
if (!slot && waitMax > 0 && attempt === 1) {
out("");
out(`all pool apps are in use by other worktrees -- waiting up to ${waitMax}s for a free slot.`);
out(
withSlack
? `all pool apps are in use by other worktrees -- waiting up to ${waitMax}s for a free slot.`
: `all local slots are in use by other worktrees -- waiting up to ${waitMax}s for a free one.`,
);
out(` this is normal contention, not an error. held now: ${takenSummary(store)}`);
let waited = 0;
while (waited < waitMax && !slot) {
await sleep(5000);
waited += 5;
await reapStale();
if (await reclaimReclaimable()) slot = claimNext(excluded);
if (!slot) slot = claimNext(excluded);
if (await reclaimReclaimable()) slot = claim();
if (!slot) slot = claim();
}
}
if (!slot) {
emitJson({ ok: false, reason: "no free pool slot", held: takenSummary(store) });
out(
`no free pool app. Another worktree holds each one -- 'dev down' one of them, add a poolN.env, or raise DEV_INSTANCE_WAIT.`,
withSlack
? `no free pool app. Another worktree holds each one -- 'dev down' one of them, add a poolN.env, or raise DEV_INSTANCE_WAIT.`
: `no free local slot. 'dev down' another worktree or raise DEV_INSTANCE_WAIT.`,
);
return EXIT.noFreeSlot;
}
Expand Down Expand Up @@ -404,15 +442,17 @@ async function cmdDown(): Promise<number> {
return EXIT.ok;
}
const slot = mine.slot;
const tokens = slotTokens(slot, store);
const tokens = mine.meta.slack === "0" ? null : slotTokens(slot, store);
await teardownLease(mine);
const residue: string[] = [];
for (const [name, port] of Object.entries(slotPorts(slot))) {
if (name === "supervisor" || name === "prodProxy") continue;
const holders = portHolders(port);
if (holders.length) residue.push(`port ${port} (${name}) still held by pid(s) ${holders.join(",")}`);
}
const swept = await sweepSlackTokenOrphans(tokens.appToken, new Set(), (m) => out(m));
const swept = tokens
? await sweepSlackTokenOrphans(tokens.appToken, new Set(), (m) => out(m))
: { swept: [] as string[] };
if (residue.length) {
emitJson({ ok: false, slot, residue });
out(`[!] down completed with residue:\n ${residue.join("\n ")}`);
Expand All @@ -435,15 +475,19 @@ async function cmdStatus(): Promise<number> {
}
})();
const rows: Record<string, unknown>[] = [];
for (const slot of listSlots(store)) {
const leases = listLeases(store);
const known = [...new Set([...listSlots(store), ...leases.map((l) => l.slot)])].sort(
(a, b) => Number(a.replace(/^pool/, "")) - Number(b.replace(/^pool/, "")),
);
for (const slot of known) {
const lock = lockDir(slot, store);
const ports = slotPorts(slot);
const flag = readSlotFlag(slot, store);
if (!existsSync(lock)) {
rows.push({ slot, state: flag && slotFlagged(slot, store) ? `flagged(${flag.reason})` : "free", ports });
continue;
}
const lease = listLeases(store).find((l) => l.slot === slot);
const lease = leases.find((l) => l.slot === slot);
if (!lease) continue;
const sock = resolveSocketPath(lock);
if (await supervisorReachable(sock)) {
Expand Down Expand Up @@ -511,7 +555,7 @@ async function cmdStatus(): Promise<number> {
}
const taken = rows.filter((r) => r.state !== "free" && !String(r.state).startsWith("flagged")).length;
console.log("");
console.log(`${taken} taken / ${rows.length - taken} free / ${rows.length} pool apps total`);
console.log(`${taken} taken / ${rows.length - taken} free / ${rows.length} slots total`);
console.log("live = supervised + verified. Reclaim never touches a slot with a fresh supervisor heartbeat.");
return EXIT.ok;
}
Expand Down Expand Up @@ -597,10 +641,10 @@ async function main(): Promise<number> {
case "logs":
return await cmdLogs();
case "doctor":
return await runDoctor({ json: opts.json, fix: opts.fix, store });
return await runDoctor({ json: opts.json, fix: opts.fix, store, slack: withSlack });
default:
console.error(
"usage: dev [up|down|status|restart|canary|logs|doctor] [--json] [--force] [--rotate] [--strict] [--sandbox local|sprites|auto] [--no-watch] [--org id] [--fix]",
"usage: dev [up|down|status|restart|canary|logs|doctor] [--json] [--force] [--rotate] [--strict] [--sandbox local|sprites|auto] [--no-slack] [--no-watch] [--org id] [--fix]",
);
return EXIT.usage;
}
Expand Down
83 changes: 46 additions & 37 deletions scripts/dev/commands/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ interface Check {
autoFixable?: boolean;
}

export async function runDoctor(opts: { json: boolean; fix: boolean; store: string }): Promise<number> {
export async function runDoctor(opts: { json: boolean; fix: boolean; store: string; slack: boolean }): Promise<number> {
const checks: Check[] = [];
const worktree = (() => {
try {
Expand All @@ -28,16 +28,23 @@ export async function runDoctor(opts: { json: boolean; fix: boolean; store: stri
}
})();

const mine = worktree ? myLease(worktree, opts.store) : null;
// A browser-only instance (--no-slack, or a live lease booted that way) needs no pool app.
const needsPool = opts.slack && mine?.meta.slack !== "0";
const slots = listSlots(opts.store);
let poolDetail = "Slack off -- no pool slot needed";
if (needsPool) {
poolDetail = slots.length ? `${slots.length} pool slot(s) configured` : "no poolN.env files in the pool store";
}
checks.push({
id: "pool",
ok: slots.length > 0,
severity: "critical",
detail: slots.length ? `${slots.length} pool slot(s) configured` : "no poolN.env files in the pool store",
remedy: slots.length ? undefined : "add poolN.env files (see the dev-instance skill runbook)",
ok: !needsPool || slots.length > 0,
severity: needsPool ? "critical" : "info",
detail: poolDetail,
remedy: needsPool && !slots.length ? "add poolN.env files (see the dev-instance skill runbook)" : undefined,
});

for (const slot of slots) {
for (const slot of needsPool ? slots : []) {
const flag = readSlotFlag(slot, opts.store);
if (flag && slotFlagged(slot, opts.store)) {
checks.push({
Expand All @@ -53,7 +60,6 @@ export async function runDoctor(opts: { json: boolean; fix: boolean; store: stri
}
}

const mine = worktree ? myLease(worktree, opts.store) : null;
if (!mine) {
checks.push({ id: "lease", ok: true, severity: "info", detail: "no dev instance for this worktree" });
} else {
Expand Down Expand Up @@ -83,37 +89,40 @@ export async function runDoctor(opts: { json: boolean; fix: boolean; store: stri
autoFixable: child?.state !== "healthy",
});
}
const slack = status.children.core?.slack;
const conns = slack?.numConnections ?? null;
checks.push({
id: "slack-socket",
ok: conns === 1,
severity: "critical",
detail:
conns === null
? "num_connections unknown (introspection tap degraded)"
: `num_connections=${conns}${slack?.helloHost ? ` (hello host ${slack.helloHost})` : ""}`,
remedy: conns !== null && conns > 1 ? "another live connection is stealing events: dev up --rotate" : undefined,
});
const canary = (await supervisorRequest(sock, "POST", "/canary", {}, 40_000)).body as {
ok: boolean;
rttMs?: number;
reason?: string;
};
const unconfigured = !canary.ok && /no canary channel configured/.test(canary.reason ?? "");
let eventDeliveryRemedy: string | undefined;
if (!canary.ok) {
eventDeliveryRemedy = unconfigured
? "set CANARY_CHANNEL in the slot env (a channel the bot is in), then dev down && dev up"
: "events are not arriving: dev up --rotate (stolen/stale app), or check the slack log";
if (status.slackEnabled !== false) {
const slack = status.children.core?.slack;
const conns = slack?.numConnections ?? null;
checks.push({
id: "slack-socket",
ok: conns === 1,
severity: "critical",
detail:
conns === null
? "num_connections unknown (introspection tap degraded)"
: `num_connections=${conns}${slack?.helloHost ? ` (hello host ${slack.helloHost})` : ""}`,
remedy:
conns !== null && conns > 1 ? "another live connection is stealing events: dev up --rotate" : undefined,
});
const canary = (await supervisorRequest(sock, "POST", "/canary", {}, 40_000)).body as {
ok: boolean;
rttMs?: number;
reason?: string;
};
const unconfigured = !canary.ok && /no canary channel configured/.test(canary.reason ?? "");
let eventDeliveryRemedy: string | undefined;
if (!canary.ok) {
eventDeliveryRemedy = unconfigured
? "set CANARY_CHANNEL in the slot env (a channel the bot is in), then dev down && dev up"
: "events are not arriving: dev up --rotate (stolen/stale app), or check the slack log";
}
checks.push({
id: "event-delivery",
ok: canary.ok,
severity: unconfigured ? "warn" : "critical",
detail: canary.ok ? `canary round trip ${canary.rttMs}ms` : `canary failed: ${canary.reason}`,
remedy: eventDeliveryRemedy,
});
}
checks.push({
id: "event-delivery",
ok: canary.ok,
severity: unconfigured ? "warn" : "critical",
detail: canary.ok ? `canary round trip ${canary.rttMs}ms` : `canary failed: ${canary.reason}`,
remedy: eventDeliveryRemedy,
});
const gitNow = gitHead(worktree);
checks.push({
id: "git-drift",
Expand Down
3 changes: 3 additions & 0 deletions scripts/dev/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export interface BootPhaseEvent {

export interface BootResult {
ok: boolean;
slackEnabled?: boolean;
reason?: string;
slot: string;
handle?: string;
Expand All @@ -94,6 +95,7 @@ export interface StatusReport {
sandbox: { backend: string; detail: string };
durability: { sessionStore: string; runStore: string; databaseUrl: boolean };
harness: string;
slackEnabled: boolean;
watch: boolean;
turnsLive: boolean;
publicApiUrl: string | null;
Expand All @@ -109,6 +111,7 @@ export interface BootSpec {
sandbox: "local" | "sprites" | "auto";
canaryChannel?: string;
strict: boolean;
slack?: boolean;
}

export interface LeaseInfo {
Expand Down
Loading