Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): cite messages via --reply/replyToSeq end-to-end

Gus710867a3a024
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index db7e37690..c7470257f 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -106,6 +106,62 @@ describe("channel alignment (message send)", () => {
});
});
+describe("message send --reply", () => {
+ it("strips a leading # from --reply and forwards replyToSeq", async () => {
+ const sendSpy = vi.fn(async () => ({
+ state: "sent" as const,
+ message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "on it" }, time: "" },
+ }));
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "on it", "--reply", "#37"]);
+ expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: 37 }));
+ });
+
+ it("accepts a bare numeric --reply", async () => {
+ const sendSpy = vi.fn(async () => ({
+ state: "sent" as const,
+ message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "on it" }, time: "" },
+ }));
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "on it", "--reply", "37"]);
+ expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: 37 }));
+ });
+
+ it("omits replyToSeq (undefined) when --reply is absent", async () => {
+ const sendSpy = vi.fn(async () => ({
+ state: "sent" as const,
+ message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "hi" }, time: "" },
+ }));
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "hi"]);
+ expect(sendSpy).toHaveBeenCalledWith(expect.objectContaining({ replyToSeq: undefined }));
+ });
+
+ it("rejects a non-numeric --reply with a CliError, never calling send", async () => {
+ const sendSpy = vi.fn(async () => ({
+ state: "sent" as const,
+ message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "" }, time: "" },
+ }));
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "hi", "--reply", "x"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.error).toContain("--reply must be a message seq");
+ expect(sendSpy).not.toHaveBeenCalled();
+ });
+
+ it("rejects --reply 0 (not a real seq) with a CliError", async () => {
+ const sendSpy = vi.fn(async () => ({
+ state: "sent" as const,
+ message: { seq: "#8", channel: "/s/general", sender: "@a", content: { text: "" }, time: "" },
+ }));
+ setApiForTesting(stubApi({ send: sendSpy }));
+ await main(["message", "send", "--target", "/s/general", "--text", "hi", "--reply", "0"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.error).toContain("--reply must be a message seq");
+ expect(sendSpy).not.toHaveBeenCalled();
+ });
+});
+
describe("inbox pull", () => {
it("acks by default and returns messages in success", async () => {
const ackSpy = vi.fn(async () => undefined);
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index d16242a78..e2198154e 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -153,11 +153,28 @@ async function cmdMessageSend(opts: Record<string, unknown>): Promise<unknown> {
throw new CliError("message send: --text <text>, --file <path>, or --attachment <id> is required");
}
+ // `--reply` accepts the hash form the agent already sees in payloads (`"#37"`)
+ // or a bare number; strip the leading `#` and require a positive integer.
+ let replyToSeq: number | undefined;
+ const replyFlag = opts.reply as string | number | undefined;
+ if (replyFlag !== undefined && replyFlag !== "") {
+ const raw = String(replyFlag).trim();
+ const stripped = raw.startsWith("#") ? raw.slice(1) : raw;
+ // Require a plain decimal seq. `Number("0x25")`/`Number("1e3")` would
+ // otherwise coerce hex/exponential forms to a silently-wrong seq.
+ const n = Number(stripped);
+ if (!/^\d+$/.test(stripped) || !Number.isInteger(n) || n < 1) {
+ throw new CliError('message send: --reply must be a message seq like "#37"');
+ }
+ replyToSeq = n;
+ }
+
const res = await api.send({
agentId: agent,
channel,
content: { text: text ?? "" },
attachments: attachmentIds.length > 0 ? attachmentIds : undefined,
+ replyToSeq,
});
if (res.state === "blocked") {
throw new CliError(
@@ -415,6 +432,7 @@ function buildProgram(): Command {
(v, prev: string[] = []) => [...prev, v],
[] as string[],
)
+ .option("--reply <seq>", 'reply to a message by its seq in --target (e.g. "#37" or 37)')
.exitOverride()
.configureOutput({ writeOut: () => {}, writeErr: () => {} })
.action(async function (this: Command) {
diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.ts
index 67b3aa8dc..8febf0fe1 100644
--- a/src/daemon/src/cli/proxyServerApi.test.ts
+++ b/src/daemon/src/cli/proxyServerApi.test.ts
@@ -127,6 +127,25 @@ describe("createProxyServerApi — reactAdd", () => {
});
});
+describe("createProxyServerApi — send forwards replyToSeq", () => {
+ it("POSTs replyToSeq in the body (agentId stripped, replyToSeq retained)", async () => {
+ const seen: Array<{ url: string; init?: RequestInit }> = [];
+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {
+ seen.push({ url, init });
+ return jsonBody(
+ JSON.stringify({ state: "sent", message: { seq: "#8", channel: "/demo/general", sender: "@a", content: { text: "on it" }, time: "" } }),
+ { status: 200 },
+ );
+ });
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ await api.send({ agentId: "a1", channel: "/demo/general", content: { text: "on it" }, replyToSeq: 37 });
+ expect(seen[0].url).toBe("http://proxy.test/api/send");
+ const body = JSON.parse(String(seen[0].init?.body ?? "{}"));
+ expect(body.replyToSeq).toBe(37);
+ expect(body.agentId).toBeUndefined();
+ });
+});
+
describe("createProxyServerApi — callUpload via parseJsonResponse", () => {
it("throws 'non-JSON body' on empty 500", async () => {
const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 6ab4bde9d..e2b341d8e 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -162,6 +162,8 @@ function messagingSection(): string {
"When uncertain, read history (below) or DM the relevant people.",
`- Short reply: \`${CLI} message send --target <ref> --text "brief reply"\`.`,
`- Long or complicated: write body to a tmp file, then \`${CLI} message send --target <ref> --file ./temp_msg.md\`.`,
+ `- Cite a specific message: \`${CLI} message send --target <ref> --reply "#37" --text "on it"\` — ` +
+ "`--reply` takes the `#N` seq (within `--target`) of the message you're answering.",
"",
"### Channel refs",
"",
@@ -213,10 +215,13 @@ function messagingSection(): string {
"",
"```json",
'{"seq": "#3", "channel": "/demo/general", "sender": "@gustavo#4821", "content": {"text": "hello"}, "time": "2026-06-01T12:00:00Z"}',
+ '{"seq": "#42", "channel": "/demo/general", "sender": "@gustavo#4821", "content": {"text": "yes, ship it", "replyTo": {"seq": "#37", "sender": "@ana#0012"}}, "time": "2026-06-01T12:01:00Z"}',
"```",
"",
"`channel` is the reply ref. `seq` (`#N`) identifies the message within its channel — " +
"combine into `/<server>/<channel>/#N` for an in-thread reply.",
+ "`content.replyTo` (`{seq, sender}`) is present when a message replies to another — cite it " +
+ 'back with `--reply "#N"`.',
].join("\n");
}
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index 3d14d9a98..728391dbe 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -175,10 +175,26 @@ export interface AgentAttachmentRef {
size: number | null;
}
+/** Cited message preview on a reply — seq + sender only, no body. */
+export interface ReplyRef {
+ /** Display form "#N" — matches `Message.seq` (string), NOT the numeric `Seq`. */
+ seq: string;
+ /** Sender global handle (`name#0042`), e.g. "@ana#0012". */
+ sender: string;
+}
+
export interface MessageContent {
text: string;
/** Populated only on the read side (`inboxPull`, `send` response, `resolve`). */
attachments?: AgentAttachmentRef[];
+ /**
+ * Present only on the read side, and only when this message replies to an
+ * in-scope, non-deleted message. Lives inside `content` alongside
+ * `text`/`attachments`. On the write side the reply intent travels as the
+ * top-level `SendRequest.replyToSeq`, not here — the route ignores any
+ * `content.replyTo` on input.
+ */
+ replyTo?: ReplyRef;
/** Future: embeds, etc. — added without breaking `text`. */
[extra: string]: unknown;
}
@@ -300,6 +316,13 @@ export interface SendRequest {
* can't render it moot.
*/
seenUpToSeq?: Seq;
+ /**
+ * Seq (within `channel`) of the message this send replies to. The route
+ * resolves it to the target's message id — scope-first, within `channel`
+ * only — and stores it as `replyToId`. A seq with no matching message in
+ * scope is rejected 400 (no cross-scope citing).
+ */
+ replyToSeq?: Seq;
}
/**
diff --git a/src/shared/src/db/queries/community/agent-inbox.ts b/src/shared/src/db/queries/community/agent-inbox.ts
index d59588a69..36a13ddcd 100644
--- a/src/shared/src/db/queries/community/agent-inbox.ts
+++ b/src/shared/src/db/queries/community/agent-inbox.ts
@@ -26,12 +26,15 @@ import {
DM_SERVER,
type AgentAttachmentRef,
type Message,
+ type MessageContent,
+ type ReplyRef,
type Seq,
type ChannelRef,
} from "../../../community-cli-contract";
import { formatHandle } from "../../../lib/discriminator";
import { listVisibleChannelIdsForUser } from "./channel";
import { listParticipatingThreadIds } from "./thread";
+import { getMessagesByIdsInScope, type MessageScope } from "./message";
import { isThread, isForumPost } from "../../../utils/community-roles";
type RawAgentMessage = {
@@ -42,6 +45,7 @@ type RawAgentMessage = {
channelId: string | null;
dmConversationId: string | null;
seq: number;
+ replyToId: string | null;
};
const AGENT_MESSAGE_COLUMNS = {
@@ -52,6 +56,7 @@ const AGENT_MESSAGE_COLUMNS = {
channelId: communityMessage.channelId,
dmConversationId: communityMessage.dmConversationId,
seq: communityMessage.seq,
+ replyToId: communityMessage.replyToId,
} as const;
/** One entry per distinct scope (channel or DM) needing a `ChannelRef`. */
@@ -187,12 +192,13 @@ export async function toAgentMessages(
): Promise<Message[]> {
if (rows.length === 0) return [];
- const [refs, users] = await Promise.all([
+ const [refs, users, replyByMessageId] = await Promise.all([
resolveScopeRefs(db, rows, viewerId),
db
.select({ id: user.id, name: user.name, discriminator: user.discriminator })
.from(user)
.where(inArray(user.id, [...new Set(rows.map((r) => r.authorId))])),
+ resolveReplyRefs(db, rows),
]);
const userById = new Map(users.map((u) => [u.id, u]));
@@ -204,16 +210,72 @@ export async function toAgentMessages(
// Absent (not empty array) when a message has no attachments — smaller
// wire payload; documented invariant in the plan.
const atts = attachmentsByMessageId?.get(r.id);
+ const content: MessageContent = { text: r.content };
+ if (atts && atts.length > 0) content.attachments = atts;
+ const replyTo = r.replyToId ? replyByMessageId.get(r.replyToId) : undefined;
+ if (replyTo) content.replyTo = replyTo;
return {
seq: formatSeq(r.seq),
channel,
sender: `@${sender}`,
- content: atts && atts.length > 0 ? { text: r.content, attachments: atts } : { text: r.content },
+ content,
time: r.createdAt,
};
});
}
+/**
+ * Resolve each row's `replyToId` into a `ReplyRef` ({ seq, sender }) — the
+ * cited-message preview surfaced inside `content.replyTo`. Scope-first: a
+ * `replyToId` is only ever resolved WITHIN its own row's channel/DM (via
+ * `getMessagesByIdsInScope`), so a cite can never leak a message from another
+ * scope. Rows are grouped by scope and one batch query runs per distinct
+ * scope. Targets with `seq <= 0` (legacy sentinel rows) are dropped — they'd
+ * otherwise emit a bogus `"#0"`. Returns a map keyed by `replyToId`; a
+ * `replyToId` absent from the map (deleted / out-of-scope / seq 0) means the
+ * caller omits `replyTo` entirely.
+ */
+async function resolveReplyRefs(
+ db: Database,
+ rows: RawAgentMessage[]
+): Promise<Map<string, ReplyRef>> {
+ // Group each row's replyToId by the row's OWN scope (channel or DM).
+ const idsByScope = new Map<string, { scope: MessageScope; ids: Set<string> }>();
+ for (const r of rows) {
+ if (!r.replyToId) continue;
+ const scope: MessageScope | null = r.channelId
+ ? { channelId: r.channelId }
+ : r.dmConversationId
+ ? { dmConversationId: r.dmConversationId }
+ : null;
+ if (!scope) continue;
+ const key = scopeRefKey(r);
+ let bucket = idsByScope.get(key);
+ if (!bucket) {
+ bucket = { scope, ids: new Set<string>() };
+ idsByScope.set(key, bucket);
+ }
+ bucket.ids.add(r.replyToId);
+ }
+ if (idsByScope.size === 0) return new Map();
+
+ const perScope = await Promise.all(
+ [...idsByScope.values()].map((b) => getMessagesByIdsInScope(db, [...b.ids], b.scope))
+ );
+
+ const out = new Map<string, ReplyRef>();
+ for (const targets of perScope) {
+ for (const t of targets) {
+ if (t.seq <= 0) continue;
+ out.set(t.id, {
+ seq: formatSeq(t.seq),
+ sender: `@${formatHandle(t.authorName, t.discriminator)}`,
+ });
+ }
+ }
+ return out;
+}
+
/**
* Strict single-scope ref resolver for `UnreadNotice.channel`
* (`buildUnreadWakeCommand`, minimal-wake-queue-unread-notice plan §4). Unlike
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 455e3f6f6..8410a61b0 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -815,6 +815,7 @@ export async function getMessageByChannelAndSeq(
channelId: communityMessage.channelId,
dmConversationId: communityMessage.dmConversationId,
seq: communityMessage.seq,
+ replyToId: communityMessage.replyToId,
})
.from(communityMessage)
.where(and(scopeCond, eq(communityMessage.seq, seq)));
@@ -1008,10 +1009,12 @@ export async function getMessagesByIdsInScope(db: Database, ids: string[], scope
replyToId: communityMessage.replyToId,
embeds: communityMessage.embeds,
flags: communityMessage.flags,
+ seq: communityMessage.seq,
createdAt: communityMessage.createdAt,
channelId: communityMessage.channelId,
dmConversationId: communityMessage.dmConversationId,
authorName: user.name,
+ discriminator: user.discriminator,
authorEmail: user.email,
authorImage: user.image,
})
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 54f27eb58..7a7682c2b 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1128,6 +1128,7 @@ export const CommunityAgentSendRequestSchema = z
.max(MAX_ATTACHMENTS_PER_MESSAGE)
.default([]),
seenUpToSeq: CommunityAgentSeqSchema.optional(),
+ replyToSeq: CommunityAgentPositiveSeqSchema.optional(),
})
.refine(
(d) => d.content.text.trim().length > 0 || d.attachments.length > 0,
diff --git a/src/shared/test/queries/community-agent-inbox.test.ts b/src/shared/test/queries/community-agent-inbox.test.ts
index 8cc80a081..15a517160 100644
--- a/src/shared/test/queries/community-agent-inbox.test.ts
+++ b/src/shared/test/queries/community-agent-inbox.test.ts
@@ -52,6 +52,7 @@ function rawMsg(overrides: Partial<Record<string, unknown>> = {}) {
channelId: "ch_1",
dmConversationId: null,
seq: 1,
+ replyToId: null,
...overrides,
};
}
@@ -144,6 +145,148 @@ describe("toAgentMessages", () => {
const [msg] = await agentInbox.toAgentMessages(db, [rawMsg({ authorId: "u_ghost" })], "viewer_1");
expect(msg!.sender).toBe("@u_ghost");
});
+
+ it("read/resolvable: a channel reply gets content.replyTo = { seq, sender } from the in-scope target", async () => {
+ // Call order (synchronous phase): 0 channels, 1 author names, 2 reply-scope
+ // getMessagesByIdsInScope query; then (post-await) 3 servers.
+ const db = createSequentialDb([
+ [{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [{ id: "m_target", seq: 37, authorName: "Ana", discriminator: "0012" }],
+ [{ id: "srv_1", name: "studio" }],
+ ]);
+ const [msg] = await agentInbox.toAgentMessages(
+ db,
+ [rawMsg({ replyToId: "m_target" })],
+ "viewer_1"
+ );
+ expect(msg!.content.replyTo).toEqual({ seq: formatSeq(37), sender: "@Ana#0012" });
+ });
+
+ it("read/DM scope: a DM reply resolves the peer's seq + handle correctly", async () => {
+ // Call order: 0 dms, 1 author names, 2 reply-scope query, 3 DM-peer lookup.
+ const db = createSequentialDb([
+ [{ id: "dm_1", user1Id: "viewer_1", user2Id: "peer_1" }],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [{ id: "m_target", seq: 8, authorName: "Bob", discriminator: "9999" }],
+ [{ id: "peer_1", name: "Bob", discriminator: "9999" }],
+ ]);
+ const [msg] = await agentInbox.toAgentMessages(
+ db,
+ [rawMsg({ channelId: null, dmConversationId: "dm_1", replyToId: "m_target" })],
+ "viewer_1"
+ );
+ expect(msg!.content.replyTo).toEqual({ seq: formatSeq(8), sender: "@Bob#9999" });
+ });
+
+ it("read/deleted target: replyToId with no in-scope target → replyTo absent (no sentinel)", async () => {
+ const db = createSequentialDb([
+ [{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [], // target row deleted / not returned
+ [{ id: "srv_1", name: "studio" }],
+ ]);
+ const [msg] = await agentInbox.toAgentMessages(
+ db,
+ [rawMsg({ replyToId: "m_gone" })],
+ "viewer_1"
+ );
+ expect(msg!.content).not.toHaveProperty("replyTo");
+ });
+
+ it("read/out-of-scope target: scope-first query returns nothing → replyTo absent", async () => {
+ // getMessagesByIdsInScope scopes on the ROW's own channel; a target that
+ // lives in another channel simply doesn't come back in the batch.
+ const db = createSequentialDb([
+ [{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [], // target is in a different channel → not returned by the scoped query
+ [{ id: "srv_1", name: "studio" }],
+ ]);
+ const [msg] = await agentInbox.toAgentMessages(
+ db,
+ [rawMsg({ replyToId: "m_elsewhere" })],
+ "viewer_1"
+ );
+ expect(msg!.content).not.toHaveProperty("replyTo");
+ });
+
+ it("read/seq-0 target: replyToId → a legacy seq 0 row → replyTo absent", async () => {
+ const db = createSequentialDb([
+ [{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [{ id: "m_legacy", seq: 0, authorName: "Ana", discriminator: "0012" }],
+ [{ id: "srv_1", name: "studio" }],
+ ]);
+ const [msg] = await agentInbox.toAgentMessages(
+ db,
+ [rawMsg({ replyToId: "m_legacy" })],
+ "viewer_1"
+ );
+ expect(msg!.content).not.toHaveProperty("replyTo");
+ });
+
+ it("read/non-reply: replyToId null → no replyTo key and no extra reply query", async () => {
+ // Only 3 selects (channels, authors, servers) — resolveReplyRefs returns
+ // early with no db call when no row carries a replyToId.
+ const db = createSequentialDb([
+ [{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [{ id: "srv_1", name: "studio" }],
+ ]);
+ const [msg] = await agentInbox.toAgentMessages(db, [rawMsg()], "viewer_1");
+ expect(msg!.content).not.toHaveProperty("replyTo");
+ expect(db.select).toHaveBeenCalledTimes(3);
+ });
+
+ it("read/cited-author-not-in-batch: sender comes from the scoped target row, not the batch", async () => {
+ // The only row's author is u_1/Alice; the cited target's author is Ana,
+ // who authored no row in this batch. replyTo.sender must still resolve to
+ // Ana's handle — proving it's read off getMessagesByIdsInScope, not the
+ // `users` batch lookup.
+ const db = createSequentialDb([
+ [{ id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null }],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [{ id: "m_target", seq: 4, authorName: "Ana", discriminator: "0012" }],
+ [{ id: "srv_1", name: "studio" }],
+ ]);
+ const [msg] = await agentInbox.toAgentMessages(
+ db,
+ [rawMsg({ replyToId: "m_target" })],
+ "viewer_1"
+ );
+ expect(msg!.content.replyTo?.sender).toBe("@Ana#0012");
+ });
+
+ it("read/cross-scope batch: two channels each with a reply resolve within their own scope", async () => {
+ // Two rows in two channels, each replying to a target in its OWN channel.
+ // resolveReplyRefs groups by scope and issues one query per scope.
+ // Sync call phase: 0 channels, 1 authors, 2 reply-scope(ch_1), 3
+ // reply-scope(ch_2); then 4 servers.
+ const db = createSequentialDb([
+ [
+ { id: "ch_1", name: "general", serverId: "srv_1", parentChannelId: null, parentMessageId: null },
+ { id: "ch_2", name: "random", serverId: "srv_1", parentChannelId: null, parentMessageId: null },
+ ],
+ [{ id: "u_1", name: "Alice", discriminator: "1234" }],
+ [{ id: "t_1", seq: 11, authorName: "Ana", discriminator: "0012" }],
+ [{ id: "t_2", seq: 22, authorName: "Ben", discriminator: "3456" }],
+ [{ id: "srv_1", name: "studio" }],
+ ]);
+ const msgs = await agentInbox.toAgentMessages(
+ db,
+ [
+ rawMsg({ id: "m_a", channelId: "ch_1", replyToId: "t_1" }),
+ rawMsg({ id: "m_b", channelId: "ch_2", replyToId: "t_2" }),
+ ],
+ "viewer_1"
+ );
+ const byChannel = new Map(msgs.map((m) => [m.channel, m]));
+ expect(byChannel.get(formatRef({ server: "studio", channel: "general" }))!.content.replyTo)
+ .toEqual({ seq: formatSeq(11), sender: "@Ana#0012" });
+ expect(byChannel.get(formatRef({ server: "studio", channel: "random" }))!.content.replyTo)
+ .toEqual({ seq: formatSeq(22), sender: "@Ben#3456" });
+ });
});
describe("toAgentMessage", () => {
diff --git a/src/shared/test/schemas/community-agent-send.test.ts b/src/shared/test/schemas/community-agent-send.test.ts
new file mode 100644
index 000000000..88625fd26
--- /dev/null
+++ b/src/shared/test/schemas/community-agent-send.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect } from "vitest";
+import { CommunityAgentSendRequestSchema } from "../../src/schemas";
+
+describe("CommunityAgentSendRequestSchema — replyToSeq", () => {
+ it("accepts a valid positive replyToSeq", () => {
+ const parsed = CommunityAgentSendRequestSchema.safeParse({
+ channel: "/studio/general",
+ content: { text: "on it" },
+ replyToSeq: 37,
+ });
+ expect(parsed.success).toBe(true);
+ if (parsed.success) expect(parsed.data.replyToSeq).toBe(37);
+ });
+
+ it("is optional — a send with no replyToSeq still parses", () => {
+ const parsed = CommunityAgentSendRequestSchema.safeParse({
+ channel: "/studio/general",
+ content: { text: "hi" },
+ });
+ expect(parsed.success).toBe(true);
+ if (parsed.success) expect(parsed.data.replyToSeq).toBeUndefined();
+ });
+
+ it("rejects replyToSeq = 0 (min(1) — 0 is the legacy sentinel, never a real message)", () => {
+ const parsed = CommunityAgentSendRequestSchema.safeParse({
+ channel: "/studio/general",
+ content: { text: "hi" },
+ replyToSeq: 0,
+ });
+ expect(parsed.success).toBe(false);
+ });
+
+ it("rejects a negative replyToSeq", () => {
+ const parsed = CommunityAgentSendRequestSchema.safeParse({
+ channel: "/studio/general",
+ content: { text: "hi" },
+ replyToSeq: -3,
+ });
+ expect(parsed.success).toBe(false);
+ });
+
+ it("rejects a non-integer replyToSeq", () => {
+ const parsed = CommunityAgentSendRequestSchema.safeParse({
+ channel: "/studio/general",
+ content: { text: "hi" },
+ replyToSeq: 3.5,
+ });
+ expect(parsed.success).toBe(false);
+ });
+});
diff --git a/src/web/src/app/api/community/agent/resolve/route.test.ts b/src/web/src/app/api/community/agent/resolve/route.test.ts
index 72fd531a7..569aee3e7 100644
--- a/src/web/src/app/api/community/agent/resolve/route.test.ts
+++ b/src/web/src/app/api/community/agent/resolve/route.test.ts
@@ -142,4 +142,23 @@ describe("POST /api/community/agent/resolve", () => {
const res = await POST(req({ channel: "/.dm/peer_1", seq: 2 }, { Authorization: "Bearer crk_abc" }))
expect(res.status).toBe(400)
})
+
+ it("read/resolve-route parity: the reply row's replyToId is threaded into toAgentMessage (guards the getMessageByChannelAndSeq projection)", async () => {
+ mockResolveServerByNameForMember.mockResolvedValue([{ id: "srv_1" }])
+ mockResolveChannelByNameForMember.mockResolvedValue([{ id: "ch_1" }])
+ mockGetChannelForMember.mockResolvedValue({ id: "ch_1", serverId: "srv_1", parentChannelId: null })
+ // getMessageByChannelAndSeq now projects replyToId (see message.ts) — the
+ // route feeds this row straight into toAgentMessage, which surfaces
+ // content.replyTo. If replyToId were dropped from the projection this row
+ // wouldn't carry it (and TS would fail to compile RawAgentMessage).
+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_1", seq: 42, content: "yes", replyToId: "m_target" })
+ const res = await POST(req({ channel: "/studio/general", seq: 42 }, { Authorization: "Bearer crk_abc" }))
+ expect(res.status).toBe(200)
+ expect(mockToAgentMessage).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ replyToId: "m_target" }),
+ "bot_1",
+ expect.anything()
+ )
+ })
})
diff --git a/src/web/src/app/api/community/agent/send/route.test.ts b/src/web/src/app/api/community/agent/send/route.test.ts
index 747002941..dcf7ba135 100644
--- a/src/web/src/app/api/community/agent/send/route.test.ts
+++ b/src/web/src/app/api/community/agent/send/route.test.ts
@@ -22,6 +22,7 @@ const mockAreFriends = vi.fn()
const mockGetLatestSeqForScope = vi.fn()
const mockGetReadState = vi.fn()
const mockToAgentMessage = vi.fn()
+const mockGetMessageByChannelAndSeq = vi.fn()
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
@@ -51,6 +52,7 @@ vi.mock("@alook/shared", async () => {
},
communityMessage: {
...actual.queries.communityMessage, // keep the real scopeKeyForTarget
+ getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),
},
communityAgentInbox: {
getLatestSeqForScope: (...a: unknown[]) => mockGetLatestSeqForScope(...a),
@@ -93,6 +95,7 @@ describe("POST /api/community/agent/send", () => {
mockGetLatestSeqForScope.mockResolvedValue(0)
mockGetReadState.mockResolvedValue(null)
mockToAgentMessage.mockImplementation((_db: unknown, row: unknown) => Promise.resolve({ ...row as object, wireShaped: true }))
+ mockGetMessageByChannelAndSeq.mockResolvedValue(null)
})
it("401 without Authorization", async () => {
@@ -338,4 +341,57 @@ describe("POST /api/community/agent/send", () => {
// must not have reached createCommunityMessage.
expect(mockCreateCommunityMessage).toHaveBeenCalledTimes(1)
})
+
+ it("reply/happy path: replyToSeq resolves to an in-scope message id, passed as body.replyToId", async () => {
+ mockGetLatestSeqForScope.mockResolvedValue(5)
+ mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })
+ mockGetMessageByChannelAndSeq.mockResolvedValue({ id: "m_target", seq: 3 })
+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 6, content: "on it" } })
+ const res = await POST(
+ req(
+ { channel: "/studio/general", content: { text: "on it" }, replyToSeq: 3 },
+ { Authorization: "Bearer crk_abc" }
+ )
+ )
+ expect(res.status).toBe(200)
+ expect((await res.json()).state).toBe("sent")
+ // Resolution is scope-first: the same scopeTarget the send targets.
+ expect(mockGetMessageByChannelAndSeq).toHaveBeenCalledWith(
+ expect.anything(),
+ { channelId: "ch_1" },
+ 3
+ )
+ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ body: { content: "on it", replyToId: "m_target" } })
+ )
+ })
+
+ it("reply/bad seq: replyToSeq with no matching in-scope message → 400, no row inserted", async () => {
+ mockGetLatestSeqForScope.mockResolvedValue(5)
+ mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })
+ mockGetMessageByChannelAndSeq.mockResolvedValue(null)
+ const res = await POST(
+ req(
+ { channel: "/studio/general", content: { text: "on it" }, replyToSeq: 99999 },
+ { Authorization: "Bearer crk_abc" }
+ )
+ )
+ expect(res.status).toBe(400)
+ expect(await res.json()).toEqual({ error: "reply target #99999 not found in /studio/general" })
+ expect(mockCreateCommunityMessage).not.toHaveBeenCalled()
+ })
+
+ it("reply/no reply: send without replyToSeq → body carries no replyToId (undefined)", async () => {
+ mockGetLatestSeqForScope.mockResolvedValue(5)
+ mockGetReadState.mockResolvedValue({ lastReadSeq: 5 })
+ mockCreateCommunityMessage.mockResolvedValue({ ok: true, row: { id: "m_1", seq: 6, content: "hi" } })
+ const res = await POST(
+ req({ channel: "/studio/general", content: { text: "hi" } }, { Authorization: "Bearer crk_abc" })
+ )
+ expect(res.status).toBe(200)
+ expect(mockGetMessageByChannelAndSeq).not.toHaveBeenCalled()
+ expect(mockCreateCommunityMessage).toHaveBeenCalledWith(
+ expect.objectContaining({ body: { content: "hi", replyToId: undefined } })
+ )
+ })
})
diff --git a/src/web/src/app/api/community/agent/send/route.ts b/src/web/src/app/api/community/agent/send/route.ts
index 2b1d3c4e3..05c2a3573 100644
--- a/src/web/src/app/api/community/agent/send/route.ts
+++ b/src/web/src/app/api/community/agent/send/route.ts
@@ -112,6 +112,27 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
}
}
+ // Reply/cite (plan agent-reply-cite.md §Write) — resolve the cited seq to a
+ // message id WITHIN `scopeTarget` (the same channel/DM this send targets).
+ // Scope-first: a `replyToSeq` can never cross-cite into another scope. A seq
+ // with no matching message here (typo, wrong scope, deleted) is a hard 400 —
+ // nothing is posted.
+ let replyToId: string | undefined
+ if (body.replyToSeq !== undefined) {
+ const replyTarget = await queries.communityMessage.getMessageByChannelAndSeq(
+ db,
+ scopeTarget,
+ body.replyToSeq,
+ )
+ if (!replyTarget) {
+ return NextResponse.json(
+ { error: `reply target #${body.replyToSeq} not found in ${body.channel}` },
+ { status: 400 },
+ )
+ }
+ replyToId = replyTarget.id
+ }
+
// `expectedSeq: latestSeq` reuses the exact snapshot the alignment gate
// above already fetched — no new query. If another agent's `send` wins
// the race between that snapshot and this claim, `createCommunityMessage`
@@ -123,7 +144,7 @@ export const POST = withAgentRunnerAuth(async (req: NextRequest, ctx) => {
db,
authorId: ctx.botUserId,
target,
- body: { content: body.content.text },
+ body: { content: body.content.text, replyToId },
source: "cli",
expectedSeq: latestSeq,
attachmentIds: body.attachments.length > 0 ? body.attachments : undefined,