From a9a7e167c3c6205b25e73b8ee531f494c3669750 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 19:38:26 -0800 Subject: [PATCH 01/12] test: automatic memory recalls only facts a blind check calls standing Fails on the current code: candidates are saved without a check, nothing records a verdict, recall offers every saved fact, and there is no checkFactStanding operation for the eval to run. `pnpm memory-standing-check --no-check` shows the old behaviour failing the four set-aside cases. Co-Authored-By: Claude Opus 5.5 --- .../knowledge/AssistedLearning.test.ts | 92 +++++++++++++++- .../knowledge/ProjectKnowledge.test.ts | 94 +++++++++++++++- .../ClaudeTextGeneration.test.ts | 54 ++++++---- .../CodexTextGeneration.test.ts | 43 +++++--- .../ProjectMemoryPanel.browser.test.tsx | 6 ++ evals/README.md | 1 + evals/memory-standing-check/README.md | 15 +++ evals/memory-standing-check/cases.ts | 73 +++++++++++++ evals/memory-standing-check/run.ts | 101 ++++++++++++++++++ evals/package.json | 3 +- .../server/textGenerationOperations.test.ts | 30 ++++++ 11 files changed, 477 insertions(+), 35 deletions(-) create mode 100644 evals/memory-standing-check/README.md create mode 100644 evals/memory-standing-check/cases.ts create mode 100644 evals/memory-standing-check/run.ts diff --git a/apps/server/src/project/knowledge/AssistedLearning.test.ts b/apps/server/src/project/knowledge/AssistedLearning.test.ts index e763dd67920a0..9297ddf39bbad 100644 --- a/apps/server/src/project/knowledge/AssistedLearning.test.ts +++ b/apps/server/src/project/knowledge/AssistedLearning.test.ts @@ -41,6 +41,9 @@ import * as ProjectKnowledge from "./ProjectKnowledge.ts"; const isTextGenerationError = Schema.is(TextGenerationError); type Generate = TextGeneration.TextGeneration["Service"]["generateKnowledgeCandidates"]; +type Check = TextGeneration.TextGeneration["Service"]["checkFactStanding"]; +const allStanding: Check = (input) => + Effect.succeed({ verdicts: input.statements.map(() => "standing" as const) }); const projectId = ProjectId.make("learning"); const threadId = ThreadId.make("learning-thread"); @@ -51,10 +54,14 @@ const at = DateTime.makeUnsafe(Date.UTC(2026, 9, 1)); const makeLayer = ( generate: Generate, settings: Parameters[0] = {}, + check: Check = allStanding, ) => AssistedLearning.layerRunner.pipe( Layer.provide( - Layer.mock(TextGeneration.TextGeneration)({ generateKnowledgeCandidates: generate }), + Layer.mock(TextGeneration.TextGeneration)({ + generateKnowledgeCandidates: generate, + checkFactStanding: check, + }), ), Layer.provideMerge(ProjectKnowledge.layer.pipe(Layer.provide(HolographicMemory.layer))), Layer.provideMerge( @@ -316,6 +323,87 @@ it.effect("saves a settled run's cited facts exactly once, recallable without re }).pipe(Effect.provide(makeLayer(model.generate))); }); +it.effect("stores what the blind check set aside without making it recallable", () => { + const scopeLimit = { + kind: "constraint" as const, + content: "Keep this change limited to the API handlers.", + entities: [], + citations: ["M1"], + }; + const model = scripted([{ candidates: [snakeCase, scopeLimit] }]); + const checks: Array[0]> = []; + const check: Check = (input) => { + checks.push(input); + return Effect.succeed({ verdicts: ["standing", "task"] }); + }; + return Effect.gen(function* () { + yield* seedRun; + const runner = yield* AssistedLearningRunner; + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + yield* runner.extractRun({ threadId, runId, runOutcome: "completed" }); + // Only the statements reach the check, from outside the project's workspace. + assert.equal(checks.length, 1); + assert.deepEqual(checks[0]!.statements, [ + { kind: snakeCase.kind, content: snakeCase.content }, + { kind: scopeLimit.kind, content: scopeLimit.content }, + ]); + assert.notEqual(checks[0]!.cwd, `/work/${projectId}`); + const saved = (yield* knowledge.list({ projectId, status: "saved" })).facts; + assert.deepEqual( + saved.map((fact) => [fact.content, fact.verdict?.value, fact.verdict?.by]).toSorted(), + [ + [snakeCase.content, "standing", "check"], + [scopeLimit.content, "task", "check"], + ], + ); + assert.deepEqual( + (yield* knowledge.list({ projectId, verdict: "set_aside" })).facts.map( + (fact) => fact.content, + ), + [scopeLimit.content], + ); + const lastRun = (yield* knowledge.status({ projectId })).assistedLearning?.lastRun; + assert.deepEqual([lastRun?.saved, lastRun?.reason], [1, "1 set aside: 1 task note."]); + }).pipe(Effect.provide(makeLayer(model.generate, {}, check))); +}); + +it.effect("saves nothing when the check fails, and retries the batch before giving up", () => { + const model = scripted([{ candidates: [snakeCase] }]); + let checks = 0; + const check: Check = () => { + checks += 1; + return Effect.fail( + new TextGenerationError({ operation: "checkFactStanding", detail: "Rate limited." }), + ); + }; + return Effect.gen(function* () { + yield* seedRun; + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.add(at, { minutes: 10 }))); + const runner = yield* AssistedLearningRunner; + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const sql = yield* SqlClient.SqlClient; + yield* runner.enqueueRun({ threadId, runId, runOutcome: "completed" }); + yield* TestClock.adjust("30 minutes"); + yield* runner.drainDue; + yield* runner.drainDue; + assert.deepEqual([model.calls.length, checks], [1, 1]); + assert.equal((yield* knowledge.status({ projectId })).assistedLearning?.lastRun, null); + assert.equal((yield* sql`SELECT * FROM project_knowledge_learning_queue`).length, 1); + yield* TestClock.adjust("30 minutes"); + yield* runner.drainDue; + yield* TestClock.adjust("30 minutes"); + yield* runner.drainDue; + assert.deepEqual([model.calls.length, checks], [3, 3]); + const lastRun = (yield* knowledge.status({ projectId })).assistedLearning?.lastRun; + assert.deepEqual( + [lastRun?.result, lastRun?.reason], + ["failed", "Standing check failed: Rate limited."], + ); + assert.deepEqual(yield* sql`SELECT * FROM project_knowledge_learning_queue`, []); + assert.deepEqual((yield* knowledge.list({ projectId, status: "saved" })).facts, []); + }).pipe(Effect.provide(makeLayer(model.generate, {}, check))); +}); + /** Marks a message as a peer's reply, as a group conversation's published turn item does. */ const speakAsPeer = (input: { readonly threadId: ThreadId; @@ -565,6 +653,7 @@ it.effect( const result = yield* knowledge.saveAutomatic( { ...create(`crowded-auto-${index}`, content), sources: facts[0]!.sources }, { kind: "assisted", threadId, runId, runOutcome: "completed" }, + "standing", ); assert.equal(result.outcome, "duplicate"); } @@ -604,6 +693,7 @@ it.effect( .saveAutomatic( { ...create(`negation-${index}`, content), sources: facts[0]!.sources }, { kind: "assisted", threadId, runId, runOutcome: "completed" }, + "standing", ) .pipe(Effect.map((result) => result.outcome)), ); diff --git a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts index b17b833330e73..47aaca7955eb5 100644 --- a/apps/server/src/project/knowledge/ProjectKnowledge.test.ts +++ b/apps/server/src/project/knowledge/ProjectKnowledge.test.ts @@ -2286,6 +2286,91 @@ it.effect("recall keeps the most trusted fact when more than the bound match equ }).pipe(Effect.provide(layerTest)), ); +it.effect("recall skips facts the check set aside, which search still finds", () => + Effect.gen(function* () { + const knowledge = yield* ProjectKnowledge.ProjectKnowledge; + const sql = yield* SqlClient.SqlClient; + const projectId = ProjectId.make("recall-set-aside"); + yield* createProject(projectId); + const [standing, setAside, unchecked] = ["standing", "set-aside", "unchecked"].map((id) => + ProjectFactId.make(id), + ); + for (const factId of [standing, setAside, unchecked]) + yield* knowledge.mutate(createFact(projectId, factId), { kind: "user" }); + for (const [factId, verdict] of [ + [standing, "standing"], + [setAside, "task"], + ] as const) + yield* sql`UPDATE project_knowledge_facts + SET verdict = ${verdict}, verdict_by = 'check', verdict_at = '2026-11-16T00:00:00.000Z' + WHERE id = ${factId}`; + const recall = (id: string, query: string) => + knowledge.recall({ + projectId, + threadId: ThreadId.make(id), + requestId: CommandId.make(id), + query, + composer: { text: query, records: [] }, + knowledgeAllowance: 48000, + }); + const tenantQuery = "Change cache keys to include tenant IDs."; + assert.deepEqual(attachedFactIds(yield* recall("recall-set-aside", tenantQuery)).toSorted(), [ + standing, + unchecked, + ]); + const searched = yield* knowledge.search({ + projectId, + query: "tenant cache", + requestId: CommandId.make("search-set-aside"), + }); + assert.deepEqual( + searched.facts.state === "available" + ? searched.facts.matches.map((match) => match.fact.id).toSorted() + : [], + [setAside, standing, unchecked], + ); + // The verdict judged the old text, so an edit leaves the fact unchecked and recallable. + const { fact } = yield* knowledge.readFact({ projectId, factId: setAside }); + yield* knowledge.mutate( + { + ...createFact(projectId, setAside), + action: "edit", + commandId: CommandId.make("edit-set-aside"), + expectedRevision: fact.revision, + content: "Cache keys include tenant IDs and region codes.", + }, + { kind: "user" }, + ); + assert.isUndefined((yield* knowledge.readFact({ projectId, factId: setAside })).fact.verdict); + assert.deepEqual( + attachedFactIds(yield* recall("recall-after-edit", "Add region codes to cache keys.")), + [setAside], + ); + }).pipe( + Effect.provide( + knowledgeTestLayer( + Layer.succeed(HolographicMemory.HolographicMemory, { + scoreCandidates: (input) => + Effect.succeed( + input.candidates.map((candidate) => ({ + id: candidate.id, + rawCosine: 1, + holographic: 1, + decay: 1, + reinforcement: 0, + score: 1, + scoreMillionths: 1_000_000, + tokenOverlap: 1, + fts: 1, + coverage: 1, + })), + ), + }), + ), + ), + ), +); + it.effect("recall does not score with the holographic kernel", () => Effect.gen(function* () { const knowledge = yield* ProjectKnowledge.ProjectKnowledge; @@ -3379,8 +3464,10 @@ it.effect("automatic corroboration appends validated sources without rewriting c runOutcome: "completed" as const, }; const candidate = { ...createFact(projectId, "automatic"), sources: [citation.source] }; - assert.equal((yield* knowledge.saveAutomatic(candidate, actor)).outcome, "duplicate"); + assert.equal((yield* knowledge.saveAutomatic(candidate, actor, "task")).outcome, "duplicate"); const merged = (yield* knowledge.readFact({ projectId, factId: original.id })).fact; + // A verdict is written once: a duplicate's check does not reclassify the fact it joins. + assert.isUndefined(merged.verdict); assert.deepEqual(merged.sources, [...original.sources, citation.source]); assert.equal(merged.content, original.content); assert.deepEqual(merged.origin, original.origin); @@ -3388,6 +3475,7 @@ it.effect("automatic corroboration appends validated sources without rewriting c yield* knowledge.saveAutomatic( { ...candidate, factId: ProjectFactId.make("automatic-repeat") }, actor, + "standing", ); assert.deepEqual((yield* knowledge.readFact({ projectId, factId: original.id })).fact, merged); const invalid = yield* knowledge @@ -3398,6 +3486,7 @@ it.effect("automatic corroboration appends validated sources without rewriting c sources: [{ ...citation.source, runId: RunId.make("fabricated") }], }, actor, + "standing", ) .pipe(Effect.result); assert.equal(invalid._tag, "Failure"); @@ -3411,6 +3500,7 @@ it.effect("automatic corroboration appends validated sources without rewriting c yield* knowledge.saveAutomatic( { ...candidate, factId: ProjectFactId.make("automatic-cap"), sources: extraSources }, actor, + "standing", ); const capped = (yield* knowledge.readFact({ projectId, factId: original.id })).fact; assert.equal(capped.sources.length, 16); @@ -3425,7 +3515,7 @@ it.effect("automatic corroboration appends validated sources without rewriting c }, { kind: "user" }, ); - yield* knowledge.saveAutomatic({ ...candidate, factId: original.id }, actor); + yield* knowledge.saveAutomatic({ ...candidate, factId: original.id }, actor, "standing"); assert.equal( (yield* knowledge.readFact({ projectId, factId: original.id })).fact.status, "forgotten", diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index 66b0785870ab0..83df4d6b87918 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -203,27 +203,45 @@ it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { ), ); - it.effect("extracts memory without checkout instructions or customizations", () => - withFakeClaudeEnv( - { - output: JSON.stringify({ structured_output: { candidates: [] } }), + it.effect("extracts and checks memory without checkout instructions or customizations", () => + Effect.gen(function* () { + const isolation = { cwdMustNotBe: process.cwd(), argsMustContain: "--safe-mode --disallowedTools * --setting-sources", argsMustNotContain: "--bare", - }, - (textGeneration) => - textGeneration.generateKnowledgeCandidates({ - cwd: process.cwd(), - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: SYNTHETIC_CLAUDE_STANDARD_MODEL, - }, - runOutcome: "completed", - messages: [ - { ref: "M1", role: "user", text: "Use concise explanations in this project." }, - ], - }), - ), + }; + const modelSelection = { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: SYNTHETIC_CLAUDE_STANDARD_MODEL, + }; + yield* withFakeClaudeEnv( + { ...isolation, output: JSON.stringify({ structured_output: { candidates: [] } }) }, + (textGeneration) => + textGeneration.generateKnowledgeCandidates({ + cwd: process.cwd(), + modelSelection, + runOutcome: "completed", + messages: [ + { ref: "M1", role: "user", text: "Use concise explanations in this project." }, + ], + }), + ); + const checked = yield* withFakeClaudeEnv( + { + ...isolation, + output: JSON.stringify({ + structured_output: { results: [{ ref: 1, verdict: "standing", selfContained: true }] }, + }), + }, + (textGeneration) => + textGeneration.checkFactStanding({ + cwd: process.cwd(), + modelSelection, + statements: [{ kind: "convention", content: "Use concise explanations in Acme." }], + }), + ); + expect(checked.verdicts).toEqual(["standing"]); + }), ); it.effect("isolates blind evaluation without disabling subscription authentication", () => diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index ab28cfa696ec1..d4887a53b2118 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -561,21 +561,38 @@ it.layer(layerCodexTextGenerationTest)("CodexTextGeneration", (it) => { ), ); - it.effect("keeps checkout instructions out of automatic memory extraction", () => - withFakeCodexEnv( - { - output: JSON.stringify({ candidates: [] }), + it.effect("keeps checkout instructions out of automatic memory extraction and checks", () => + Effect.gen(function* () { + const modelSelection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-6-luna"); + const isolation = { requireArg: "--config project_doc_max_bytes=0", requiredCwd: process.cwd(), - }, - (textGeneration) => - textGeneration.generateKnowledgeCandidates({ - cwd: process.cwd(), - modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-6-luna"), - runOutcome: "completed", - messages: [{ ref: "M1", role: "user", text: "Use the shared test runner." }], - }), - ), + }; + yield* withFakeCodexEnv( + { ...isolation, output: JSON.stringify({ candidates: [] }) }, + (textGeneration) => + textGeneration.generateKnowledgeCandidates({ + cwd: process.cwd(), + modelSelection, + runOutcome: "completed", + messages: [{ ref: "M1", role: "user", text: "Use the shared test runner." }], + }), + ); + yield* withFakeCodexEnv( + { + ...isolation, + output: JSON.stringify({ + results: [{ ref: 1, verdict: "standing", selfContained: true }], + }), + }, + (textGeneration) => + textGeneration.checkFactStanding({ + cwd: process.cwd(), + modelSelection, + statements: [{ kind: "convention", content: "Acme uses the shared test runner." }], + }), + ); + }), ); it.effect("preserves custom PR instructions while allowing checkout inspection", () => diff --git a/apps/web/src/components/projectKnowledge/ProjectMemoryPanel.browser.test.tsx b/apps/web/src/components/projectKnowledge/ProjectMemoryPanel.browser.test.tsx index 89fc4195f9dd4..bd0df873c1a05 100644 --- a/apps/web/src/components/projectKnowledge/ProjectMemoryPanel.browser.test.tsx +++ b/apps/web/src/components/projectKnowledge/ProjectMemoryPanel.browser.test.tsx @@ -1170,6 +1170,7 @@ it("shows automatic facts as saved, with citations and the project switch", asyn projectKnowledge: true, projectKnowledgeHistory: true, projectKnowledgeAssistedLearning: true, + projectKnowledgeStandingCheck: true, projectSettingsOverrides: true, }, }, @@ -1204,6 +1205,11 @@ it("shows automatic facts as saved, with citations and the project switch", asyn await expect.element(toggle).toBeChecked(); await expect.element(page.getByText("Last run: saved 1.")).toBeVisible(); + await page.getByRole("button", { name: "Set aside", exact: true }).click(); + expect(state.listRequest).toHaveBeenLastCalledWith({ + environmentId: scope.environmentId, + input: { projectId: scope.projectId, status: "saved", verdict: "set_aside" }, + }); await page.getByRole("button", { name: "Automatic", exact: true }).click(); expect(state.listRequest).toHaveBeenLastCalledWith({ environmentId: scope.environmentId, diff --git a/evals/README.md b/evals/README.md index 8472ee28bc933..8f9ead6c92971 100644 --- a/evals/README.md +++ b/evals/README.md @@ -12,6 +12,7 @@ Write or run an eval when a change affects what a model sees or does: agent inst | [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | | [conversation-summaries](conversation-summaries/) | Whether summaries credit a peer's proposal to the peer, and a roll-up keeps reversals, attribution and open items within its budget. | | [memory-capture](memory-capture/) | Whether memory extraction retains useful corrections and reasons without saving task limits, code descriptions or temporary failures. | +| [memory-standing-check](memory-standing-check/) | Whether the blind standing check sets aside one task's limits and unnamed references while keeping durable project rules. | | [model-evaluations](model-evaluations/) | Whether blind judges use outcome evidence, respect task scope, ignore injected scoring instructions, and abstain when evidence is missing. | | [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | | [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | diff --git a/evals/memory-standing-check/README.md b/evals/memory-standing-check/README.md new file mode 100644 index 0000000000000..fd37270cbb9c6 --- /dev/null +++ b/evals/memory-standing-check/README.md @@ -0,0 +1,15 @@ +# Memory standing check + +Runs the production standing check against authored statements. Automatic memory saves every fact, but recalls only the ones this check calls standing and self-contained. The cases separate one task's limits, the behaviour of unmerged work and statements that do not name what they refer to (set aside) from a data-safety rule and a merge convention (kept). + +```sh +cd evals +pnpm memory-standing-check --no-check --out runs/standing-before +pnpm memory-standing-check --model morph-kimik31 --concurrency 1 --out runs/standing-after +``` + +`--no-check` reproduces capture before the check: every proposed fact was recalled, so the set-aside cases fail. `--model gpt-6-luna` uses the local Codex subscription. Morph uses the free endpoint configured as described in [MCP tool use](../mcp-tool-use/README.md); it limits input tokens per minute, so keep `--concurrency 1`. Each sample is one call with one statement, so the default three samples make 18 calls. A case passes when a majority of its samples pass. + +`results.json` holds each verdict. `--case ` restricts cases and `--baseline` keeps an earlier results file beside the new one. These clear-cut cases guard against regressions; they do not estimate how often the check agrees with people on real facts. + +Add a case with its source, the statement and its kind, and whether recall should keep it. Keep user data out of statements. diff --git a/evals/memory-standing-check/cases.ts b/evals/memory-standing-check/cases.ts new file mode 100644 index 0000000000000..d247626406264 --- /dev/null +++ b/evals/memory-standing-check/cases.ts @@ -0,0 +1,73 @@ +import type { FactStandingCheckStatement } from "@t3tools/provider-core/server/textGenerationPrompts"; + +export interface StandingCase { + readonly id: string; + readonly source: string; + readonly statement: FactStandingCheckStatement; + /** "kept" is recalled into later work; "set_aside" is stored but never recalled. */ + readonly expected: "kept" | "set_aside"; +} + +const audit = + "2026-11 project-memory audit: about half of saved facts were one task's limits or code descriptions; authored Acme examples."; + +export const cases: ReadonlyArray = [ + { + id: "delegate-scope-limit", + source: audit, + statement: { + kind: "constraint", + content: + "Keep the delegated change limited to the invoice parser; do not modify the retry policy or the export queue.", + }, + expected: "set_aside", + }, + { + id: "unmerged-pr-behaviour", + source: audit, + statement: { + kind: "decision", + content: + "The open pull request that adds CSV export retries a failed upload three times before showing an error.", + }, + expected: "set_aside", + }, + { + id: "one-pr-authorization", + source: audit, + statement: { + kind: "convention", + content: "For this pull request, merging without waiting for CI is authorized.", + }, + expected: "set_aside", + }, + { + id: "unnamed-reference", + source: audit, + statement: { + kind: "decision", + content: "Use the new approach from the fix for every similar handler.", + }, + expected: "set_aside", + }, + { + id: "live-database-privacy", + source: audit, + statement: { + kind: "constraint", + content: + "Never open the production customer database read-write from a development machine; copy it and work on the copy.", + }, + expected: "kept", + }, + { + id: "merge-order-convention", + source: audit, + statement: { + kind: "convention", + content: + "Acme merges stacked pull requests bottom-up, and rebases each layer onto main after the layer below it merges.", + }, + expected: "kept", + }, +]; diff --git a/evals/memory-standing-check/run.ts b/evals/memory-standing-check/run.ts new file mode 100644 index 0000000000000..b4844594a2fc8 --- /dev/null +++ b/evals/memory-standing-check/run.ts @@ -0,0 +1,101 @@ +#!/usr/bin/env node +import * as NodeUtil from "node:util"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { CodexSettings, ProviderInstanceId, type ProjectFactVerdict } from "@t3tools/contracts"; +import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; +import * as CodexTextGeneration from "../../apps/server/src/textGeneration/CodexTextGeneration.ts"; +import * as ServerConfig from "../../apps/server/src/config.ts"; +import { morphRunner } from "../shared/morph.ts"; +import { cases } from "./cases.ts"; + +const decodeSettings = Schema.decodeUnknownSync(CodexSettings); +const encodeResults = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); + +const { values } = NodeUtil.parseArgs({ + options: { + model: { type: "string" }, + out: { type: "string" }, + baseline: { type: "string" }, + case: { type: "string" }, + samples: { type: "string", default: "3" }, + concurrency: { type: "string", default: "1" }, + // Capture before the check: every proposed fact was saved for recall. + "no-check": { type: "boolean", default: false }, + }, +}); +if (!values.out || (!values.model && !values["no-check"])) + throw new Error("Use --model --out , or --no-check --out ."); +const model = values["no-check"] ? "no-check" : values.model!; +const out = values.out; +const samples = Number(values.samples); +const concurrency = Number(values.concurrency); +if (!Number.isSafeInteger(samples) || samples < 1) throw new Error("Invalid sample count."); +if (!Number.isSafeInteger(concurrency) || concurrency < 1) throw new Error("Invalid concurrency."); +const selected = cases.filter( + (fixture) => !values.case || values.case.split(",").includes(fixture.id), +); +if (!selected.length) throw new Error("No matching cases."); + +await Effect.runPromise( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-standing-eval-" }); + const morph = model.startsWith("morph-"); + const generation = values["no-check"] + ? null + : morph + ? TextGenerationOperations.fromRunner("Morph", morphRunner()) + : yield* CodexTextGeneration.makeCodexTextGeneration(decodeSettings({})); + const modelSelection = { + instanceId: ProviderInstanceId.make(morph ? "morph" : "codex"), + model, + }; + yield* fs.makeDirectory(out, { recursive: true }); + if (values.baseline) + yield* fs.writeFileString( + path.join(out, "baseline.json"), + yield* fs.readFileString(values.baseline), + ); + const runs = selected.flatMap((fixture) => + Array.from({ length: samples }, (_, sample) => ({ fixture, sample })), + ); + const results = yield* Effect.forEach( + runs, + ({ fixture, sample }) => + Effect.gen(function* () { + const verdict: ProjectFactVerdict = + generation === null + ? "standing" + : (yield* generation.checkFactStanding({ + cwd, + modelSelection, + statements: [fixture.statement], + })).verdicts[0]!; + const outcome = verdict === "standing" ? "kept" : "set_aside"; + return { id: fixture.id, sample, model, verdict, passed: outcome === fixture.expected }; + }), + { concurrency }, + ); + yield* fs.writeFileString(path.join(out, "results.json"), yield* encodeResults(results)); + for (const fixture of selected) { + const passed = results.filter((row) => row.id === fixture.id && row.passed).length; + const verdicts = results.filter((row) => row.id === fixture.id).map((row) => row.verdict); + yield* Effect.log( + `${fixture.id} (${fixture.expected}): ${passed}/${samples} ${passed * 2 > samples ? "PASS" : "FAIL"} [${verdicts.join(", ")}]`, + ); + } + }).pipe( + Effect.provide( + ServerConfig.layerTest(process.cwd(), { prefix: "t3-standing-eval-state-" }).pipe( + Layer.provideMerge(NodeServices.layer), + ), + ), + Effect.scoped, + ), +); diff --git a/evals/package.json b/evals/package.json index b81b0400cb43c..c5ce9282d788c 100644 --- a/evals/package.json +++ b/evals/package.json @@ -15,7 +15,8 @@ "test-signal": "node --env-file-if-exists=../.env test-signal/run.ts", "typecheck": "effect-tsgo tsrs --noEmit", "test": "vp test run --config ../vite.config.ts --dir .", - "memory-capture": "node --env-file-if-exists=../.env memory-capture/run.ts" + "memory-capture": "node --env-file-if-exists=../.env memory-capture/run.ts", + "memory-standing-check": "node --env-file-if-exists=../.env memory-standing-check/run.ts" }, "dependencies": { "@effect/platform-node": "catalog:", diff --git a/packages/provider-core/src/server/textGenerationOperations.test.ts b/packages/provider-core/src/server/textGenerationOperations.test.ts index cd4e7f7417098..69ddde4029e9c 100644 --- a/packages/provider-core/src/server/textGenerationOperations.test.ts +++ b/packages/provider-core/src/server/textGenerationOperations.test.ts @@ -181,3 +181,33 @@ it.effect("fails a thread title reply that is only the schema key", () => assert.strictEqual(outcome.operation, "generateThreadTitle"); }), ); + +it.effect("sets aside every statement the standing check does not clearly keep", () => + Effect.gen(function* () { + const check = (reply: string) => + fromRunner("Stub", (request) => decodeJsonReply(request, "Stub", reply)).checkFactStanding({ + cwd: process.cwd(), + modelSelection, + statements: ["one", "two", "three", "four", "five"].map((content) => ({ + kind: "convention" as const, + content: `Acme rule ${content}.`, + })), + }); + const { verdicts } = yield* check( + JSON.stringify({ + results: [ + { ref: 1, verdict: "standing", selfContained: true }, + { ref: 2, verdict: "standing", selfContained: false }, + { ref: 3, verdict: "code", selfContained: true }, + { ref: 4, verdict: "standing", selfContained: true }, + { ref: 4, verdict: "standing", selfContained: true }, + { ref: 9, verdict: "standing", selfContained: true }, + ], + }), + ); + // Statement 5 is unanswered; 4 is answered twice; 9 does not exist. + assert.deepStrictEqual(verdicts, ["standing", "task", "code", "task", "task"]); + const offSchema = yield* check('{"results":[{"ref":1,"verdict":"keep"}]}').pipe(Effect.flip); + assert.strictEqual(offSchema.operation, "checkFactStanding"); + }), +); From e240c680d2276e85a8a2c96dc35a4618f0eb6f5b Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Mon, 16 Nov 2026 19:39:05 -0800 Subject: [PATCH 02/12] feat(server): automatic memory recalls only facts a blind check calls standing After extraction, one more call reads only the proposed statements, from an empty directory, and classifies each as standing, task or code. Every candidate is saved with that verdict; recall offers only standing and unchecked facts, through one SQL fragment, while search and the new Set aside filter still show the rest. A failed check saves nothing and retries the batch in 30 minutes, recording a failure after three attempts. Editing a fact's text clears a check verdict. Co-Authored-By: Claude Opus 5.5 --- .../src/components/ProjectKnowledgeEntry.tsx | 3 + .../components/ProjectKnowledgeFactDetail.tsx | 7 + .../components/ProjectKnowledgeFactList.tsx | 19 +- .../src/environment/ServerEnvironment.ts | 1 + apps/server/src/git/GitManager.test.ts | 1 + .../ProviderEventIngestor.test.ts | 1 + apps/server/src/persistence/Migrations.ts | 2 + .../115_ProjectKnowledgeFactVerdict.ts | 14 ++ .../reconcileV2PreviewMigration.test.ts | 2 + .../externalHistory/ExternalHistory.test.ts | 1 + .../src/project/knowledge/AssistedLearning.ts | 196 ++++++++++++------ .../src/project/knowledge/ProjectKnowledge.ts | 25 ++- .../src/project/knowledge/persistence.ts | 49 ++++- .../src/provider/Drivers/ClaudeDriver.ts | 2 + .../src/provider/Drivers/CodexDriver.ts | 2 + .../provider/Drivers/CodexManagedProvider.ts | 2 + .../src/provider/agentContextBudget.json | 2 +- .../providerMaintenanceRunner.test.ts | 1 + apps/server/src/speech/http.test.ts | 1 + .../textGeneration/ClaudeTextGeneration.ts | 15 +- .../src/textGeneration/CodexTextGeneration.ts | 4 +- .../src/textGeneration/TextGeneration.ts | 10 +- .../ProjectMemoryInspector.tsx | 7 + .../projectKnowledge/ProjectMemoryPanel.tsx | 14 +- .../settings/useScopedModelAvailability.ts | 1 + docs/user/composer.md | 8 + .../src/projectKnowledge/index.ts | 19 ++ packages/contracts/src/environment.ts | 2 + packages/contracts/src/projectKnowledge.ts | 14 ++ packages/contracts/src/server.ts | 1 + .../src/server/driver.ts | 1 + .../src/server/textGeneration.ts | 18 ++ .../src/server/textGenerationOperations.ts | 25 +++ .../src/server/textGenerationPrompts.ts | 52 +++++ .../src/server/textGeneration.ts | 2 +- packages/provider-fx/src/server/driver.ts | 1 + packages/provider-kiro/src/server/driver.ts | 1 + .../provider-opencode/src/server/driver.ts | 5 + .../src/server/textGeneration.ts | 3 +- .../src/server/v2/textGeneration.ts | 7 +- 40 files changed, 439 insertions(+), 102 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/115_ProjectKnowledgeFactVerdict.ts diff --git a/apps/mobile/src/components/ProjectKnowledgeEntry.tsx b/apps/mobile/src/components/ProjectKnowledgeEntry.tsx index 9289c933613b4..1f58634fa343d 100644 --- a/apps/mobile/src/components/ProjectKnowledgeEntry.tsx +++ b/apps/mobile/src/components/ProjectKnowledgeEntry.tsx @@ -134,6 +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} seedMessage={open.seed} onClose={() => setOpen(null)} /> @@ -144,6 +145,7 @@ function ProjectKnowledgeSheet( props: Scope & { readonly history: boolean; readonly assisted: boolean; + readonly standingCheck: boolean; readonly seedMessage: MessageCitation | null; readonly onClose: () => void; }, @@ -460,6 +462,7 @@ function ProjectKnowledgeSheet( projectId={props.projectId} browse={browse} assisted={props.assisted} + standingCheck={props.standingCheck} canMutate={canMutate} busy={busy} selectionState={selectionState} diff --git a/apps/mobile/src/components/ProjectKnowledgeFactDetail.tsx b/apps/mobile/src/components/ProjectKnowledgeFactDetail.tsx index 93b36e449b2b2..b94d17ae18257 100644 --- a/apps/mobile/src/components/ProjectKnowledgeFactDetail.tsx +++ b/apps/mobile/src/components/ProjectKnowledgeFactDetail.tsx @@ -20,6 +20,7 @@ import { isSupersededFact, knowledgeConflictHintLabel, knowledgeOriginLabel, + projectFactVerdictLabel, projectFactHistoryLabel, } from "@t3tools/client-runtime/projectKnowledge"; @@ -160,6 +161,12 @@ export function ProjectFactInspector(props: { {fact.kind} · {fact.status} · {knowledgeOriginLabel(fact.origin)} + {fact.verdict ? ( + + {projectFactVerdictLabel(fact.verdict)}{" "} + {historyTimeFormatter.format(new Date(fact.verdict.at))} + + ) : null} Trust signal {fact.trust.toFixed(2)} · revision {fact.revision} diff --git a/apps/mobile/src/components/ProjectKnowledgeFactList.tsx b/apps/mobile/src/components/ProjectKnowledgeFactList.tsx index dd4594a384962..d722119c09c8c 100644 --- a/apps/mobile/src/components/ProjectKnowledgeFactList.tsx +++ b/apps/mobile/src/components/ProjectKnowledgeFactList.tsx @@ -35,7 +35,7 @@ import { KnowledgeHealthRow } from "./ProjectKnowledgeFactDetail"; import { AppText, AppTextInput } from "./ui/AppText"; import { Button } from "./ui/Button"; -type StatusFilter = "saved" | "automatic" | "forgotten"; +type StatusFilter = "saved" | "automatic" | "set_aside" | "forgotten"; /** Filters, search and paging for the fact list. The sheet reads its results for draft labels. */ export function useProjectKnowledgeBrowse(props: { @@ -60,7 +60,9 @@ export function useProjectKnowledgeBrowse(props: { ? { sourceState: "unavailable" as const } : status === "automatic" ? { status: "saved" as const, origin: "assisted" as const } - : { status }), + : status === "set_aside" + ? { status: "saved" as const, verdict: "set_aside" as const } + : { status }), ...(afterId ? { afterId } : {}), ...(props.history && showSuperseded ? { includeSuperseded: true } : {}), }, @@ -202,6 +204,7 @@ 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; @@ -240,13 +243,17 @@ export function ProjectKnowledgeFactList(props: { - {(props.assisted - ? (["saved", "automatic", "forgotten"] as const) - : (["saved", "forgotten"] as const) + {( + [ + "saved", + ...(props.assisted ? (["automatic"] as const) : []), + ...(props.standingCheck ? (["set_aside"] as const) : []), + "forgotten", + ] as const ).map((value) => (