Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

daemon(cli): C3+C2 — humanize daemon list/stop, wire stop-by-id (cli-humanize charter)

Gusef0e26959ebe
diff --git a/src/daemon/src/cli/daemonList.test.ts b/src/daemon/src/cli/daemonList.test.ts
new file mode 100644
index 000000000..7b707e97e
--- /dev/null
+++ b/src/daemon/src/cli/daemonList.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect, beforeEach, afterEach } from "vitest";
+import * as fs from "fs";
+import * as os from "os";
+import * as path from "path";
+import { daemonList } from "./daemonStart";
+import { renderDaemonList } from "./index";
+
+/*
+ * C3 (plans/daemon-cli-humanize-charter.md): `daemon list` returns an addressing
+ * `id` (= pidfile name, what `daemon stop <id>` eats) + agents/lastActive from
+ * status.json + pid/alive — and NO machine-key/credential. The renderer prints a
+ * human table, not JSON, with the machine key nowhere in sight (red line 2).
+ */
+
+describe("daemonList — C3 fields", () => {
+ let baseDir: string;
+
+ beforeEach(() => {
+ baseDir = fs.mkdtempSync(path.join(os.tmpdir(), "alook-daemonlist-"));
+ });
+ afterEach(() => {
+ fs.rmSync(baseDir, { recursive: true, force: true });
+ });
+
+ it("returns id (pidfile name) + pid + alive, and NEVER the machine key", () => {
+ const daemonsDir = path.join(baseDir, "daemons");
+ fs.mkdirSync(daemonsDir, { recursive: true });
+ // A live daemon: use our own pid (definitely alive).
+ fs.writeFileSync(path.join(daemonsDir, "abc123def456.pid"), JSON.stringify({ pid: process.pid, key: "cmk_super_secret_key" }));
+
+ const list = daemonList({ baseDir });
+ expect(list).toHaveLength(1);
+ expect(list[0]!.id).toBe("abc123def456"); // the pidfile name = the stop id
+ expect(list[0]!.pid).toBe(process.pid);
+ expect(list[0]!.alive).toBe(true);
+ // The credential must not appear anywhere in the returned shape.
+ expect(JSON.stringify(list[0])).not.toContain("cmk_super_secret_key");
+ expect(JSON.stringify(list[0])).not.toContain("secret");
+ });
+
+ it("prunes a dead pidfile and reports nothing alive for it", () => {
+ const daemonsDir = path.join(baseDir, "daemons");
+ fs.mkdirSync(daemonsDir, { recursive: true });
+ // pid 1 is init — process.kill(1, 0) from a normal user throws EPERM, which
+ // isProcessAlive treats as... alive. Use a pid that's almost certainly dead.
+ const deadPid = 2 ** 22; // very unlikely to be a live pid
+ fs.writeFileSync(path.join(daemonsDir, "deadone00000.pid"), JSON.stringify({ pid: deadPid, key: "cmk_x" }));
+
+ const list = daemonList({ baseDir });
+ const dead = list.find((d) => d.id === "deadone00000");
+ if (dead) {
+ expect(dead.alive).toBe(false);
+ expect(dead.agents).toBeNull(); // no live agents attributed to a dead daemon
+ }
+ // pidfile pruned on read
+ expect(fs.existsSync(path.join(daemonsDir, "deadone00000.pid"))).toBe(false);
+ });
+
+ it("empty when no daemons dir", () => {
+ expect(daemonList({ baseDir })).toEqual([]);
+ });
+});
+
+describe("renderDaemonList — human table (C2)", () => {
+ const NOW = 1_000_000_000_000;
+
+ it("prints a table with the ID column and no machine key", () => {
+ const out = renderDaemonList(
+ [{ id: "0ad8e360b064", pid: 39967, alive: true, agents: 8, lastActiveMs: NOW - 12_000 }],
+ NOW,
+ );
+ expect(out).toContain("ID");
+ expect(out).toContain("0ad8e360b064");
+ expect(out).toContain("8"); // agents
+ expect(out).toContain("39967"); // pid
+ expect(out).toContain("running");
+ expect(out).toContain("just now (12s)");
+ expect(out).not.toContain("cmk_");
+ expect(out).not.toContain("cmt_");
+ });
+
+ it("empty state is human, not JSON", () => {
+ const out = renderDaemonList([], NOW);
+ expect(out).toBe("No daemons running on this machine.");
+ });
+
+ it("footnotes the global-status caveat only with >1 daemon (red line 5)", () => {
+ const one = renderDaemonList([{ id: "a", pid: 1, alive: true, agents: 3, lastActiveMs: NOW }], NOW);
+ expect(one).not.toContain("last writer");
+ const two = renderDaemonList(
+ [
+ { id: "a", pid: 1, alive: true, agents: 3, lastActiveMs: NOW },
+ { id: "b", pid: 2, alive: true, agents: 3, lastActiveMs: NOW },
+ ],
+ NOW,
+ );
+ expect(two).toContain("last writer");
+ });
+
+ it("renders — for missing agents/lastActive (dead or no snapshot)", () => {
+ const out = renderDaemonList([{ id: "x", pid: 5, alive: false, agents: null, lastActiveMs: null }], NOW);
+ expect(out).toContain("○ dead");
+ expect(out).toContain("—");
+ });
+});
diff --git a/src/daemon/src/cli/daemonStart.ts b/src/daemon/src/cli/daemonStart.ts
index 01314ac53..1ec064df4 100644
--- a/src/daemon/src/cli/daemonStart.ts
+++ b/src/daemon/src/cli/daemonStart.ts
@@ -30,10 +30,8 @@ const CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server"
const STOP_GRACE_MS = 5000;
/** How often `daemonStop` polls `isProcessAlive` while waiting on SIGTERM. */
const POLL_MS = 100;
-/** How many hex chars of the machine-key SHA-256 make up the pidfile name. */
+/** How many hex chars of the machine-key SHA-256 make up the pidfile name (= the list/stop `id`). */
const MACHINE_KEY_HASH_PREFIX_LEN = 12;
-/** How many chars of the pasted machine key `daemonList` shows as the "keyPrefix". */
-const MACHINE_KEY_DISPLAY_PREFIX_LEN = 20;
function resolveDefaultBaseDir(): string {
const root = process.env.ALOOK_PROJECT_ROOT || path.join(homedir(), ".alook");
@@ -112,10 +110,25 @@ export interface DaemonListOpts {
}
export interface DaemonInfo {
- keyHash: string;
- keyPrefix: string;
+ /**
+ * The daemon's addressing id, shown to humans and passed to `daemon stop
+ * <id>`. It is the pidfile's keyHash name — NOT the machine key (a credential
+ * that must never enter the human operation path, red line 2). list shows it,
+ * stop eats it → the two compose (the whole point of C3).
+ */
+ id: string;
pid: number;
alive: boolean;
+ /**
+ * Agent count + last-activity ms-epoch from status.json (the daemon's
+ * periodic snapshot). NULL when no snapshot yet. CAVEAT (red line 5):
+ * status.json is per-baseDir/GLOBAL, not per-daemon — so these two are
+ * accurate at the common one-daemon-per-machine case; with multiple daemons
+ * sharing a baseDir they reflect the last writer, not this row. The CLI
+ * renderer surfaces that caveat.
+ */
+ agents: number | null;
+ lastActiveMs: number | null;
}
export function daemonList(opts: DaemonListOpts): DaemonInfo[] {
@@ -123,6 +136,12 @@ export function daemonList(opts: DaemonListOpts): DaemonInfo[] {
const dir = daemonsDir(baseDir);
if (!fs.existsSync(dir)) return [];
+ // status.json is per-baseDir (global). Read once; attach to each row with the
+ // documented caveat that it's the last writer, exact only at 1 daemon/baseDir.
+ const status = daemonStatus({ baseDir });
+ const agents = status.found ? status.agents.length : null;
+ const lastActiveMs = status.writtenAt;
+
const files = fs.readdirSync(dir).filter((f) => f.endsWith(".pid"));
const results: DaemonInfo[] = [];
@@ -136,10 +155,11 @@ export function daemonList(opts: DaemonListOpts): DaemonInfo[] {
try { fs.unlinkSync(filePath); } catch { /* ok */ }
}
results.push({
- keyHash: file.replace(".pid", ""),
- keyPrefix: data.key.slice(0, MACHINE_KEY_DISPLAY_PREFIX_LEN) + "…",
+ id: file.replace(".pid", ""),
pid: data.pid,
alive,
+ agents: alive ? agents : null,
+ lastActiveMs: alive ? lastActiveMs : null,
});
}
@@ -206,17 +226,27 @@ export function daemonStatus(opts: DaemonStatusOpts): DaemonStatusResult {
/* ------------------------------------------------------------------ */
export interface DaemonStopOpts {
- machineKey: string;
+ /** Stop by the id shown in `daemon list` (= the pidfile's keyHash name). */
+ id?: string;
+ /** Legacy/programmatic: stop by full machine key (hashed to the pidfile). */
+ machineKey?: string;
baseDir?: string;
}
-export async function daemonStop(opts: DaemonStopOpts): Promise<void> {
- const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
- const pf = pidfilePath(baseDir, opts.machineKey);
+/**
+ * Core stop: SIGTERM → wait for the daemon's own ordered shutdown (stopAll
+ * agent children, close channel/proxy, remove pidfile) → escalate to SIGKILL
+ * only if it overruns the grace window. This kill/teardown semantic is
+ * UNCHANGED by stop-by-id (plans/daemon-cli-humanize-charter.md red line 3) —
+ * only HOW the daemon is addressed changed (id vs machine key resolve to the
+ * same pidfile). `notFoundHint` tailors the "nothing here" message to how the
+ * caller addressed it.
+ */
+async function stopByPidfile(pf: string, notFoundHint: string): Promise<void> {
const data = readPidFile(pf);
if (!data) {
- log.info("no daemon running for this machine key (pidfile not found)");
+ log.info(notFoundHint);
return;
}
if (!isProcessAlive(data.pid)) {
@@ -242,6 +272,25 @@ export async function daemonStop(opts: DaemonStopOpts): Promise<void> {
try { fs.unlinkSync(pf); } catch { /* ok */ }
}
+export async function daemonStop(opts: DaemonStopOpts): Promise<void> {
+ const baseDir = opts.baseDir || process.env.ALOOK_DATA_DIR || DEFAULT_BASE_DIR;
+ // Prefer the id (what `daemon list` shows and a human passes) — it IS the
+ // pidfile's keyHash name, so it resolves directly with no machine key. A
+ // machine key is still accepted for programmatic/legacy callers (hashed to
+ // the same pidfile). The credential never has to enter the human's stop
+ // command (red line 2): `daemon stop <id>`, not `--machine-key <secret>`.
+ if (opts.id) {
+ const pf = path.join(daemonsDir(baseDir), `${opts.id}.pid`);
+ await stopByPidfile(pf, `no daemon with id '${opts.id}' (pidfile not found — check \`alook daemon list\`)`);
+ return;
+ }
+ if (opts.machineKey) {
+ await stopByPidfile(pidfilePath(baseDir, opts.machineKey), "no daemon running for this machine key (pidfile not found)");
+ return;
+ }
+ log.error("daemon stop: an id (from `alook daemon list`) is required");
+}
+
/* ------------------------------------------------------------------ */
/* daemon start */
/* ------------------------------------------------------------------ */
diff --git a/src/daemon/src/cli/daemonStop.test.ts b/src/daemon/src/cli/daemonStop.test.ts
index 1b8930f5c..0ccabfa30 100644
--- a/src/daemon/src/cli/daemonStop.test.ts
+++ b/src/daemon/src/cli/daemonStop.test.ts
@@ -56,4 +56,31 @@ describe("daemonStop — event-loop friendly (no spin loop)", () => {
await exited;
expect(child.exitCode !== null || child.signalCode !== null).toBe(true);
}, 15_000);
+
+ it("stops by ID (the pidfile name shown in `daemon list`) — no machine key needed (C3)", async () => {
+ const child = spawn(process.execPath, ["-e", "setInterval(()=>{}, 1000)"], { stdio: "ignore" });
+ const exited = new Promise<void>((resolve) => child.once("exit", () => resolve()));
+
+ const machineKey = "cmk_secret_should_not_be_needed";
+ const daemonsDir = path.join(baseDir, "daemons");
+ fs.mkdirSync(daemonsDir, { recursive: true });
+ const crypto = await import("crypto");
+ const id = crypto.createHash("sha256").update(machineKey).digest("hex").slice(0, 12);
+ pidfile = path.join(daemonsDir, `${id}.pid`);
+ fs.writeFileSync(pidfile, JSON.stringify({ pid: child.pid, key: machineKey }));
+
+ // Stop using ONLY the id (what `daemon list` shows) — the credential
+ // (machineKey) never enters the call. This is the C3 compose: list shows id,
+ // stop eats id.
+ await daemonStop({ id, baseDir });
+
+ expect(fs.existsSync(pidfile)).toBe(false); // same SIGTERM→cleanup semantic
+ await exited;
+ expect(child.exitCode !== null || child.signalCode !== null).toBe(true);
+ }, 15_000);
+
+ it("stop with an unknown id is a no-op (no throw), points at `daemon list`", async () => {
+ // No pidfile for this id → graceful message, no crash.
+ await expect(daemonStop({ id: "deadbeef0000", baseDir })).resolves.toBeUndefined();
+ });
});
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 6360177d1..db1fe0a09 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -21,7 +21,7 @@ import { pathToFileURL } from "node:url";
import type { ServerApi, Cursor, Message } from "../server/contract.js";
import { parseRef } from "../server/contract.js";
import { proxyServerApiFromEnv } from "./proxyServerApi.js";
-import { daemonStart, daemonStop, daemonList, daemonStatus } from "./daemonStart.js";
+import { daemonStart, daemonStop, daemonList, daemonStatus, type DaemonInfo } from "./daemonStart.js";
import { parseInviteToken } from "@alook/shared/lib/invite-link";
import { MAX_EMOJI_BYTES } from "@alook/shared/constants/community";
import { nowLocalISO, toLocalISO } from "../util/localTime.js";
@@ -63,6 +63,43 @@ function printEnvelope(env: Envelope): void {
process.stdout.write(JSON.stringify(out) + "\n");
}
+/** "just now (12s)" / "3m ago" / "2h ago" — human relative time from an ms epoch. */
+function relTime(ms: number | null, nowMs: number): string {
+ if (ms == null) return "—";
+ const s = Math.max(0, Math.round((nowMs - ms) / 1000));
+ if (s < 60) return `just now (${s}s)`;
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m ago`;
+ return `${Math.round(m / 60)}h ago`;
+}
+
+/**
+ * Render `daemon list` as a human table (C2/C3). Columns: ID (pass to `daemon
+ * stop <id>`), AGENTS + LAST ACTIVE (from the global status.json — accurate at
+ * one-daemon-per-machine, a footnote flags the multi-daemon caveat, red line 5),
+ * PID, STATE. NO machine key / hash prefix (credential stays out of human view).
+ */
+export function renderDaemonList(daemons: DaemonInfo[], nowMs: number = Date.now()): string {
+ if (daemons.length === 0) return "No daemons running on this machine.";
+ const header = ["ID", "AGENTS", "LAST ACTIVE", "PID", "STATE"];
+ const rows = daemons.map((d) => [
+ d.id,
+ d.agents == null ? "—" : String(d.agents),
+ relTime(d.lastActiveMs, nowMs),
+ String(d.pid),
+ d.alive ? "● running" : "○ dead",
+ ]);
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i]!.length)));
+ const fmt = (cols: string[]) => cols.map((c, i) => c.padEnd(widths[i]!)).join(" ");
+ const lines = [fmt(header), ...rows.map(fmt)];
+ // Footnote the global-status caveat only when it could mislead (>1 daemon).
+ if (daemons.length > 1) {
+ lines.push("");
+ lines.push("Note: AGENTS/LAST ACTIVE come from a per-machine snapshot; with multiple daemons they reflect the last writer, not each row.");
+ }
+ return lines.join("\n");
+}
+
/* ------------------------------------------------------------------ */
/* API resolution */
/* ------------------------------------------------------------------ */
@@ -773,15 +810,17 @@ function buildProgram(): Command {
daemon
.command("stop")
- .description("stop the daemon for a specific machine key")
- .requiredOption("--machine-key <key>", "machine key identifying which daemon to stop")
+ .argument("[id]", "daemon id from `alook daemon list` (the ID column)")
+ .description("stop a daemon by its id (from `alook daemon list`)")
+ .option("--machine-key <key>", "legacy: identify the daemon by full machine key instead of id")
.option("--base-dir <path>", "data directory (or ALOOK_DATA_DIR env)")
.exitOverride()
.configureOutput({ writeOut: () => {}, writeErr: () => {} })
- .action(async function (this: Command) {
+ .action(async function (this: Command, id: string | undefined) {
const localOpts = this.opts();
await daemonStop({
- machineKey: localOpts.machineKey as string,
+ id,
+ machineKey: localOpts.machineKey as string | undefined,
baseDir: localOpts.baseDir as string | undefined,
});
});
@@ -795,7 +834,10 @@ function buildProgram(): Command {
.action(function (this: Command) {
const localOpts = this.opts();
const daemons = daemonList({ baseDir: localOpts.baseDir as string | undefined });
- printEnvelope({ success: { daemons } });
+ // `daemon list` is for a HUMAN operator — print a table, not JSON (the
+ // agent-facing commands keep their JSON envelope). The ID column is what
+ // you pass to `daemon stop <id>`.
+ process.stdout.write(renderDaemonList(daemons) + "\n");
});
daemon
diff --git a/src/daemon/src/constants.test.ts b/src/daemon/src/constants.test.ts
index 0b60c0caf..b4aab8ccc 100644
--- a/src/daemon/src/constants.test.ts
+++ b/src/daemon/src/constants.test.ts
@@ -70,13 +70,13 @@ describe("magic-number extractions", () => {
it("MACHINE_KEY_HASH_PREFIX_LEN is set to 12 in cli/daemonStart.ts", () => {
expect(readSrc("cli/daemonStart.ts")).toMatch(/MACHINE_KEY_HASH_PREFIX_LEN\s*=\s*12\b/);
});
-
- it("MACHINE_KEY_DISPLAY_PREFIX_LEN is set to 20 in cli/daemonStart.ts", () => {
- expect(readSrc("cli/daemonStart.ts")).toMatch(/MACHINE_KEY_DISPLAY_PREFIX_LEN\s*=\s*20\b/);
- });
});
describe("deleted symbols stay deleted", () => {
+ it("MACHINE_KEY_DISPLAY_PREFIX_LEN is gone from cli/daemonStart.ts (C3 dropped keyPrefix; list shows no credential)", () => {
+ expect(readSrc("cli/daemonStart.ts")).not.toMatch(/\bMACHINE_KEY_DISPLAY_PREFIX_LEN\b/);
+ });
+
it("readCommandVersion is no longer exported by drivers/probe.ts", () => {
expect(readSrc("drivers/probe.ts")).not.toMatch(/\breadCommandVersion\b/);
});