Skip to content

Commit 9770a2e

Browse files
chore: update PR 98 with audited PR 97
2 parents c08baaa + c05eb46 commit 9770a2e

6 files changed

Lines changed: 169 additions & 118 deletions

File tree

‎apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts‎

Lines changed: 106 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1451,74 +1451,115 @@ effectIt.effect("recovers an abandoned failed turn before continuing its native
14511451
}),
14521452
);
14531453

1454-
effectIt.effect("offers bounded fact references to unattended first turns only", () =>
1455-
Effect.gen(function* () {
1456-
const text = "Review SQLite migrations for project memory";
1457-
const projectId = ProjectId.make("project-native-account-command");
1458-
const suggest = vi.fn<ProjectKnowledge.ProjectKnowledge["Service"]["suggest"]>(() =>
1459-
Effect.succeed([
1460-
{
1461-
fact: {
1462-
id: ProjectFactId.make("fact-migrations"),
1463-
projectId,
1464-
status: "saved",
1465-
kind: "decision",
1466-
origin: { kind: "user" },
1467-
content: "Private assertion body",
1468-
entities: [],
1469-
tags: [],
1470-
sources: [{ kind: "user" }],
1471-
revision: 1,
1472-
trust: 0.8,
1473-
retrievalCount: 0,
1474-
createdAt: "2026-09-04T12:00:00.000Z",
1475-
updatedAt: "2026-09-04T12:00:00.000Z",
1476-
forgottenAt: null,
1477-
},
1478-
score: {
1479-
holographic: 1,
1480-
lexical: 1,
1481-
tokenOverlap: 1,
1482-
temporalDecay: 1,
1483-
reinforcement: 0,
1484-
trust: 0.8,
1485-
combined: 1,
1454+
effectIt.effect.each([
1455+
"success",
1456+
"error",
1457+
"defect",
1458+
"interrupted",
1459+
"interrupted-error",
1460+
"interrupted-defect",
1461+
] as const)(
1462+
"offers bounded fact references to unattended first turns with lookup outcome %s",
1463+
(outcome) =>
1464+
Effect.gen(function* () {
1465+
const text = "Review SQLite migrations for project memory. ".repeat(100);
1466+
const projectId = ProjectId.make("project-native-account-command");
1467+
const suggest = vi.fn<ProjectKnowledge.ProjectKnowledge["Service"]["suggest"]>(() => {
1468+
if (outcome === "error")
1469+
return Effect.fail(new ProjectKnowledgeError({ reason: "storage", projectId }));
1470+
if (outcome === "defect") return Effect.die(new Error("Memory search encoding failed"));
1471+
if (outcome === "interrupted") return Effect.interrupt;
1472+
if (outcome === "interrupted-error" || outcome === "interrupted-defect")
1473+
return Effect.failCause(
1474+
Cause.combine(
1475+
Cause.interrupt(),
1476+
outcome === "interrupted-error"
1477+
? Cause.fail(new ProjectKnowledgeError({ reason: "storage", projectId }))
1478+
: Cause.die(new Error("Memory cleanup failed")),
1479+
),
1480+
);
1481+
return Effect.succeed([
1482+
{
1483+
fact: {
1484+
id: ProjectFactId.make("fact-migrations"),
1485+
projectId,
1486+
status: "saved",
1487+
kind: "decision",
1488+
origin: { kind: "user" },
1489+
content: "Private assertion body",
1490+
entities: [],
1491+
tags: [],
1492+
sources: [{ kind: "user" }],
1493+
revision: 1,
1494+
trust: 0.8,
1495+
retrievalCount: 0,
1496+
createdAt: "2026-09-04T12:00:00.000Z",
1497+
updatedAt: "2026-09-04T12:00:00.000Z",
1498+
forgottenAt: null,
1499+
},
1500+
score: {
1501+
holographic: 1,
1502+
lexical: 1,
1503+
tokenOverlap: 1,
1504+
temporalDecay: 1,
1505+
reinforcement: 0,
1506+
trust: 0.8,
1507+
combined: 1,
1508+
},
1509+
reason: "Private match explanation",
14861510
},
1487-
reason: "Private match explanation",
1488-
},
1489-
]),
1490-
);
1491-
for (const [source, ordinal] of [
1492-
["web", 1],
1493-
["mobile", 1],
1494-
["mcp", 2],
1495-
["mcp", 1],
1496-
] as const) {
1497-
const harness = makeLocalCommandHarness({
1498-
text,
1499-
previousTurn: { runStatus: "completed", turnStatus: "completed" },
1500-
suggestKnowledge: suggest,
1501-
});
1502-
const projection = harness.projection();
1503-
harness.setProjection({
1504-
...projection,
1505-
runs: projection.runs.map((run) => (run.status === "starting" ? { ...run, ordinal } : run)),
1506-
messages: projection.messages.map((message) => ({ ...message, creationSource: source })),
1511+
]);
15071512
});
1508-
yield* harness.start;
1509-
const prompt = harness.startRootRun.mock.calls[0]?.[0].message.text;
1510-
if (source === "mcp" && ordinal === 1) {
1511-
expect(suggest).toHaveBeenCalledOnce();
1512-
expect(suggest.mock.calls[0]?.[0]).toMatchObject({ projectId, query: text });
1513-
expect(prompt).toContain("fact-migrations");
1514-
expect(prompt).toContain(text);
1515-
expect(prompt).not.toContain("Private");
1516-
} else {
1517-
expect(suggest).not.toHaveBeenCalled();
1518-
expect(prompt).toBe(text);
1513+
for (const [source, ordinal] of [
1514+
["web", 1],
1515+
["mobile", 1],
1516+
["mcp", 2],
1517+
["mcp", 1],
1518+
["server", 1],
1519+
] as const) {
1520+
suggest.mockClear();
1521+
const harness = makeLocalCommandHarness({
1522+
text,
1523+
previousTurn: { runStatus: "completed", turnStatus: "completed" },
1524+
suggestKnowledge: suggest,
1525+
});
1526+
const projection = harness.projection();
1527+
harness.setProjection({
1528+
...projection,
1529+
runs: projection.runs.map((run) =>
1530+
run.status === "starting" ? { ...run, ordinal } : run,
1531+
),
1532+
messages: projection.messages.map((message) => ({ ...message, creationSource: source })),
1533+
});
1534+
const exit = yield* Effect.exit(harness.start);
1535+
const unattended = (source === "mcp" || source === "server") && ordinal === 1;
1536+
if (unattended && outcome.startsWith("interrupted")) {
1537+
expect(suggest).toHaveBeenCalledOnce();
1538+
expect(exit._tag).toBe("Failure");
1539+
if (exit._tag === "Failure") expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
1540+
expect(harness.startRootRun).not.toHaveBeenCalled();
1541+
expect(harness.nativeStart).not.toHaveBeenCalled();
1542+
continue;
1543+
}
1544+
expect(exit._tag).toBe("Success");
1545+
yield* dispatchKnowledge(harness.startRootRun.mock.calls[0]![0]);
1546+
const prompt = harness.nativeStart.mock.calls[0]?.[0].message.text;
1547+
if (unattended) {
1548+
expect(suggest).toHaveBeenCalledOnce();
1549+
expect(suggest.mock.calls[0]?.[0]).toMatchObject({ projectId, query: text });
1550+
if (outcome === "success") {
1551+
expect(prompt).toContain("fact-migrations");
1552+
expect(prompt).toContain(text);
1553+
expect(prompt).not.toContain("Private");
1554+
} else {
1555+
expect(prompt).toBe(text);
1556+
}
1557+
} else {
1558+
expect(suggest).not.toHaveBeenCalled();
1559+
expect(prompt).toBe(text);
1560+
}
15191561
}
1520-
}
1521-
}),
1562+
}),
15221563
);
15231564

15241565
effectIt.effect.each([

‎apps/server/src/orchestration-v2/ProviderTurnStartService.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
RunId,
2424
ThreadId,
2525
} from "@t3tools/contracts";
26+
import * as Cause from "effect/Cause";
2627
import * as Context from "effect/Context";
2728
import * as DateTime from "effect/DateTime";
2829
import * as Effect from "effect/Effect";
@@ -140,7 +141,15 @@ const unattendedMemoryHint = Effect.fn("ProviderTurnStartService.unattendedMemor
140141
})
141142
.pipe(
142143
Effect.timeoutOption("150 millis"),
143-
Effect.orElseSucceed(() => Option.none()),
144+
Effect.catchCause((cause) => {
145+
if (Cause.hasInterrupts(cause)) return Effect.interrupt;
146+
if (Cause.hasDies(cause))
147+
return Effect.logWarning("Optional project memory lookup failed", {
148+
projectId,
149+
runId,
150+
}).pipe(Effect.andThen(Effect.succeedNone));
151+
return Effect.succeedNone;
152+
}),
144153
);
145154
// IDs can also be supplied by clients. Only opaque identifiers belong in a provider hint.
146155
const opaqueId = /^[a-zA-Z0-9_:.-]{1,128}$/;

‎apps/server/src/orchestration-v2/testkit/GroupConversation.integration.test.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
ProviderInstanceId,
1717
ProviderThreadId,
1818
ProviderTurnId,
19+
type ResponseStreamingMode,
1920
type RunId,
2021
RuntimeRequestId,
2122
ThreadId,
@@ -380,6 +381,7 @@ const makeHarness = Effect.fn("GroupConversationTest.makeHarness")(function* (
380381
name: string,
381382
options: {
382383
readonly enabled?: boolean;
384+
readonly responseStreamingMode?: ResponseStreamingMode;
383385
/** Runs right after a seat's records are read, to land a change behind that read. */
384386
readonly afterSeatRead?: (threadId: ThreadId) => Effect.Effect<void>;
385387
readonly runEffectWorker?: boolean;
@@ -469,7 +471,10 @@ const makeHarness = Effect.fn("GroupConversationTest.makeHarness")(function* (
469471
registry,
470472
{
471473
databaseLayer: database,
472-
settings: { providerInstances: options.orchestratorInstances ?? CONFIGURED_INSTANCES },
474+
settings: {
475+
providerInstances: options.orchestratorInstances ?? CONFIGURED_INSTANCES,
476+
responseStreamingMode: options.responseStreamingMode ?? "turn",
477+
},
473478
...(options.runEffectWorker === undefined
474479
? {}
475480
: { runEffectWorker: options.runEffectWorker }),
@@ -1019,7 +1024,7 @@ describe("group conversations", () => {
10191024
it.live("stops every running member and publishes what a seat had said", () =>
10201025
Effect.scoped(
10211026
Effect.gen(function* () {
1022-
const harness = yield* makeHarness("stop");
1027+
const harness = yield* makeHarness("stop", { responseStreamingMode: "paragraph" });
10231028
const threadId = ThreadId.make("thread:group:stop");
10241029
yield* withReactor(
10251030
Effect.gen(function* () {
@@ -1029,7 +1034,7 @@ describe("group conversations", () => {
10291034
const silent = yield* invite(threadId, OPUS);
10301035
const holds = [
10311036
yield* hold(harness.control, threadId, "Primary was saying"),
1032-
yield* hold(harness.control, talker, "STREAMEDMARK half a thought"),
1037+
yield* hold(harness.control, talker, "STREAMEDMARK half a thought\n\n"),
10331038
yield* hold(harness.control, silent),
10341039
];
10351040
yield* say(threadId, "go", "Go");
@@ -1046,7 +1051,11 @@ describe("group conversations", () => {
10461051
seats.every((projection) =>
10471052
projection.providerTurns.some((turn) => turn.status === "running"),
10481053
) &&
1049-
seats[1]!.turnItems.some((item) => item.text === "STREAMEDMARK half a thought")
1054+
seats[1]!.turnItems.some(
1055+
(item) =>
1056+
item.type === "assistant_message" &&
1057+
item.text === "STREAMEDMARK half a thought\n\n",
1058+
)
10501059
);
10511060
}),
10521061
);
@@ -1075,7 +1084,7 @@ describe("group conversations", () => {
10751084
const rows = publishedRows(after);
10761085
assert.deepEqual(
10771086
rows.map((row) => row.text),
1078-
["STREAMEDMARK half a thought"],
1087+
["STREAMEDMARK half a thought\n\n"],
10791088
"a seat with no text publishes nothing",
10801089
);
10811090
assert.equal(

‎apps/server/src/project/knowledge/ProjectKnowledge.test.ts‎

Lines changed: 21 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
ProviderThreadId,
1818
RunAttemptId,
1919
RunId,
20+
THREAD_SEARCH_QUERY_MAX_LENGTH,
2021
ThreadId,
2122
TurnItemId,
2223
type OrchestrationV2DomainEvent,
@@ -1716,22 +1717,6 @@ it.effect.each(["rolled", "edited", "deleted", "project-deleted", "archive"] as
17161717
}).pipe(Effect.provide(receiptTestLayer)),
17171718
);
17181719

1719-
it.effect("accepts long delegated prompts for optional memory suggestions", () =>
1720-
Effect.gen(function* () {
1721-
const knowledge = yield* ProjectKnowledge.ProjectKnowledge;
1722-
const projectId = ProjectId.make("long-delegated-prompt");
1723-
yield* createProject(projectId);
1724-
assert.deepEqual(
1725-
yield* knowledge.suggest({
1726-
projectId,
1727-
requestId: CommandId.make("suggest-long-delegated-prompt"),
1728-
query: "Review SQLite migrations for project memory. ".repeat(100),
1729-
}),
1730-
[],
1731-
);
1732-
}).pipe(Effect.provide(layerTest)),
1733-
);
1734-
17351720
it.effect("browsing searches can opt out of reinforcing retrieval counts", () =>
17361721
Effect.gen(function* () {
17371722
const knowledge = yield* ProjectKnowledge.ProjectKnowledge;
@@ -1764,20 +1749,27 @@ it.effect("browsing searches can opt out of reinforcing retrieval counts", () =>
17641749
}),
17651750
[],
17661751
);
1767-
const suggestions = yield* knowledge.suggest({
1768-
projectId,
1769-
requestId: CommandId.make("suggest-relevant"),
1770-
query: "cache keys tenant",
1771-
});
1772-
assert.equal(suggestions.length, 1);
1773-
assert.equal(suggestions[0]?.fact.id, ProjectFactId.make("fact-one"));
1774-
assert.equal(suggestions[0]?.fact.sources[0]?.kind, "user");
17751752
const sql = yield* SqlClient.SqlClient;
1776-
assert.equal(
1777-
(yield* sql`SELECT command_id FROM project_knowledge_commands WHERE command_id = ${"suggest-relevant"}`)
1778-
.length,
1779-
0,
1780-
);
1753+
const longQuery = "cache keys tenant ".repeat(100);
1754+
for (const [name, query] of [
1755+
["short", "cache keys tenant"],
1756+
["limit", longQuery.slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH)],
1757+
["over-limit", longQuery.slice(0, THREAD_SEARCH_QUERY_MAX_LENGTH + 1)],
1758+
["long-with-whitespace", ` \n\t${longQuery}\n\t `],
1759+
] as const) {
1760+
const requestId = CommandId.make(`suggest-relevant-${name}`);
1761+
const suggestions = yield* knowledge.suggest({ projectId, requestId, query });
1762+
assert.equal(suggestions.length, 1);
1763+
assert.equal(suggestions[0]?.fact.id, ProjectFactId.make("fact-one"));
1764+
assert.equal(suggestions[0]?.fact.sources[0]?.kind, "user");
1765+
assert.equal(suggestions[0]?.fact.retrievalCount, 0);
1766+
assert.equal(yield* storedCount, 0);
1767+
assert.equal(
1768+
(yield* sql`SELECT command_id FROM project_knowledge_commands WHERE command_id = ${requestId}`)
1769+
.length,
1770+
0,
1771+
);
1772+
}
17811773

17821774
assert.deepEqual(
17831775
yield* knowledge.suggest({

‎apps/server/src/project/knowledge/ProjectKnowledge.ts‎

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,8 @@ const encodeText = Schema.encodeSync(Schema.fromJsonString(Schema.String));
161161
const encodeMutation = Schema.encodeSync(
162162
Schema.fromJsonString(Schema.Struct({ actor: KnowledgeOrigin, input: ProjectKnowledgeMutation })),
163163
);
164-
const encodeSearch = Schema.encodeSync(Schema.fromJsonString(ProjectKnowledgeSearchInput));
165-
const encodeQuery = Schema.encodeSync(
164+
const encodeSearch = Schema.encodeEffect(Schema.fromJsonString(ProjectKnowledgeSearchInput));
165+
const encodeQuery = Schema.encodeEffect(
166166
Schema.fromJsonString(
167167
Schema.Struct({
168168
projectId: ProjectKnowledgeSearchInput.fields.projectId,
@@ -844,19 +844,18 @@ const make = Effect.gen(function* () {
844844
...new Set((input.entities ?? []).map((entity) => entity.toLowerCase())),
845845
].sort();
846846
const minTrust = input.minTrust ?? 0.3;
847-
const queryDigest = yield* digest(
848-
encodeQuery({
849-
projectId: input.projectId,
850-
query: input.query,
851-
entities,
852-
entityMatch: input.entityMatch ?? "any",
853-
includeArchived: input.includeArchived ?? false,
854-
minTrust,
855-
...(input.includeSuperseded ? { includeSuperseded: true } : {}),
856-
}),
857-
).pipe(Effect.mapError(storageError(input.projectId)));
847+
const queryDigest = yield* encodeQuery({
848+
projectId: input.projectId,
849+
query: input.query,
850+
entities,
851+
entityMatch: input.entityMatch ?? "any",
852+
includeArchived: input.includeArchived ?? false,
853+
minTrust,
854+
...(input.includeSuperseded ? { includeSuperseded: true } : {}),
855+
}).pipe(Effect.flatMap(digest), Effect.mapError(storageError(input.projectId)));
858856
const { cursor: _messageCursor, ...factInput } = input;
859-
const requestDigest = yield* digest(encodeSearch(factInput)).pipe(
857+
const requestDigest = yield* encodeSearch(factInput).pipe(
858+
Effect.flatMap(digest),
860859
Effect.mapError(storageError(input.projectId)),
861860
);
862861
const searchedAt = yield* DateTime.now;

0 commit comments

Comments
 (0)