Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions apps/mobile/src/components/ProjectKnowledgeEntry.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type { SheetProps } from "./ui/Sheet.types";
const state = vi.hoisted(() => ({
uuidSequence: 0,
deliveryCapabilities: {} as Record<string, boolean | undefined>,
curation: false,
deliveries: null as unknown,
readDeliveries: vi.fn(),
focused: true,
Expand Down Expand Up @@ -165,6 +166,7 @@ vi.mock("../state/server", () => ({
capabilities: {
projectKnowledge: true,
projectKnowledgeHistory: true,
projectKnowledgeCuration: state.curation,
projectKnowledgeDeliveries: state.deliveryCapabilities[environmentId],
},
},
Expand Down Expand Up @@ -287,9 +289,10 @@ const deliveryRecord: ProjectKnowledgeDeliveries = {
},
],
};
function setup(entries: Array<typeof scope> = [scope]) {
function setup(entries: Array<typeof scope> = [scope], curation = false) {
state.uuidSequence = 0;
state.deliveryCapabilities = {};
state.curation = curation;
state.deliveries = null;
state.readDeliveries.mockReset();
state.focused = true;
Expand Down Expand Up @@ -672,8 +675,8 @@ it("forgets a fact only after the permanent-erase warning is confirmed", async (
});
});

it("marks a superseded fact read-only and lists superseded facts on request", async () => {
using screen = setup();
it.each([false, true])("handles superseded facts with curation support %s", async (curation) => {
using screen = setup([scope], curation);
state.list = {
facts: [{ ...fact, supersededBy: ProjectFactId.make("replacement") }],
nextCursor: null,
Expand All @@ -684,6 +687,7 @@ it("marks a superseded fact read-only and lists superseded facts on request", as
const labels = [...screen.container.querySelectorAll("button")].map((item) => item.textContent);
expect(labels).not.toContain("Edit");
expect(labels).not.toContain("Supersede");
expect(labels.includes("Restore to recall")).toBe(curation);
await screen.click("Back");
expect(state.listInputs.at(-1)).not.toHaveProperty("includeSuperseded");
await act(async () =>
Expand All @@ -692,6 +696,20 @@ it("marks a superseded fact read-only and lists superseded facts on request", as
).click(),
);
expect(state.listInputs.at(-1)).toMatchObject({ includeSuperseded: true });
if (!curation) return;
await screen.click(`Inspect fact: ${fact.content}`);
await screen.click("Restore to recall");
expect(state.mutate).toHaveBeenCalledWith({
environmentId: scope.environmentId,
input: {
action: "restore",
commandId: expect.any(String),
projectId: scope.projectId,
factId: fact.id,
expectedRevision: fact.revision,
},
});
expect(screen.container.textContent).not.toContain("Restore to recall");
});

it("supersedes a fact with a new replacement and shows the returned conflict hints", async () => {
Expand Down
7 changes: 4 additions & 3 deletions apps/mobile/src/components/ProjectKnowledgeEntry.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ export function ProjectKnowledgeEntry(props: Scope) {
// Older servers lack readFact, status and supersede.
history={config.environment.capabilities.projectKnowledgeHistory === true}
assisted={config.environment.capabilities.projectKnowledgeAssistedLearning === true}
standingCheck={config.environment.capabilities.projectKnowledgeStandingCheck === true}
curation={config.environment.capabilities.projectKnowledgeCuration === true}
seedMessage={open.seed}
onClose={() => setOpen(null)}
/>
Expand All @@ -145,7 +145,7 @@ function ProjectKnowledgeSheet(
props: Scope & {
readonly history: boolean;
readonly assisted: boolean;
readonly standingCheck: boolean;
readonly curation: boolean;
readonly seedMessage: MessageCitation | null;
readonly onClose: () => void;
},
Expand Down Expand Up @@ -462,7 +462,6 @@ function ProjectKnowledgeSheet(
projectId={props.projectId}
browse={browse}
assisted={props.assisted}
standingCheck={props.standingCheck}
canMutate={canMutate}
busy={busy}
selectionState={selectionState}
Expand All @@ -485,6 +484,7 @@ function ProjectKnowledgeSheet(
detail={detailData}
detailError={detail.error}
history={props.history}
curation={props.curation}
sourceUnavailable={
detailData?.sourceUnavailable ??
browse.unavailableReasons.get(inspectedFact.id) ??
Expand Down Expand Up @@ -517,6 +517,7 @@ function ProjectKnowledgeSheet(
void apply({ action: "forget", ...factMutation(inspectedFact) }),
})
}
onRestore={() => void apply({ action: "restore", ...factMutation(inspectedFact) })}
onFeedback={(helpful) =>
void apply({ action: "feedback", helpful, ...factMutation(inspectedFact) })
}
Expand Down
23 changes: 23 additions & 0 deletions apps/mobile/src/components/ProjectKnowledgeFactDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ import type {
import { messageAuthorLabel } from "@t3tools/client-runtime/conversationSummaries";
import {
KNOWLEDGE_SOURCE_UNAVAILABLE_LABEL,
canRestoreFactToRecall,
isSupersededFact,
knowledgeConflictHintLabel,
knowledgeOriginLabel,
memoryCurationRunLabel,
projectFactVerdictLabel,
projectFactHistoryLabel,
} from "@t3tools/client-runtime/projectKnowledge";
Expand Down Expand Up @@ -96,6 +98,9 @@ function HistoryRow(props: { readonly entry: ProjectFactHistoryEntry }) {
Trust {entry.trustBefore.toFixed(2)} → {entry.trustAfter.toFixed(2)}
</AppText>
) : null}
{entry.reason ? (
<AppText className="text-xs text-foreground-muted">{entry.reason}</AppText>
) : null}
{content !== null ? (
<AppText className="text-sm" numberOfLines={4}>
{content.length > REVISION_PREVIEW_LENGTH
Expand All @@ -118,6 +123,7 @@ export function ProjectFactInspector(props: {
readonly detail: ProjectKnowledgeFactDetail | null;
readonly detailError: string | null;
readonly history: boolean;
readonly curation: boolean;
readonly sourceUnavailable: KnowledgeSourceUnavailableReason | null;
readonly hints: ReadonlyArray<KnowledgeConflictHint>;
readonly selection: KnowledgeSelectionState | null;
Expand All @@ -129,6 +135,7 @@ export function ProjectFactInspector(props: {
readonly onOpenFact: OpenFact;
readonly onEdit: (mode: "edit" | "supersede") => void;
readonly onForget: () => void;
readonly onRestore: () => void;
readonly onFeedback: (helpful: boolean) => void;
readonly onDismissHints: () => void;
}) {
Expand Down Expand Up @@ -203,6 +210,14 @@ export function ProjectFactInspector(props: {

{active ? (
<View className="flex-row flex-wrap gap-2">
{props.curation && canRestoreFactToRecall(fact) ? (
<Button
label="Restore to recall"
tone="secondary"
disabled={!mutable}
onPress={props.onRestore}
/>
) : null}
{!superseded ? (
<Button
label="Edit"
Expand Down Expand Up @@ -350,6 +365,14 @@ export function KnowledgeHealthRow(props: {
{status.belowRecallThreshold} below recall · {status.feedback.helpful} helpful ·{" "}
{status.feedback.unhelpful} unhelpful
</AppText>
{status.curation ? (
<AppText className="text-xs text-foreground-muted">
{memoryCurationRunLabel(status.curation)}
{status.curation.completedAt
? ` · ${historyTimeFormatter.format(new Date(status.curation.completedAt))}`
: ""}
</AppText>
) : null}
{lost > 0 ? (
<Button
label={`${status.unavailableSourcesCoverage === "partial" ? "At least " : ""}${
Expand Down
40 changes: 16 additions & 24 deletions apps/mobile/src/components/ProjectKnowledgeFactList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import { KnowledgeHealthRow } from "./ProjectKnowledgeFactDetail";
import { AppText, AppTextInput } from "./ui/AppText";
import { Button } from "./ui/Button";

type StatusFilter = "saved" | "automatic" | "set_aside" | "forgotten";
type StatusFilter = "saved" | "automatic" | "forgotten";

/** Filters, search and paging for the fact list. The sheet reads its results for draft labels. */
export function useProjectKnowledgeBrowse(props: {
Expand All @@ -60,9 +60,7 @@ export function useProjectKnowledgeBrowse(props: {
? { sourceState: "unavailable" as const }
: status === "automatic"
? { status: "saved" as const, origin: "assisted" as const }
: status === "set_aside"
? { status: "saved" as const, verdict: "set_aside" as const }
: { status }),
: { status }),
...(afterId ? { afterId } : {}),
...(props.history && showSuperseded ? { includeSuperseded: true } : {}),
},
Expand Down Expand Up @@ -204,7 +202,6 @@ export function ProjectKnowledgeFactList(props: {
readonly projectId: ProjectId;
readonly browse: ProjectKnowledgeBrowse;
readonly assisted: boolean;
readonly standingCheck: boolean;
readonly canMutate: boolean;
readonly busy: boolean;
readonly selectionState: (current: KnowledgeSelection) => SelectionState;
Expand Down Expand Up @@ -243,25 +240,20 @@ export function ProjectKnowledgeFactList(props: {
</View>

<View className="flex-row flex-wrap gap-2">
{(
[
"saved",
...(props.assisted ? (["automatic"] as const) : []),
...(props.standingCheck ? (["set_aside"] as const) : []),
"forgotten",
] as const
).map((value) => (
<Button
key={value}
label={value === "set_aside" ? "set aside" : value}
tone={
browse.status === value && !searchInput && !browse.lostSourcesOnly
? "primary"
: "secondary"
}
onPress={() => browse.selectStatus(value)}
/>
))}
{(["saved", ...(props.assisted ? (["automatic"] as const) : []), "forgotten"] as const).map(
(value) => (
<Button
key={value}
label={value}
tone={
browse.status === value && !searchInput && !browse.lostSourcesOnly
? "primary"
: "secondary"
}
onPress={() => browse.selectStatus(value)}
/>
),
)}
</View>
{browse.history ? (
<View className="flex-row items-center gap-3">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,12 @@ import {
SettingsWorktreesRouteScreen,
} from "./SettingsServerControlsRouteScreen";

function environment(environmentId: string, label: string, assistedLearning?: boolean) {
function environment(
environmentId: string,
label: string,
assistedLearning?: boolean,
memoryCuration?: boolean,
) {
return {
environmentId,
label,
Expand All @@ -179,6 +184,7 @@ function environment(environmentId: string, label: string, assistedLearning?: bo
threadAutoSettlement: true,
projectKnowledge: true,
projectKnowledgeAssistedLearning: assistedLearning,
projectKnowledgeCuration: memoryCuration,
},
},
},
Expand Down Expand Up @@ -241,25 +247,37 @@ describe("SettingsServerControlsRouteScreen", () => {
expect(container.textContent).toContain("Old server");
});

it("turns automatic memory off for a supported project without targeting unrelated older environments", async () => {
mocks.targets = [environment("new", "New server", true), environment("old", "Old server")];
mocks.projectSelected = true;
mocks.projectEnvironmentIds = ["new"];
act(() => root.render(<SettingsZackRouteScreen />));
const toggle = Array.from(
container.querySelectorAll<HTMLButtonElement>('[role="switch"]'),
).find((button) => button.textContent === "Save facts from finished runs")!;
it.each(["enableAssistedLearning", "enableMemoryCuration"] as const)(
"turns %s off for a supported project without targeting unrelated older environments",
async (setting) => {
mocks.targets = [
environment("new", "New server", true, true),
environment("old", "Old server"),
];
mocks.projectSelected = true;
mocks.projectEnvironmentIds = ["new"];
act(() => root.render(<SettingsZackRouteScreen />));
const toggle = Array.from(
container.querySelectorAll<HTMLButtonElement>('[role="switch"]'),
).find(
(button) =>
button.textContent ===
(setting === "enableMemoryCuration"
? "Curate project memories"
: "Save facts from finished runs"),
)!;

await act(async () => toggle.click());
await act(async () => toggle.click());

expect(toggle.disabled).toBe(false);
expect(mocks.updateSettings).toHaveBeenCalledExactlyOnceWith({
environmentId: "new",
input: {
patch: { projectSettingsOverrides: { project: { enableAssistedLearning: false } } },
},
});
});
expect(toggle.disabled).toBe(false);
expect(mocks.updateSettings).toHaveBeenCalledExactlyOnceWith({
environmentId: "new",
input: {
patch: { projectSettingsOverrides: { project: { [setting]: false } } },
},
});
},
);

it("sends a draft saved during a pending write once that write settles", async () => {
const pending = Promise.withResolvers<AsyncResult.Success<void>>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,12 @@ const PAGE_PROJECT_KEYS: Record<SettingsPage, readonly ProjectScopedServerSettin
"branchNameInstructions",
],
maintenance: ["continueThreadsAfterServerUpdate"],
zack: ["enableAssistedLearning", "enableConversationSummaries", "contextRestartAboveTokens"],
zack: [
"enableAssistedLearning",
"enableMemoryCuration",
"enableConversationSummaries",
"contextRestartAboveTokens",
],
};

const SUBMODULE_CHOICES: ReadonlyArray<{
Expand Down Expand Up @@ -221,6 +226,10 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
? `Automatic memory is supported on only some selected environments. Update T3 Code on ${unsupportedAssistedLearning.map((target) => target.environment.label).join(", ")}, or select a supported environment.`
: `Automatic memory is not supported on ${unsupportedAssistedLearning.map((target) => target.environment.label).join(", ")}. Update T3 Code on ${unsupportedAssistedLearning.length === 1 ? "that environment" : "those environments"}.`;
const [pendingWrites, setPendingWrites] = useState(0);
const memoryCurationUnavailable = targets.some(
(target) =>
target.environment.serverConfig.environment.capabilities.projectKnowledgeCuration !== true,
);
const writeInFlight = useRef(false);
// Closing views can save after controls disable; queue those patches behind the pending write.
const queuedPatch = useRef<{ key: string; patch: ServerSettingsPatch } | null>(null);
Expand All @@ -246,6 +255,7 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
const write = (patch: ServerSettingsPatch) => {
if (patch.enableAssistedLearning !== undefined && assistedLearningUnavailableReason !== null)
return;
if (patch.enableMemoryCuration !== undefined && memoryCurationUnavailable) return;
if (writeInFlight.current) {
const queued = queuedPatch.current;
queuedPatch.current = {
Expand Down Expand Up @@ -476,6 +486,18 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
}
onValueChange={(value) => write({ enableAssistedLearning: value })}
/>
<SettingsSwitchRow
icon="brain"
label="Curate project memories"
subtitle={
memoryCurationUnavailable
? "Update the selected T3 Code servers to use memory curation."
: "Review agent memories within each project. Set aside task notes and link duplicates or replaced decisions, keeping the content and review reasons available to inspect or restore. Uses your text generation model."
}
value={uniform("enableMemoryCuration")}
disabled={disabledFor("enableMemoryCuration") || memoryCurationUnavailable}
onValueChange={(value) => write({ enableMemoryCuration: value })}
/>
</SettingsSection>
<SettingsSection title="LCM: conversation summaries">
<SettingsSwitchRow
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/environment/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ export const make = Effect.gen(function* () {
projectKnowledgeDeliveries: true,
projectKnowledgeAssistedLearning: true,
projectKnowledgeStandingCheck: true,
projectKnowledgeCuration: true,
conversationSummaries: true,
conversationSummarySourceFormat: 2,
externalHistory: 1,
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/git/GitManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,7 @@ function createTextGeneration(
generateKnowledgeCandidates: () => Effect.succeed({ candidates: [] }),
generateConversationSummary: () => Effect.succeed({ statements: [] }),
checkFactStanding: () => Effect.succeed({ verdicts: [] }),
curateProjectMemory: () => Effect.succeed({ decisions: [] }),
supportsOperation: () => Effect.succeed(true),
generateModelEvaluation: () => Effect.die("Unused evaluation fixture"),
generateThreadTitle: () =>
Expand Down Expand Up @@ -377,6 +378,7 @@ function createTextGeneration(
generateConversationSummary: (input) => implementation.generateConversationSummary(input),
generateModelEvaluation: (input) => implementation.generateModelEvaluation(input),
checkFactStanding: (input) => implementation.checkFactStanding(input),
curateProjectMemory: (input) => implementation.curateProjectMemory(input),
supportsOperation: (operation, instanceId) =>
implementation.supportsOperation(operation, instanceId),
generateTranscriptionPostProcessing: (input) =>
Expand Down
Loading
Loading