Skip to content
Draft
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
60 changes: 60 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1700,6 +1700,19 @@ it.effect("shells read founder @-mentions only from assistant replies and founde
id,
);
}
// The shell also says when the mentioning message was written, so a founder who has read past
// it can be told apart from one who has not. Both the SQL and in-memory paths must agree.
const mentionedAt = Effect.gen(function* () {
const sql = (yield* store.getThreadShell(threadId))?.attentionMentionsAt;
const memory = ProjectionStore.threadShellFromProjection(
yield* store.getThreadProjection(threadId),
).attentionMentionsAt;
return [
sql === undefined ? undefined : DateTime.formatIso(sql),
memory === undefined ? undefined : DateTime.formatIso(memory),
];
});
assert.deepEqual(yield* mentionedAt, [undefined, undefined]);
// An assistant reply that writes at a founder does.
assert.deepEqual(
yield* send("assistant", {
Expand All @@ -1709,11 +1722,19 @@ it.effect("shells read founder @-mentions only from assistant replies and founde
}),
[["kameron"], ["kameron"]],
);
const assistantAt = DateTime.formatIso(DateTime.add(at, { seconds: 3 }));
assert.deepEqual(yield* mentionedAt, [assistantAt, assistantAt]);
// 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"]],
);
assert.deepEqual(yield* mentionedAt, [assistantAt, assistantAt]);
assert.deepEqual(
yield* send("routine-reply", { role: "assistant", createdBy: "agent", text: "All green." }),
[["kameron"], ["kameron"]],
);
assert.deepEqual(yield* mentionedAt, [assistantAt, assistantAt]);
// A founder's own note to the other founder still pings.
assert.deepEqual(
yield* send("note", {
Expand All @@ -1724,6 +1745,45 @@ it.effect("shells read founder @-mentions only from assistant replies and founde
}),
[["jeff"], ["jeff"]],
);
// A newer mention carries a newer time, which is what shows a founder a fresh pill.
const noteAt = DateTime.formatIso(DateTime.add(at, { seconds: 6 }));
assert.deepEqual(yield* mentionedAt, [noteAt, noteAt]);
const mentionTimes = Effect.gen(function* () {
const shells = [
yield* store.getThreadShell(threadId),
ProjectionStore.threadShellFromProjection(yield* store.getThreadProjection(threadId)),
];
return shells.map((shell) =>
Object.fromEntries(
Object.entries(shell?.attentionMentionsAtByFounder ?? {}).flatMap(([founder, time]) =>
time === undefined ? [] : [[founder, DateTime.formatIso(time)]],
),
),
);
});
assert.deepEqual(yield* mentionTimes, [
{ kameron: assistantAt, jeff: noteAt },
{ kameron: assistantAt, jeff: noteAt },
]);
yield* send("later-routine", {
role: "assistant",
createdBy: "agent",
text: "All green. `@Kameron`",
});
assert.deepEqual(yield* mentionTimes, [
{ kameron: assistantAt, jeff: noteAt },
{ kameron: assistantAt, jeff: noteAt },
]);
// Editing away a mention removes its index entry, rather than leaving stale attention.
yield* send("note", { role: "user", createdBy: "user", humanNote: true, text: "All green." });
assert.deepEqual(yield* mentionTimes, [{ kameron: assistantAt }, { kameron: assistantAt }]);
yield* send("reminder", {
role: "assistant",
createdBy: "agent",
text: "@Kameron another question",
});
const reminderAt = DateTime.formatIso(DateTime.add(at, { seconds: 9 }));
assert.deepEqual(yield* mentionTimes, [{ kameron: reminderAt }, { kameron: reminderAt }]);
}).pipe(Effect.provide(layerTest)),
);

Expand Down
113 changes: 74 additions & 39 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { founderMentions } from "./founderMentions.ts";
import type { ProjectThreadAwarenessV2Input } from "@t3tools/shared/agentAwareness";
import {
applyOrchestrationV2ThreadVisit,
attentionMentionsFromText,
ATTENTION_MENTION_TEXT_LIMIT,
Founder,
inboxAfterFounderReply,
pendingGuestMessageCount,
projectThreadInbox,
Expand Down Expand Up @@ -1341,7 +1341,8 @@ type ShellThreadRow = {
readonly pending_link_request_payload_json: string | null;
readonly latest_user_message_at: string | null;
readonly latest_user_authored_message_at: string | null;
readonly latest_visible_text: string | null;
readonly kameron_mentioned_at: string | null;
readonly jeff_mentioned_at: string | null;
readonly has_actionable_proposed_plan: number;
};

Expand Down Expand Up @@ -1938,19 +1939,29 @@ 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 };
const shellAttentionMentions = (
attentionMentionsAtByFounder: NonNullable<
OrchestrationV2ThreadShell["attentionMentionsAtByFounder"]
>,
) => {
const attentionMentions = Founder.literals.filter(
(founder) => attentionMentionsAtByFounder[founder] !== undefined,
);
if (attentionMentions.length === 0) return {};
const attentionMentionsAt = attentionMentions.reduce<DateTime.Utc | undefined>(
(latest, founder) => {
const at = attentionMentionsAtByFounder[founder]!;
return latest === undefined || DateTime.isGreaterThan(at, latest) ? at : latest;
},
undefined,
);
return {
attentionMentions: attentionMentions.filter((founder) =>
DateTime.Equivalence(attentionMentionsAtByFounder[founder]!, attentionMentionsAt!),
),
attentionMentionsAt,
attentionMentionsAtByFounder,
};
};

const shellInbox = (
Expand Down Expand Up @@ -2038,14 +2049,15 @@ export function threadShellFromProjection(
}
}
const latestUserMessage = userMessages[0] ?? null;
const latestVisibleText =
projection.messages
.filter((message) => idleCompactionOf(message) === undefined && isFounderPingSource(message))
.toSorted(
(left, right) =>
DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
right.id.localeCompare(left.id),
)[0]?.text ?? null;
const attentionMentionsAtByFounder: Partial<Record<Founder, DateTime.Utc>> = {};
for (const message of projection.messages) {
for (const founder of founderMentions(message)) {
const previous = attentionMentionsAtByFounder[founder];
if (previous === undefined || DateTime.isGreaterThan(message.updatedAt, previous)) {
attentionMentionsAtByFounder[founder] = message.updatedAt;
}
}
}
const pendingBackgroundTasks = derivePendingBackgroundWork({
latestRun,
providerThreads: projection.providerThreads,
Expand Down Expand Up @@ -2119,7 +2131,7 @@ export function threadShellFromProjection(
// Thread detail owns message bodies. Keeping them out of shell rows makes
// initial hydration and streaming updates independent of transcript size.
latestVisibleMessage: null,
...shellAttentionMentions(latestVisibleText),
...shellAttentionMentions(attentionMentionsAtByFounder),
latestUserMessageAt: latestUserMessage?.updatedAt ?? null,
latestUserAuthoredMessageAt,
hasActionableProposedPlan: projection.plans.some(
Expand Down Expand Up @@ -2271,7 +2283,9 @@ type ShellThreadState = {
readonly pendingRuntimeRequest: OrchestrationV2PendingRuntimeRequestSummary | null;
readonly latestUserMessageAt: DateTime.Utc | null;
readonly latestUserAuthoredMessageAt: DateTime.Utc | null;
readonly attentionMentions: OrchestrationV2ThreadShell["attentionMentions"];
readonly attentionMentions?: OrchestrationV2ThreadShell["attentionMentions"];
readonly attentionMentionsAt?: OrchestrationV2ThreadShell["attentionMentionsAt"];
readonly attentionMentionsAtByFounder?: OrchestrationV2ThreadShell["attentionMentionsAtByFounder"];
readonly hasActionableProposedPlan: boolean;
readonly pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"];
readonly providerInstanceHistory: OrchestrationV2ThreadShell["providerInstanceHistory"];
Expand Down Expand Up @@ -2462,6 +2476,12 @@ function shellFromState(input: {
...(input.state.attentionMentions === undefined
? {}
: { attentionMentions: input.state.attentionMentions }),
...(input.state.attentionMentionsAt === undefined
? {}
: { attentionMentionsAt: input.state.attentionMentionsAt }),
...(input.state.attentionMentionsAtByFounder === undefined
? {}
: { attentionMentionsAtByFounder: input.state.attentionMentionsAtByFounder }),
latestUserMessageAt: input.state.latestUserMessageAt,
latestUserAuthoredMessageAt: input.state.latestUserAuthoredMessageAt,
hasActionableProposedPlan: input.state.hasActionableProposedPlan,
Expand Down Expand Up @@ -3282,6 +3302,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
break;
}
case "message.updated": {
const mentions = founderMentions(event.payload);
const payloadJson = yield* encodeMessagePayload(event.payload);
const createdAt = yield* encodePayloadTimestamp(event.payload.createdAt);
const updatedAt = yield* encodePayloadTimestamp(event.payload.updatedAt);
Expand All @@ -3296,7 +3317,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
created_at,
updated_at,
payload_json,
search_text
search_text,
mentions_kameron,
mentions_jeff
)
VALUES (
${event.payload.id},
Expand All @@ -3308,7 +3331,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
${createdAt},
${updatedAt},
${payloadJson},
${readableSearchText(event.payload.text)}
${readableSearchText(event.payload.text)},
${Number(mentions.includes("kameron"))},
${Number(mentions.includes("jeff"))}
)
ON CONFLICT(message_id)
DO UPDATE SET
Expand All @@ -3320,7 +3345,9 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
created_at = excluded.created_at,
updated_at = excluded.updated_at,
payload_json = excluded.payload_json,
search_text = excluded.search_text
search_text = excluded.search_text,
mentions_kameron = excluded.mentions_kameron,
mentions_jeff = excluded.mentions_jeff
`;
const founder = event.payload.sentBy?.founder;
if (
Expand Down Expand Up @@ -8923,18 +8950,19 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
LIMIT 1
) AS latest_user_authored_message_at,
(
SELECT substr(json_extract(message.payload_json, '$.text'), 1, ${ATTENTION_MENTION_TEXT_LIMIT})
SELECT message.updated_at
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")}
WHERE message.thread_id = t.thread_id AND message.mentions_kameron = 1
ORDER BY message.updated_at DESC, message.message_id DESC
LIMIT 1
) AS kameron_mentioned_at,
(
SELECT message.updated_at
FROM orchestration_v2_projection_messages message
WHERE message.thread_id = t.thread_id AND message.mentions_jeff = 1
ORDER BY message.updated_at DESC, message.message_id DESC
LIMIT 1
) AS latest_visible_text,
) AS jeff_mentioned_at,
EXISTS (
SELECT 1
FROM orchestration_v2_projection_plans plan
Expand Down Expand Up @@ -9659,7 +9687,14 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
? null
: DateTime.makeUnsafe(row.latest_user_message_at),
latestUserAuthoredMessageAt,
attentionMentions: attentionMentionsFromText(row.latest_visible_text),
...shellAttentionMentions({
...(row.kameron_mentioned_at === null
? {}
: { kameron: DateTime.makeUnsafe(row.kameron_mentioned_at) }),
...(row.jeff_mentioned_at === null
? {}
: { jeff: DateTime.makeUnsafe(row.jeff_mentioned_at) }),
}),
hasActionableProposedPlan: row.has_actionable_proposed_plan === 1,
pendingBackgroundTasks,
providerInstanceHistory: providerInstanceHistoryForShell({
Expand Down
12 changes: 12 additions & 0 deletions apps/server/src/orchestration-v2/founderMentions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { attentionMentionsFromText } from "@t3tools/contracts";

export function founderMentions(message: {
readonly role: string;
readonly text: string;
readonly humanNote?: boolean | undefined;
}) {
// Incoming messages and agent digests relay text; only replies and human notes can ping.
return message.role === "assistant" || message.humanNote === true
? (attentionMentionsFromText(message.text) ?? [])
: [];
}
2 changes: 2 additions & 0 deletions apps/server/src/persistence/Migrations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ import Migration0115 from "./Migrations/115_WorkflowRunTags.ts";
import Migration0116 from "./Migrations/116_ForkHistoryMembership.ts";
import Migration0117 from "./Migrations/117_WorkflowMailSender.ts";
import Migration0118 from "./Migrations/118_WorkflowPools.ts";
import Migration0119 from "./Migrations/119_FounderMentionIndex.ts";

/**
* Closura: deployed fork databases record the fork's own migrations at ledger ids 97 to 102.
Expand Down Expand Up @@ -269,6 +270,7 @@ const migrationEntries = [
[116 + UPSTREAM_MIGRATION_ID_OFFSET, "ForkHistoryMembership", Migration0116],
[117 + UPSTREAM_MIGRATION_ID_OFFSET, "WorkflowMailSender", Migration0117],
[118 + UPSTREAM_MIGRATION_ID_OFFSET, "WorkflowPools", Migration0118],
[119 + UPSTREAM_MIGRATION_ID_OFFSET, "FounderMentionIndex", Migration0119],
] as const;

export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { assert, it } from "@effect/vitest";
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/sql/SqlClient";

import { runMigrations, UPSTREAM_MIGRATION_ID_OFFSET } from "../Migrations.ts";

it.layer(NodeSqliteClient.layer({ filename: ":memory:" }))("119_FounderMentionIndex", (it) => {
it.effect("backfills genuine mentions and serves each founder from a covering index", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 118 + UPSTREAM_MIGRATION_ID_OFFSET });
const messages = [
["assistant", "assistant", "@Kameron please decide", false, 1, 0],
["note", "user", "@Jeff please look", true, 0, 1],
["both", "assistant", "@Kameron @Jeff", false, 1, 1],
["code", "assistant", "`@Kameron`", false, 0, 0],
["quote", "assistant", "> @Jeff\nAll green.", false, 0, 0],
["digest", "user", "@Kameron @Jeff", false, 0, 0],
] as const;
for (const [id, role, text, humanNote] of messages) {
yield* sql`
INSERT INTO orchestration_v2_projection_messages (
message_id, thread_id, role, streaming, created_at, updated_at, payload_json
) VALUES (
${id}, 'thread-1', ${role}, 0, '2026-12-01T00:00:00.000Z',
'2026-12-01T00:00:00.000Z', ${JSON.stringify({ role, text, humanNote })}
)
`;
}
yield* runMigrations();
const rows = yield* sql<{
readonly message_id: string;
readonly mentions_kameron: number;
readonly mentions_jeff: number;
}>`SELECT message_id, mentions_kameron, mentions_jeff FROM orchestration_v2_projection_messages`;
for (const [id, , , , kameron, jeff] of messages) {
assert.deepEqual(
rows.find((row) => row.message_id === id),
{
message_id: id,
mentions_kameron: kameron,
mentions_jeff: jeff,
},
);
}
for (const founder of ["kameron", "jeff"]) {
const plan = yield* sql<{ readonly detail: string }>`
EXPLAIN QUERY PLAN SELECT updated_at
FROM orchestration_v2_projection_messages
WHERE thread_id = 'thread-1' AND ${sql.literal(`mentions_${founder}`)} = 1
ORDER BY updated_at DESC, message_id DESC LIMIT 1
`;
assert.include(
plan.map((row) => row.detail).join("\n"),
`orchestration_v2_messages_${founder}_mention_idx`,
);
}
}),
);
});
Loading
Loading