feat: give every Hermes instance a Home thread for proactive delivery

Hermes has a first-class "home channel": the default destination for output
nobody asked for at a specific address — a cron result, an agent-initiated
`send_message`, a gateway lifecycle notice, a `/handoff`. The T3 plugin opted
out, suppressing Hermes' "Type /sethome" nudge without designating anything.
A cron job with `deliver=t3` went nowhere, `send_message` to a bare `t3`
target errored, and `/handoff t3` hard-failed.

Each enrolled instance now gets one Home thread, pinned first in its agent
project, fully conversational, undeletable, created automatically.

Protocol v3. `connection.hello` gains `role: "gateway" | "delivery"`;
`connection.accepted` carries `homeThreadId`. Two new frames: `home.deliver`
and `home.deliver.ack`.

Designation converges on read, like agent projects — a precondition every
handshake runs rather than an event one caller owns, so an instance enrolled
before this shipped, or one whose thread creation failed once, heals on the
next connect. It lives in the instance's settings blob beside `connectorUrl`
and `revoked`; the plugin's `T3_HOME_CHANNEL` is a cache of it, reconciled
every handshake.

The existence check deliberately ignores archive state. Every other thread
read filters `archived_at IS NULL`, which is right for "what should the user
see" and wrong for "does this row exist" — an archived Home read as deleted
and the self-healing path replaced it, stranding the history in a thread the
user had merely parked. A delivery to an archived Home now un-archives it,
the same way incoming activity wakes a settled or snoozed thread.

Deliveries bypass the turn machinery entirely. One may arrive while the home
thread has a live user turn, so it appends as a turnless assistant message
carrying `notification` provenance rather than joining the turn — attributing
it would fold it away behind that turn's "Worked for …". Everything except a
lifecycle notice un-settles the thread and pushes; lifecycle notices land
quietly.

Idempotency is load-bearing, because the plugin's durable queue retries
anything it has not seen acked. T3 dedupes on `deliveryId` against
`projection_thread_messages` before dispatching — the decider's own scan sees
the in-memory read model, which is built with `messages: []`, so it cannot
catch a replay after a restart. The ack is sent only after the write lands.

An out-of-process cron run dials in with `role: "delivery"`: authenticated
identically, but never registered as the instance's primary connection, so it
cannot displace a live gateway socket or answer its pending requests.

Plugin side, the proactive branch in `send()` gates on provenance rather than
turn absence. The naive rule — "no active turn, so deliver" — would let a
notify-stamped cron delivery complete a user's live turn with cron output as
its answer. A bare session-key mismatch is not enough either, since
`HERMES_SESSION_KEY` resolves empty whenever the context did not propagate;
that would tear a genuine reply out of its turn. Bypassing a live turn
requires positively identified cron/lifecycle/handoff provenance.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Ben DavisandClaude Opus 5 committed 2026-07-26 13:10:35 -07:00
1 parent 5bfb90db61
commit 784fcb71e6
73 files changed
+5907 -119

No files matched your search

@@ -107,6 +107,7 @@ describe("CheckpointDiffQuery.layer", () => {
});
}),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -201,6 +202,7 @@ describe("CheckpointDiffQuery.layer", () => {
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -285,6 +287,7 @@ describe("CheckpointDiffQuery.layer", () => {
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -354,6 +357,7 @@ describe("CheckpointDiffQuery.layer", () => {
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -408,6 +412,7 @@ describe("CheckpointDiffQuery.layer", () => {
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -203,6 +203,7 @@ describe("OrchestrationEngine", () => {
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -2368,6 +2368,139 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("projects notification deliveries into the message row and shell summary", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
const createdAt = "2026-07-01T09:00:00.000Z";
yield* appendAndProject({
type: "project.created",
eventId: EventId.make("evt-notify-project"),
aggregateKind: "project",
aggregateId: ProjectId.make("project-notify"),
occurredAt: createdAt,
commandId: CommandId.make("cmd-notify-project"),
causationEventId: null,
correlationId: CommandId.make("cmd-notify-project"),
metadata: {},
payload: {
projectId: ProjectId.make("project-notify"),
title: "Hermes",
workspaceRoot: "/tmp/project-notify",
defaultModelSelection: null,
scripts: [],
createdAt,
updatedAt: createdAt,
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.make("evt-notify-thread"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-notify"),
occurredAt: createdAt,
commandId: CommandId.make("cmd-notify-thread"),
causationEventId: null,
correlationId: CommandId.make("cmd-notify-thread"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-notify"),
projectId: ProjectId.make("project-notify"),
title: "Home",
modelSelection: {
instanceId: ProviderInstanceId.make("hermes"),
model: "hermes",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
updatedAt: createdAt,
},
});
const deliveredAt = "2026-07-01T09:05:00.000Z";
yield* appendAndProject({
type: "thread.notification-delivered",
eventId: EventId.make("evt-notify-delivery"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-notify"),
occurredAt: deliveredAt,
commandId: CommandId.make("cmd-notify-delivery"),
causationEventId: null,
correlationId: CommandId.make("cmd-notify-delivery"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-notify"),
messageId: MessageId.make("message-notify"),
text: "Digest ready.",
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: deliveredAt,
updatedAt: deliveredAt,
},
});
const messageRows = yield* sql<{
readonly messageId: string;
readonly text: string;
readonly turnId: string | null;
readonly role: string;
readonly isStreaming: number;
readonly notification: string | null;
}>`
SELECT
message_id AS "messageId",
text,
turn_id AS "turnId",
role,
is_streaming AS "isStreaming",
notification_json AS "notification"
FROM projection_thread_messages
WHERE thread_id = 'thread-notify'
`;
assert.equal(messageRows.length, 1);
assert.equal(messageRows[0]?.messageId, "message-notify");
assert.equal(messageRows[0]?.turnId, null);
assert.equal(messageRows[0]?.role, "assistant");
assert.equal(messageRows[0]?.isStreaming, 0);
assert.deepEqual(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.parse(messageRows[0]?.notification ?? "null"),
{ kind: "cron", label: "Cron: daily-digest", deliveryId: "delivery-1" },
);
// The shell summary is what the sidebar and the push relay read; the
// provenance is invisible to them unless it is flattened here.
const threadRows = yield* sql<{
readonly updatedAt: string;
readonly latestNotification: string | null;
}>`
SELECT
updated_at AS "updatedAt",
latest_notification_json AS "latestNotification"
FROM projection_threads
WHERE thread_id = 'thread-notify'
`;
assert.equal(threadRows[0]?.updatedAt, deliveredAt);
assert.deepEqual(
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.parse(threadRows[0]?.latestNotification ?? "null"),
{ kind: "cron", label: "Cron: daily-digest", deliveredAt },
);
}),
);
it.effect("does not fallback-retain messages whose turnId is removed by revert", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -34,7 +34,10 @@ import {
type ProjectionTurn,
ProjectionTurnRepository,
} from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionThreadRepository } from "../../persistence/Services/ProjectionThreads.ts";
import {
type ProjectionThread,
ProjectionThreadRepository,
} from "../../persistence/Services/ProjectionThreads.ts";
import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts";
import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts";
import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts";
@@ -564,6 +567,11 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
]);
let latestUserMessageAt: string | null = null;
// Newest proactive delivery, flattened for shell readers that never load
// messages (sidebar rows, agent awareness). Ties break on message id so
// two deliveries stamped in the same millisecond resolve deterministically.
let latestNotification: ProjectionThread["latestNotification"] = null;
let latestNotificationKey: string | null = null;
for (const message of messages) {
if (
message.role === "user" &&
@@ -571,6 +579,17 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
) {
latestUserMessageAt = message.createdAt;
}
if (message.notification !== undefined) {
const key = `${message.createdAt}${message.messageId}`;
if (latestNotificationKey === null || key > latestNotificationKey) {
latestNotificationKey = key;
latestNotification = {
kind: message.notification.kind,
label: message.notification.label,
deliveredAt: message.createdAt,
};
}
}
}
const pendingApprovalCount = pendingApprovals.filter(
@@ -588,6 +607,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
pendingApprovalCount,
pendingUserInputCount,
hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0,
latestNotification,
});
});
@@ -617,6 +637,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
pendingApprovalCount: 0,
pendingUserInputCount: 0,
hasActionableProposedPlan: 0,
latestNotification: null,
deletedAt: null,
});
return;
@@ -784,6 +805,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
case "thread.message-sent":
case "thread.notification-delivered":
case "thread.proposed-plan-upserted":
case "thread.activity-appended":
case "thread.approval-response-requested":
@@ -917,6 +939,24 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
return;
}
case "thread.notification-delivered": {
// No merge accounting: a delivery is written whole, never streamed,
// and a replay re-emits the identical payload (the decider rebuilds
// it from the persisted row), so the upsert is idempotent.
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
turnId: null,
role: "assistant",
text: event.payload.text,
notification: event.payload.notification,
isStreaming: false,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.reverted": {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
threadId: event.payload.threadId,
@@ -441,6 +441,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
hasPendingApprovals: true,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
latestNotification: null,
},
]);
@@ -5,6 +5,7 @@ import {
MessageId,
NonNegativeInt,
OrchestrationCheckpointFile,
OrchestrationMessageNotification,
OrchestrationProposedPlanId,
OrchestrationReadModel,
OrchestrationShellSnapshot,
@@ -22,6 +23,7 @@ import {
type OrchestrationThreadActivity,
type OrchestrationThreadShell,
ModelSelection,
OrchestrationThreadNotificationSummary,
ProjectId,
ProviderInstanceId,
ThreadId,
@@ -73,12 +75,19 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
isStreaming: Schema.Number,
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
notification: Schema.NullOr(Schema.fromJsonString(OrchestrationMessageNotification)),
}),
);
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
// Stored as a JSON string, like `modelSelection`. Every column the row
// schema does not decode here arrives as raw text and fails the field's
// object schema — which takes the whole thread read down with it.
latestNotification: Schema.NullOr(
Schema.fromJsonString(OrchestrationThreadNotificationSummary),
),
}),
);
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
@@ -348,6 +357,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
ORDER BY created_at ASC, thread_id ASC
@@ -380,6 +390,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
@@ -414,6 +425,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
@@ -434,6 +446,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
notification_json AS "notification",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -786,6 +799,26 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// Existence, not visibility: deliberately no `archived_at IS NULL`. Selects
// only the two columns it needs so it cannot be broken by an undecoded
// JSON column elsewhere in the row.
const getThreadArchiveStateRowById = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: Schema.Struct({
archivedAt: Schema.NullOr(Schema.String),
deletedAt: Schema.NullOr(Schema.String),
}),
execute: ({ threadId }) =>
sql`
SELECT
archived_at AS "archivedAt",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE thread_id = ${threadId}
LIMIT 1
`,
});
const getActiveThreadRowById = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadDbRowSchema,
@@ -812,6 +845,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE thread_id = ${threadId}
@@ -833,6 +867,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
notification_json AS "notification",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -1104,6 +1139,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
role: row.role,
text: row.text,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
...(row.notification !== null ? { notification: row.notification } : {}),
turnId: row.turnId,
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
@@ -1586,6 +1622,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
latestNotification: row.latestNotification,
} satisfies OrchestrationThreadShell)
: Result.failVoid,
),
@@ -1724,6 +1761,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
latestNotification: row.latestNotification,
}),
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
@@ -1946,6 +1984,26 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
});
const getThreadArchiveStateById: ProjectionSnapshotQueryShape["getThreadArchiveStateById"] = (
threadId,
) =>
getThreadArchiveStateRowById({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadArchiveStateById:query",
"ProjectionSnapshotQuery.getThreadArchiveStateById:decodeRow",
),
),
Effect.map(
Option.flatMap((row) =>
// A soft-deleted row is gone; an archived one is merely parked.
row.deletedAt !== null
? Option.none<{ readonly archivedAt: string | null }>()
: Option.some({ archivedAt: row.archivedAt }),
),
),
);
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
@@ -2001,6 +2059,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
latestNotification: threadRow.value.latestNotification,
} satisfies OrchestrationThreadShell);
});
@@ -2096,7 +2155,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedAt: threadRow.value.snoozedAt,
deletedAt: null,
messages: messageRows.map((row) => {
const message = {
const message: OrchestrationMessage = {
id: row.messageId,
role: row.role,
text: row.text,
@@ -2104,10 +2163,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
streaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
...(row.notification !== null ? { notification: row.notification } : {}),
};
if (row.attachments !== null) {
return Object.assign(message, { attachments: row.attachments });
}
return message;
}),
proposedPlans: proposedPlanRows.map(mapProposedPlanRow),
@@ -2190,6 +2248,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getThreadCheckpointContext,
getFullThreadDiffContext,
getThreadShellById,
getThreadArchiveStateById,
getThreadDetailById,
getThreadDetailSnapshot,
} satisfies ProjectionSnapshotQueryShape;
+2
View File
@@ -19,6 +19,7 @@ import {
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,
ThreadNotificationDeliveredPayload as ContractsThreadNotificationDeliveredPayloadSchema,
ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,
ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,
ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,
@@ -49,6 +50,7 @@ export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;
export const ThreadNotificationDeliveredPayload = ContractsThreadNotificationDeliveredPayloadSchema;
export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;
export const ThreadTurnInterruptRequestedPayload =
@@ -165,6 +165,24 @@ export interface ProjectionSnapshotQueryShape {
threadId: ThreadId,
) => Effect.Effect<Option.Option<OrchestrationThreadShell>, ProjectionRepositoryError>;
/**
* Answer "does this thread row exist", independent of archive state.
*
* Every other thread read here filters `archived_at IS NULL`, which is right
* for "what should the user see" and wrong for existence: an archived thread
* is parked, not gone. Callers holding a durable reference to a specific
* thread — the Hermes home-thread designation — need this distinction, or
* archiving reads as deletion and they replace a thread the user still has.
*
* A soft-deleted row still reports absent.
*/
readonly getThreadArchiveStateById: (
threadId: ThreadId,
) => Effect.Effect<
Option.Option<{ readonly archivedAt: string | null }>,
ProjectionRepositoryError
>;
/**
* Read a single active thread detail snapshot by id.
*/
@@ -68,6 +68,7 @@ const makeQueryLayer = (
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadArchiveStateById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
});
@@ -0,0 +1,237 @@
import {
CommandId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationReadModel,
type OrchestrationThread,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
const NOW = "2026-07-01T00:00:00.000Z";
const DELIVERED_AT = "2026-06-30T09:00:00.000Z";
const SETTLED_AT = "2026-06-29T00:00:00.000Z";
const SNOOZED_UNTIL = "2026-07-02T00:00:00.000Z";
function makeReadModel(input: {
readonly settledOverride?: OrchestrationThread["settledOverride"];
readonly snoozedUntil?: string | null;
readonly messages?: OrchestrationThread["messages"];
}): OrchestrationReadModel {
const settledOverride = input.settledOverride ?? null;
return {
snapshotSequence: 0,
projects: [],
threads: [
{
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Home",
modelSelection: { instanceId: ProviderInstanceId.make("hermes"), model: "hermes" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: NOW,
updatedAt: NOW,
archivedAt: null,
settledOverride,
settledAt: settledOverride === "settled" ? SETTLED_AT : null,
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedUntil != null ? SETTLED_AT : null,
deletedAt: null,
messages: input.messages ?? [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
updatedAt: NOW,
};
}
function deliverCommand(overrides: {
readonly commandId: string;
readonly kind?: "cron" | "message" | "lifecycle" | "handoff" | "other";
readonly deliveryId?: string;
readonly messageId?: string;
readonly text?: string;
}) {
return {
type: "thread.notification.deliver",
commandId: CommandId.make(overrides.commandId),
threadId: ThreadId.make("thread-1"),
messageId: MessageId.make(overrides.messageId ?? "message-1"),
deliveryId: overrides.deliveryId ?? "delivery-1",
kind: overrides.kind ?? "cron",
label: "Cron: daily-digest",
text: overrides.text ?? "Digest ready.",
createdAt: NOW,
} as const;
}
const deliveredMessage: OrchestrationThread["messages"][number] = {
id: MessageId.make("message-1"),
role: "assistant",
text: "Digest ready.",
turnId: null,
streaming: false,
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: DELIVERED_AT,
updatedAt: DELIVERED_AT,
};
it.layer(NodeServices.layer)("notification delivery decider", (it) => {
it.effect("appends a turnless notification message and un-settles the thread", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
command: deliverCommand({ commandId: "cmd-deliver" }),
readModel: makeReadModel({ settledOverride: "settled" }),
});
const events = Array.isArray(result) ? result : [result];
expect(events.map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.notification-delivered",
]);
const unsettled = events[0];
if (unsettled?.type === "thread.unsettled") {
expect(unsettled.payload.reason).toBe("activity");
}
const delivered = events[1];
if (delivered?.type === "thread.notification-delivered") {
expect(delivered.payload.messageId).toBe("message-1");
expect(delivered.payload.text).toBe("Digest ready.");
expect(delivered.payload.notification).toEqual({
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
});
// Nothing about a delivery belongs to a turn; attributing it to the
// thread's live turn would fold it behind that turn's summary.
expect("turnId" in delivered.payload).toBe(false);
}
}),
);
it.effect("un-snoozes as well as un-settles, and does neither when neither applies", () =>
Effect.gen(function* () {
const both = yield* decideOrchestrationCommand({
command: deliverCommand({ commandId: "cmd-deliver-both" }),
readModel: makeReadModel({ settledOverride: "settled", snoozedUntil: SNOOZED_UNTIL }),
});
expect((Array.isArray(both) ? both : [both]).map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.unsnoozed",
"thread.notification-delivered",
]);
const neither = yield* decideOrchestrationCommand({
command: deliverCommand({ commandId: "cmd-deliver-neither" }),
readModel: makeReadModel({}),
});
expect((Array.isArray(neither) ? neither : [neither]).map((event) => event.type)).toEqual([
"thread.notification-delivered",
]);
}),
);
it.effect("appends lifecycle notices quietly, leaving settled and snoozed state alone", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
command: deliverCommand({ commandId: "cmd-lifecycle", kind: "lifecycle" }),
readModel: makeReadModel({ settledOverride: "settled", snoozedUntil: SNOOZED_UNTIL }),
});
const events = Array.isArray(result) ? result : [result];
// Unread indicator only: a restart notice must not drag a thread the
// user has parked back into the inbox.
expect(events.map((event) => event.type)).toEqual(["thread.notification-delivered"]);
}),
);
it.effect("dedupes a replayed deliveryId without appending or waking the thread", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
// The plugin's retry queue resends with a fresh command id, a new
// message id, and possibly edited text — only deliveryId is stable.
command: deliverCommand({
commandId: "cmd-deliver-retry",
messageId: "message-retry",
text: "Digest ready (retry).",
}),
readModel: makeReadModel({
settledOverride: "settled",
snoozedUntil: SNOOZED_UNTIL,
messages: [deliveredMessage],
}),
});
const events = Array.isArray(result) ? result : [result];
// No un-settle/un-snooze: a replay is not new activity.
expect(events.map((event) => event.type)).toEqual(["thread.notification-delivered"]);
const delivered = events[0];
if (delivered?.type === "thread.notification-delivered") {
// Re-emitted from the persisted row, so reducing it a second time is
// a byte-identical no-op rather than a duplicate or an overwrite.
expect(delivered.payload.messageId).toBe("message-1");
expect(delivered.payload.text).toBe("Digest ready.");
expect(delivered.payload.createdAt).toBe(DELIVERED_AT);
expect(delivered.payload.updatedAt).toBe(DELIVERED_AT);
expect(delivered.occurredAt).toBe(DELIVERED_AT);
}
}),
);
it.effect("treats a different deliveryId on the same thread as a new delivery", () =>
Effect.gen(function* () {
const result = yield* decideOrchestrationCommand({
command: deliverCommand({
commandId: "cmd-deliver-second",
deliveryId: "delivery-2",
messageId: "message-2",
text: "Second digest.",
}),
readModel: makeReadModel({
settledOverride: "settled",
messages: [deliveredMessage],
}),
});
const events = Array.isArray(result) ? result : [result];
expect(events.map((event) => event.type)).toEqual([
"thread.unsettled",
"thread.notification-delivered",
]);
const delivered = events[1];
if (delivered?.type === "thread.notification-delivered") {
expect(delivered.payload.messageId).toBe("message-2");
expect(delivered.payload.notification.deliveryId).toBe("delivery-2");
}
}),
);
it.effect("rejects a delivery for a thread that does not exist", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
...deliverCommand({ commandId: "cmd-deliver-missing" }),
threadId: ThreadId.make("thread-missing"),
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
+96
View File
@@ -1197,6 +1197,102 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
return [unsettledEvent, activityAppendedEvent];
}
case "thread.notification.deliver": {
const thread = yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
// Dedupe on deliveryId: the plugin's durable queue retries anything it
// has not seen acked, so the same delivery legitimately arrives more
// than once. Idempotency is by re-emission (see thread.settle) because
// the engine rejects a command that produces no events — but unlike
// settle, the payload must be rebuilt from the ALREADY-WRITTEN message
// rather than from the command, so reducing it a second time lands on
// byte-identical state instead of rewriting the row from a retry whose
// messageId or text may differ.
//
// NOT SUFFICIENT ON ITS OWN. This scans the in-memory read model, which
// `getCommandReadModel` builds with `messages: []` on every thread — it
// deliberately does not hydrate message bodies at boot. So this catches
// only replays of deliveries appended since the process started, and
// sees nothing after a restart. The delivery path re-checks against
// `projection_thread_messages` before dispatching
// (`hermesGatewayHttp.ts`), and that read is what actually holds across
// a restart. Keep both: this one keeps the aggregate self-consistent for
// any future caller, the other one is load-bearing.
const duplicate = thread.messages.find(
(message) => message.notification?.deliveryId === command.deliveryId,
);
const notificationEvent: Omit<OrchestrationEvent, "sequence"> = {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: duplicate?.createdAt ?? command.createdAt,
commandId: command.commandId,
})),
type: "thread.notification-delivered",
payload: {
threadId: command.threadId,
messageId: duplicate?.id ?? command.messageId,
text: duplicate?.text ?? command.text,
notification: duplicate?.notification ?? {
kind: command.kind,
label: command.label,
deliveryId: command.deliveryId,
},
createdAt: duplicate?.createdAt ?? command.createdAt,
updatedAt: duplicate?.updatedAt ?? command.createdAt,
},
};
// A replay is not new activity: it must never wake a thread the user
// has since settled or snoozed.
if (duplicate !== undefined) {
return notificationEvent;
}
// A lifecycle notice ("agent restarted") is bookkeeping, not a claim on
// the user's attention: it appends quietly and leaves a settled or
// snoozed thread where it is. Every other kind is the agent raising its
// hand and resets the lifecycle exactly like a user message does.
if (command.kind === "lifecycle") {
return notificationEvent;
}
const lifecycleResetEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];
if (thread.settledOverride !== null) {
lifecycleResetEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsettled",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
});
}
if (thread.snoozedUntil != null) {
lifecycleResetEvents.push({
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.unsnoozed",
payload: {
threadId: command.threadId,
reason: "activity",
updatedAt: command.createdAt,
},
});
}
return [...lifecycleResetEvents, notificationEvent];
}
default: {
command satisfies never;
const fallback = command as never as { type: string };
@@ -0,0 +1,408 @@
import { assert, it } from "@effect/vitest";
import {
DEFAULT_HERMES_MODEL,
HERMES_DRIVER_KIND,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationCommand,
type OrchestrationProject,
type OrchestrationThreadShell,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { ServerConfig } from "../config.ts";
import * as ServerSettings from "../serverSettings.ts";
import { OrchestrationCommandInvariantError } from "./Errors.ts";
import {
HOME_THREAD_TITLE,
getDesignatedHomeThreadId,
getOrCreateHomeThread,
isHomeThread,
readHomeThreadId,
} from "./homeThreads.ts";
import * as OrchestrationEngine from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
const INSTANCE_ID = ProviderInstanceId.make("hermes-siva-local-abc123");
const OTHER_INSTANCE_ID = ProviderInstanceId.make("hermes-other-def456");
const HOME_THREAD_ID = ThreadId.make("thread-home-1");
const BASE_DIR = "/tmp/t3-home-threads-test";
const agentProject: OrchestrationProject = {
id: ProjectId.make("agent-project-1"),
title: "Hermes Siva Local",
workspaceRoot: `${BASE_DIR}/agents/${INSTANCE_ID}`,
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
agentInstanceId: INSTANCE_ID,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
};
const threadShell = (id: ThreadId): OrchestrationThreadShell =>
({
id,
projectId: agentProject.id,
title: HOME_THREAD_TITLE,
modelSelection: { instanceId: INSTANCE_ID, model: DEFAULT_HERMES_MODEL },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
}) as OrchestrationThreadShell;
const hermesInstance = (config: Record<string, unknown>) => ({
driver: HERMES_DRIVER_KIND,
displayName: "Hermes Siva Local",
enabled: true,
config,
});
/**
* Query stub answering thread reads from a mutable queue, so a test can model
* "designated but deleted" — the self-healing path this module exists for.
*/
const makeQueryLayer = (
threads: Ref.Ref<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>,
archiveStates?: ReadonlyArray<Option.Option<{ readonly archivedAt: string | null }>>,
) =>
Layer.succeed(ProjectionSnapshotQuery, {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.die("unused"),
getActiveAgentProject: () => Effect.succeed(Option.some(agentProject)),
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadArchiveStateById: () =>
Effect.gen(function* () {
if (archiveStates?.[0] !== undefined) return archiveStates[0];
// Default: mirror the shell queue, since a thread visible to the shell
// query is also present. Tests about archiving pass this explicitly.
const queue = yield* Ref.get(threads);
return Option.map(queue[0] ?? Option.none(), () => ({ archivedAt: null }));
}),
getThreadShellById: () =>
Effect.gen(function* () {
const queue = yield* Ref.get(threads);
const [head, ...rest] = queue;
if (head === undefined) return Option.none<OrchestrationThreadShell>();
yield* Ref.set(threads, rest.length > 0 ? rest : [head]);
return head;
}),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
} as unknown as ProjectionSnapshotQuery["Service"]);
const makeEngineLayer = (
dispatched: Ref.Ref<ReadonlyArray<OrchestrationCommand>>,
options: { readonly fail?: boolean } = {},
) =>
Layer.succeed(OrchestrationEngine.OrchestrationEngineService, {
readEvents: () => Stream.empty,
dispatch: (command: OrchestrationCommand) =>
Ref.update(dispatched, (calls) => [...calls, command]).pipe(
Effect.andThen(
options.fail
? Effect.fail(
new OrchestrationCommandInvariantError({
commandType: "thread.create",
detail: "Simulated dispatch failure.",
}),
)
: Effect.succeed({ sequence: 1 }),
),
),
streamDomainEvents: Stream.empty,
latestSequence: Effect.succeed(0),
} as OrchestrationEngine.OrchestrationEngineService["Service"]);
const configLayer = Layer.succeed(ServerConfig, {
baseDir: BASE_DIR,
} as unknown as ServerConfig["Service"]);
const testLayer = (input: {
readonly threads: Ref.Ref<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>;
readonly dispatched: Ref.Ref<ReadonlyArray<OrchestrationCommand>>;
readonly providerInstances: Record<string, unknown>;
readonly failDispatch?: boolean;
/**
* Archive-state rows. Unlike the shell queue these ignore archive state, so
* a test can model "archived, therefore invisible to the shell query but
* still very much present" — the case that used to mint a second Home.
*/
readonly archiveStates?: ReadonlyArray<Option.Option<{ readonly archivedAt: string | null }>>;
}) =>
Layer.mergeAll(
makeQueryLayer(input.threads, input.archiveStates),
makeEngineLayer(input.dispatched, input.failDispatch ? { fail: true } : {}),
configLayer,
ServerSettings.layerTest({
providerInstances: input.providerInstances,
} as never),
NodeServices.layer,
);
it("reads a designation only from a Hermes envelope", () => {
assert.equal(
readHomeThreadId(hermesInstance({ homeThreadId: HOME_THREAD_ID }) as never),
HOME_THREAD_ID,
);
assert.equal(readHomeThreadId(hermesInstance({}) as never), undefined);
// An empty string is "not designated", not a thread whose id is "".
assert.equal(readHomeThreadId(hermesInstance({ homeThreadId: "" }) as never), undefined);
// A designation on a non-Hermes envelope is not ours to honour.
assert.equal(
readHomeThreadId({ driver: "codex", homeThreadId: HOME_THREAD_ID } as never),
undefined,
);
});
it.effect("returns the designated thread without dispatching anything", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.some(threadShell(HOME_THREAD_ID)),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
},
}),
),
);
assert.equal(resolved, HOME_THREAD_ID);
// This runs on every handshake; it must not create anything on the happy path.
assert.deepEqual(yield* Ref.get(dispatched), []);
}),
);
it.effect("creates and persists a Home thread when none is designated", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.none(),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
yield* Effect.gen(function* () {
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
});
const commands = yield* Ref.get(dispatched);
const created = commands.find((command) => command.type === "thread.create");
assert.isDefined(created);
if (created?.type === "thread.create") {
assert.equal(created.threadId, resolved);
assert.equal(created.title, HOME_THREAD_TITLE);
assert.equal(created.projectId, agentProject.id);
// Binds to the fixed Hermes slug, not to whatever model the plugin
// currently reports — otherwise the thread orphans on a model change.
assert.equal(created.modelSelection.model, DEFAULT_HERMES_MODEL);
}
// The designation must be durable, or the next handshake mints a second
// Home and the first one's history is stranded.
assert.equal(yield* getDesignatedHomeThreadId(INSTANCE_ID), resolved);
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
providerInstances: { [INSTANCE_ID]: hermesInstance({}) },
}),
),
);
}),
);
it.effect("self-heals a designation whose thread no longer exists", () =>
Effect.gen(function* () {
// A deleted home thread must not strand the instance: it re-designates
// rather than failing every future delivery.
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.none(),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: "thread-deleted-long-ago" }),
},
}),
),
);
assert.notEqual(resolved, "thread-deleted-long-ago");
const commands = yield* Ref.get(dispatched);
assert.isDefined(commands.find((command) => command.type === "thread.create"));
}),
);
it.effect("adopts a racing caller's designation when its own dispatch fails", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.none(),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
// The loser of the race sees a dispatch failure but must still return the
// winner's thread rather than surfacing an error to the handshake.
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
failDispatch: true,
providerInstances: {
// Designated, but the thread read says gone — so it falls through
// to create, fails, and re-reads the designation.
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
},
}),
),
);
assert.equal(resolved, HOME_THREAD_ID);
}),
);
it.effect("recognizes any instance's home thread as undeletable", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
yield* Effect.gen(function* () {
assert.isTrue(yield* isHomeThread(HOME_THREAD_ID));
// Scans every instance, not just one — the delete path knows only a thread.
assert.isTrue(yield* isHomeThread(ThreadId.make("thread-home-2")));
assert.isFalse(yield* isHomeThread(ThreadId.make("thread-ordinary")));
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
[OTHER_INSTANCE_ID]: hermesInstance({ homeThreadId: "thread-home-2" }),
},
}),
),
);
}),
);
it.effect("keeps an archived Home rather than minting a replacement", () =>
Effect.gen(function* () {
// The bug this pins: `getThreadShellById` filters `archived_at IS NULL`, so
// an archived Home read as *deleted* and the self-healing path created a
// second one — stranding the real history and silently re-pointing the
// designation at an empty thread.
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.none(),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
const resolved = yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
archiveStates: [Option.some({ archivedAt: "2026-01-02T00:00:00.000Z" })],
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
},
}),
),
);
assert.equal(resolved, HOME_THREAD_ID);
const commands = yield* Ref.get(dispatched);
assert.isUndefined(
commands.find((command) => command.type === "thread.create"),
"an archived Home must never be replaced by a new thread",
);
// A delivery is the agent raising its hand, so it brings the thread back
// rather than landing somewhere the user cannot see.
const unarchive = commands.find((command) => command.type === "thread.unarchive");
assert.isDefined(unarchive);
if (unarchive?.type === "thread.unarchive") {
assert.equal(unarchive.threadId, HOME_THREAD_ID);
}
}),
);
it.effect("does not un-archive a Home that was never archived", () =>
Effect.gen(function* () {
const threads = yield* Ref.make<ReadonlyArray<Option.Option<OrchestrationThreadShell>>>([
Option.some(threadShell(HOME_THREAD_ID)),
]);
const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationCommand>>([]);
yield* getOrCreateHomeThread({
instanceId: INSTANCE_ID,
title: "Hermes Siva Local",
}).pipe(
Effect.provide(
testLayer({
threads,
dispatched,
archiveStates: [Option.some({ archivedAt: null })],
providerInstances: {
[INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }),
},
}),
),
);
// The common path stays free of writes; this runs on every handshake.
assert.deepEqual(yield* Ref.get(dispatched), []);
}),
);
@@ -0,0 +1,242 @@
/**
* Home threads — the one thread per agent instance that receives its agent's
* proactive output.
*
* Hermes has a first-class "home channel" concept: a per-platform default
* destination for output nobody asked for at a specific address — a cron job's
* result, an agent-initiated `send_message`, a gateway online notice, a
* `/handoff`. Every other Hermes surface designates one interactively via
* `/sethome`. T3 designates one automatically instead, because there is no
* "current channel" here for a user to point at: threads are created on
* demand, and asking someone to pick one before their first cron job can fire
* is setup for a decision they have no basis to make.
*
* ## Converge-on-read, like agent projects
*
* `getOrCreateHomeThread` is a **precondition every caller runs**, not a
* lifecycle event one caller owns — the same reasoning as
* `getOrCreateAgentProject`, and for the same failure modes: an instance
* enrolled before this shipped has no designation, a dispatch that failed once
* would otherwise leave the instance permanently unable to receive, and a
* thread deleted out from under the designation would strand every future
* delivery. Each of those self-heals on the next handshake.
*
* ## Why settings and not a table
*
* The designation is per-instance enrollment metadata, exactly like
* `connectorUrl` and `revoked`, and it lives beside them in the Hermes
* instance's config blob. That keeps one source of truth for "facts about this
* enrollment" and avoids a migration for a single nullable id.
*
* The plugin's `T3_HOME_CHANNEL` env var is a *cache* of this value, reconciled
* on every `connection.accepted`. This module is authoritative; drift is
* bounded by one reconnect.
*
* @module orchestration/homeThreads
*/
import {
CommandId,
DEFAULT_HERMES_MODEL,
DEFAULT_PROVIDER_INTERACTION_MODE,
HERMES_DRIVER_KIND,
ThreadId,
type ProviderInstanceConfig,
type ProviderInstanceId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { ServerSettingsService } from "../serverSettings.ts";
import { getOrCreateAgentProject } from "./agentProjects.ts";
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
/**
* Title of the home thread. Plain, no emoji: it sits in the same list as the
* user's own threads and should not shout.
*/
export const HOME_THREAD_TITLE = "Home";
/** Read the designated home thread id out of a Hermes instance envelope. */
export const readHomeThreadId = (
config: ProviderInstanceConfig | undefined,
): ThreadId | undefined => {
if (!config || config.driver !== HERMES_DRIVER_KIND) return undefined;
const blob = config.config && typeof config.config === "object" ? config.config : {};
const raw = (blob as Record<string, unknown>).homeThreadId;
return typeof raw === "string" && raw !== "" ? ThreadId.make(raw) : undefined;
};
/**
* Read one instance's designation straight from settings.
*
* Callers that only need to *know* the designation — the snapshot builder, the
* delete guard — use this rather than `getOrCreateHomeThread`, so a read never
* has the side effect of creating a thread.
*/
export const getDesignatedHomeThreadId = Effect.fn("getDesignatedHomeThreadId")(function* (
instanceId: ProviderInstanceId,
) {
const settings = yield* ServerSettingsService;
const current = yield* settings.getSettings;
return readHomeThreadId(current.providerInstances[instanceId]);
});
/**
* Whether a thread is some instance's home thread, and therefore undeletable.
*
* Scans every configured instance rather than taking an instance id, because
* the delete path knows only the thread. The map is small — one entry per
* configured provider instance — and this runs once per delete.
*/
export const isHomeThread = Effect.fn("isHomeThread")(function* (threadId: ThreadId) {
const settings = yield* ServerSettingsService;
const current = yield* settings.getSettings;
for (const config of Object.values(current.providerInstances)) {
if (readHomeThreadId(config) === threadId) return true;
}
return false;
});
/**
* Read the designated thread's row regardless of archive state.
*
* The snapshot query's thread reads filter `archived_at IS NULL`, which is
* correct for "what should the user see" and wrong for "does this row exist".
* Going to the repository directly is what keeps an archived Home from looking
* deleted — and thereby keeps this module from minting a second one. A
* soft-deleted row still counts as gone.
*/
const readHomeThreadRow = Effect.fn("readHomeThreadRow")(function* (threadId: ThreadId) {
const query = yield* ProjectionSnapshotQuery;
const row = yield* query.getThreadArchiveStateById(threadId);
return Option.getOrUndefined(row);
});
/** Persist a designation into the instance's Hermes config blob. */
const persistHomeThreadId = (input: {
readonly instanceId: ProviderInstanceId;
readonly threadId: ThreadId;
}) =>
Effect.gen(function* () {
const settings = yield* ServerSettingsService;
yield* settings.updateSettingsWith((latest) => {
// Re-read under the settings write lock: the envelope may have been
// replaced (or the driver changed) between our read and this write, and
// writing a Hermes designation onto a non-Hermes envelope would corrupt
// it. Returning an empty patch is the established no-op here.
const existing = latest.providerInstances[input.instanceId];
if (!existing || existing.driver !== HERMES_DRIVER_KIND) return {};
const currentConfig =
existing.config && typeof existing.config === "object"
? (existing.config as Record<string, unknown>)
: {};
return {
providerInstances: {
...latest.providerInstances,
[input.instanceId]: {
...existing,
config: { ...currentConfig, homeThreadId: input.threadId },
},
},
};
});
});
/**
* Resolve the home thread for one provider instance, creating it if absent.
*
* Safe to call on every handshake: the common path is one settings read plus
* one indexed thread read. Idempotent, and concurrent callers converge —
* the loser of a race re-reads and adopts the winner's thread.
*/
export const getOrCreateHomeThread = Effect.fn("getOrCreateHomeThread")(function* (input: {
readonly instanceId: ProviderInstanceId;
/** Instance nickname, used as the agent project's title on first creation. */
readonly title: string;
}) {
const engine = yield* OrchestrationEngineService;
const crypto = yield* Crypto.Crypto;
const designated = yield* getDesignatedHomeThreadId(input.instanceId);
if (designated !== undefined) {
// Deliberately NOT `getThreadShellById`: that query filters
// `archived_at IS NULL`, so an archived Home reads as absent and this
// function would "self-heal" by minting a second Home — stranding the
// history in the archived one and silently re-pointing the designation.
// Archiving is a user parking a thread, not destroying it; only a row
// that is really gone justifies a replacement.
const existing = yield* readHomeThreadRow(designated);
if (existing !== undefined) {
// Un-archive rather than deliver into a hidden thread. A delivery is
// the agent raising its hand, and the same rule the decider applies to
// settled/snoozed threads applies here: incoming activity brings the
// thread back. Best-effort — a failure here must not cost the delivery.
if (existing.archivedAt !== null) {
yield* engine
.dispatch({
type: "thread.unarchive",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId: designated,
})
.pipe(
Effect.catchCause((cause) =>
Effect.logWarning("could not un-archive the home thread", {
instanceId: input.instanceId,
threadId: designated,
cause: Cause.pretty(cause),
}),
),
);
}
return designated;
}
}
const project = yield* getOrCreateAgentProject({
instanceId: input.instanceId,
title: input.title,
});
const threadId = ThreadId.make(yield* crypto.randomUUIDv4);
const createdAt = DateTime.formatIso(yield* DateTime.now);
const dispatched = yield* Effect.result(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId,
projectId: project.id,
title: HOME_THREAD_TITLE,
// The same fixed slug every Hermes thread binds to — the reported model
// name is display-only, and following it here would orphan the thread
// whenever Hermes' own config changed.
modelSelection: { instanceId: input.instanceId, model: DEFAULT_HERMES_MODEL },
runtimeMode: "full-access",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
branch: null,
worktreePath: null,
createdAt,
}),
);
if (dispatched._tag === "Failure") {
// A concurrent handshake may have won and already persisted its thread.
// Re-read before surfacing the error, matching getOrCreateAgentProject.
const raced = yield* getDesignatedHomeThreadId(input.instanceId);
if (raced !== undefined) return raced;
return yield* Effect.fail(dispatched.failure);
}
yield* persistHomeThreadId({ instanceId: input.instanceId, threadId });
// Re-read rather than trusting our own write: if a racing caller persisted
// first, both callers must agree on one thread, and settings is the
// tiebreaker. Our orphaned thread stays as an empty thread in the project
// rather than becoming a second home.
const settled = yield* getDesignatedHomeThreadId(input.instanceId);
return settled ?? threadId;
});
@@ -0,0 +1,149 @@
import {
CommandId,
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const CREATED_AT = "2026-07-01T09:00:00.000Z";
const DELIVERED_AT = "2026-07-01T09:05:00.000Z";
function makeEvent(input: {
readonly sequence: number;
readonly type: OrchestrationEvent["type"];
readonly occurredAt: string;
readonly payload: unknown;
}): OrchestrationEvent {
return {
sequence: input.sequence,
eventId: EventId.make(`event-${input.sequence}`),
type: input.type,
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-home"),
occurredAt: input.occurredAt,
commandId: CommandId.make(`command-${input.sequence}`),
causationEventId: null,
correlationId: null,
metadata: {},
payload: input.payload as never,
} as OrchestrationEvent;
}
const threadCreatedEvent = makeEvent({
sequence: 1,
type: "thread.created",
occurredAt: CREATED_AT,
payload: {
threadId: ThreadId.make("thread-home"),
projectId: ProjectId.make("project-1"),
title: "Home",
modelSelection: { instanceId: ProviderInstanceId.make("hermes"), model: "hermes" },
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: CREATED_AT,
updatedAt: CREATED_AT,
},
});
const deliveryEvent = makeEvent({
sequence: 2,
type: "thread.notification-delivered",
occurredAt: DELIVERED_AT,
payload: {
threadId: ThreadId.make("thread-home"),
messageId: MessageId.make("notification:msg-1"),
text: "Digest ready.",
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: DELIVERED_AT,
updatedAt: DELIVERED_AT,
},
});
const expectedMessage = {
id: "notification:msg-1",
role: "assistant",
text: "Digest ready.",
// A delivery belongs to no turn and is never streamed.
turnId: null,
streaming: false,
notification: {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
},
createdAt: DELIVERED_AT,
updatedAt: DELIVERED_AT,
};
it.effect("appends a notification delivery as a turnless assistant message", () =>
Effect.gen(function* () {
const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent);
const delivered = yield* projectEvent(created, deliveryEvent);
const thread = delivered.threads[0];
expect(thread?.messages).toHaveLength(1);
expect(thread?.messages[0]).toEqual(expectedMessage);
expect(thread?.updatedAt).toBe(DELIVERED_AT);
// Nothing about a delivery touches turn state — attributing it to the
// thread's live turn would fold it behind that turn's summary.
expect(thread?.latestTurn).toBeNull();
}),
);
it.effect("replays a delivery onto the same message instead of duplicating it", () =>
Effect.gen(function* () {
const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent);
const delivered = yield* projectEvent(created, deliveryEvent);
// The decider re-emits the persisted row for a replayed deliveryId, so
// reducing the event twice must be a no-op rather than an append.
const replayed = yield* projectEvent(delivered, { ...deliveryEvent, sequence: 3 });
expect(replayed.threads[0]?.messages).toHaveLength(1);
expect(replayed.threads[0]?.messages[0]).toEqual(expectedMessage);
}),
);
it.effect("keeps deliveries alongside ordinary turn messages", () =>
Effect.gen(function* () {
const created = yield* projectEvent(createEmptyReadModel(CREATED_AT), threadCreatedEvent);
const withUserMessage = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.message-sent",
occurredAt: "2026-07-01T09:01:00.000Z",
payload: {
threadId: ThreadId.make("thread-home"),
messageId: MessageId.make("msg-user"),
role: "user",
text: "hi",
turnId: null,
streaming: false,
createdAt: "2026-07-01T09:01:00.000Z",
updatedAt: "2026-07-01T09:01:00.000Z",
},
}),
);
const delivered = yield* projectEvent(withUserMessage, { ...deliveryEvent, sequence: 3 });
expect(delivered.threads[0]?.messages.map((message) => message.id)).toEqual([
"msg-user",
"notification:msg-1",
]);
// Absence of `notification` is what marks an ordinary message; it must
// never be synthesized onto one.
expect(delivered.threads[0]?.messages[0]?.notification).toBeUndefined();
}),
);
@@ -21,6 +21,7 @@ import {
ThreadDeletedPayload,
ThreadInteractionModeSetPayload,
ThreadMetaUpdatedPayload,
ThreadNotificationDeliveredPayload,
ThreadProposedPlanUpsertedPayload,
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
@@ -722,6 +723,55 @@ export function projectEvent(
}),
);
case "thread.notification-delivered":
return Effect.gen(function* () {
const payload = yield* decodeForEvent(
ThreadNotificationDeliveredPayload,
event.payload,
event.type,
"payload",
);
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
const message: OrchestrationMessage = yield* decodeForEvent(
OrchestrationMessage,
{
id: payload.messageId,
role: "assistant",
text: payload.text,
// A delivery belongs to no turn: it arrives outside the turn
// machinery and may land while an unrelated turn is live.
turnId: null,
streaming: false,
notification: payload.notification,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
},
event.type,
"message",
);
// Replays of an already-written delivery re-emit the persisted row, so
// replacing in place is a byte-identical no-op rather than a duplicate.
const existingMessage = thread.messages.find((entry) => entry.id === message.id);
const messages = (
existingMessage
? thread.messages.map((entry) => (entry.id === message.id ? message : entry))
: [...thread.messages, message]
).slice(-MAX_THREAD_MESSAGES);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
messages,
updatedAt: event.occurredAt,
}),
};
});
case "thread.activity-appended":
return decodeForEvent(
ThreadActivityAppendedPayload,
@@ -100,6 +100,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
pendingApprovalCount: 0,
pendingUserInputCount: 0,
hasActionableProposedPlan: 0,
latestNotification: null,
deletedAt: null,
});
@@ -162,6 +163,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
pendingApprovalCount: 0,
pendingUserInputCount: 0,
hasActionableProposedPlan: 0,
latestNotification: null,
deletedAt: null,
});
@@ -66,6 +66,80 @@ layer("ProjectionThreadMessageRepository", (it) => {
}),
);
it.effect("round-trips notification provenance and preserves it across later upserts", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.make("thread-notification");
const messageId = MessageId.make("message-notification");
const createdAt = "2026-07-01T09:00:00.000Z";
const notification = {
kind: "cron" as const,
label: "Cron: daily-digest",
deliveryId: "delivery-1",
};
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "assistant",
text: "Digest ready.",
notification,
isStreaming: false,
createdAt,
updatedAt: createdAt,
});
const rows = yield* repository.listByThreadId({ threadId });
assert.equal(rows.length, 1);
assert.deepEqual(rows[0]?.notification, notification);
// Same COALESCE rule as attachments: an unrelated update that omits the
// field must not erase a delivery's provenance.
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "assistant",
text: "Digest ready (edited).",
isStreaming: false,
createdAt,
updatedAt: "2026-07-01T09:00:02.000Z",
});
const rowById = yield* repository.getByMessageId({ messageId });
assert.equal(rowById._tag, "Some");
if (rowById._tag === "Some") {
assert.equal(rowById.value.text, "Digest ready (edited).");
assert.deepEqual(rowById.value.notification, notification);
}
}),
);
it.effect("leaves notification absent on ordinary messages", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.make("thread-ordinary-message");
const messageId = MessageId.make("message-ordinary");
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "user",
text: "hello",
isStreaming: false,
createdAt: "2026-07-01T09:10:00.000Z",
updatedAt: "2026-07-01T09:10:00.000Z",
});
const rows = yield* repository.listByThreadId({ threadId });
// Absent, not a synthesized default — consumers key on its absence to
// tell an ordinary message from a proactive delivery.
assert.equal(rows[0]?.notification, undefined);
}),
);
it.effect("allows explicit attachment clearing with an empty array", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
@@ -5,7 +5,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Struct from "effect/Struct";
import { ChatAttachment } from "@t3tools/contracts";
import { ChatAttachment, OrchestrationMessageNotification } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
@@ -21,6 +21,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
Struct.assign({
isStreaming: Schema.Number,
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
notification: Schema.NullOr(Schema.fromJsonString(OrchestrationMessageNotification)),
}),
);
@@ -37,6 +38,7 @@ function toProjectionThreadMessage(
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
...(row.notification !== null ? { notification: row.notification } : {}),
};
}
@@ -48,6 +50,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
execute: (row) => {
const nextAttachmentsJson =
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
const nextNotificationJson =
row.notification !== undefined ? JSON.stringify(row.notification) : null;
return sql`
INSERT INTO projection_thread_messages (
message_id,
@@ -56,6 +60,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
role,
text,
attachments_json,
notification_json,
is_streaming,
created_at,
updated_at
@@ -74,6 +79,14 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
WHERE message_id = ${row.messageId}
)
),
COALESCE(
${nextNotificationJson},
(
SELECT notification_json
FROM projection_thread_messages
WHERE message_id = ${row.messageId}
)
),
${row.isStreaming ? 1 : 0},
${row.createdAt},
${row.updatedAt}
@@ -88,6 +101,10 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
excluded.attachments_json,
projection_thread_messages.attachments_json
),
notification_json = COALESCE(
excluded.notification_json,
projection_thread_messages.notification_json
),
is_streaming = excluded.is_streaming,
created_at = excluded.created_at,
updated_at = excluded.updated_at
@@ -107,6 +124,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
notification_json AS "notification",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -128,6 +146,7 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
role,
text,
attachments_json AS "attachments",
notification_json AS "notification",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
@@ -14,11 +14,14 @@ import {
ProjectionThreadRepository,
type ProjectionThreadRepositoryShape,
} from "../Services/ProjectionThreads.ts";
import { ModelSelection } from "@t3tools/contracts";
import { ModelSelection, OrchestrationThreadNotificationSummary } from "@t3tools/contracts";
const ProjectionThreadDbRow = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
latestNotification: Schema.NullOr(
Schema.fromJsonString(OrchestrationThreadNotificationSummary),
),
}),
);
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
@@ -28,8 +31,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
const upsertProjectionThreadRow = SqlSchema.void({
Request: ProjectionThread,
execute: (row) =>
sql`
execute: (row) => {
const latestNotificationJson =
row.latestNotification === null ? null : JSON.stringify(row.latestNotification);
return sql`
INSERT INTO projection_threads (
thread_id,
project_id,
@@ -51,6 +56,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
latest_notification_json,
deleted_at
)
VALUES (
@@ -74,6 +80,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.pendingApprovalCount},
${row.pendingUserInputCount},
${row.hasActionableProposedPlan},
${latestNotificationJson},
${row.deletedAt}
)
ON CONFLICT (thread_id)
@@ -97,8 +104,10 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
pending_approval_count = excluded.pending_approval_count,
pending_user_input_count = excluded.pending_user_input_count,
has_actionable_proposed_plan = excluded.has_actionable_proposed_plan,
latest_notification_json = excluded.latest_notification_json,
deleted_at = excluded.deleted_at
`,
`;
},
});
const getProjectionThreadRow = SqlSchema.findOneOption({
@@ -127,6 +136,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE thread_id = ${threadId}
@@ -159,6 +169,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
latest_notification_json AS "latestNotification",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE project_id = ${projectId}
@@ -48,6 +48,8 @@ import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionProjectsAgentInstance.ts";
import Migration0036 from "./Migrations/036_ProjectionThreadMessageNotification.ts";
import Migration0037 from "./Migrations/037_ProjectionThreadsLatestNotification.ts";
/**
* Migration loader with all migrations defined inline.
@@ -95,6 +97,8 @@ export const migrationEntries = [
[33, "ProjectionThreadsSettled", Migration0033],
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionProjectsAgentInstance", Migration0035],
[36, "ProjectionThreadMessageNotification", Migration0036],
[37, "ProjectionThreadsLatestNotification", Migration0037],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,109 @@
import { assert, it } from "@effect/vitest";
import { OrchestrationMessageNotification } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("036_ProjectionThreadMessageNotification", (it) => {
it.effect("adds the notification column without disturbing existing messages", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 35 });
// An ordinary message written before the column existed. Proactive
// deliveries are the exception, so every pre-existing row must survive
// the migration with no notification rather than a synthesized default.
yield* sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
is_streaming,
created_at,
updated_at
) VALUES (
'message-1',
'thread-1',
'turn-1',
'assistant',
'an ordinary answer',
0,
'2026-01-01T00:00:00.000Z',
'2026-01-01T00:00:00.000Z'
)
`;
yield* runMigrations({ toMigrationInclusive: 36 });
const rows = yield* sql<{
readonly message_id: string;
readonly text: string;
readonly notification_json: string | null;
}>`
SELECT message_id, text, notification_json
FROM projection_thread_messages
WHERE message_id = 'message-1'
`;
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "an ordinary answer");
assert.equal(rows[0]?.notification_json, null);
// And the new column accepts a delivery's provenance.
yield* sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
is_streaming,
created_at,
updated_at,
notification_json
) VALUES (
'message-2',
'thread-1',
NULL,
'assistant',
'Your digest is ready.',
0,
'2026-01-01T00:01:00.000Z',
'2026-01-01T00:01:00.000Z',
'{"kind":"cron","label":"Cron: daily-digest","deliveryId":"delivery-1"}'
)
`;
const delivered = yield* sql<{
readonly notification_json: string | null;
readonly turn_id: string | null;
}>`
SELECT notification_json, turn_id
FROM projection_thread_messages
WHERE message_id = 'message-2'
`;
assert.equal(delivered.length, 1);
// A delivery belongs to no turn — attributing it to the thread's live
// turn would fold it away behind that turn's "Worked for …" row.
assert.equal(delivered[0]?.turn_id, null);
const decodedNotification = yield* Schema.decodeUnknownEffect(
Schema.fromJsonString(OrchestrationMessageNotification),
)(delivered[0]?.notification_json ?? "");
assert.deepEqual(decodedNotification, {
kind: "cron",
label: "Cron: daily-digest",
deliveryId: "delivery-1",
});
}),
);
});
@@ -0,0 +1,11 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_thread_messages
ADD COLUMN notification_json TEXT
`;
});
@@ -0,0 +1,80 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("037_ProjectionThreadsLatestNotification", (it) => {
it.effect("adds a nullable latest_notification_json column, leaving existing rows null", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 36 });
const before = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
assert.ok(!before.some((column) => column.name === "latest_notification_json"));
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
deleted_at
)
VALUES (
'thread-pre-037',
'project-pre-037',
'Existing thread',
'{"instanceId":"codex","model":"gpt-5.4"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-07-01T00:00:00.000Z',
'2026-07-01T00:00:00.000Z',
NULL
)
`;
yield* runMigrations({ toMigrationInclusive: 37 });
const after = yield* sql<{
readonly name: string;
readonly type: string;
readonly notnull: number;
readonly dflt_value: string | null;
}>`
PRAGMA table_info(projection_threads)
`;
const column = after.find((entry) => entry.name === "latest_notification_json");
assert.ok(column);
assert.strictEqual(column.type, "TEXT");
assert.strictEqual(column.notnull, 0);
assert.strictEqual(column.dflt_value, null);
// No backfill is needed or possible: notification_json (migration 036)
// is newer than every pre-existing row, so nothing to summarize.
const rows = yield* sql<{ readonly latestNotification: string | null }>`
SELECT latest_notification_json AS "latestNotification"
FROM projection_threads
WHERE thread_id = 'thread-pre-037'
`;
assert.deepStrictEqual(rows, [{ latestNotification: null }]);
}),
);
});
@@ -0,0 +1,22 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as Effect from "effect/Effect";
/**
* Materializes the thread's newest proactive delivery onto the shell row.
*
* Shell consumers (sidebar, agent-awareness/push) never read a thread's
* messages, so notification provenance that lives on the message row is
* invisible to them unless it is summarized here — the same reason
* `latest_user_message_at` exists.
*
* No backfill: `projection_thread_messages.notification_json` is introduced by
* migration 036, so no delivery predates this column.
*/
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN latest_notification_json TEXT
`;
});
@@ -9,6 +9,7 @@
import {
ChatAttachment,
MessageId,
OrchestrationMessageNotification,
OrchestrationMessageRole,
ThreadId,
TurnId,
@@ -28,6 +29,14 @@ export const ProjectionThreadMessage = Schema.Struct({
role: OrchestrationMessageRole,
text: Schema.String,
attachments: Schema.optional(Schema.Array(ChatAttachment)),
/**
* Proactive-delivery provenance, present only on notification rows.
*
* Optional like `attachments`, and persisted with the same
* `COALESCE(excluded, existing)` upsert rule: an ordinary update that omits
* it must not erase the provenance of a row that has it.
*/
notification: Schema.optional(OrchestrationMessageNotification),
isStreaming: Schema.Boolean,
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -10,6 +10,7 @@ import {
IsoDateTime,
ModelSelection,
NonNegativeInt,
OrchestrationThreadNotificationSummary,
ProjectId,
ProviderInteractionMode,
RuntimeMode,
@@ -44,6 +45,12 @@ export const ProjectionThread = Schema.Struct({
pendingApprovalCount: NonNegativeInt,
pendingUserInputCount: NonNegativeInt,
hasActionableProposedPlan: NonNegativeInt,
/**
* Newest proactive delivery on this thread, summarized so shell readers do
* not have to load messages. Refreshed alongside the other shell-summary
* columns; `null` on every thread that has never received a delivery.
*/
latestNotification: Schema.NullOr(OrchestrationThreadNotificationSummary),
deletedAt: Schema.NullOr(IsoDateTime),
});
export type ProjectionThread = typeof ProjectionThread.Type;
@@ -44,6 +44,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadArchiveStateById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
});
@@ -4,13 +4,17 @@ import {
HermesSettings,
TextGenerationError,
type ServerProvider,
type ServerSettings,
} from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { readHomeThreadId } from "../../orchestration/homeThreads.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import type { TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { makeHermesAdapter } from "../Layers/HermesAdapter.ts";
import {
@@ -23,7 +27,7 @@ import { HermesGatewayBroker } from "../Services/HermesGatewayBroker.ts";
const decodeHermesSettings = Schema.decodeSync(HermesSettings);
export type HermesDriverEnv = Crypto.Crypto;
export type HermesDriverEnv = Crypto.Crypto | ServerSettingsService;
const unsupportedTextGeneration = (
operation:
@@ -57,6 +61,9 @@ export const HermesDriver: ProviderDriver<HermesSettings, HermesDriverEnv> = {
create: ({ instanceId, displayName, accentColor, enabled }) =>
Effect.gen(function* () {
const broker = yield* HermesGatewayBroker;
// Captured once at construction: `getSnapshot` must be context-free
// (`R = never`) because the registry calls it outside this scope.
const settings = yield* ServerSettingsService;
const adapter = yield* makeHermesAdapter({ instanceId });
const continuationIdentity = defaultProviderContinuationIdentity({
driverKind: HERMES_DRIVER_KIND,
@@ -71,7 +78,19 @@ export const HermesDriver: ProviderDriver<HermesSettings, HermesDriverEnv> = {
const status = yield* broker
.getInstanceStatus(instanceId)
.pipe(Effect.catchTag("HermesGatewayManagementError", () => Effect.succeed(undefined)));
// Read-only: a snapshot must never create the thread as a side effect
// (this runs on every status tick). The handshake owns creation.
// A settings read that fails degrades to "no designation" rather than
// failing the whole snapshot — the pin is cosmetic, the status is not.
const currentSettings = yield* settings.getSettings.pipe(
Effect.map(Option.some),
Effect.orElseSucceed(() => Option.none<ServerSettings>()),
);
const homeThreadId = Option.isSome(currentSettings)
? readHomeThreadId(currentSettings.value.providerInstances[instanceId])
: undefined;
return {
...(homeThreadId !== undefined ? { homeThreadId } : {}),
instanceId,
driver: HERMES_DRIVER_KIND,
...(displayName ? { displayName } : {}),
@@ -39,6 +39,13 @@ import {
makeHermesGatewayBroker,
} from "./HermesGatewayBroker.ts";
/**
* A version this server does not speak. Expressed relative to the supported
* version rather than as a literal, so bumping the protocol does not turn
* these "must be rejected" cases into "is the current version" cases.
*/
const UNSUPPORTED_PROTOCOL_VERSION = HERMES_GATEWAY_PROTOCOL_VERSION + 1;
const instanceId = ProviderInstanceId.make("hermes_remote");
const otherInstanceId = ProviderInstanceId.make("hermes_other");
const defaultHermesInstanceId = ProviderInstanceId.make("hermes");
@@ -94,7 +101,10 @@ const testLayer = Layer.mergeAll(
const hello = (
authentication: HermesGatewayConnectionHello["authentication"],
protocolVersion: number = HERMES_GATEWAY_PROTOCOL_VERSION,
overrides: { readonly model?: string } = {},
overrides: {
readonly model?: string;
readonly role?: HermesGatewayConnectionHello["role"];
} = {},
): HermesGatewayConnectionHello => ({
type: "connection.hello",
requestId: HermesGatewayRequestId.make(`hello-${protocolVersion}`),
@@ -103,6 +113,7 @@ const hello = (
hermesVersion: "1.0.0",
capabilities: { ...capabilities, protocolVersion },
authentication,
role: overrides.role ?? "gateway",
...(overrides.model !== undefined ? { model: overrides.model } : {}),
});
@@ -174,7 +185,7 @@ it.effect("authenticates before applying incompatible connection state", () =>
instanceId,
credential: HermesGatewayCredential.make("not-the-real-credential"),
},
3,
UNSUPPORTED_PROTOCOL_VERSION,
),
second.transport,
),
@@ -202,7 +213,7 @@ it.effect("authenticates before applying incompatible connection state", () =>
instanceId,
credential: registered.accepted.credential!,
},
3,
UNSUPPORTED_PROTOCOL_VERSION,
),
second.transport,
),
@@ -214,7 +225,10 @@ it.effect("authenticates before applying incompatible connection state", () =>
const otherEnrollment = yield* enroll(broker, otherInstanceId, "Other Hermes");
const incompatibleEnrollment = yield* Effect.flip(
broker.registerConnection(
hello({ type: "enrollment-token", token: otherEnrollment.oneTimeToken }, 3),
hello(
{ type: "enrollment-token", token: otherEnrollment.oneTimeToken },
UNSUPPORTED_PROTOCOL_VERSION,
),
second.transport,
),
);
@@ -1226,3 +1240,85 @@ it.effect("migrates a revoked legacy instance and drops its credential", () =>
assert.equal(reconnect.code, "invalid-authentication");
}).pipe(Effect.provide(testLayer)),
);
it.effect("a delivery connection never displaces the live gateway connection", () =>
Effect.gen(function* () {
// The failure this guards: an out-of-process cron run dials in to hand
// over one delivery, `registerConnection` treats it as a replacement, and
// the real plugin gets closed with 4001 — knocking Hermes offline for the
// duration of a cron job.
const broker = yield* makeBroker(makeSecretStore());
const enrollment = yield* enroll(broker, instanceId, "Remote Hermes");
const live = recordingTransport();
const gateway = yield* broker.registerConnection(
hello({ type: "enrollment-token", token: enrollment.oneTimeToken }),
live.transport,
);
assert.equal(gateway.role, "gateway");
assert.isTrue(yield* broker.isConnected(instanceId));
const credential = gateway.accepted.credential!;
const cron = recordingTransport();
const delivery = yield* broker.registerConnection(
hello(
{ type: "instance-credential", instanceId, credential },
HERMES_GATEWAY_PROTOCOL_VERSION,
{ role: "delivery" },
),
cron.transport,
);
assert.equal(delivery.role, "delivery");
// No generation: it was never registered, so there is nothing for it to
// be stale against — and a generation would let it be compared with, and
// mistaken for, the live connection.
assert.equal(delivery.generation, null);
assert.deepEqual(live.closes, [], "the live gateway socket must not be closed");
assert.isTrue(yield* broker.isConnected(instanceId));
// A delivery socket holds no session, so it must not be able to answer
// the live connection's outstanding requests — otherwise a throwaway cron
// socket could speak for the real plugin.
const threadId = ThreadId.make("delivery-fencing-thread");
const pendingRequestId = HermesGatewayRequestId.make("delivery-fencing-session");
const pending = yield* broker
.request(instanceId, {
type: "session.ensure",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: pendingRequestId,
threadId,
})
.pipe(Effect.forkChild({ startImmediately: true }));
yield* Effect.yieldNow;
yield* broker.receive(delivery, {
type: "session.ready",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: pendingRequestId,
threadId,
sessionId: HermesGatewaySessionId.make("delivery-forged-session"),
resumed: false,
});
yield* Effect.yieldNow;
assert.isUndefined(
pending.pollUnsafe(),
"a delivery connection must not complete the live connection's requests",
);
// The live connection still can.
yield* broker.receive(gateway, {
type: "session.ready",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
requestId: pendingRequestId,
threadId,
sessionId: HermesGatewaySessionId.make("real-session"),
resumed: false,
});
assert.equal((yield* Fiber.join(pending)).type, "session.ready");
// Closing the delivery socket is its normal lifecycle and must leave the
// instance's liveness untouched.
yield* broker.disconnect(delivery);
assert.isTrue(yield* broker.isConnected(instanceId));
assert.deepEqual(live.closes, []);
}).pipe(Effect.provide(testLayer)),
);
@@ -965,6 +965,31 @@ export const makeHermesGatewayBroker = Effect.gen(function* () {
);
}
// ── Delivery connections: authenticated, but never the primary.
//
// An out-of-process cron run dials in only to hand over a `home.deliver`
// and leave. Registering it would displace the instance's live gateway
// socket ("replaced by a newer connection") and bump the generation,
// knocking the real plugin offline for the duration of a cron job. So it
// is accepted and then deliberately left out of the connection registry:
// no generation, no liveness ping, no status publish, nothing to
// disconnect. The existing primary is untouched.
if (hello.role === "delivery") {
return {
instanceId,
generation: null,
role: "delivery",
accepted: {
type: "connection.accepted",
requestId: hello.requestId,
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
instanceId,
nickname: record.nickname,
...(credential ? { credential } : {}),
},
} as const satisfies HermesGatewayConnectionRegistration;
}
const observed: HermesObservedConnection = {
pluginVersion: hello.pluginVersion,
hermesVersion: hello.hermesVersion,
@@ -986,6 +1011,7 @@ export const makeHermesGatewayBroker = Effect.gen(function* () {
const registration = {
instanceId,
generation: accepted.generation,
role: "gateway",
accepted: {
type: "connection.accepted",
requestId: hello.requestId,
@@ -1009,6 +1035,14 @@ export const makeHermesGatewayBroker = Effect.gen(function* () {
const receive = (registration: HermesGatewayConnectionRegistration, message: PluginMessage) =>
Effect.gen(function* () {
// A delivery connection's one frame — `home.deliver` — is handled at the
// transport layer, because its ack has to go back to that specific
// short-lived socket. Anything else it sends is outside its remit and is
// dropped here: it holds no session, so completing a correlated request
// or publishing a status off it would let a throwaway cron socket speak
// for the live connection.
if (registration.role === "delivery") return;
if (message.type === "connection.status") {
// Generation-fenced inside the Ref update; a stale registration is a
// no-op rather than an overwrite.
@@ -1031,6 +1065,10 @@ export const makeHermesGatewayBroker = Effect.gen(function* () {
const disconnect = (registration: HermesGatewayConnectionRegistration) =>
Effect.gen(function* () {
// Delivery sockets close as a matter of course — that is their whole
// lifecycle. They were never in the registry, so retiring one must not
// touch the instance's liveness or fail the live connection's requests.
if (registration.role === "delivery") return;
const retired = yield* connections.disconnect(registration);
if (!retired) return;
yield* publishCurrentStatus(registration.instanceId, "get-status");
@@ -205,6 +205,7 @@ describe("ProviderSessionReaper", () => {
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
getThreadShellById: (threadId) =>
Effect.succeed(
input.readModel.threads.find((thread) => thread.id === threadId)
@@ -1,5 +1,6 @@
import type {
HermesGatewayConnectionHello,
HermesGatewayConnectionRole,
HermesGatewayCreateEnrollmentInput,
HermesGatewayEnrollmentResult,
HermesGatewayInstanceStatus,
@@ -27,7 +28,22 @@ export interface HermesGatewayTransport {
export interface HermesGatewayConnectionRegistration {
readonly instanceId: ProviderInstanceId;
readonly generation: number;
/**
* Fencing token for the instance's primary connection, or `null` for a
* delivery connection.
*
* A delivery connection is deliberately outside the generation scheme: it
* was never registered as the primary, so there is nothing for it to be
* stale against, and giving it a generation would let it be compared —
* and therefore mistaken for a replacement — against the live socket.
*/
readonly generation: number | null;
/**
* What this socket registered as. `delivery` sockets may only hand over
* `home.deliver` frames; they carry no session, take no ping loop, and
* their disconnect must not disturb the instance's liveness state.
*/
readonly role: HermesGatewayConnectionRole;
readonly accepted: Extract<
HermesGatewayT3ToPluginMessage,
{ readonly type: "connection.accepted" }
+146 -1
View File
@@ -1,8 +1,14 @@
import {
CommandId,
HERMES_GATEWAY_PROTOCOL_VERSION,
HermesGatewayConnectionHello,
HermesGatewayPluginToT3Message,
HermesGatewayT3ToPluginMessage,
MessageId,
type ThreadId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -11,6 +17,9 @@ import * as Schema from "effect/Schema";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import * as Socket from "effect/unstable/socket/Socket";
import { getOrCreateHomeThread } from "../orchestration/homeThreads.ts";
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import {
HermesGatewayBroker,
type HermesGatewayConnectionRegistration,
@@ -28,6 +37,107 @@ const isConnectionHello = Schema.is(HermesGatewayConnectionHello);
export const hermesGatewayWebSocketRouteLayer = Layer.unwrap(
Effect.gen(function* () {
const broker = yield* HermesGatewayBroker;
const engine = yield* OrchestrationEngineService;
const query = yield* ProjectionSnapshotQuery;
const crypto = yield* Crypto.Crypto;
/**
* Write one proactive delivery into the instance's home thread and ack it.
*
* The ack is sent **only after the dispatch succeeds**. The plugin purges
* its queued copy on the ack and on nothing else, so acking optimistically
* would silently drop deliveries whenever a write failed. An unacked
* delivery is retried on the next connect and deduped there by
* `deliveryId`, which makes the pessimistic order the safe one.
*
* Accepted from either connection role, and deliberately not generation-
* fenced: a delivery carries no session and cannot conflict with the live
* connection's turns, and fencing it would reject exactly the out-of-
* process cron case this exists to serve.
*/
const deliverHomeNotification = (
registration: HermesGatewayConnectionRegistration,
message: Extract<HermesGatewayPluginToT3Message, { readonly type: "home.deliver" }>,
transport: {
readonly send: (
frame: HermesGatewayT3ToPluginMessage,
) => Effect.Effect<void, ProviderAdapterRequestError>;
},
) =>
Effect.gen(function* () {
// Re-resolve rather than trusting the plugin's threadId: its cached
// T3_HOME_CHANNEL may name a thread from a previous designation, and a
// delivery must never land in an arbitrary caller-named thread.
const homeThreadId = yield* getOrCreateHomeThread({
instanceId: registration.instanceId,
title: registration.accepted.nickname,
});
// Dedupe here, against the projection, before dispatching.
//
// The decider also dedupes, but it can only see the in-memory command
// read model — which is built with `messages: []` on every thread
// (`getCommandReadModel`, deliberately, to avoid hydrating message
// bodies at boot). Its scan therefore matches nothing, and a replay
// after a server restart appends a second copy. This read hits
// `projection_thread_messages`, where the delivery actually lives, so
// it is the check that holds across a restart — exactly the case the
// plugin's durable queue exists to produce.
const alreadyDelivered = (threadId: ThreadId) =>
query.getThreadDetailById(threadId).pipe(
Effect.map(
Option.match({
onNone: () => false,
onSome: (thread) =>
thread.messages.some(
(candidate) => candidate.notification?.deliveryId === message.deliveryId,
),
}),
),
Effect.orElseSucceed(() => false),
);
if (!(yield* alreadyDelivered(homeThreadId))) {
const dispatched = yield* Effect.result(
engine.dispatch({
type: "thread.notification.deliver",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId: homeThreadId,
messageId: MessageId.make(yield* crypto.randomUUIDv4),
deliveryId: message.deliveryId,
kind: message.kind,
label: message.label,
text: message.text,
createdAt: message.createdAt,
}),
);
// A dispatch failure is not proof the delivery is absent — a racing
// socket may have won between the read above and this write. Re-read
// before giving up, or that delivery goes unacked forever and the
// plugin replays it on every single reconnect.
if (dispatched._tag === "Failure" && !(yield* alreadyDelivered(homeThreadId))) {
return yield* Effect.fail(dispatched.failure);
}
}
yield* transport.send({
type: "home.deliver.ack",
protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION,
deliveryId: message.deliveryId,
});
}).pipe(
Effect.catchCause((cause) =>
// Deliberately no ack: the plugin keeps the delivery queued and
// retries it on the next connect.
Effect.logWarning("Hermes home delivery failed", {
instanceId: registration.instanceId,
deliveryId: message.deliveryId,
cause: Cause.pretty(cause),
}),
),
);
return HttpRouter.add(
"GET",
HERMES_GATEWAY_WEBSOCKET_PATH,
@@ -76,7 +186,31 @@ export const hermesGatewayWebSocketRouteLayer = Layer.unwrap(
),
);
yield* Ref.set(registration, Option.some(registered));
yield* transport.send(registered.accepted);
// Resolve the home thread here rather than inside
// `registerConnection`, whose error channel is exactly
// `connection.rejected`: a thread-creation failure is not a
// reason to refuse an authenticated plugin. On failure the
// handshake completes without `homeThreadId`, the plugin keeps
// whatever designation it already had, and the next connect
// converges — which is the whole point of converge-on-read.
const homeThreadId = yield* getOrCreateHomeThread({
instanceId: registered.instanceId,
title: registered.accepted.nickname,
}).pipe(
Effect.map(Option.some),
Effect.catchCause((cause) =>
Effect.logWarning("home thread resolution failed", {
instanceId: registered.instanceId,
cause: Cause.pretty(cause),
}).pipe(Effect.as(Option.none<ThreadId>())),
),
);
yield* transport.send({
...registered.accepted,
...(Option.isSome(homeThreadId) ? { homeThreadId: homeThreadId.value } : {}),
});
return;
}
@@ -84,6 +218,17 @@ export const hermesGatewayWebSocketRouteLayer = Layer.unwrap(
yield* transport.close(4002, "connection.hello may only be sent once");
return;
}
// Deliveries are handled on the socket that carried them rather
// than through the broker's event stream, because the ack has to
// go back to *this* connection — which for an out-of-process cron
// run is a short-lived delivery socket that no stream subscriber
// can address.
if (message.type === "home.deliver") {
yield* deliverHomeNotification(current.value, message, transport);
return;
}
yield* broker.receive(current.value, message);
}).pipe(
Effect.catch((cause) =>
@@ -201,6 +201,30 @@ describe.sequential("signRelayAgentActivityPublishProof", () => {
},
} as unknown as OrchestrationEvent),
).toBe(false);
// A cron result or agent-initiated message is exactly the news push
// exists for; a lifecycle notice appends quietly and must never ring.
for (const kind of ["cron", "message", "handoff", "other"] as const) {
expect(
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
...base,
type: "thread.notification-delivered",
payload: {
threadId: "thread-1" as ThreadId,
notification: { kind, label: "Cron: daily-digest", deliveryId: "delivery-1" },
},
} as unknown as OrchestrationEvent),
).toBe(true);
}
expect(
AgentAwarenessRelay.shouldPublishAgentAwarenessEvent({
...base,
type: "thread.notification-delivered",
payload: {
threadId: "thread-1" as ThreadId,
notification: { kind: "lifecycle", label: "Agent restarted", deliveryId: "delivery-2" },
},
} as unknown as OrchestrationEvent),
).toBe(false);
});
it("deduplicates awareness state updates whose only change is their event timestamp", () => {
@@ -78,6 +78,11 @@ export function shouldPublishAgentAwarenessEvent(event: OrchestrationEvent): boo
case "thread.runtime-mode-set":
case "thread.interaction-mode-set":
return false;
case "thread.notification-delivered":
// A cron result or agent-initiated message is exactly the kind of news
// push exists for. A lifecycle notice ("agent restarted") is not: it
// appends quietly and must never ring a device.
return event.payload.notification.kind !== "lifecycle";
case "thread.activity-appended":
return (
event.payload.activity.kind === "approval.requested" ||
@@ -96,6 +96,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadArchiveStateById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
@@ -161,6 +162,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadArchiveStateById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
}),
@@ -206,6 +208,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadArchiveStateById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
}),
@@ -257,6 +260,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadArchiveStateById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
getThreadDetailSnapshot: () => Effect.die("unused"),
}),
+22
View File
@@ -73,6 +73,7 @@ import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { getOrCreateAgentProject } from "./orchestration/agentProjects.ts";
import { isHomeThread } from "./orchestration/homeThreads.ts";
import {
observeRpcEffect as instrumentRpcEffect,
observeRpcStream as instrumentRpcStream,
@@ -262,6 +263,7 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
{
type:
| "thread.message-sent"
| "thread.notification-delivered"
| "thread.proposed-plan-upserted"
| "thread.activity-appended"
| "thread.turn-diff-completed"
@@ -271,6 +273,9 @@ function isThreadDetailEvent(event: OrchestrationEvent): event is Extract<
> {
return (
event.type === "thread.message-sent" ||
// A proactive delivery appends a transcript message, so an open detail
// subscription has to receive it or the row only appears on reload.
event.type === "thread.notification-delivered" ||
event.type === "thread.proposed-plan-upserted" ||
event.type === "thread.activity-appended" ||
event.type === "thread.turn-diff-completed" ||
@@ -1124,6 +1129,23 @@ const makeWsRpcLayer = (
ORCHESTRATION_WS_METHODS.dispatchCommand,
Effect.gen(function* () {
const normalizedCommand = yield* normalizeDispatchCommand(command);
// A home thread is a fixed designation, not a movable one:
// deleting it would leave its agent with nowhere to deliver, and
// the next handshake would silently mint a replacement, orphaning
// the history in the old one. This is the real guard — the UI
// only declines to offer the action.
if (
normalizedCommand.type === "thread.delete" &&
(yield* isHomeThread(normalizedCommand.threadId))
) {
return yield* Effect.fail(
new OrchestrationDispatchCommandError({
message: "This agent's Home thread cannot be deleted.",
}),
);
}
const shouldStopSessionAfterArchive =
normalizedCommand.type === "thread.archive"
? yield* projectionSnapshotQuery