Skip to content
Open
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
84 changes: 84 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1464,6 +1464,90 @@ it.effect("shells flag a latest run triggered by a provider background wake", ()
}).pipe(Effect.provide(layerTest)),
);

it.effect("shells read founder @-mentions only from assistant replies and founder notes", () =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
const threadId = yield* addRolledBackRecoveryCandidate("attention-mentions");
const at = (yield* store.getThreadProjection(threadId)).updatedAt;
let seconds = 1;
const send = (
id: string,
message: {
readonly role: "user" | "assistant";
readonly createdBy: "user" | "agent";
readonly text: string;
readonly humanNote?: true;
},
) =>
Effect.gen(function* () {
const updatedAt = DateTime.add(at, { seconds: seconds++ });
yield* store.apply({
id: EventId.make(`event:attention-mentions:${id}`),
type: "message.updated",
threadId,
occurredAt: updatedAt,
payload: {
id: MessageId.make(`message:attention-mentions:${id}`),
threadId,
runId: null,
nodeId: null,
creationSource: "server",
attachments: [],
streaming: false,
createdAt: updatedAt,
updatedAt,
...message,
},
});
return [
(yield* store.getThreadShell(threadId))?.attentionMentions,
ProjectionStore.threadShellFromProjection(yield* store.getThreadProjection(threadId))
.attentionMentions,
];
});

// An incoming message or agent-to-agent digest that only talks about the rules never pings.
for (const [id, createdBy] of [
["incoming-user", "user"],
["digest", "agent"],
] as const) {
assert.deepEqual(
yield* send(id, {
role: "user",
createdBy,
text: "Remember: @kameron and @jeff are pinged only by an assistant reply.",
}),
[undefined, undefined],
id,
);
}
// An assistant reply that writes at a founder does.
assert.deepEqual(
yield* send("assistant", {
role: "assistant",
createdBy: "agent",
text: "Need a call on the rollout, @kameron.",
}),
[["kameron"], ["kameron"]],
);
// A later incoming message does not replace what the assistant said, and never adds a name.
assert.deepEqual(
yield* send("later-digest", { role: "user", createdBy: "agent", text: "fyi @jeff" }),
[["kameron"], ["kameron"]],
);
// A founder's own note to the other founder still pings.
assert.deepEqual(
yield* send("note", {
role: "user",
createdBy: "user",
humanNote: true,
text: "please look @jeff",
}),
[["jeff"], ["jeff"]],
);
}).pipe(Effect.provide(layerTest)),
);

it.effect("SQL queue readiness skips held runs without bypassing active work", () =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
Expand Down
16 changes: 15 additions & 1 deletion apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1774,6 +1774,16 @@ const linkCardStillAsks = (
latestUserAuthoredMessageAt === null ||
!DateTime.isGreaterThan(latestUserAuthoredMessageAt, item.startedAt ?? item.updatedAt);

/**
* Only an assistant reply, or a founder's own note, can ping a founder. An incoming user message
* or agent-to-agent digest merely relays text (often about how pings work), so scanning it would
* light the pill on the recipient bot.
*/
const isFounderPingSource = (message: {
readonly role: string;
readonly humanNote?: boolean | undefined;
}) => message.role === "assistant" || message.humanNote === true;

const shellAttentionMentions = (text: string | null | undefined) => {
const attentionMentions = attentionMentionsFromText(text);
return attentionMentions === undefined ? {} : { attentionMentions };
Expand Down Expand Up @@ -1866,7 +1876,7 @@ export function threadShellFromProjection(
const latestUserMessage = userMessages[0] ?? null;
const latestVisibleText =
projection.messages
.filter((message) => idleCompactionOf(message) === undefined)
.filter((message) => idleCompactionOf(message) === undefined && isFounderPingSource(message))
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
Expand Down Expand Up @@ -8271,6 +8281,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
FROM orchestration_v2_projection_messages message
INDEXED BY orchestration_v2_projection_messages_thread_updated_idx
WHERE message.thread_id = t.thread_id
AND (
message.role = 'assistant'
OR json_extract(message.payload_json, '$.humanNote') = 1
)
AND NOT ${isIdleCompactionMessage("message")}
ORDER BY message.updated_at DESC, message.message_id DESC
LIMIT 1
Expand Down
120 changes: 116 additions & 4 deletions packages/contracts/src/botAttention.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const inbox = (patch: Partial<ThreadInbox> = {}): ThreadInbox => ({
...patch,
});

const shared = () => inbox({ audience: "shared", attentionKind: "FYI", reason: "fyi" });

const ask = (founder: "kameron" | "jeff") => ({
founder,
kind: "decision" as const,
Expand All @@ -24,6 +26,41 @@ describe("mentionedFounders", () => {
expect(mentionedFounders("@Jeff's draft")).toEqual(["jeff"]);
expect(mentionedFounders(null)).toEqual([]);
});

it("ignores names in code, emails and quoted logs, but not a ping beside them", () => {
expect(mentionedFounders("run `git log @kameron` now")).toEqual([]);
expect(mentionedFounders("```\nnotify @jeff\n```")).toEqual([]);
expect(mentionedFounders("```\nnotify @jeff")).toEqual([]);
expect(mentionedFounders("mail kameron.smith@closura.ai or ops@jeff.example")).toEqual([]);
expect(mentionedFounders("> @kameron said ship\n > @jeff too")).toEqual([]);
expect(mentionedFounders("```\n@kameron\n```\nplease review @Jeff")).toEqual(["jeff"]);
expect(mentionedFounders("> log @kameron\n`x`\n@kameron decide?")).toEqual(["kameron"]);
});

it("reads multi-backtick code spans as one span and ignores unmatched runs", () => {
expect(mentionedFounders("run ``@kameron`` now")).toEqual([]);
expect(mentionedFounders("run ``use `x` @jeff`` now")).toEqual([]);
expect(mentionedFounders("```@kameron``` is code")).toEqual([]);
expect(mentionedFounders("`` ``\n@jeff look")).toEqual(["jeff"]);
expect(mentionedFounders("an empty `` pair, @kameron?")).toEqual(["kameron"]);
expect(mentionedFounders("``a`` `b` @jeff")).toEqual(["jeff"]);
expect(mentionedFounders("``a ` b`` @kameron")).toEqual(["kameron"]);
});

it("closes a fence only on at least as many fence characters and no trailing text", () => {
// A single-line triple-backtick span must not swallow the lines after it.
expect(mentionedFounders("```@kameron```\nping @jeff")).toEqual(["jeff"]);
// A longer fence is not closed by a shorter one, so the ping inside stays code.
expect(mentionedFounders("````\n```\n@kameron\n```\n````\n@jeff")).toEqual(["jeff"]);
expect(mentionedFounders("~~~~\n~~~\n@kameron\n~~~~\nping @jeff")).toEqual(["jeff"]);
// Longer closers and trailing whitespace close; trailing text does not.
expect(mentionedFounders("```\n@kameron\n````` \n@jeff")).toEqual(["jeff"]);
expect(mentionedFounders("```\n@kameron\n``` done\n@jeff\n```\nafter @kameron")).toEqual([
"kameron",
]);
// A tilde fence is not closed by backticks.
expect(mentionedFounders("~~~\n@kameron\n```\n@jeff\n~~~\n@kameron")).toEqual(["kameron"]);
});
});

describe("resolveBotAttention", () => {
Expand Down Expand Up @@ -65,7 +102,7 @@ describe("resolveBotAttention", () => {
).toEqual({ kind: "badge", label: "Approval" });
expect(
resolveBotAttention({
inbox: inbox(),
inbox: shared(),
viewingFounder: "kameron",
latestText: "please look @Jeff",
}),
Expand Down Expand Up @@ -108,20 +145,20 @@ describe("resolveBotAttention", () => {
it("badges names the shell already resolved, and not text it was not given", () => {
expect(
resolveBotAttention({
inbox: inbox(),
inbox: shared(),
viewingFounder: "kameron",
mentioned: ["jeff"],
latestText: "cc @Kameron",
}),
).toEqual({ kind: "badge", label: "Jeff" });
expect(
resolveBotAttention({
inbox: inbox(),
inbox: shared(),
viewingFounder: "kameron",
mentioned: [],
latestText: "cc @Kameron",
}),
).toEqual({ kind: "quiet" });
).toEqual({ kind: "fyi" });
});

it("keeps a one-founder ask as a badge", () => {
Expand All @@ -134,4 +171,79 @@ describe("resolveBotAttention", () => {
}).kind,
).toBe("badge");
});

describe("false founder pills", () => {
const incidental = [
"Kameron and Jeff were mentioned in the report",
"see `@kameron` and `@jeff` in the config",
"```\n@kameron @jeff\n```",
"owner kameron.smith@closura.ai, cc jeff@closura.ai, ops@kameron.example",
"> @kameron @jeff pinged earlier\nall green",
];

it("never badges agent-only work on a name, even an explicit ping", () => {
const agentOnly = inbox({ audience: "agent-only", attentionKind: "background" });
for (const latestText of [...incidental, "@Kameron @Jeff please look"]) {
expect(
resolveBotAttention({ inbox: agentOnly, viewingFounder: "kameron", latestText }),
).toEqual({
kind: "quiet",
});
}
expect(
resolveBotAttention({
inbox: agentOnly,
viewingFounder: "kameron",
mentioned: ["kameron", "jeff"],
}),
).toEqual({ kind: "quiet" });
});

it("still badges agent-only work that holds a decision request", () => {
expect(
resolveBotAttention({
inbox: inbox({ audience: "agent-only", decisionRequest: ask("kameron") }),
viewingFounder: "kameron",
latestText: "@Jeff",
}),
).toEqual({ kind: "badge", label: "Decision" });
});

it("keeps shared FYI chatter a dot when names only appear incidentally", () => {
const fyi = inbox({
audience: "shared",
attentionKind: "FYI",
reason: "fyi",
assignee: null,
});
for (const latestText of incidental) {
expect(resolveBotAttention({ inbox: fyi, viewingFounder: "kameron", latestText })).toEqual({
kind: "fyi",
});
}
});

it("badges shared FYI work for a real ping or a decision request", () => {
const fyi = inbox({
audience: "shared",
attentionKind: "FYI",
reason: "fyi",
assignee: null,
});
expect(
resolveBotAttention({
inbox: fyi,
viewingFounder: "kameron",
latestText: "```\n@kameron\n```\n@Jeff @Kameron can you approve?",
}),
).toEqual({ kind: "badge", label: "Kameron · Jeff" });
expect(
resolveBotAttention({
inbox: { ...fyi, decisionRequest: ask("jeff") },
viewingFounder: "kameron",
latestText: "see `@kameron`",
}),
).toEqual({ kind: "badge", label: "Decision" });
});
});
});
35 changes: 31 additions & 4 deletions packages/contracts/src/botAttention.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,34 @@ const JOINT_SIGN_OFF_FOUNDERS: readonly Founder[] = Founder.literals;
/** How much of a message is scanned for an @-mention. The shell stores the names, not the text. */
export const ATTENTION_MENTION_TEXT_LIMIT = 2000;

const FOUNDER_MENTION = /@(kameron|jeff)\b/gi;
// The lookbehind keeps an address such as `ops@jeff.example` from being read as a ping.
const FOUNDER_MENTION = /(?<![\w.+-])@(kameron|jeff)\b/gi;

/** The founders an @-mention names. `@jefferson` is not Jeff. */
/**
* What is not prose, per CommonMark: a fenced block, a `>` quoted line, or an inline code span.
* - A fence is 3+ backticks or tildes. A backtick fence's info string holds no backtick, so
* ```` ```@kameron``` ```` on one line is a code span, not a fence. The closing fence repeats the
* opener's character at least as many times and has only trailing whitespace. An unterminated
* fence runs to the end.
* - A code span opens on a run of N backticks and closes on the next run of exactly N, so
* ``` ``use `x` @jeff`` ``` is one span and a lone ``` `` ``` closes nothing.
*/
const NON_PING_TEXT =
/^[ \t]*(`{3,})[^`\n]*$(?:\n[\s\S]*?^[ \t]*\1`*[ \t]*$|[\s\S]*)|^[ \t]*(~{3,})[^\n]*(?:\n[\s\S]*?^[ \t]*\2~*[ \t]*$|[\s\S]*)|^[ \t]*>.*$|(?<!`)(`+)(?!`)[^\n]*?(?<!`)\3(?!`)/gm;

/**
* A founder is pinged only by prose written at them. Logs, code and quotes that merely contain an
* `@kameron` are incidental, so they must not light the bright pill.
*/
function pingableText(text: string): string {
return text.replace(NON_PING_TEXT, " ");
}

/** The founders an @-mention names. `@jefferson` is not Jeff. Code, quoted lines and emails do not count. */
export function mentionedFounders(text: string | null | undefined): ReadonlyArray<Founder> {
if (!text) return [];
const found = new Set<Founder>();
for (const match of text.matchAll(FOUNDER_MENTION)) {
for (const match of pingableText(text).matchAll(FOUNDER_MENTION)) {
const name = match[1]?.toLowerCase();
if (name === "kameron" || name === "jeff") found.add(name);
}
Expand Down Expand Up @@ -63,8 +84,14 @@ export function resolveBotAttention(input: {
if (ask !== undefined) {
return { kind: "badge", label: decisionBadgeLabel(ask.kind) };
}
// Agent-only work is not on a founder's plate, so a name in its text never badges. Only a real
// decision request (above) can.
const mentioned =
input.mentioned !== undefined ? input.mentioned : mentionedFounders(input.latestText);
input.inbox?.audience === "agent-only"
? []
: input.mentioned !== undefined
? input.mentioned
: mentionedFounders(input.latestText);
if (mentioned.length > 0) {
return { kind: "badge", label: mentionBadgeLabel(mentioned) };
}
Expand Down
Loading