Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(daemon): require message send reminder choice (#529)

Gustavo Ye27ec2d8e2bc4
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index 9d1d9e2f3..8c6f682be 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -105,7 +105,10 @@ beforeEach(() => {
delete process.env[k];
}
mockArmMessageReminder.mockReset();
- mockArmMessageReminder.mockResolvedValue({ armed: true, dueAt: 123456 });
+ mockArmMessageReminder.mockImplementation(async (input: { remindAfterMs: number }) =>
+ input.remindAfterMs === 0
+ ? { armed: false as const, reason: "disabled" }
+ : { armed: true as const, dueAt: 123456 });
});
afterEach(() => {
cap.restore();
@@ -195,10 +198,15 @@ describe("envelope contract", () => {
}),
}),
);
- const code = await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
+ const code = await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"]);
const env = parseEnvelope(cap.lines());
expect(code).toBe(0);
- expect(env).toEqual({ success: { sent: "/s#0042/general#7" } });
+ expect(env).toEqual({
+ success: {
+ sent: "/s#0042/general#7",
+ reminder: { armed: false, reason: "disabled" },
+ },
+ });
expect("error" in env).toBe(false);
expect("hint" in env).toBe(false); // null fields omitted
});
@@ -259,7 +267,7 @@ describe("channel alignment (message send)", () => {
setApiForTesting(
stubApi({ send: async () => ({ state: "blocked", reason: "unaligned", unreadCount: 3, latestSeq: 12 }) }),
);
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"]);
const env = parseEnvelope(cap.lines());
expect("success" in env).toBe(false);
expect(env.error).toContain("not aligned");
@@ -278,14 +286,34 @@ describe("message send --remind-after", () => {
message: { seq: "#7", channel: "/s#0042/general/#3", sender: "@a", content: { text: "hi" }, time: "" },
};
- it("keeps the no-flag result shape byte-compatible and makes no local arm call", async () => {
- setApiForTesting(stubApi({ send: async () => ok }));
+ it("requires the flag before sending or making a local timer call", async () => {
+ const send = vi.fn(async () => ok);
+ setApiForTesting(stubApi({ send }));
await mainWithStdin(["message", "send", "--target", "/s#0042/general/#3", "--stdin"]);
- expect(parseEnvelope(cap.lines())).toEqual({ success: { sent: "/s#0042/general/#3#7" } });
+ expect(parseEnvelope(cap.lines()).error).toContain("--remind-after");
+ expect(send).not.toHaveBeenCalled();
expect(mockArmMessageReminder).not.toHaveBeenCalled();
});
- it.each(["0m", "25h", "1s", "1.5h"])("rejects invalid duration %s before sending", async (duration) => {
+ it("sends with zero and clears using the server's canonical channel and seq", async () => {
+ setApiForTesting(stubApi({ send: async () => ok }));
+ await mainWithStdin([
+ "message", "send", "--target", "/alias#0042/input", "--stdin", "--remind-after", "0",
+ ]);
+ expect(mockArmMessageReminder).toHaveBeenCalledWith({
+ channel: "/s#0042/general/#3",
+ sentSeq: 7,
+ remindAfterMs: 0,
+ });
+ expect(parseEnvelope(cap.lines())).toEqual({
+ success: {
+ sent: "/s#0042/general/#3#7",
+ reminder: { armed: false, reason: "disabled" },
+ },
+ });
+ });
+
+ it.each(["0m", "0h", "00", "25h", "1s", "1.5h"])("rejects invalid duration %s before sending", async (duration) => {
const send = vi.fn(async () => ok);
setApiForTesting(stubApi({ send }));
await mainWithStdin([
@@ -357,10 +385,12 @@ describe("message send --remind-after", () => {
expect(JSON.stringify(envelope)).not.toContain("vch_secret");
});
- it("documents optional one-shot daemon-lifetime behavior in command help", async () => {
+ it("documents required zero-or-duration daemon-lifetime behavior in command help", async () => {
await main(["message", "send", "-h"]);
const output = cap.lines().join("");
- expect(output).toContain("--remind-after <duration>");
+ expect(output).toContain("--remind-after <0|Nm|Nh>");
+ expect(output).toMatch(/required idle follow-up/);
+ expect(output).toMatch(/0 disables/);
expect(output).toMatch(/daemon\s+restart cancels it/);
});
});
@@ -372,7 +402,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "on it" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--reply", "#37"], "on it");
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0", "--reply", "#37"], "on it");
expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: 37 }));
});
@@ -382,7 +412,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "on it" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--reply", "37"], "on it");
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0", "--reply", "37"], "on it");
expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: 37 }));
});
@@ -392,7 +422,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "hi" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"]);
expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: undefined }));
});
@@ -402,7 +432,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--reply", "x"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0", "--reply", "x"]);
const env = parseEnvelope(cap.lines());
expect(env.error).toContain("--reply must be a message seq");
expect(sendSpy).not.toHaveBeenCalled();
@@ -414,7 +444,7 @@ describe("message send --reply", () => {
message: { seq: "#8", channel: "/s#0042/general", sender: "@a", content: { text: "" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--reply", "0"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0", "--reply", "0"]);
const env = parseEnvelope(cap.lines());
expect(env.error).toContain("--reply must be a message seq");
expect(sendSpy).not.toHaveBeenCalled();
@@ -613,7 +643,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
it("attaches a nonce to the send request", async () => {
const sendSpy = vi.fn(async () => okRes);
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"]);
const arg = sendSpy.mock.calls[0]![0] as { nonce?: string };
expect(typeof arg.nonce).toBe("string");
expect((arg.nonce ?? "").length).toBeGreaterThan(0);
@@ -629,7 +659,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
return okRes;
});
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"]);
const env = parseEnvelope(cap.lines());
expect(env.success.sent).toBe("/s#0042/general#8"); // succeeded, not an error
expect(calls).toBe(2); // retried once
@@ -639,7 +669,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
it("treats a `deduped` success (same-nonce retry matched the committed message) as sent, not an error", async () => {
const sendSpy = vi.fn(async () => ({ ...okRes, deduped: true }));
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"]);
const env = parseEnvelope(cap.lines());
expect(env.success.sent).toBe("/s#0042/general#8");
expect(env.error).toBeUndefined();
@@ -648,7 +678,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
it("does NOT retry a blocked/unaligned business outcome (it's a return, not transient)", async () => {
const sendSpy = vi.fn(async () => ({ state: "blocked" as const, reason: "unaligned" as const, unreadCount: 2, latestSeq: 9 }));
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"]);
const env = parseEnvelope(cap.lines());
expect(env.error).toContain("channel not aligned");
expect(sendSpy).toHaveBeenCalledTimes(1); // no retry on a business outcome
@@ -657,7 +687,7 @@ describe("message send — idempotent retry (mutation-idempotency ②)", () => {
it("does NOT retry a non-transient thrown error (e.g. 4xx), surfaces it once", async () => {
const sendSpy = vi.fn(async () => { throw new Error("reply target #5 not found in /s#0042/general"); });
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"]);
const env = parseEnvelope(cap.lines());
expect(env.error).toContain("reply target");
expect(sendSpy).toHaveBeenCalledTimes(1); // deterministic business error — not retried
@@ -1728,7 +1758,7 @@ describe("message send — literal stdin/file body contract", () => {
}),
);
const literal = ` \`marker\` $(touch ${marker}) \${HOME} ' \\\" \\\\ a\\\\nb\n# markdown\n总部 🎉 \n`;
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"], literal);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"], literal);
expect(sentText).toBe(literal);
expect(fs.existsSync(marker)).toBe(false);
});
@@ -1744,7 +1774,7 @@ describe("message send — literal stdin/file body contract", () => {
return { state: "sent", message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" } };
},
}));
- await main(["message", "send", "--target", "/s#0042/general", "--stdin"], { stdin: input });
+ await main(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"], { stdin: input });
expect(sentText).toBe(literal);
});
@@ -1765,7 +1795,7 @@ describe("message send — literal stdin/file body contract", () => {
},
}),
);
- await main(["message", "send", "--target", "/s#0042/general", "--file", file]);
+ await main(["message", "send", "--target", "/s#0042/general", "--file", file, "--remind-after", "0"]);
fs.rmSync(dir, { recursive: true, force: true });
expect(sentText).toBe(literal);
});
@@ -1773,7 +1803,7 @@ describe("message send — literal stdin/file body contract", () => {
it("rejects --stdin with --file before sending", async () => {
const sendSpy = vi.fn();
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--file", "body.md"]);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0", "--file", "body.md"]);
expect(parseEnvelope(cap.lines()).error).toContain("mutually exclusive");
expect(sendSpy).not.toHaveBeenCalled();
});
@@ -1781,7 +1811,7 @@ describe("message send — literal stdin/file body contract", () => {
it("fails fast when --stdin is attached to a TTY", async () => {
const sendSpy = vi.fn();
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"], "", true);
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"], "", true);
expect(parseEnvelope(cap.lines()).error).toContain("requires piped input");
expect(sendSpy).not.toHaveBeenCalled();
});
@@ -1792,13 +1822,13 @@ describe("message send — literal stdin/file body contract", () => {
message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"], " \n");
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"], " \n");
expect(parseEnvelope(cap.lines()).error).toContain("--stdin");
expect(sendSpy).not.toHaveBeenCalled();
cap.lines().length = 0;
await mainWithStdin(
- ["message", "send", "--target", "/s#0042/general", "--stdin", "--attachment", "att_1"],
+ ["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0", "--attachment", "att_1"],
" \n",
);
expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ content: { text: " \n" } }));
@@ -1810,7 +1840,7 @@ describe("message send — literal stdin/file body contract", () => {
message: { seq: "#1", channel: "/s/c", sender: "@a", content: { text: "" }, time: "" },
}));
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--attachment", "att_1"]);
+ await main(["message", "send", "--target", "/s#0042/general", "--attachment", "att_1", "--remind-after", "0"]);
expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({
content: { text: "" },
attachments: ["att_1"],
@@ -1822,12 +1852,12 @@ describe("message send — literal stdin/file body contract", () => {
const path = await import("path");
const sendSpy = vi.fn();
setApiForTesting(stubApi({ send: sendSpy }));
- await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin"], "");
+ await mainWithStdin(["message", "send", "--target", "/s#0042/general", "--stdin", "--remind-after", "0"], "");
expect(parseEnvelope(cap.lines()).error).toContain("--stdin");
cap.lines().length = 0;
const missing = path.join(os.tmpdir(), `alook-missing-${Date.now()}-${Math.random()}.md`);
- await main(["message", "send", "--target", "/s#0042/general", "--file", missing]);
+ await main(["message", "send", "--target", "/s#0042/general", "--file", missing, "--remind-after", "0"]);
expect(parseEnvelope(cap.lines()).error).toContain("cannot read file");
expect(sendSpy).not.toHaveBeenCalled();
});
@@ -1842,7 +1872,7 @@ describe("message send — literal stdin/file body contract", () => {
it("removes --text from the public parser", async () => {
const sendSpy = vi.fn();
setApiForTesting(stubApi({ send: sendSpy }));
- await main(["message", "send", "--target", "/s#0042/general", "--text", "legacy"]);
+ await main(["message", "send", "--target", "/s#0042/general", "--text", "legacy", "--remind-after", "0"]);
expect(parseEnvelope(cap.lines()).error).toContain("unknown option '--text'");
expect(sendSpy).not.toHaveBeenCalled();
});
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 071754574..b7ad03be1 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -292,10 +292,10 @@ async function sendWithRetry(
}
async function cmdMessageSend(opts: Record<string, unknown>, stdin: CliInputStream): Promise<unknown> {
- const remindAfterFlag = opts.remindAfter as string | undefined;
- // Validate the full duration before any server mutation. A bad opt-in flag
- // must never send a message and then report a local validation failure.
- const remindAfterMs = remindAfterFlag === undefined ? undefined : parseRemindAfter(remindAfterFlag);
+ // Commander enforces presence via requiredOption. Validate the full duration
+ // before any server mutation so a bad value can never send a message first.
+ const remindAfterFlag = opts.remindAfter as string;
+ const remindAfterMs = parseRemindAfter(remindAfterFlag);
const api = getApi();
const agent = agentId(opts);
const channel = opts.target as string;
@@ -361,8 +361,6 @@ async function cmdMessageSend(opts: Record<string, unknown>, stdin: CliInputStre
// SUCCESS — the message is in the channel; surface its canonical ref exactly
// like a fresh send, never as an error.
const sent = `${res.message.channel}${res.message.seq}`;
- if (remindAfterMs === undefined) return { sent };
-
const seqText = res.message.seq.replace(/^#/, "");
const sentSeq = Number(seqText);
if (!/^\d+$/.test(seqText) || !Number.isSafeInteger(sentSeq) || sentSeq < 1) {
@@ -769,9 +767,9 @@ function buildProgram(stdin: CliInputStream): Command {
[] as string[],
)
.option("--reply <seq>", 'reply to a message by its seq in --target (e.g. "#37" or 37)')
- .option(
- "--remind-after <duration>",
- "optionally arm one local follow-up wake after 1m..24h; a newer same-scope message or daemon restart cancels it",
+ .requiredOption(
+ "--remind-after <0|Nm|Nh>",
+ "required idle follow-up: 0 disables; 1m..24h arms/resets one same-scope timer; a newer message or daemon restart cancels it",
)
.exitOverride()
.configureOutput({ writeOut: () => {}, writeErr: () => {} })
diff --git a/src/daemon/src/cli/messageReminderClient.test.ts b/src/daemon/src/cli/messageReminderClient.test.ts
index 4382ef493..c7b5120e8 100644
--- a/src/daemon/src/cli/messageReminderClient.test.ts
+++ b/src/daemon/src/cli/messageReminderClient.test.ts
@@ -19,13 +19,14 @@ function tokenEnv(token = "vch_test_secret"): NodeJS.ProcessEnv {
describe("parseRemindAfter", () => {
it.each([
+ ["0", 0],
["1m", 60_000],
["90m", 5_400_000],
["1h", 3_600_000],
["24h", 86_400_000],
])("parses %s", (value, expected) => expect(parseRemindAfter(value)).toBe(expected));
- it.each(["", "0m", "1s", "1.5h", "25h", "1441m", "-1m", " 1m"])("rejects %j", (value) => {
+ it.each(["", "0m", "0h", "00", "1s", "1.5h", "25h", "1441m", "-1m", " 1m"])("rejects %j", (value) => {
expect(() => parseRemindAfter(value)).toThrow(/--remind-after/);
});
});
diff --git a/src/daemon/src/cli/messageReminderClient.ts b/src/daemon/src/cli/messageReminderClient.ts
index 5248b0bd2..b8b9fad5e 100644
--- a/src/daemon/src/cli/messageReminderClient.ts
+++ b/src/daemon/src/cli/messageReminderClient.ts
@@ -15,14 +15,15 @@ export type LocalMessageReminderResult =
| { armed: false; reason: string };
export function parseRemindAfter(value: string): number {
+ if (value === "0") return 0;
const match = /^(\d+)(m|h)$/.exec(value);
if (!match) {
- throw new Error("message send: --remind-after must be a positive integer followed by m or h (1m..24h)");
+ throw new Error("message send: --remind-after must be 0 or a positive integer followed by m or h (1m..24h)");
}
const amount = Number(match[1]);
const milliseconds = amount * (match[2] === "h" ? 60 * 60_000 : 60_000);
if (!Number.isSafeInteger(milliseconds) || milliseconds < MIN_REMINDER_MS || milliseconds > MAX_REMINDER_MS) {
- throw new Error("message send: --remind-after must be between 1m and 24h");
+ throw new Error("message send: --remind-after must be 0 or between 1m and 24h");
}
return milliseconds;
}
diff --git a/src/daemon/src/cli/messageSendRepositoryContract.test.ts b/src/daemon/src/cli/messageSendRepositoryContract.test.ts
new file mode 100644
index 000000000..96bc6e8db
--- /dev/null
+++ b/src/daemon/src/cli/messageSendRepositoryContract.test.ts
@@ -0,0 +1,152 @@
+import { readdirSync, readFileSync } from "node:fs";
+import { extname, join, relative } from "node:path";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const repositoryRoot = fileURLToPath(new URL("../../../../", import.meta.url));
+const scannedExtensions = new Set([
+ ".bash",
+ ".cjs",
+ ".js",
+ ".json",
+ ".jsonc",
+ ".jsx",
+ ".md",
+ ".mdx",
+ ".mjs",
+ ".sh",
+ ".ts",
+ ".tsx",
+ ".txt",
+ ".yaml",
+ ".yml",
+ ".zsh",
+]);
+const excludedDirectories = new Set([
+ ".git",
+ ".turbo",
+ ".wrangler",
+ "coverage",
+ "dist",
+ "node_modules",
+ "plans",
+]);
+
+const commandWordsPattern = String.raw`message\s+send`;
+
+// These are parser/audit fixtures or explanatory prose, never runnable CLI examples.
+// Keep the allowlist exact so a newly added invocation still has to carry the flag.
+const nonRunnableInvocationAllowlist = new Map<string, RegExp[]>([
+ [
+ "src/daemon/src/manager/managerRuntime.test.ts",
+ [
+ new RegExp(String.raw`input: \{ command: " alook ${commandWordsPattern} @gus hi" \}`),
+ new RegExp(String.raw`extractToolAudit\("Bash", \{ command: " alook\s+${commandWordsPattern}" \}\)`),
+ new RegExp(String.raw`isAlookShellInvocation\(" alook ${commandWordsPattern}"\)`),
+ new RegExp(String.raw`isAlookShellInvocation\("\$\{ALOOK_CLI\} ${commandWordsPattern}"\)`),
+ new RegExp(String.raw`runtime_event.*command: "alook ${commandWordsPattern}"`),
+ ],
+ ],
+ [
+ "src/daemon/src/daemon/createDaemon.ts",
+ [new RegExp(String.raw`Implicit typing\.stop on \`alook ${commandWordsPattern}\``)],
+ ],
+]);
+
+const environmentCliPattern = String.raw`(?:\$ALOOK_CLI|\$\{ALOOK_CLI\}|\$\{CLI\})`;
+const invocationPattern = new RegExp(
+ String.raw`(?:\balook|"${environmentCliPattern}"|${environmentCliPattern})\s+${commandWordsPattern}\b`,
+);
+
+function isMessageSendInvocation(text: string): boolean {
+ return invocationPattern.test(text);
+}
+
+function hasRequiredReminderFlag(text: string): boolean {
+ return text.includes("--remind-after");
+}
+
+function normalizeRepositoryPath(path: string): string {
+ return path.replaceAll("\\", "/");
+}
+
+function repositoryFiles(directory: string): string[] {
+ const files: string[] = [];
+
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
+ if (entry.isSymbolicLink()) continue;
+
+ const absolutePath = join(directory, entry.name);
+ if (entry.isDirectory()) {
+ if (!excludedDirectories.has(entry.name)) files.push(...repositoryFiles(absolutePath));
+ continue;
+ }
+
+ if (entry.isFile() && scannedExtensions.has(extname(entry.name))) files.push(absolutePath);
+ }
+
+ return files;
+}
+
+describe("message send repository contract", () => {
+ const commandWords = ["message", "send"].join(" ");
+ const environmentPrefixes = ["$" + "ALOOK_CLI", "${" + "ALOOK_CLI}", "${" + "CLI}"];
+ const executablePrefixes = ["alook", ...environmentPrefixes.flatMap((prefix) => [prefix, `"${prefix}"`])];
+
+ it.each(executablePrefixes)("recognizes executable prefix %s and enforces the flag", (prefix) => {
+ const missingFlag = `${prefix} ${commandWords} --target /demo#1234/general --stdin`;
+ const withFlag = `${prefix} ${commandWords} --target /demo#1234/general --remind-after 0 --stdin`;
+
+ expect(isMessageSendInvocation(missingFlag)).toBe(true);
+ expect(hasRequiredReminderFlag(missingFlag)).toBe(false);
+ expect(isMessageSendInvocation(withFlag)).toBe(true);
+ expect(hasRequiredReminderFlag(withFlag)).toBe(true);
+ });
+
+ it("does not classify prose or implementation errors as invocations", () => {
+ const nonInvocations = [
+ `Use ${commandWords} when discussing the feature in prose.`,
+ `${commandWords}: --target <ref> is required`,
+ `The community ${commandWords} rate limit is shared.`,
+ ];
+
+ expect(nonInvocations.map(isMessageSendInvocation)).toEqual([false, false, false]);
+ });
+
+ it("normalizes Windows repository paths before exact allowlist matching", () => {
+ expect(normalizeRepositoryPath(String.raw`src\daemon\src\manager\managerRuntime.test.ts`)).toBe(
+ "src/daemon/src/manager/managerRuntime.test.ts",
+ );
+ });
+
+ it("requires --remind-after on every runnable repository invocation", () => {
+ const invocations: Array<{ path: string; line: number; text: string }> = [];
+
+ for (const absolutePath of repositoryFiles(repositoryRoot)) {
+ const path = normalizeRepositoryPath(relative(repositoryRoot, absolutePath));
+
+ for (const [lineIndex, text] of readFileSync(absolutePath, "utf8").split("\n").entries()) {
+ if (isMessageSendInvocation(text)) invocations.push({ path, line: lineIndex + 1, text: text.trim() });
+ }
+ }
+
+ const usedAllowlistEntries = new Set<string>();
+ const missingRequiredFlag = invocations.filter((invocation) => {
+ const allowlist = nonRunnableInvocationAllowlist.get(invocation.path) ?? [];
+ const allowlistIndex = allowlist.findIndex((pattern) => pattern.test(invocation.text));
+ if (allowlistIndex !== -1) {
+ usedAllowlistEntries.add(`${invocation.path}:${allowlistIndex}`);
+ return false;
+ }
+ return !hasRequiredReminderFlag(invocation.text);
+ });
+
+ const unusedAllowlistEntries = [...nonRunnableInvocationAllowlist].flatMap(([path, patterns]) =>
+ patterns.flatMap((_, index) => (usedAllowlistEntries.has(`${path}:${index}`) ? [] : [`${path}:${index}`])),
+ );
+
+ expect(invocations.length).toBeGreaterThan(0);
+ expect(missingRequiredFlag).toEqual([]);
+ expect(unusedAllowlistEntries).toEqual([]);
+ });
+});
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.ts
index 99fe6e286..2cd050b80 100644
--- a/src/daemon/src/credentials/credentialProxy.test.ts
+++ b/src/daemon/src/credentials/credentialProxy.test.ts
@@ -270,6 +270,31 @@ describe("startCredentialProxy (zero-trust end to end)", () => {
expect(onProxyRequest).not.toHaveBeenCalled();
});
+ it("accepts an authenticated zero-duration clear locally", async () => {
+ const upstream = await startUpstream();
+ upstreamClose = upstream.close;
+ const broker = new CredentialBroker({ upstreamBaseUrl: upstream.url });
+ const onMessageReminderArm = vi.fn(async () => ({ armed: false as const, reason: "disabled" }));
+ proxy = await startCredentialProxy(broker, { onMessageReminderArm });
+ const reg = broker.mint("agent-derived", "l", ["send"], REAL_KEY);
+
+ const response = await fetch(`${proxy.url}${LOCAL_MESSAGE_REMINDER_PATH}`, {
+ method: "PUT",
+ headers: { authorization: `Bearer ${reg.voucher}`, "content-type": "application/json" },
+ body: JSON.stringify({ channel: "/s#0042/general", sentSeq: 8, remindAfterMs: 0 }),
+ });
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ armed: false, reason: "disabled" });
+ expect(onMessageReminderArm).toHaveBeenCalledWith({
+ agentId: "agent-derived",
+ channel: "/s#0042/general",
+ sentSeq: 8,
+ remindAfterMs: 0,
+ });
+ expect(upstream.seen).toEqual([]);
+ });
+
it("requires a valid send-capable voucher for the local reminder endpoint", async () => {
const upstream = await startUpstream();
upstreamClose = upstream.close;
@@ -324,6 +349,7 @@ describe("startCredentialProxy (zero-trust end to end)", () => {
JSON.stringify({ ...valid, channel: "/.dm/no-discriminator" }),
JSON.stringify({ ...valid, channel: "/s#0042/general/#0" }),
JSON.stringify({ ...valid, sentSeq: 1.5 }),
+ JSON.stringify({ ...valid, remindAfterMs: -1 }),
JSON.stringify({ ...valid, remindAfterMs: 59_999 }),
JSON.stringify({ ...valid, remindAfterMs: 86_400_001 }),
]) {
diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.ts
index cbfb52d2e..b3b0a8520 100644
--- a/src/daemon/src/credentials/credentialProxy.ts
+++ b/src/daemon/src/credentials/credentialProxy.ts
@@ -409,7 +409,8 @@ function parseLocalMessageReminderBody(body: Buffer, agentId: string): LocalMess
if (!Number.isSafeInteger(record.sentSeq) || (record.sentSeq as number) < 1) return null;
if (
!Number.isSafeInteger(record.remindAfterMs) ||
- (record.remindAfterMs as number) < LOCAL_MESSAGE_REMINDER_MIN_MS ||
+ ((record.remindAfterMs as number) !== 0 &&
+ (record.remindAfterMs as number) < LOCAL_MESSAGE_REMINDER_MIN_MS) ||
(record.remindAfterMs as number) > LOCAL_MESSAGE_REMINDER_MAX_MS
) return null;
return {
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index 43adbc257..47c04cd35 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -464,11 +464,11 @@ for await (const line of createInterface({ input: process.stdin })) {
const timer = timers[index]!;
if (!timer.cancelled) timer.callback();
};
- const arm = (sentSeq: number) =>
+ const arm = (sentSeq: number, remindAfterMs = 60_000) =>
realFetch(`${daemon.proxyUrl}/__alook/local/message-reminder`, {
method: "PUT",
headers: { authorization: "Bearer vch_test", "content-type": "application/json" },
- body: JSON.stringify({ channel: "/demo#1234/general", sentSeq, remindAfterMs: 60_000 }),
+ body: JSON.stringify({ channel: "/demo#1234/general", sentSeq, remindAfterMs }),
});
try {
@@ -491,45 +491,50 @@ for await (const line of createInterface({ input: process.stdin })) {
}));
await arm(8);
+ expect(await (await arm(9, 0)).json()).toEqual({ armed: false, reason: "disabled" });
+ runTimer(1);
+ expect(deliver).toHaveBeenCalledTimes(2);
+
+ await arm(10);
sockets[0]!.emit("message", JSON.stringify({
type: "agent:wake",
agentId: "bot_1",
config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },
launchId: "launch_2",
- unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 9 },
+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 11 },
}));
await new Promise((resolve) => setTimeout(resolve, 0));
- runTimer(1);
+ runTimer(2);
expect(deliver).toHaveBeenCalledTimes(2);
- await arm(10);
+ await arm(12);
sockets[0]!.emit("message", JSON.stringify({
type: "agent:wake",
agentId: "bot_1",
config: { version: 1, runtime: "mock", model: { kind: "default" }, mode: { kind: "default" } },
launchId: "launch_duplicate",
- unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 9 },
+ unreadNotice: { kind: "unread_notice", channel: "/demo#1234/general", latestSeq: 11 },
}));
await new Promise((resolve) => setTimeout(resolve, 0));
- runTimer(2);
+ runTimer(3);
expect(deliver).toHaveBeenCalledTimes(3);
expect(deliver).toHaveBeenLastCalledWith("bot_1", expect.objectContaining({
- text: expect.stringContaining("/demo#1234/general#10"),
+ text: expect.stringContaining("/demo#1234/general#12"),
}));
- await arm(11);
+ await arm(13);
sockets[0]!.emit("message", JSON.stringify({ type: "agent:stop", agentId: "bot_1" }));
- runTimer(3);
+ runTimer(4);
expect(deliver).toHaveBeenCalledTimes(3);
- await arm(12);
+ await arm(14);
sockets[0]!.emit("message", JSON.stringify({ type: "bot:removed", botId: "bot_1" }));
- runTimer(4);
+ runTimer(5);
expect(deliver).toHaveBeenCalledTimes(3);
- await arm(13);
+ await arm(15);
await daemon.stop();
- runTimer(5);
+ runTimer(6);
expect(deliver).toHaveBeenCalledTimes(3);
} finally {
// stop is idempotent enough for the failure path and keeps the loopback
diff --git a/src/daemon/src/daemon/messageReminderScheduler.test.ts b/src/daemon/src/daemon/messageReminderScheduler.test.ts
index bbee5c13e..4a3ba37af 100644
--- a/src/daemon/src/daemon/messageReminderScheduler.test.ts
+++ b/src/daemon/src/daemon/messageReminderScheduler.test.ts
@@ -24,6 +24,45 @@ describe("MessageReminderScheduler", () => {
]);
});
+ it("restarts the countdown when a later send replaces the exact-scope reminder", () => {
+ const deliver = vi.fn();
+ const scheduler = new MessageReminderScheduler({ deliver });
+ scheduler.arm({ agentId: "a1", channel: "/s#0001/a", sentSeq: 1, remindAfterMs: 60_000 });
+
+ vi.advanceTimersByTime(30_000);
+ scheduler.arm({ agentId: "a1", channel: "/s#0001/a", sentSeq: 2, remindAfterMs: 60_000 });
+
+ vi.advanceTimersByTime(30_000);
+ expect(deliver).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(30_000);
+ expect(deliver).toHaveBeenCalledOnce();
+ expect(deliver).toHaveBeenCalledWith("a1", expect.objectContaining({
+ text: expect.stringContaining("/s#0001/a#2"),
+ }));
+ });
+
+ it("zero clears only the exact agent+scope reminder and is idempotent", () => {
+ const deliver = vi.fn();
+ const scheduler = new MessageReminderScheduler({ deliver });
+ scheduler.arm({ agentId: "a1", channel: "/s#0001/a", sentSeq: 1, remindAfterMs: 60_000 });
+ scheduler.arm({ agentId: "a1", channel: "/s#0001/b", sentSeq: 1, remindAfterMs: 60_000 });
+ scheduler.arm({ agentId: "a2", channel: "/s#0001/a", sentSeq: 1, remindAfterMs: 60_000 });
+
+ expect(
+ scheduler.arm({ agentId: "a1", channel: "/s#0001/a", sentSeq: 2, remindAfterMs: 0 }),
+ ).toEqual({ armed: false, reason: "disabled" });
+ expect(
+ scheduler.arm({ agentId: "a1", channel: "/s#0001/a", sentSeq: 2, remindAfterMs: 0 }),
+ ).toEqual({ armed: false, reason: "disabled" });
+
+ vi.advanceTimersByTime(60_000);
+ expect(deliver).toHaveBeenCalledTimes(2);
+ expect(deliver.mock.calls.map((call) => [call[0], call[1].text])).toEqual([
+ ["a1", expect.stringContaining("/s#0001/b#1")],
+ ["a2", expect.stringContaining("/s#0001/a#1")],
+ ]);
+ });
+
it("only a newer wake in the exact same scope cancels", () => {
const deliver = vi.fn();
const scheduler = new MessageReminderScheduler({ deliver });
diff --git a/src/daemon/src/daemon/messageReminderScheduler.ts b/src/daemon/src/daemon/messageReminderScheduler.ts
index ccc135c7e..9d34304f2 100644
--- a/src/daemon/src/daemon/messageReminderScheduler.ts
+++ b/src/daemon/src/daemon/messageReminderScheduler.ts
@@ -9,7 +9,7 @@ export interface MessageReminderArmInput {
export type MessageReminderArmResult =
| { armed: true; dueAt: number }
- | { armed: false; reason: "newer_message_observed" };
+ | { armed: false; reason: "disabled" | "newer_message_observed" };
interface ReminderRecord extends MessageReminderArmInput {
sentRef: string;
@@ -49,6 +49,10 @@ export class MessageReminderScheduler {
arm(input: MessageReminderArmInput): MessageReminderArmResult {
const key = reminderKey(input.agentId, input.channel);
+ if (input.remindAfterMs === 0) {
+ this.clearReminder(key);
+ return { armed: false, reason: "disabled" };
+ }
const latest = this.latestObservedSeq.get(key);
if (latest !== undefined && latest > input.sentSeq) {
return { armed: false, reason: "newer_message_observed" };
diff --git a/src/daemon/src/drivers/systemPrompt.test.ts b/src/daemon/src/drivers/systemPrompt.test.ts
index 11712ceff..b12e22649 100644
--- a/src/daemon/src/drivers/systemPrompt.test.ts
+++ b/src/daemon/src/drivers/systemPrompt.test.ts
@@ -23,6 +23,8 @@ const baseConfig: LaunchConfig = {
* - Only test the INPUT → OUTPUT contract: values that come in via
* `LaunchConfig` must round-trip verbatim into the output, and their
* absence must NOT leak into the output.
+ * - Stable executable CLI grammar is also a contract: generated command
+ * examples may be scanned for required flags without asserting prose.
* - DO NOT ADD tests that assert on specific prompt content (section headings,
* command names, feature strings, tone words). If you find yourself writing
* `expect(prompt).toContain("some english phrase")` for a phrase that isn't
@@ -59,4 +61,13 @@ describe("buildCliSystemPrompt", () => {
expect(withoutRole).not.toContain("You are the onboarding assistant.");
});
+ it("includes the required reminder flag in every generated message-send instruction", () => {
+ const sendLines = buildCliSystemPrompt(baseConfig)
+ .split("\n")
+ .filter((line) => line.includes("message send"));
+
+ expect(sendLines.length).toBeGreaterThan(0);
+ expect(sendLines.filter((line) => !line.includes("--remind-after"))).toEqual([]);
+ });
+
});
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 85cc93cbc..52d76b219 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -107,15 +107,15 @@ function cliCommandsSection(): string {
"",
`1. \`${CLI} inbox pull\` — fetch unread messages (advances your read waterline by default, ` +
`so they won't re-pull; \`--no-ack\` to peek without advancing).`,
- `2. \`${CLI} message send\` — send to a channel, DM, or thread. ` +
+ `2. \`${CLI} message send --remind-after <0|Nm|Nh>\` — send to a channel, DM, or thread. ` +
`For a short body, use explicit \`--stdin\` with a quoted heredoc; for a long or complicated body, ` +
- `use \`--file <path>\`. Attach with \`--attachment <id>\` (repeatable, order matters). Optionally add ` +
- `\`--remind-after <duration>\` to be reminded if the same channel, thread, or DM receives no ` +
- `newer message after your send. Use a whole number of minutes or hours from \`1m\` to \`24h\`, ` +
- `such as \`15m\` or \`2h\`.`,
+ `use \`--file <path>\`. Attach with \`--attachment <id>\` (repeatable, order matters). ` +
+ `\`--remind-after\` is required on every send: use bare \`0\` when no follow-up timer is needed, ` +
+ `or use a whole number of minutes or hours from \`1m\` to \`24h\` (such as \`15m\` or \`2h\`) ` +
+ `to be reminded if that same channel, thread, or DM receives no newer message.`,
`3. \`${CLI} message attachment upload --target <ref> --file <path>\` — upload a file; ` +
`returns an id stable across pending→persisted. Feed it into ` +
- `\`message send --attachment <id>\`.`,
+ `\`message send --remind-after <0|Nm|Nh> --attachment <id>\`.`,
`4. \`${CLI} message attachment download --id <id> [--out <path>]\` — download any ` +
`attachment you can see (or your own pending uploads).`,
`5. \`${CLI} message emoji --target <ref> --emoji <e>\` — react with a single emoji. ` +
@@ -184,17 +184,17 @@ function messagingSection(): string {
"### Sending & receiving",
"",
"You can initiate conversations — send to any channel or DM someone directly. You're not " +
- "limited to replying. Use the same `message send` command whether you're replying or " +
+ "limited to replying. Use the same `message send --remind-after <0|Nm|Nh>` command whether you're replying or " +
"starting a conversation.",
"",
"- Reply where the message came from. Post results in the channel that owns the topic. " +
"When uncertain, read history (below) or DM the relevant people.",
"Free-form message bodies never go in command arguments.",
"",
- `- Short reply: use \`${CLI} message send --target <ref> --stdin\` with the quoted-heredoc form shown ` +
+ `- Short reply: use \`${CLI} message send --target <ref> --remind-after 0 --stdin\` with the quoted-heredoc form shown ` +
"under *Message formatting*. Choose a fresh quoted delimiter that does not occur as a standalone line in the body.",
`- Long or complicated: write the body to a temporary file with a filesystem tool, then ` +
- `\`${CLI} message send --target <ref> --file ./temp_msg.md\`.`,
+ `\`${CLI} message send --target <ref> --remind-after 0 --file ./temp_msg.md\`.`,
`- Cite a specific message: add \`--reply "#37"\` to either form — \`--reply\` takes the \`#N\` seq ` +
"(within `--target`) of the message you're answering.",
"",
@@ -249,7 +249,7 @@ function messagingSection(): string {
"",
"```bash",
"# Choose a fresh quoted delimiter that does not occur as a standalone line in the body.",
- `${CLI} message send --target \"/demo#1234/general\" --stdin <<'ALOOK_MESSAGE_7F3C'`,
+ `${CLI} message send --target \"/demo#1234/general\" --remind-after 0 --stdin <<'ALOOK_MESSAGE_7F3C'`,
"@alice#0001 Please review /demo#1234/general#42",
"ALOOK_MESSAGE_7F3C",
"```",
@@ -279,7 +279,7 @@ function channelTypesSection(): string {
"### Text channels",
"",
"- A text channel is a linear conversation. Send directly to its ref with `message send --target " +
- "/<server>/<channel>`.",
+ "/<server>/<channel> --remind-after 0` when no follow-up timer is needed.",
"- A text-channel message may have a side thread at `/<server>/<channel>/#N`. Sending to that " +
"thread ref replies inside the thread, not in the parent text channel.",
"",
@@ -288,10 +288,10 @@ function channelTypesSection(): string {
"- A forum is a collection of posts, not one linear conversation.",
"- Each top-level message in a forum is a post title. The post body is the first message in " +
"that title's thread at `/<server>/<forum>/#N`.",
- "- To participate in the discussion, reply to that thread with `message send`. Inside the " +
+ "- To participate in the discussion, reply to that thread with `message send --remind-after 0`. Inside the " +
"thread, messaging works like a normal text channel.",
- "- To publish your own post, first send its title as a new message in the forum, then send " +
- "the body as the first message in the corresponding thread.",
+ "- To publish your own post, first send its title as a new message in the forum with " +
+ "`message send --remind-after 0`, then send the body in the corresponding thread with the same required flag.",
].join("\n");
}
@@ -334,13 +334,13 @@ function utilsSection(): string {
"",
"### Follow up when a conversation goes quiet",
"",
- `Use \`message send --remind-after <duration>\` when you send something that may need a later ` +
+ `Use \`message send --remind-after <Nm|Nh>\` when you send something that may need a later ` +
"follow-up — for example, a question, approval request, handoff, or blocker — and silence would " +
"leave the work unfinished. If no newer message appears in that channel, thread, or DM during " +
"the duration, you'll receive a reminder to return and decide what to do next. Don't add it to " +
"ordinary messages that need no follow-up.",
"",
- `Example: ${CLI} message send --target "/demo#1234/team" --remind-after 1m --file ./message.md`,
+ `Example: ${CLI} message send --target "/demo#1234/team" --remind-after 5m --file ./message.md`,
].join("\n");
}
@@ -356,7 +356,7 @@ function criticalRulesSection(): string {
`- **\`${CLI}\` is the only way to communicate.** Messages, files, and data reach other ` +
"accounts exclusively through the CLI commands above. Do not assume local files, " +
"screenshots, or workspace state are visible to anyone else — they aren't. If someone " +
- `needs to see something, send it via \`${CLI} message send\` or \`${CLI} message ` +
+ `needs to see something, send it via \`${CLI} message send --remind-after <0|Nm|Nh>\` or \`${CLI} message ` +
"attachment upload\`.",
"- **Never expose tokens, keys, or secrets.** Redact credential-like strings from tool output " +
"before sharing.",