From 56b4599dfa358b4b85ace3b8689fd24bb49c90ca Mon Sep 17 00:00:00 2001 From: vu1n <2105991+vu1n@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:56:27 +0000 Subject: [PATCH 1/5] worker: a used rating from another session confirms a candidate; say when a claim is an echo --- docs/features/hosted-worker.md | 15 +++ worker/README.md | 3 +- worker/src/consolidate.ts | 14 ++- worker/src/mcp.ts | 32 +++++-- worker/src/memory.ts | 33 +++++-- worker/src/store.ts | 48 +++++++++- worker/test/confirm.test.ts | 168 +++++++++++++++++++++++++++++++++ worker/test/feedback.test.ts | 8 +- worker/test/rollup.test.ts | 4 +- 9 files changed, 299 insertions(+), 26 deletions(-) create mode 100644 worker/test/confirm.test.ts diff --git a/docs/features/hosted-worker.md b/docs/features/hosted-worker.md index 2cf9ec4..f13b7d3 100644 --- a/docs/features/hosted-worker.md +++ b/docs/features/hosted-worker.md @@ -14,6 +14,7 @@ tests: - "worker/test/keycard.test.ts" - "worker/test/readonly.test.ts" - "worker/test/feedback.test.ts" + - "worker/test/confirm.test.ts" --- # Hosted Worker @@ -182,6 +183,20 @@ TypeSafe API's shape, for GitHub Actions OIDC tokens (`worker/src/oidc.ts`) and and the feedback insert drops the note itself when the claim carries `metadata.purged_at`. One call keeps only the last rating per claim, so `created_at` orders a session's verdicts. The local `kypp serve` has no `feedback` yet. +- A `used` rating confirms: consolidate loads each candidate's newest-verdict `used` raters + (`store.confirmations`) and `recurs` counts each as that session's support at the rating's time, so + the recurrence gap still applies. The claim's own writer never confirms it. A session's verdict is + its newest rating, and it confirms only if that rating is `used` and marked `writable`. `feedback` + marks a rating writable only when the current caller could write at the claim's level (`mayWrite` + in `mcp.ts`: not read-only, inside a pin, the caller's own user or room lane), because a session id + is not bound to a credential and read visibility alone would let a reader confirm another lane's + claim. Rows from before the mark never confirm, and a later unmarked `wrong` still withdraws. An unstamped survivor (an echo) never supersedes a stamped candidate until the group + promotes, so the claim the echo reply tells the agent to rate stays live. The plan + carries the ratings it counted (`GroupPlan.confirmed`) and `apply` refuses it if any is no longer + that session's newest verdict (`created_at`, then `rowid`), because a rating never touches the + claim rows the version guard reads. This is the only way a session that was + shown a candidate can help accept it: its re-claim is an echo, and the claim reply says so. The + Python arbiter doesn't count ratings, so local and hosted promote differently here. - `initialize` instructions are built from `STEPS` in `mcp.ts`, keeping only the steps whose tool the caller can see (`visibleTools`), so a read-only or `KYPP_CORRECT=off` caller is never told to call a tool it lacks. diff --git a/worker/README.md b/worker/README.md index 21c53c1..ecfdbdc 100644 --- a/worker/README.md +++ b/worker/README.md @@ -38,7 +38,8 @@ a remote MCP server with OAuth. Local kypp is unchanged; this is the optional ho - **Categories:** the claim types (pitfall, decision, procedure, preference, fact, artifact, hypothesis). The briefing is grouped by type. - **Promotion:** a claim is accepted once it recurs in two sessions at least - `KYPP_RECUR_GAP_MINUTES` (default 60) apart. That measures repetition, not independent evidence: + `KYPP_RECUR_GAP_MINUTES` (default 60) apart. A session that was shown the claim and rated it + `used` with `feedback` counts as one of them; re-claiming what it was shown doesn't. That measures repetition, not independent evidence: one client can open two sessions, so the gap just makes faking it slow. Session ids are signed, so a client can't invent one. A newer claim on an accepted subject waits as a pending update and replaces the old answer once it recurs. diff --git a/worker/src/consolidate.ts b/worker/src/consolidate.ts index 0664318..48239f3 100644 --- a/worker/src/consolidate.ts +++ b/worker/src/consolidate.ts @@ -19,7 +19,15 @@ export async function planWithJudge(live: Claim[], policy: Policy, s1: S1Client return plans; } -export async function consolidate(store: D1Store, policy: Policy, s1: S1Client | null, - filter?: Parameters[0]) { - return store.apply(await planWithJudge(await store.liveClaims({ ...filter, filed: true }), policy, s1)); +type Filter = Parameters[0]; + +// Live filed claims, each candidate carrying the sessions whose current verdict on it is `used`. +export async function plan(store: D1Store, policy: Policy, s1: S1Client | null, filter?: Filter): Promise { + const live = await store.liveClaims({ ...filter, filed: true }); + const confirmed = await store.confirmations(live.filter((c) => c.status === "candidate").map((c) => c.id)); + return planWithJudge(live.map((c) => confirmed.has(c.id) ? { ...c, confirmations: confirmed.get(c.id) } : c), policy, s1); +} + +export async function consolidate(store: D1Store, policy: Policy, s1: S1Client | null, filter?: Filter) { + return store.apply(await plan(store, policy, s1, filter)); } diff --git a/worker/src/mcp.ts b/worker/src/mcp.ts index 6fc8cc3..51bba25 100644 --- a/worker/src/mcp.ts +++ b/worker/src/mcp.ts @@ -25,7 +25,8 @@ const STEPS: { tool?: string; text: string }[] = [ { text: "BEFORE non-trivial work — `recall(\"\")`; `expand(handle)` for the full claim." }, { tool: "claim", text: `WHEN YOU LEARN SOMETHING DURABLE — \`claim\` a distilled, model-agnostic lesson. \`subject\` is its identity: reuse a subject to update it. Claims land as candidates; one is accepted once a second - session claims the same subject. Don't store status ("shipped", "PR merged") — git holds that. + session claims the same subject or rates it \`used\` with \`feedback\`. Don't store status + ("shipped", "PR merged") — git holds that. WHERE IT GOES: you don't choose. Say which repo you are in and the server files and shares the lesson. Set \`scope: "user"\` only for how this person works, in every repo. Reads show other agents' unconfirmed (?) claims in this repo: weigh them. Don't re-claim a lesson @@ -35,7 +36,7 @@ const STEPS: { tool?: string; text: string }[] = [ { tool: "feedback", text: `BEFORE YOU FINISH — \`feedback\` on the handles you were shown: \`used\` if it held up in your work (say what you checked in \`note\`), \`not_used\` if it didn't bear on the task, \`wrong\` if it misled you (say how in \`note\`, and claim the fix under the same subject). One call with every - handle; the ratings tune what memory shows.` }, + handle; the ratings tune what memory shows, and a \`used\` from another session confirms a claim.` }, ]; const INTRO = `kypp is shared memory for coding agents — durable lessons governed by status (candidate → accepted), authority (human > verified > agent) and provenance.`; @@ -235,6 +236,11 @@ async function afterClaim(store: D1Store, at: Lane, id: string, subject: string, + (near.length ? `\nnearby subjects here: ${near.map((n) => JSON.stringify(n)).join(", ")}. If one is the same lesson, claim it again with the same content under that subject; this claim is then withdrawn.` : ""); } +// Why: an echo used to be stored with no sign it earned nothing, so agents kept re-claiming to agree. +const echoNote = (echoOf: string[]) => echoOf.length + ? `\necho: this session was shown another session's unconfirmed claim on this subject, so this one doesn't count toward accepting it. If that claim held up in your work, rate it \`used\` with \`feedback\`; that does count.` + : ""; + // What this claim counts as: an echo when the session was shown the subject, or when it renames a // claim that was itself an echo (a rename must not launder relayed content into recurrence). // A session shown another session's candidate on this subject doesn't count toward accepting it. @@ -300,7 +306,7 @@ async function roomTool(store: D1Store, name: string, a: Args, ctx: ToolCtx, key confidence: a.confidence ?? 0.7, sourceIds: stamp, codeRefs: [], accept: false, agent: identity, user: identity, metadata, ...(share !== null ? { sharedFrom: key } : {}), }); - return id + await afterClaim(store, at, id, subject, content, ctx.session, prior); + return id + echoNote(echoOf) + await afterClaim(store, at, id, subject, content, ctx.session, prior); } case "expand": { const c = await store.get(String(a.handle ?? ""), identity, ctx.session, room); @@ -315,7 +321,17 @@ async function roomTool(store: D1Store, name: string, a: Args, ctx: ToolCtx, key const VERDICTS: Record = { used: 1, not_used: 0, wrong: -1 }; const MAX_RATINGS = 50, MAX_NOTE = 300; -async function feedback(store: D1Store, a: Args, session: string | null): Promise { +// Whether this caller could have written a claim at `c`'s level: only such a caller's `used` can confirm it. +// Read visibility is not enough, because one session id can be carried across credentials. +function mayWrite(caller: Caller, c: { scope: string; project: string | null; user: string | null }): boolean { + if (caller.readOnly) return false; + if (caller.room) return c.scope === "room" && c.user === caller.user; + if (c.scope === "user") return c.user !== null && c.user === caller.user; + if (c.scope !== "project") return false; + return !caller.projects || (c.project !== null && caller.projects.includes(c.project)); +} + +async function feedback(store: D1Store, a: Args, session: string | null, caller: Caller): Promise { if (!session) throw new Error("feedback needs the session id from initialize: it rates what this session was shown"); const ratings: unknown[] = Array.isArray(a.ratings) ? a.ratings : []; if (!ratings.length) throw new Error("ratings must list at least one {handle, verdict}"); @@ -332,8 +348,10 @@ async function feedback(store: D1Store, a: Args, session: string | null): Promis return shown ? { ...shown, score: VERDICTS[verdict], verdict, note } : `${handle}: not shown to this session`; })); // Two ratings of one claim in a call (a prefix and the full id, say): the last one listed wins. - const rated = [...new Map(checked.filter((c) => typeof c !== "string").map((c) => [c.id, c])).values()]; + const shown = [...new Map(checked.filter((c) => typeof c !== "string").map((c) => [c.id, c])).values()]; const skipped = checked.filter((c) => typeof c === "string"); + const lanes = await store.lanes(shown.map((r) => r.id)); + const rated = shown.map((r) => ({ ...r, writable: !!lanes.get(r.id) && mayWrite(caller, lanes.get(r.id)!) })); await store.recordFeedback(session, rated); return `recorded ${rated.length} rating${rated.length === 1 ? "" : "s"}` + (skipped.length ? `\nskipped:\n${skipped.join("\n")}` : ""); } @@ -345,7 +363,7 @@ const visibleTools = (ctx: ToolCtx) => ctx.caller.room ? ROOM_TOOLS export async function callTool(store: D1Store, name: string, a: Args, ctx: ToolCtx): Promise { // Feedback reaches only claims a read already showed this session, so every lane's visibility rule still holds. - if (name === "feedback") return feedback(store, a, ctx.session); + if (name === "feedback") return feedback(store, a, ctx.session, ctx.caller); if (ctx.caller.room) return roomTool(store, name, a, ctx, ctx.caller.room); if (ctx.caller.readOnly && WRITES.has(name)) throw new Error(`this token is read-only: ${name} is not available`); // The caller says where it is; only a registered project is a place, so an unknown name can't start a separate memory. @@ -450,7 +468,7 @@ async function repoTool(store: D1Store, name: string, a: Args, ctx: ToolCtx, accept: false, agent: ctx.caller.agent, user, metadata, }); // Why: clients that can't send a header shouldn't wait an hour for defrag to file their claim. - if (at) return id + await afterClaim(store, at, id, subject, content, ctx.session, prior); + if (at) return id + echoNote(echoOf) + await afterClaim(store, at, id, subject, content, ctx.session, prior); try { if (await fileClaim(store, ctx.s1, { id, subject, content, origin }, projects)) return id; } catch (e) { diff --git a/worker/src/memory.ts b/worker/src/memory.ts index 1ce7d14..b1e078e 100644 --- a/worker/src/memory.ts +++ b/worker/src/memory.ts @@ -61,8 +61,12 @@ export interface Claim { updated_at: string; verify?: string | null; // the operator's freshness command; set only through POST /v1/operator pointer?: boolean; // set by recall when a path, anchor or doc:// ref in the query matched the claim, not its words + confirmations?: Confirmation[]; // set by consolidate: other sessions whose newest feedback on this claim is `used` } +// A session that was shown the claim, acted on it, and rated it `used` with a note on what it checked. +export interface Confirmation { session: string; at: string } + // Rank survivors by authority first; agent < verified < human. export function rank(c: Claim): [number, number, number, number, string] { return [AUTHORITIES.indexOf(c.authority), c.status === "accepted" ? 1 : 0, c.confidence ?? 0, @@ -91,12 +95,16 @@ export function corroboration(members: Claim[]): number { // The two-session rule measures recurrence, not independent evidence: one client can open two // sessions. Requiring the supporting sessions to span `minGapMs` makes "it came up again later" the // thing being counted, and makes faking it slow. +// A `used` rating counts as its session's support at the rating's time, because the rater checked the +// claim against its own work; re-claiming what it was shown (an echo) still counts for nothing. export function recurs(members: Claim[], k: number, minGapMs: number): boolean { - if (members.length < k) return false; const firstSeen = new Map(); + const seen = (s: string, t: number) => firstSeen.set(s, Math.min(firstSeen.get(s) ?? t, t)); for (const m of members) { const t = Date.parse(m.created_at); - for (const s of m.source_ids) firstSeen.set(s, Math.min(firstSeen.get(s) ?? t, t)); + for (const s of m.source_ids) seen(s, t); + // A session never confirms its own claim. + for (const c of m.confirmations ?? []) if (c.session !== m.session) seen(`session:${c.session}`, Date.parse(c.at)); } if (firstSeen.size < k) return false; const times = [...firstSeen.values()]; @@ -116,7 +124,12 @@ export interface GroupKey { subject: string; scope: Scope; project: string | nul // `version` is the group's live-row count and newest updated_at at read time; apply() refuses a plan // whose group changed since (a correction or new claim landed), so a stale plan can't undo it. // `support` is the claims whose recurrence justifies the promotion, for an agreement check. -export interface GroupPlan { key: GroupKey; version: string; supersede: string[]; promote: string[]; support: string[] } +// `confirmed` is the (claim, session) `used` ratings the promotion counted; apply() refuses the plan if one was withdrawn since. +export interface GroupPlan { key: GroupKey; version: string; supersede: string[]; promote: string[]; support: string[]; confirmed?: Rated[] } +export interface Rated { claim: string; session: string } + +const countedConfirmations = (members: Claim[]): Rated[] => + members.flatMap((m) => (m.confirmations ?? []).filter((c) => c.session !== m.session).map((c) => ({ claim: m.id, session: c.session }))); export function groupVersion(members: Claim[]): string { return `${members.length}:${members.reduce((m, c) => (c.updated_at > m ? c.updated_at : m), "")}`; @@ -145,15 +158,23 @@ export function planGroup(members: Claim[], policy: Policy = DEFAULT_POLICY): Gr const winner = survivor(updates); plan.promote.push(winner.id); plan.support = updates.map((u) => u.id); + plan.confirmed = countedConfirmations(updates); plan.supersede.push(...members.filter((m) => m.id !== winner.id).map((m) => m.id)); return plan; } - const pending = new Set(updates.map((u) => u.id)); - plan.supersede.push(...members.filter((m) => m.id !== best.id && !pending.has(m.id)).map((m) => m.id)); // Why: accept only when >= K distinct claims from distinct sessions agree; one session's guess must not become the swarm's truth. - if (best.status === "candidate" && recurs(members, policy.k, policy.minGapMs) && policy.autoAccept(best)) { + const promoting = best.status === "candidate" && recurs(members, policy.k, policy.minGapMs) && policy.autoAccept(best); + // An unstamped survivor (an echo) never retires a stamped candidate: that claim is the subject's evidence, and the + // one a later `used` rating names. + const keep = new Set(updates.map((u) => u.id)); + if (!promoting && best.status === "candidate" && !best.source_ids.length) { + for (const m of members) if (m.status === "candidate" && m.source_ids.length) keep.add(m.id); + } + plan.supersede.push(...members.filter((m) => m.id !== best.id && !keep.has(m.id)).map((m) => m.id)); + if (promoting) { plan.promote.push(best.id); plan.support = members.map((m) => m.id); + plan.confirmed = countedConfirmations(members); } return plan; } diff --git a/worker/src/store.ts b/worker/src/store.ts index 7c4f927..7fe0636 100644 --- a/worker/src/store.ts +++ b/worker/src/store.ts @@ -1,5 +1,5 @@ // store.ts — the D1 side of kypp/store.py: claim, recall, get, usage, live claims, status writes. -import { type Claim, type ClaimType, type GroupPlan, SCOPES, type Scope, TYPES, ownedScope, ftsQuery, resolveOrigin } from "./memory.ts"; +import { type Claim, type ClaimType, type Confirmation, type GroupPlan, SCOPES, type Scope, TYPES, ownedScope, ftsQuery, resolveOrigin } from "./memory.ts"; import { normalizedContent } from "./claim-machine.ts"; import type { ProjectInfo } from "./s1.ts"; @@ -109,6 +109,8 @@ function hydrate(r: Record): Claim { } const UNSORTED = "scope = 'project' AND project IS NULL"; +// A session's verdict is its newest rating of the claim; it confirms only if that rating is `used` and marked writable. +const CONFIRMING = "CASE WHEN json_extract(u.metadata, '$.writable') = 1 THEN u.score END"; /** A claim's level, keyed the way its group is: a project, a person's own scope, or a room's lane. */ export type Lane = { project: string } | { user: string } | { room: string }; @@ -483,10 +485,22 @@ export class D1Store { return results.length ? results[0] as { id: string; project: string | null; scope: string } : null; } + // Each claim's level, for an authorization check on what was shown. + async lanes(ids: string[]): Promise> { + if (!ids.length) return new Map(); + const { results } = await this.db.prepare( + "SELECT c.id, c.scope, c.project, c.user FROM memory_claims c JOIN json_each(?) j ON j.value = c.id", + ).bind(JSON.stringify(ids)).all(); + return new Map(results.map((r) => [r.id as string, { scope: r.scope as string, project: r.project as string | null, user: r.user as string | null }])); + } + // A session's verdict on claims it was shown: its own usage rows (surface "feedback"), never a change // to the claim. The newest row per consumer and claim is the verdict; earlier ones stay as history. - // One call holds at most one rating per claim (the caller dedupes), so created_at orders them. - async recordFeedback(consumer: string, rated: { id: string; project: string | null; scope: string; score: number; verdict: string; note: string | null }[]): Promise { + // One call holds at most one rating per claim (the caller dedupes); rowid breaks created_at ties between calls. + // Only a rating from a caller that may write at the claim's level is marked `writable`, and only a marked + // rating confirms a claim; a rating stored before the mark can't show who made it. + async recordFeedback(consumer: string, + rated: { id: string; project: string | null; scope: string; score: number; verdict: string; note: string | null; writable: boolean }[]): Promise { if (!rated.length) return; const ts = now(); // A purged claim's tombstone is checked in the insert itself, so a note can't bring erased text back. @@ -494,7 +508,27 @@ export class D1Store { "INSERT INTO claim_usages(id,consumer,claim_id,project,scope,surface,score,metadata,created_at)" + " SELECT ?,?,?,?,?,'feedback',?,CASE WHEN json_extract(metadata, '$.purged_at') IS NULL THEN ? ELSE ? END,? FROM memory_claims WHERE id = ?", ).bind(uid(), consumer, r.id, r.project, r.scope, r.score, - JSON.stringify(r.note ? { verdict: r.verdict, note: r.note } : { verdict: r.verdict }), JSON.stringify({ verdict: r.verdict }), ts, r.id))); + JSON.stringify({ verdict: r.verdict, ...(r.note ? { note: r.note } : {}), ...(r.writable ? { writable: true } : {}) }), + JSON.stringify({ verdict: r.verdict, ...(r.writable ? { writable: true } : {}) }), ts, r.id))); + } + + // Per claim, the sessions whose newest rating of it is a writable `used`, with when they rated it. + async confirmations(ids: string[]): Promise> { + const out = new Map(); + if (!ids.length) return out; + const { results } = await this.db.prepare( + `SELECT u.claim_id, u.consumer, ${CONFIRMING} AS score, u.created_at FROM claim_usages u JOIN json_each(?) j ON j.value = u.claim_id` + + " WHERE u.surface = 'feedback' ORDER BY u.created_at, u.rowid", + ).bind(JSON.stringify(ids)).all(); + // The newest row per (consumer, claim) is that session's verdict; a later not_used or wrong withdraws a used. + const latest = new Map>(); + for (const r of results) latest.set(`${r.claim_id}\u0000${r.consumer}`, r); + for (const r of latest.values()) { + if (r.score !== 1) continue; + const id = r.claim_id as string; + out.set(id, [...(out.get(id) ?? []), { session: r.consumer as string, at: r.created_at as string }]); + } + return out; } // Every group or org `project` rolls up to, nearest first, through parents of parents up to three @@ -723,6 +757,12 @@ export class D1Store { + " AND c.status IN ('candidate','accepted') AND c.subject = ? AND c.scope = ? AND c.project IS ?" + " AND (c.scope NOT IN ('user','room') OR c.user IS ?)))", ).bind(JSON.stringify([...p.supersede, ...p.promote]), subject, scope, project, user), + // A `used` rating the promotion counted must still be that session's verdict: a later rating doesn't touch the claim rows. + ...(p.confirmed?.length ? [this.db.prepare( + `INSERT INTO consolidation_guard(ok) SELECT 0 WHERE EXISTS (SELECT 1 FROM json_each(?) t WHERE IFNULL((SELECT ${CONFIRMING} FROM claim_usages u` + + ` WHERE u.surface = 'feedback' AND u.claim_id = json_extract(t.value, '$.claim') AND u.consumer = json_extract(t.value, '$.session')` + + " ORDER BY u.created_at DESC, u.rowid DESC LIMIT 1), 0) != 1)", + ).bind(JSON.stringify(p.confirmed))] : []), ...p.supersede.map((id) => this.db.prepare("UPDATE memory_claims SET status='superseded', updated_at=? WHERE id=?").bind(ts, id)), ...p.promote.map((id) => this.db.prepare("UPDATE memory_claims SET status='accepted', updated_at=? WHERE id=?").bind(ts, id)), ]; diff --git a/worker/test/confirm.test.ts b/worker/test/confirm.test.ts new file mode 100644 index 0000000..69b7809 --- /dev/null +++ b/worker/test/confirm.test.ts @@ -0,0 +1,168 @@ +// A `used` rating from another session confirms a candidate: consolidate counts it like a second +// session's claim, while a re-claim of what the session was shown (an echo) still counts for nothing. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { consolidate, plan } from "../src/consolidate.ts"; +import { type Caller, handleMcp } from "../src/mcp.ts"; +import { type Claim, type Policy, recurs } from "../src/memory.ts"; +import { D1Store } from "../src/store.ts"; +import { memoryD1 } from "./d1.ts"; + +const OWNER: Caller = { user: "owner", agent: "claude" }; +const NOW: Policy = { k: 2, minGapMs: 0, autoAccept: () => true }; + +async function setup() { + const db = memoryD1(); + await db.prepare("INSERT INTO projects(name, description, created_at) VALUES('kypp', '', '2026-11-06T00:00:00Z')").run(); + return db; +} + +function agent(db: D1Database, session: string, caller: Caller = OWNER) { + return async (name: string, args: Record = {}) => { + const req = new Request("https://k/mcp", { method: "POST", headers: { "X-Kypp-Project": "kypp", "Mcp-Session-Id": session }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) }); + const { result } = await (await handleMcp(req, db, caller, { s1: null })).json() as any; + return result.content[0].text as string; + }; +} + +const status = async (db: D1Database, id: string) => + ((await db.prepare("SELECT status FROM memory_claims WHERE id = ?").bind(id).first()) as any).status as string; + +const LESSON = { subject: "wrangler port", content: "wrangler dev listens on 8787" }; +const USED = { verdict: "used", note: "ran wrangler dev; it answered on 8787" }; + +test("a reader that re-claims what it was shown is told it's an echo; its used rating promotes the claim", async () => { + const db = await setup(), store = new D1Store(db); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + const r = agent(db, "r"); + await r("recall", { query: "wrangler port" }); + + const echo = await r("claim", LESSON); + assert.match(echo, /\necho: .*doesn't count toward accepting it.*`used`/); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "candidate", "an echo is not a second session"); + + await r("feedback", { ratings: [{ handle: id, ...USED }] }); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "accepted"); +}); + +test("a used rating counts only from another, writable session, and only while it is the newest verdict", async () => { + const db = await setup(), store = new D1Store(db); + const w = agent(db, "w"); + const id = (await w("claim", LESSON)).split("\n")[0]; + + await w("recall", { query: "wrangler port" }); + await w("feedback", { ratings: [{ handle: id, ...USED }] }); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "candidate", "the writer can't confirm its own claim"); + + const ro = agent(db, "ro", { ...OWNER, readOnly: true }); + await ro("recall", { query: "wrangler port" }); + await ro("feedback", { ratings: [{ handle: id, ...USED }] }); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "candidate", "a read-only token can't write memory, so its rating doesn't confirm"); + + const r = agent(db, "r"); + await r("recall", { query: "wrangler port" }); + await r("feedback", { ratings: [{ handle: id, ...USED }] }); + await r("feedback", { ratings: [{ handle: id, verdict: "not_used" }] }); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "candidate", "a later not_used withdraws the used, even within the same millisecond"); + + await r("feedback", { ratings: [{ handle: id, ...USED }] }); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "accepted"); +}); + +test("within one call, the last rating of a claim is the verdict", async () => { + const db = await setup(), store = new D1Store(db); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + const r = agent(db, "r"); + await r("recall", { query: "wrangler port" }); + await r("feedback", { ratings: [{ handle: id, ...USED }, { handle: id, verdict: "not_used" }] }); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "candidate"); + await r("feedback", { ratings: [{ handle: id, verdict: "not_used" }, { handle: id, ...USED }] }); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "accepted"); +}); + +test("a rating stored without the writable mark never confirms", async () => { + const db = await setup(), store = new D1Store(db); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + await agent(db, "r")("recall", { query: "wrangler port" }); + await db.prepare("INSERT INTO claim_usages(id,consumer,claim_id,project,scope,surface,score,metadata,created_at)" + + " VALUES('legacy','r',?,'kypp','project','feedback',1,?,?)").bind(id, JSON.stringify(USED), new Date().toISOString()).run(); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "candidate"); +}); + +test("a used rating withdrawn after planning stops the promotion it supported", async () => { + const db = await setup(), store = new D1Store(db); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + const r = agent(db, "r"); + await r("recall", { query: "wrangler port" }); + await r("feedback", { ratings: [{ handle: id, ...USED }] }); + const plans = await plan(store, NOW, null); + assert.deepEqual(plans.flatMap((p) => p.promote), [id]); + await r("feedback", { ratings: [{ handle: id, verdict: "wrong", note: "it listens on 8788 now" }] }); + assert.deepEqual(await store.apply(plans), { applied: 0, stale: 1 }); + assert.equal(await status(db, id), "candidate"); +}); + +test("a confirmation is timed by its rating, so the recurrence gap still applies", () => { + const claim = { id: "a", session: "w", source_ids: ["session:w"], created_at: "2026-11-06T10:00:00Z" } as Claim; + const hour = 3600_000; + assert.equal(recurs([{ ...claim, confirmations: [{ session: "r", at: "2026-11-06T10:30:00Z" }] }], 2, hour), false); + assert.equal(recurs([{ ...claim, confirmations: [{ session: "r", at: "2026-11-06T11:00:00Z" }] }], 2, hour), true); + assert.equal(recurs([{ ...claim, confirmations: [{ session: "w", at: "2026-11-07T10:00:00Z" }] }], 2, hour), false); +}); + +test("a session's newest rating decides even when it switched to a read-only token", async () => { + const db = await setup(), store = new D1Store(db); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + const r = agent(db, "r"), rRo = agent(db, "r", { ...OWNER, readOnly: true }); + await r("recall", { query: "wrangler port" }); + await r("feedback", { ratings: [{ handle: id, ...USED }] }); + const plans = await plan(store, NOW, null); + await rRo("feedback", { ratings: [{ handle: id, verdict: "wrong", note: "it listens on 8788 now" }] }); + assert.deepEqual(await store.apply(plans), { applied: 0, stale: 1 }, "the fence sees the read-only withdrawal"); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "candidate", "and so does the next pass"); +}); + +test("an echo never retires the stamped claim it echoes, so rating that claim later still confirms", async () => { + const db = await setup(), store = new D1Store(db); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + const r = agent(db, "r"); + await r("recall", { query: "wrangler port" }); + const echo = (await r("claim", { ...LESSON, content: "wrangler dev listens on 8787 unless --port is set", confidence: 0.9 })).split("\n")[0]; + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "candidate", "the higher-confidence echo didn't supersede it"); + assert.equal(await status(db, echo), "candidate"); + + await r("feedback", { ratings: [{ handle: id, ...USED }] }); + await consolidate(store, NOW, null); + assert.equal(await status(db, echo), "accepted", "the newest, strongest wording wins once the subject is confirmed"); + assert.equal(await status(db, id), "superseded"); +}); + +test("a rating confirms only for a caller that could write at the claim's level, whatever the session saw", async () => { + const db = await setup(), store = new D1Store(db); + await db.prepare("INSERT INTO projects(name, description, created_at) VALUES('other', '', '2026-11-06T00:00:00Z')").run(); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + // One session id carried across two credentials: a read-only one that can see kypp, and a writer pinned to other. + await agent(db, "s", { ...OWNER, readOnly: true })("recall", { query: "wrangler port" }); + const out = await agent(db, "s", { user: "bot", agent: "bot", projects: ["other"] })("feedback", { ratings: [{ handle: id, ...USED }] }); + assert.equal(out, "recorded 1 rating"); + const row = await db.prepare("SELECT metadata FROM claim_usages WHERE surface = 'feedback'").first() as any; + assert.equal(JSON.parse(row.metadata).writable, undefined); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "candidate"); + + await agent(db, "s", { user: "bot", agent: "bot", projects: ["kypp"] })("feedback", { ratings: [{ handle: id, ...USED }] }); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "accepted", "a writer pinned to kypp may confirm it"); +}); diff --git a/worker/test/feedback.test.ts b/worker/test/feedback.test.ts index ad0c58c..baecdc3 100644 --- a/worker/test/feedback.test.ts +++ b/worker/test/feedback.test.ts @@ -44,8 +44,8 @@ test("a session rates what it was shown; each verdict is a feedback row with its assert.equal(out.text, "recorded 2 ratings"); const rows = await feedbackRows(db); assert.deepEqual(rows.map((r) => [r.consumer, r.claim_id, r.project, r.score]), [["r", a, "kypp", 1], ["r", b, "kypp", 0]]); - assert.deepEqual(JSON.parse(rows[0].metadata), { verdict: "used", note: "ran wrangler dev; it answered on 8787" }); - assert.deepEqual(JSON.parse(rows[1].metadata), { verdict: "not_used" }); + assert.deepEqual(JSON.parse(rows[0].metadata), { verdict: "used", note: "ran wrangler dev; it answered on 8787", writable: true }); + assert.deepEqual(JSON.parse(rows[1].metadata), { verdict: "not_used", writable: true }); const claims = (await db.prepare("SELECT status FROM memory_claims").all()).results as any[]; assert.ok(claims.every((c) => c.status === "candidate"), "feedback changes no claim"); @@ -114,7 +114,7 @@ test("feedback after a purge keeps the verdict but drops the note", async () => await new D1Store(db).operatorPurge(id, "leaked key"); assert.equal((await r("feedback", { ratings: [{ handle: id, verdict: "wrong", note: "sk-123 leaked" }] })).text, "recorded 1 rating"); const [row] = await feedbackRows(db); - assert.deepEqual(JSON.parse(row.metadata), { verdict: "wrong" }); + assert.deepEqual(JSON.parse(row.metadata), { verdict: "wrong", writable: true }); }); test("purge strips feedback notes on the claim but keeps the verdicts", async () => { @@ -126,7 +126,7 @@ test("purge strips feedback notes on the claim but keeps the verdicts", async () await new D1Store(db).operatorPurge(id, "leaked key"); const [row] = await feedbackRows(db); assert.equal(row.score, -1); - assert.deepEqual(JSON.parse(row.metadata), { verdict: "wrong" }); + assert.deepEqual(JSON.parse(row.metadata), { verdict: "wrong", writable: true }); }); test("instructions name feedback for every caller that has it", async () => { diff --git a/worker/test/rollup.test.ts b/worker/test/rollup.test.ts index 8e49b8a..d34eb6e 100644 --- a/worker/test/rollup.test.ts +++ b/worker/test/rollup.test.ts @@ -146,7 +146,9 @@ test("repeating a candidate you were shown doesn't count toward accepting it", a await client(db, "kypp", "a")("claim", { subject: "heron", content: "heron cache goes stale on rename" }); const b = client(db, "kypp", "b"); await b("recall", { query: "heron" }); // b is shown a's candidate - const echo = await b("claim", { subject: "heron", content: "heron cache goes stale on rename" }); + const reply = await b("claim", { subject: "heron", content: "heron cache goes stale on rename" }); + assert.match(reply, /\necho: /, "the reply says the claim earned nothing"); + const echo = reply.split("\n")[0]; const row = await db.prepare("SELECT source_ids, metadata FROM memory_claims WHERE id = ?").bind(echo).first() as any; assert.equal(row.source_ids, "[]"); assert.equal(JSON.parse(row.metadata).echo_of.length, 1); From d7c45b02611b825a84c5a3b08dfc3ca13bb2fe74 Mon Sep 17 00:00:00 2001 From: vu1n <2105991+vu1n@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:58:35 +0000 Subject: [PATCH 2/5] worker: test that the S1 hold still applies to a feedback-backed promotion --- worker/test/confirm.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/worker/test/confirm.test.ts b/worker/test/confirm.test.ts index 69b7809..6acbea5 100644 --- a/worker/test/confirm.test.ts +++ b/worker/test/confirm.test.ts @@ -166,3 +166,17 @@ test("a rating confirms only for a caller that could write at the claim's level, await consolidate(store, NOW, null); assert.equal(await status(db, id), "accepted", "a writer pinned to kypp may confirm it"); }); + +test("a feedback-backed promotion still waits when the S1 judge finds the claims conflicted", async () => { + const s1 = { systemOne: async ({ state }: any) => + ({ answers: { agree: { type: "noul", noul: state.claims.some((c: any) => c.content.includes("8788")) ? 0.1 : 0.9 } } }) } as any; + const db = await setup(), store = new D1Store(db); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + const r = agent(db, "r"); + await r("recall", { query: "wrangler port" }); + const echo = (await r("claim", { ...LESSON, content: "wrangler dev listens on 8788", confidence: 0.9 })).split("\n")[0]; + await r("feedback", { ratings: [{ handle: id, ...USED }] }); + await consolidate(store, NOW, s1); + assert.deepEqual([await status(db, id), await status(db, echo)], ["candidate", "candidate"], + "held: nothing promotes, and the echo doesn't retire the rated claim"); +}); From a4b5857ba0d0299d161c5ce657968089a1acbd76 Mon Sep 17 00:00:00 2001 From: vu1n <2105991+vu1n@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:01:57 +0000 Subject: [PATCH 3/5] worker: a room's rating confirms claims in its linked repos --- docs/features/hosted-worker.md | 2 +- worker/src/mcp.ts | 9 +++++---- worker/test/confirm.test.ts | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/docs/features/hosted-worker.md b/docs/features/hosted-worker.md index f13b7d3..b448382 100644 --- a/docs/features/hosted-worker.md +++ b/docs/features/hosted-worker.md @@ -188,7 +188,7 @@ TypeSafe API's shape, for GitHub Actions OIDC tokens (`worker/src/oidc.ts`) and the recurrence gap still applies. The claim's own writer never confirms it. A session's verdict is its newest rating, and it confirms only if that rating is `used` and marked `writable`. `feedback` marks a rating writable only when the current caller could write at the claim's level (`mayWrite` - in `mcp.ts`: not read-only, inside a pin, the caller's own user or room lane), because a session id + in `mcp.ts`: not read-only, inside a pin, the caller's own user or room lane, or a repo the room is linked to), because a session id is not bound to a credential and read visibility alone would let a reader confirm another lane's claim. Rows from before the mark never confirm, and a later unmarked `wrong` still withdraws. An unstamped survivor (an echo) never supersedes a stamped candidate until the group promotes, so the claim the echo reply tells the agent to rate stays live. The plan diff --git a/worker/src/mcp.ts b/worker/src/mcp.ts index 51bba25..10488cf 100644 --- a/worker/src/mcp.ts +++ b/worker/src/mcp.ts @@ -323,9 +323,10 @@ const MAX_RATINGS = 50, MAX_NOTE = 300; // Whether this caller could have written a claim at `c`'s level: only such a caller's `used` can confirm it. // Read visibility is not enough, because one session id can be carried across credentials. -function mayWrite(caller: Caller, c: { scope: string; project: string | null; user: string | null }): boolean { +// A room writes its own lane, and project claims only in the repos it is linked to (share_to). +function mayWrite(caller: Caller, c: { scope: string; project: string | null; user: string | null }, roomLinks: string[]): boolean { if (caller.readOnly) return false; - if (caller.room) return c.scope === "room" && c.user === caller.user; + if (caller.room) return c.scope === "room" ? c.user === caller.user : c.scope === "project" && c.project !== null && roomLinks.includes(c.project); if (c.scope === "user") return c.user !== null && c.user === caller.user; if (c.scope !== "project") return false; return !caller.projects || (c.project !== null && caller.projects.includes(c.project)); @@ -350,8 +351,8 @@ async function feedback(store: D1Store, a: Args, session: string | null, caller: // Two ratings of one claim in a call (a prefix and the full id, say): the last one listed wins. const shown = [...new Map(checked.filter((c) => typeof c !== "string").map((c) => [c.id, c])).values()]; const skipped = checked.filter((c) => typeof c === "string"); - const lanes = await store.lanes(shown.map((r) => r.id)); - const rated = shown.map((r) => ({ ...r, writable: !!lanes.get(r.id) && mayWrite(caller, lanes.get(r.id)!) })); + const [lanes, links] = await Promise.all([store.lanes(shown.map((r) => r.id)), caller.room ? store.roomLinks(caller.room) : []]); + const rated = shown.map((r) => ({ ...r, writable: !!lanes.get(r.id) && mayWrite(caller, lanes.get(r.id)!, links) })); await store.recordFeedback(session, rated); return `recorded ${rated.length} rating${rated.length === 1 ? "" : "s"}` + (skipped.length ? `\nskipped:\n${skipped.join("\n")}` : ""); } diff --git a/worker/test/confirm.test.ts b/worker/test/confirm.test.ts index 6acbea5..856f05f 100644 --- a/worker/test/confirm.test.ts +++ b/worker/test/confirm.test.ts @@ -180,3 +180,20 @@ test("a feedback-backed promotion still waits when the S1 judge finds the claims assert.deepEqual([await status(db, id), await status(db, echo)], ["candidate", "candidate"], "held: nothing promotes, and the echo doesn't retire the rated claim"); }); + +test("a room confirms claims in the repos it is linked to, and not in others", async () => { + const db = await setup(), store = new D1Store(db); + await db.prepare("INSERT INTO projects(name, description, created_at) VALUES('other', '', '2026-11-06T00:00:00Z')").run(); + await db.prepare("INSERT INTO room_links(room, project, created_at) VALUES('huddles:r', 'kypp', '2026-11-06T00:00:00Z')").run(); + const room: Caller = { user: "room:huddles:r", agent: "room:huddles:r", room: "huddles:r" }; + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + const otherId = (await agent(db, "w2")("claim", { ...LESSON, project: "other" })).split("\n")[0]; + // The room session is shown both (the second through a read-only token carrying the same session id). + const bot = agent(db, "rs", room); + await bot("recall", { query: "wrangler port", include_candidates: true }); + await agent(db, "rs", { ...OWNER, readOnly: true })("recall", { query: "wrangler port", project: "other", include_candidates: true }); + assert.equal(await bot("feedback", { ratings: [{ handle: id, ...USED }, { handle: otherId, ...USED }] }), "recorded 2 ratings"); + await consolidate(store, NOW, null); + assert.equal(await status(db, id), "accepted", "kypp is linked to the room"); + assert.equal(await status(db, otherId), "candidate", "other isn't"); +}); From 443cd2f1ae9c0d8841a2b3d6fedd0b390a17f0b7 Mon Sep 17 00:00:00 2001 From: vu1n <2105991+vu1n@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:04:52 +0000 Subject: [PATCH 4/5] worker: recheck a room's link in the feedback insert --- worker/src/mcp.ts | 2 +- worker/src/store.ts | 15 ++++++++++----- worker/test/confirm.test.ts | 11 +++++++++++ 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/worker/src/mcp.ts b/worker/src/mcp.ts index 10488cf..9c8bfa9 100644 --- a/worker/src/mcp.ts +++ b/worker/src/mcp.ts @@ -353,7 +353,7 @@ async function feedback(store: D1Store, a: Args, session: string | null, caller: const skipped = checked.filter((c) => typeof c === "string"); const [lanes, links] = await Promise.all([store.lanes(shown.map((r) => r.id)), caller.room ? store.roomLinks(caller.room) : []]); const rated = shown.map((r) => ({ ...r, writable: !!lanes.get(r.id) && mayWrite(caller, lanes.get(r.id)!, links) })); - await store.recordFeedback(session, rated); + await store.recordFeedback(session, rated, caller.room ?? null); return `recorded ${rated.length} rating${rated.length === 1 ? "" : "s"}` + (skipped.length ? `\nskipped:\n${skipped.join("\n")}` : ""); } diff --git a/worker/src/store.ts b/worker/src/store.ts index 7fe0636..fb51f45 100644 --- a/worker/src/store.ts +++ b/worker/src/store.ts @@ -500,16 +500,21 @@ export class D1Store { // Only a rating from a caller that may write at the claim's level is marked `writable`, and only a marked // rating confirms a claim; a rating stored before the mark can't show who made it. async recordFeedback(consumer: string, - rated: { id: string; project: string | null; scope: string; score: number; verdict: string; note: string | null; writable: boolean }[]): Promise { + rated: { id: string; project: string | null; scope: string; score: number; verdict: string; note: string | null; writable: boolean }[], + room: string | null = null): Promise { if (!rated.length) return; const ts = now(); // A purged claim's tombstone is checked in the insert itself, so a note can't bring erased text back. + // A room's link to the claim's repo is rechecked in the insert too, so an unlink can't race a writable mark. await this.db.batch(rated.map((r) => this.db.prepare( "INSERT INTO claim_usages(id,consumer,claim_id,project,scope,surface,score,metadata,created_at)" - + " SELECT ?,?,?,?,?,'feedback',?,CASE WHEN json_extract(metadata, '$.purged_at') IS NULL THEN ? ELSE ? END,? FROM memory_claims WHERE id = ?", - ).bind(uid(), consumer, r.id, r.project, r.scope, r.score, - JSON.stringify({ verdict: r.verdict, ...(r.note ? { note: r.note } : {}), ...(r.writable ? { writable: true } : {}) }), - JSON.stringify({ verdict: r.verdict, ...(r.writable ? { writable: true } : {}) }), ts, r.id))); + + " SELECT ?,?,?,?,?,'feedback',?,CASE WHEN ? = 1 AND (? IS NULL OR c.scope = 'room'" + + " OR EXISTS (SELECT 1 FROM room_links l WHERE l.room = ? AND l.project = c.project))" + + " THEN json_set(c.m, '$.writable', json('true')) ELSE c.m END, ?" + + " FROM (SELECT scope, project, CASE WHEN json_extract(metadata, '$.purged_at') IS NULL THEN ? ELSE ? END AS m" + + " FROM memory_claims WHERE id = ?) c", + ).bind(uid(), consumer, r.id, r.project, r.scope, r.score, r.writable ? 1 : 0, room, room, ts, + JSON.stringify({ verdict: r.verdict, ...(r.note ? { note: r.note } : {}) }), JSON.stringify({ verdict: r.verdict }), r.id))); } // Per claim, the sessions whose newest rating of it is a writable `used`, with when they rated it. diff --git a/worker/test/confirm.test.ts b/worker/test/confirm.test.ts index 856f05f..1c358b4 100644 --- a/worker/test/confirm.test.ts +++ b/worker/test/confirm.test.ts @@ -197,3 +197,14 @@ test("a room confirms claims in the repos it is linked to, and not in others", a assert.equal(await status(db, id), "accepted", "kypp is linked to the room"); assert.equal(await status(db, otherId), "candidate", "other isn't"); }); + +test("a room unlinked between the check and the insert gets no writable mark", async () => { + const db = await setup(), store = new D1Store(db); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + const row = { id, project: "kypp", scope: "project", score: 1, verdict: "used", note: "checked", writable: true }; + await store.recordFeedback("rs", [row], "huddles:r"); // no link: the insert's own check refuses the mark + await db.prepare("INSERT INTO room_links(room, project, created_at) VALUES('huddles:r', 'kypp', '2026-11-06T00:00:00Z')").run(); + await store.recordFeedback("rs2", [row], "huddles:r"); + const marks = (await db.prepare("SELECT consumer, metadata FROM claim_usages WHERE surface = 'feedback' ORDER BY rowid").all()).results as any[]; + assert.deepEqual(marks.map((m) => [m.consumer, JSON.parse(m.metadata).writable ?? false]), [["rs", false], ["rs2", true]]); +}); From c66ba463b6afe1014490814cc39d36d2c10d8760 Mon Sep 17 00:00:00 2001 From: vu1n <2105991+vu1n@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:10:19 +0000 Subject: [PATCH 5/5] worker: fence the counted rating's time too --- docs/features/hosted-worker.md | 2 +- worker/src/memory.ts | 4 ++-- worker/src/store.ts | 5 +++-- worker/test/confirm.test.ts | 13 +++++++++++++ 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/docs/features/hosted-worker.md b/docs/features/hosted-worker.md index b448382..f93d1cf 100644 --- a/docs/features/hosted-worker.md +++ b/docs/features/hosted-worker.md @@ -193,7 +193,7 @@ TypeSafe API's shape, for GitHub Actions OIDC tokens (`worker/src/oidc.ts`) and claim. Rows from before the mark never confirm, and a later unmarked `wrong` still withdraws. An unstamped survivor (an echo) never supersedes a stamped candidate until the group promotes, so the claim the echo reply tells the agent to rate stays live. The plan carries the ratings it counted (`GroupPlan.confirmed`) and `apply` refuses it if any is no longer - that session's newest verdict (`created_at`, then `rowid`), because a rating never touches the + that session's newest verdict at the same time (`created_at`, then `rowid`), because a rating never touches the claim rows the version guard reads. This is the only way a session that was shown a candidate can help accept it: its re-claim is an echo, and the claim reply says so. The Python arbiter doesn't count ratings, so local and hosted promote differently here. diff --git a/worker/src/memory.ts b/worker/src/memory.ts index b1e078e..f96d88f 100644 --- a/worker/src/memory.ts +++ b/worker/src/memory.ts @@ -126,10 +126,10 @@ export interface GroupKey { subject: string; scope: Scope; project: string | nul // `support` is the claims whose recurrence justifies the promotion, for an agreement check. // `confirmed` is the (claim, session) `used` ratings the promotion counted; apply() refuses the plan if one was withdrawn since. export interface GroupPlan { key: GroupKey; version: string; supersede: string[]; promote: string[]; support: string[]; confirmed?: Rated[] } -export interface Rated { claim: string; session: string } +export interface Rated { claim: string; session: string; at: string } const countedConfirmations = (members: Claim[]): Rated[] => - members.flatMap((m) => (m.confirmations ?? []).filter((c) => c.session !== m.session).map((c) => ({ claim: m.id, session: c.session }))); + members.flatMap((m) => (m.confirmations ?? []).filter((c) => c.session !== m.session).map((c) => ({ claim: m.id, session: c.session, at: c.at }))); export function groupVersion(members: Claim[]): string { return `${members.length}:${members.reduce((m, c) => (c.updated_at > m ? c.updated_at : m), "")}`; diff --git a/worker/src/store.ts b/worker/src/store.ts index fb51f45..1eac5c1 100644 --- a/worker/src/store.ts +++ b/worker/src/store.ts @@ -762,9 +762,10 @@ export class D1Store { + " AND c.status IN ('candidate','accepted') AND c.subject = ? AND c.scope = ? AND c.project IS ?" + " AND (c.scope NOT IN ('user','room') OR c.user IS ?)))", ).bind(JSON.stringify([...p.supersede, ...p.promote]), subject, scope, project, user), - // A `used` rating the promotion counted must still be that session's verdict: a later rating doesn't touch the claim rows. + // A `used` rating the promotion counted must still be that session's verdict, at the time the plan counted + // (recurrence is timed by it): a later rating doesn't touch the claim rows the version guard reads. ...(p.confirmed?.length ? [this.db.prepare( - `INSERT INTO consolidation_guard(ok) SELECT 0 WHERE EXISTS (SELECT 1 FROM json_each(?) t WHERE IFNULL((SELECT ${CONFIRMING} FROM claim_usages u` + `INSERT INTO consolidation_guard(ok) SELECT 0 WHERE EXISTS (SELECT 1 FROM json_each(?) t WHERE IFNULL((SELECT CASE WHEN u.created_at = json_extract(t.value, '$.at') THEN ${CONFIRMING} END FROM claim_usages u` + ` WHERE u.surface = 'feedback' AND u.claim_id = json_extract(t.value, '$.claim') AND u.consumer = json_extract(t.value, '$.session')` + " ORDER BY u.created_at DESC, u.rowid DESC LIMIT 1), 0) != 1)", ).bind(JSON.stringify(p.confirmed))] : []), diff --git a/worker/test/confirm.test.ts b/worker/test/confirm.test.ts index 1c358b4..6bd2cd1 100644 --- a/worker/test/confirm.test.ts +++ b/worker/test/confirm.test.ts @@ -208,3 +208,16 @@ test("a room unlinked between the check and the insert gets no writable mark", a const marks = (await db.prepare("SELECT consumer, metadata FROM claim_usages WHERE surface = 'feedback' ORDER BY rowid").all()).results as any[]; assert.deepEqual(marks.map((m) => [m.consumer, JSON.parse(m.metadata).writable ?? false]), [["rs", false], ["rs2", true]]); }); + +test("re-rating a counted used before apply moves its time, so the stale plan is refused", async () => { + const db = await setup(), store = new D1Store(db); + const id = (await agent(db, "w")("claim", LESSON)).split("\n")[0]; + const r = agent(db, "r"); + await r("recall", { query: "wrangler port" }); + await r("feedback", { ratings: [{ handle: id, ...USED }] }); + await db.prepare("UPDATE claim_usages SET created_at = '2026-01-01T00:00:00.000Z' WHERE surface = 'feedback'").run(); + const plans = await plan(store, NOW, null); + assert.deepEqual(plans.flatMap((p) => p.promote), [id]); + await r("feedback", { ratings: [{ handle: id, ...USED }] }); // still used, but newer + assert.deepEqual(await store.apply(plans), { applied: 0, stale: 1 }); +});