diff --git a/docs/concepts/identities-and-namespaces.md b/docs/concepts/identities-and-namespaces.md index 102865bd1b..359543047d 100644 --- a/docs/concepts/identities-and-namespaces.md +++ b/docs/concepts/identities-and-namespaces.md @@ -392,7 +392,9 @@ A `definition` is promoted only: without it (422 `VALIDATION_FAILED`), and with 409 `PRECONDITION_FAILED` when the text no longer has it. - With a value that is a JSON object holding a non-empty string `term` and, optionally, - a list of string `aliases`; else 422 `VALIDATION_FAILED`. + a list of string `aliases`; else 422 `VALIDATION_FAILED`. Its `applies_to` (the team + or product it is for) is part of the approved text and no condition: declaring or + changing it is an edit, which needs a new promotion. - Not labelled `medium` and not reading as `medium` or `high` (422 `SENSITIVE_DEFINITION_REFUSED`; a `high` label answers `HIGH_SENSITIVITY_PROMOTION_REFUSED` first, as for any row). @@ -400,7 +402,9 @@ A `definition` is promoted only: while the namespace is past it, is refused (409 `DEFINITION_CEILING`). - Under a name no other live shared definition holds as its term or an alias (409 `DEFINITION_NAME_TAKEN`, naming the keys and the names), names compared folded: format - characters dropped, NFKC, whitespace collapsed, case-folded, then NFKC again. + characters dropped, NFKC, whitespace collapsed, case-folded, then NFKC again. A + declared `applies_to` changes none of this: one definition of a name is shared, and a + second for another team or product stays an unshared row. One namespace's definition promotions, with their ceiling and name checks, and its definition demotes run one at a time, the last to run deciding whether the definition is @@ -447,15 +451,45 @@ names are its term and aliases, folded as the name checks fold them. Its text is with case and spacing folded, or the served hash of its whole value when it has no `body` string, so two definitions that say the same in another case or spacing do not differ. -Each dispute carries its `names` (names held by the same definitions are one dispute) and -its `claims` in key order: each definition's key, id, version, content hash, term, aliases -and `body`. None is preferred: the read marks no row, writes nothing and changes no search -result, so a caller shows both or asks which applies. The claim an admin approved is the -one whose key a `governed: true` search hit carries. `term` narrows the answer to the -dispute that holds one name. - -A name leaves the answer when its definitions say the same. A writer ends a dispute with -one of two calls: +Each dispute carries its `names` (names held by the same definitions are one dispute), its +`state` and its `claims` in key order: each definition's key, id, version, content hash, +term, aliases, `body` and `applies_to`. None is preferred: the read marks no row, writes +nothing and changes no search result, so a caller shows both or asks which applies. The +claim an admin approved is the one whose key a `governed: true` search hit carries. `term` +narrows the answer to the dispute that holds one name. + +A definition says which team or product it is for in its value's `applies_to`: an object +of `team`, `product` or both, each a string of at most 64 characters. A claim's +`applies_to` carries the declared keys with their values as written, trimmed. It is empty +when the definition declares none, and when its `applies_to` is anything else: with +another key, a value that is no string or a longer value, the whole object declares +nothing, so a misspelled key separates no definitions. A blank value declares nothing for +its key only, and the other key still counts. Two claims are separated when both declare +`team`, or both declare `product`, with values that differ once folded as names are (case +and spacing make no difference). A scope on one side only, and `team` on one side with +`product` on the other, separate nothing. + +A dispute's `state` is `alternatives` when every two of its claims whose texts differ are +separated: the definitions are for different teams or products, and a caller asks which +applies. Otherwise it is `suspected`: the definitions may contradict each other. Each +pair check counts as 16 characters against the 256 KiB a call reads, and a dispute whose +pairs that bound does not pay for stays `suspected`. + +A name leaves the answer when its definitions say the same, and reads as `alternatives` +when they are meant to differ. A writer settles a dispute with one of three calls: + +- **A declared scope** on each definition that is meant to differ: `memory.set` on its key + with `applies_to` added to its value and the claim's `content_sha256` as + `if_match_sha256`, so a definition edited since the read is refused (409 + `PRECONDITION_FAILED`). `memory.set` writes a whole new version, so read the definition + and send the fields it should keep back with the value: its type, tags, entities, + confidence, sensitivity label, validity, source trace, source resource and character + limit, and its `source_class` when that is `derived`, `external` or `imported`. Leave + out any other `source_class`, which the server decides, and a `source_trace` that starts + with `copy_rule:`: `memory.set` refuses both from a caller (422). This is an edit: a + governed definition lapses (`changed`) until an admin promotes the edited text with its + hash. The name keeps one shared definition, and promoting a second is refused (409 + `DEFINITION_NAME_TAKEN`). - **An edit** of one definition to say what the other says: `memory.set` on its key, or `memory.update_by_id`. An edited definition that was governed lapses (`changed`) until @@ -477,7 +511,8 @@ is then read by its key with `memory.get`. A `term` longer than 16,384 character most a compared definition's names hold, is refused (422 `VALIDATION_FAILED`). A token narrowed to a user or a session is refused, since these definitions belong to the whole namespace. The dashboard's Review queue shows the answer above the shared definitions on -its **Definitions** tab. +its **Definitions** tab: the names that need review first, each definition with what it +applies to, and a dialog in which a writer declares the team and the product. ### Governed definitions in search diff --git a/docs/development/curation-loop-design.md b/docs/development/curation-loop-design.md index 0e6da96378..50693e9437 100644 --- a/docs/development/curation-loop-design.md +++ b/docs/development/curation-loop-design.md @@ -46,12 +46,17 @@ search](../concepts/identities-and-namespaces.md#governed-definitions-in-search) A definition's value is a JSON object, which `memory.set` stores whole in `value` and in `value_json` (the embedding reads its excerpt, as for any row): -| Field | Meaning | -| ---------- | --------------------------------------------------------------------------- | -| `term` | The name as people write it. | -| `aliases` | Other names for the same thing (an abbreviation, an older name). | -| `body` | The definition's text. | -| `rests_on` | What it is based on: for query history, the SQL and its tables and columns. | +| Field | Meaning | +| ------------ | ------------------------------------------------------------------------------------------------------------ | +| `term` | The name as people write it. | +| `aliases` | Other names for the same thing (an abbreviation, an older name). | +| `body` | The definition's text. | +| `rests_on` | What it is based on: for query history, the SQL and its tables and columns. | +| `applies_to` | The team or product it is for: an object of `team`, `product` or both, each a name of at most 64 characters. | + +Two definitions of one name that both declare a `team`, or both a `product`, with +different values are alternatives, not a contradiction ([definitions that +differ](../concepts/identities-and-namespaces.md#definitions-that-differ)). The tables and columns of a query-history `rests_on` are the ones the source's query log recorded for the SQL, marked `lists_from: "query_log"` and flagged when a list is diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index 3da6baabc7..12c4dad487 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -873,18 +873,18 @@ Admins of the current namespace get a drawer with the Review and Observe groups; platform admins also get Access, and platform admins Deployment. A viewer never sees an entry that would answer 403. -| Group | Page | URL | What it is for | -| ------- | --------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Review | **Review queue** | `/admin/review_queue` | Conflicts (pairs of memories that disagree, each with a suggested decision on request, except a sensitive one), learnings proposed for promotion, memories Loom retired on its own (Auto-resolved, each with an Undo), exceptions (the allowlist of pairs that may coexist), proposals (facts on trial, each opened from its key and accepted or rejected; `/admin/review_queue?tab=proposals&key=` opens one), the skill drafts that wait for review (Skills, for an admin: each opens the skill's page on its changes, where it is published or sent back), duplicate memories and documents with the namespace-wide repairs, the namespace's definitions (Definitions: for every role, the names whose definitions differ, each with its definitions side by side; for an admin, the shared definitions: whether each is governed, why a lapsed one lapsed and what brings it back, and the names another definition serves), who answers for each shared memory and document (Stewardship: for every role, each item's steward, the state of its review, its last and next review and what keeps the steward from acting, with the namespace's counts and filters for the caller's own items, for items with a problem and by state; a writer who is signed in as a person records a review from the row, in a dialog that shows the whole content and records only the hash of the text shown, for a document says what the review covers and what the extraction did not read, and for a correction request asks what is wrong and files it as a report on the content read before it records the review; an admin names the first steward and the review interval from a memory's More menu or a document's row menu in the Library, changes or removes a steward and ends stewardship from the row, and names the fallback steward), and what the namespace needs from a person (Curator: the proposal queue in counts, the facts to look at again, the startup budget, and the facts to pin or unpin). In the drawer for every admin of a memory namespace, even when empty; it counts open conflicts, pending proposals and the skill drafts that wait. See [conflicts and refusal](memory/conflicts-and-refusal.md). | -| Review | **Guardrails** | `/admin/guardrails` | Blacklist patterns: content Loom should never store, each added as text to find or as a regular expression, with a sweep that deletes the stored memories it already matches; for an org admin, the org's and the namespace's extraction rules and the org's model-call switch. | -| Review | **Policies** | `/admin/policies` | History policy rules, a dry run of a hypothetical call, and the decision ledger. | -| Review | **Regression suites** | `/admin/suites` | On a memory namespace: its [regression suites](regression-suites.md), each with what it covers, its cases by kind and its revision. New suite creates one; a suite's page edits its keys, prefixes and cases and publishes the changes as one revision; Retire leaves a suite covering no key. See [Regression suites](#regression-suites). | -| Observe | **Health** | `/admin/health` | Worker status and how agents in the namespace spend their calls; the namespace's memory report over a window of 7, 30, 90 or 365 days (it counts the memories older than the window that were not recalled in it), search gates and recent extractions; an admin's repairs (apply expiry, re-embed, remove an extractor's facts, roll back, snapshot and restore); an org admin's projection failures, retried or dismissed. | -| Observe | **Audit log** | `/admin/activity` | The audit feed, one readable line per event; the Erasures tab lists erasures with each one's details and, by role, erases or exports one namespace or one user; the Exposure tab shows which readers read the namespace's memories and one user's owner report. | -| Observe | **Flow** | `/flow` | Read-only: where memories flow — writes and recalls, cross-namespace reach, producer and consumer agents, memberships; collections and repositories are listed apart from the namespaces. | -| Observe | **Usage** | `/admin/usage` | LLM and embedding cost by day, operation, agent or user, the namespace's daily cap, and on **Coding agents** the coding agents' own model spend. | -| Observe | **Agents** | `/admin/agents` | Which clients connected in a window (`agents.connected`); confirms a new MCP connection works. A namespace admin can forget every memory one agent holds there. | -| Access | **Users** | `/admin/users` | Org and platform admins only: every subject, their grants (namespaces, collections and repositories) and roles, last activity, and releasing a namespace whose owner lost their password. | +| Group | Page | URL | What it is for | +| ------- | --------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Review | **Review queue** | `/admin/review_queue` | Conflicts (pairs of memories that disagree, each with a suggested decision on request, except a sensitive one), learnings proposed for promotion, memories Loom retired on its own (Auto-resolved, each with an Undo), exceptions (the allowlist of pairs that may coexist), proposals (facts on trial, each opened from its key and accepted or rejected; `/admin/review_queue?tab=proposals&key=` opens one), the skill drafts that wait for review (Skills, for an admin: each opens the skill's page on its changes, where it is published or sent back), duplicate memories and documents with the namespace-wide repairs, the namespace's definitions (Definitions: for every role, the names whose definitions differ, those that need review before those marked as alternatives, each with its definitions side by side and the team or product each applies to, which a writer declares in a dialog; for an admin, the shared definitions: whether each is governed, why a lapsed one lapsed and what brings it back, and the names another definition serves), who answers for each shared memory and document (Stewardship: for every role, each item's steward, the state of its review, its last and next review and what keeps the steward from acting, with the namespace's counts and filters for the caller's own items, for items with a problem and by state; a writer who is signed in as a person records a review from the row, in a dialog that shows the whole content and records only the hash of the text shown, for a document says what the review covers and what the extraction did not read, and for a correction request asks what is wrong and files it as a report on the content read before it records the review; an admin names the first steward and the review interval from a memory's More menu or a document's row menu in the Library, changes or removes a steward and ends stewardship from the row, and names the fallback steward), and what the namespace needs from a person (Curator: the proposal queue in counts, the facts to look at again, the startup budget, and the facts to pin or unpin). In the drawer for every admin of a memory namespace, even when empty; it counts open conflicts, pending proposals and the skill drafts that wait. See [conflicts and refusal](memory/conflicts-and-refusal.md). | +| Review | **Guardrails** | `/admin/guardrails` | Blacklist patterns: content Loom should never store, each added as text to find or as a regular expression, with a sweep that deletes the stored memories it already matches; for an org admin, the org's and the namespace's extraction rules and the org's model-call switch. | +| Review | **Policies** | `/admin/policies` | History policy rules, a dry run of a hypothetical call, and the decision ledger. | +| Review | **Regression suites** | `/admin/suites` | On a memory namespace: its [regression suites](regression-suites.md), each with what it covers, its cases by kind and its revision. New suite creates one; a suite's page edits its keys, prefixes and cases and publishes the changes as one revision; Retire leaves a suite covering no key. See [Regression suites](#regression-suites). | +| Observe | **Health** | `/admin/health` | Worker status and how agents in the namespace spend their calls; the namespace's memory report over a window of 7, 30, 90 or 365 days (it counts the memories older than the window that were not recalled in it), search gates and recent extractions; an admin's repairs (apply expiry, re-embed, remove an extractor's facts, roll back, snapshot and restore); an org admin's projection failures, retried or dismissed. | +| Observe | **Audit log** | `/admin/activity` | The audit feed, one readable line per event; the Erasures tab lists erasures with each one's details and, by role, erases or exports one namespace or one user; the Exposure tab shows which readers read the namespace's memories and one user's owner report. | +| Observe | **Flow** | `/flow` | Read-only: where memories flow — writes and recalls, cross-namespace reach, producer and consumer agents, memberships; collections and repositories are listed apart from the namespaces. | +| Observe | **Usage** | `/admin/usage` | LLM and embedding cost by day, operation, agent or user, the namespace's daily cap, and on **Coding agents** the coding agents' own model spend. | +| Observe | **Agents** | `/admin/agents` | Which clients connected in a window (`agents.connected`); confirms a new MCP connection works. A namespace admin can forget every memory one agent holds there. | +| Access | **Users** | `/admin/users` | Org and platform admins only: every subject, their grants (namespaces, collections and repositories) and roles, last activity, and releasing a namespace whose owner lost their password. | The Admin button shows the Review queue's count while its drawer is closed. That count is the review items waiting: open conflicts plus pending proposals, both from the one diff --git a/docs/guides/without-the-dashboard.md b/docs/guides/without-the-dashboard.md index c6fb82d2c2..97f1058814 100644 --- a/docs/guides/without-the-dashboard.md +++ b/docs/guides/without-the-dashboard.md @@ -85,7 +85,7 @@ are on `agent.account` and `agent.deployment`. | Ask AI: the Worklist card | `namespace.worklist namespace= limit:=5` ([the worklist](../features/namespaces-and-sharing.md#the-worklist)) | `agent.client.namespace.worklist(...)` | | Review queue (conflicts) | `conflicts.list`, `conflicts.resolve`, `learnings.review` | `agent.conflicts.list()`, `.resolve(...)` | | Review queue (proposals) | `loom proposals list`, `show `, `accept`, `reject` ([proposals](../features/memory/writing.md#deciding-proposals-from-a-script)) | `agent.client.memory.proposals(...)`, `.proposal_decide(...)` | -| Review queue (definitions) | `memory.definitions.list`, `memory.definitions.disputes` | `agent.client.memory.definitions_list()`, `.definitions_disputes()` | +| Review queue (definitions) | `memory.definitions.list`, `memory.definitions.disputes`; a definition's team or product: `memory.set` with `applies_to` in its value | `agent.client.memory.definitions_list()`, `.definitions_disputes()` | | Copy rules | `memory.copy_rule.set`, `memory.copy_rule.list`, `memory.copy_rule.delete` ([copy rules](../features/namespaces-and-sharing.md#copy-rules)) | `agent.client.memory.copy_rule_set(...)`, `.copy_rule_list(...)`, `.copy_rule_delete(...)`; TypeScript `client.memory.copyRuleSet(...)` | | Copy rule preview | `loom copy-rule run `, or `memory.copy_rule.run` ([preview a rule](../features/namespaces-and-sharing.md#preview-a-rule)) | `agent.client.memory.copy_rule_run(...)`; TypeScript `client.memory.copyRuleRun(...)`; `loom call memory.copy_rule.run rule_id=` | | Copy rule run | `loom copy-rule run --apply --revision ` ([run a rule](../features/namespaces-and-sharing.md#run-a-rule)) | `agent.client.memory.copy_rule_run({"rule_id": ..., "dry_run": False, "revision": ...})` | diff --git a/frontend/e2e/definitions.spec.ts b/frontend/e2e/definitions.spec.ts index bff24200e6..35bb121462 100644 --- a/frontend/e2e/definitions.spec.ts +++ b/frontend/e2e/definitions.spec.ts @@ -26,6 +26,7 @@ const DISPUTES = { term: "Active user", aliases: ["AU"], body: "Signed in during the last 30 days.", + applies_to: { team: "Growth" }, }, { memory_key: "definition/active-user-finance", @@ -35,6 +36,7 @@ const DISPUTES = { term: "active user", aliases: ["au"], body: LONG_BODY, + applies_to: {}, }, { memory_key: "definition/active-user-legacy-dashboard-with-a-long-key-that-must-wrap", @@ -44,8 +46,10 @@ const DISPUTES = { term: "Active User", aliases: ["AU"], body: null, + applies_to: {}, }, ], + state: "suspected", }, ], compared: 7, @@ -144,6 +148,10 @@ for (const width of [1400, 375]) { await expect(dispute.getByRole("listitem")).toHaveCount(3); await expect(dispute.getByRole("button", { name: /^Open definition\// })).toHaveCount(3); await expect(dispute.getByText("It has no text field, so it is compared by its whole value.")).toBeVisible(); + // One side says which team it is for: the name still needs review. + await expect(dispute.getByText("Needs review", { exact: true })).toBeVisible(); + await expect(dispute.getByText("Applies to: team Growth", { exact: true })).toBeVisible(); + await expect(dispute.getByText("Applies to: not declared", { exact: true })).toHaveCount(2); // The long text is cut until asked for. await expect(dispute.getByText("Test accounts are left out.", { exact: false })).toHaveCount(0); const all = dispute.getByRole("button", { name: "Show all", exact: true }); diff --git a/frontend/src/api/definitions.test.ts b/frontend/src/api/definitions.test.ts new file mode 100644 index 0000000000..4bc28e04c8 --- /dev/null +++ b/frontend/src/api/definitions.test.ts @@ -0,0 +1,120 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { declareAppliesTo, NotADefinition } from "./definitions"; + +// What a definition applies to is written into its stored value: read with memory.get, the +// `applies_to` key replaced, and written back with memory.set under the hash the claim was +// read with, so the server refuses a definition edited in between. memory.set builds the +// whole new version from its input, so the row's other fields go back with the value. + +const ID = { org: "acme", namespace: "team" }; +const CLAIM = { memory_key: "definition/active-user", content_sha256: "a".repeat(64) }; +/** The fields of the row that the write sends back as it read them. */ +const KEPT = { + memory_type: "definition", + tags: ["metrics"], + entities: ["active user"], + confidence: 0.7, + sensitivity: "low", + source_trace: "curated_doc://glossary", + source_resource_id: "doc-7", + source_class: "imported", + valid_at: "2000-01-01T00:00:00Z", + valid_to: "2000-12-31T00:00:00Z", + char_limit: 4000, +}; +const STORED = { + found: true, + value: { + term: "Active user", + body: "Signed in during the last 30 days.", + applies_to: { team: "Growth", region: "EU" }, + }, + ...KEPT, + version: 3, + pinned: false, + created_at: "2000-01-01T00:00:00Z", + content_sha256: "c".repeat(64), +}; + +/** Answers memory.get with `stored` and memory.set with a new version; returns the calls as + * [op, body], each body without the client's own `consumer` label. */ +function serve(stored: Record) { + const calls: Array<[string, Record]> = []; + vi.stubGlobal( + "fetch", + vi.fn(async (url: string, init: RequestInit) => { + const op = String(url).split("/v1/")[1]; + const { consumer: _, ...body } = JSON.parse(String(init.body)); + calls.push([op, body]); + return new Response(JSON.stringify(op === "memory.get" ? stored : { version: 2, pinned: false }), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }), + ); + return calls; +} + +beforeEach(() => vi.unstubAllGlobals()); +afterEach(() => vi.unstubAllGlobals()); + +describe("declareAppliesTo", () => { + it("replaces applies_to in the stored value and writes it back under the claim's hash", async () => { + const calls = serve(STORED); + await declareAppliesTo(ID, CLAIM, { team: "Finance", product: "" }); + expect(calls.map(([op]) => op)).toEqual(["memory.get", "memory.set"]); + // The namespace-wide row: agent `-`, and no user or session. + expect(calls[0][1]).toEqual({ ...ID, agent: "-", memory_key: CLAIM.memory_key }); + expect(calls[1][1]).toEqual({ + ...ID, + agent: "-", + memory_key: CLAIM.memory_key, + // The other fields stay; the scope is the one declared, with no key left from before. + value: { term: "Active user", body: "Signed in during the last 30 days.", applies_to: { team: "Finance" } }, + // A field the body leaves out is reset on the new version: a definition would lose + // its end date, its entities, its label and where it came from. + ...KEPT, + // The claim's hash, not the one the read just answered. + if_match_sha256: CLAIM.content_sha256, + }); + }); + + it("leaves out a class the server decides, a copy rule's mark and an end date the row does not have", async () => { + const calls = serve({ + ...STORED, + // memory.set refuses both from a caller: the class of a row a person wrote is the + // server's to set, and the mark says the rule's run wrote the text, which an edited + // value no longer is. + source_class: "asserted", + source_trace: "copy_rule:glossary@3", + valid_to: null, + }); + await declareAppliesTo(ID, CLAIM, { team: "Finance" }); + const left = ["source_class", "source_trace", "valid_to"]; + expect(calls[1][1]).toEqual({ + ...ID, + agent: "-", + memory_key: CLAIM.memory_key, + value: { term: "Active user", body: "Signed in during the last 30 days.", applies_to: { team: "Finance" } }, + // The rest goes back as read. + ...Object.fromEntries(Object.entries(KEPT).filter(([field]) => !left.includes(field))), + if_match_sha256: CLAIM.content_sha256, + }); + }); + + it("removes applies_to when neither name is given", async () => { + const calls = serve(STORED); + await declareAppliesTo(ID, CLAIM, { team: "", product: "" }); + expect(calls[1][1].value).toEqual({ term: "Active user", body: "Signed in during the last 30 days." }); + }); + + it.each([ + ["a text", { ...STORED, value: "Active user: signed in." }], + ["a list", { ...STORED, value: ["Active user"] }], + ["gone", { found: false, value: null, memory_type: null }], + ])("writes nothing when the stored value is %s", async (_, stored) => { + const calls = serve(stored); + await expect(declareAppliesTo(ID, CLAIM, { team: "Finance" })).rejects.toBeInstanceOf(NotADefinition); + expect(calls.map(([op]) => op)).toEqual(["memory.get"]); + }); +}); diff --git a/frontend/src/api/definitions.ts b/frontend/src/api/definitions.ts index 45794cbe72..ec237a7956 100644 --- a/frontend/src/api/definitions.ts +++ b/frontend/src/api/definitions.ts @@ -2,6 +2,7 @@ // barrel: only the Review queue's Definitions tab calls it. import { post } from "../api"; import type { Identity, RequestOpts } from "../api"; +import { getMemory, rowFields } from "./memory"; /** A name a governed definition loses to another governed definition that holds it. */ export interface LostName { @@ -42,6 +43,12 @@ export async function listDefinitions( return post("/v1/memory.definitions.list", { org: id.org, namespace: id.namespace }, opts.signal); } +/** The team and the product a definition says it applies to; a key it does not declare is absent. */ +export interface AppliesTo { + team?: string; + product?: string; +} + /** One live namespace-wide definition that holds a disputed name. */ export interface DefinitionClaim { memory_key: string; @@ -53,6 +60,8 @@ export interface DefinitionClaim { aliases: string[]; /** The definition's `body`; null when it has none, and it is then compared by its whole value. */ body: string | null; + /** What the definition declares it applies to. Absent from a server that reads none. */ + applies_to?: AppliesTo; } export interface DefinitionDispute { @@ -60,6 +69,10 @@ export interface DefinitionDispute { names: string[]; /** Two or more, by key. */ claims: DefinitionClaim[]; + /** `alternatives` when the definitions that differ each declare another team or product; + * `suspected` otherwise. Absent from a server that tells none apart, and a state this + * build does not hold reads as `suspected`. */ + state?: string; } export interface DefinitionDisputes { @@ -86,3 +99,42 @@ export async function listDefinitionDisputes( opts.signal, ); } + +/** The definition's stored value is no longer an object to declare a scope in: nothing is written. */ +export class NotADefinition extends Error {} + +/** The mark of a copy rule's run on a row's `source_trace`: the run wrote the row's text. */ +const COPY_RULE_TRACE = "copy_rule:"; + +/** + * Declares what a definition applies to: reads its stored value, replaces `applies_to` in it + * (removes it when both names are empty) and writes the value back under the claim's hash, + * so a definition edited since the claim was read is refused with 409 PRECONDITION_FAILED. + * The row's other fields go back with it (`rowFields`): only the scope changes. + */ +export async function declareAppliesTo( + id: Pick, + claim: Pick, + scope: AppliesTo, +): Promise { + // A compared definition is saved for the whole namespace: agent, user and session `-`. + const row = { org: id.org, namespace: id.namespace, agent: "-" }; + const stored = await getMemory(row, claim.memory_key); + const value = stored.value; + if (!stored.found || typeof value !== "object" || value === null || Array.isArray(value)) throw new NotADefinition(); + const next: Record = { ...value }; + const declared = Object.fromEntries(Object.entries(scope).filter(([, name]) => name)); + if (Object.keys(declared).length > 0) next.applies_to = declared; + else delete next.applies_to; + const fields = rowFields(stored); + // An edited value is no longer the text the rule's run wrote, and memory.set refuses the + // mark from a caller. + if (stored.source_trace?.startsWith(COPY_RULE_TRACE)) delete fields.source_trace; + await post("/v1/memory.set", { + ...row, + memory_key: claim.memory_key, + value: next, + ...fields, + if_match_sha256: claim.content_sha256, + }); +} diff --git a/frontend/src/api/memory.ts b/frontend/src/api/memory.ts index f3e4e9c5f3..36efb7687c 100644 --- a/frontend/src/api/memory.ts +++ b/frontend/src/api/memory.ts @@ -204,18 +204,12 @@ export function rowIdentity(id: Identity, row: MemoryDetail): Identity & { user_ }; } -/** Pin a row read with `getMemory`, at `rowIdentity`. memory.pin writes a whole new - * version as memory.set does, so the row's fields go back with it; leaving - * ttl_seconds out keeps the row's expiry. */ -export async function pinMemory( - id: Identity, - key: string, - row: MemoryDetail, -): Promise<{ version: number; pinned: boolean }> { +/** The fields of a row read with `getMemory` that a write of a new version of it sends + * back. memory.set and memory.pin build the whole version from their input, so a field + * the body leaves out is reset on the new row; leaving ttl_seconds out keeps the row's + * expiry. */ +export function rowFields(row: MemoryDetail): Record { const body: Record = { - ...rowIdentity(id, row), - memory_key: key, - value: row.value, memory_type: row.memory_type, tags: row.tags, entities: row.entities, @@ -230,6 +224,21 @@ export async function pinMemory( if (row.valid_at) body.valid_at = row.valid_at; if (row.valid_to) body.valid_to = row.valid_to; if (row.char_limit != null) body.char_limit = row.char_limit; + return body; +} + +/** Pin a row read with `getMemory`, at `rowIdentity`, with its value and `rowFields`. */ +export async function pinMemory( + id: Identity, + key: string, + row: MemoryDetail, +): Promise<{ version: number; pinned: boolean }> { + const body: Record = { + ...rowIdentity(id, row), + memory_key: key, + value: row.value, + ...rowFields(row), + }; // A change to the value since the read answers 409 instead of being reverted. if (row.content_sha256) body.if_match_sha256 = row.content_sha256; return post<{ version: number; pinned: boolean }>("/v1/memory.pin", body); diff --git a/frontend/src/components/MemoryInspector.rename.test.tsx b/frontend/src/components/MemoryInspector.rename.test.tsx index 0134fe03aa..887c63421d 100644 --- a/frontend/src/components/MemoryInspector.rename.test.tsx +++ b/frontend/src/components/MemoryInspector.rename.test.tsx @@ -249,6 +249,47 @@ describe("MemoryInspector rename with redirect", () => { expect(setMemory).toHaveBeenCalledTimes(1); }); + it("refuses to save unparseable text over an object value", async () => { + seed("writer"); + const stored = { term: "ARR", body: "Annual recurring revenue." }; + vi.mocked(getMemory).mockResolvedValue({ ...LIVE, memory_type: "definition", value: stored }); + render( {}} onChanged={() => {}} />); + await userEvent.click(await screen.findByRole("button", { name: "Edit" })); + const value = screen.getByLabelText("Memory value"); + // The closing brace is lost: saved as it is, the text would replace the object with a string. + await userEvent.clear(value); + await userEvent.click(value); + await userEvent.paste('{"term": "ARR", "body": "Yearly recurring revenue."'); + await userEvent.click(screen.getByRole("button", { name: "Save new version" })); + expect(value).toHaveAccessibleDescription( + "This memory holds an object and the text is not valid JSON, so it was not saved. Correct it, or cancel to keep the stored value.", + ); + expect(value).toHaveAttribute("aria-invalid", "true"); + expect(setMemory).not.toHaveBeenCalled(); + expect(screen.getByLabelText("Memory value")).toBe(value); + // The error leaves with the next keystroke, and the corrected text is saved as an object. + await userEvent.type(value, "}"); + expect(value).not.toHaveAttribute("aria-invalid"); + vi.mocked(setMemory).mockResolvedValueOnce({ version: 4, pinned: false }); + await userEvent.click(screen.getByRole("button", { name: "Save new version" })); + await waitFor(() => expect(setMemory).toHaveBeenCalledTimes(1)); + expect(vi.mocked(setMemory).mock.calls[0][2]).toEqual({ term: "ARR", body: "Yearly recurring revenue." }); + }); + + it("saves text that is no JSON over a stored text, as it is", async () => { + seed("writer"); + await open(); + await userEvent.click(screen.getByRole("button", { name: "Edit" })); + const value = screen.getByLabelText("Memory value"); + await userEvent.clear(value); + await userEvent.click(value); + await userEvent.paste('{"milk": "oat"'); + vi.mocked(setMemory).mockResolvedValueOnce({ version: 4, pinned: false }); + await userEvent.click(screen.getByRole("button", { name: "Save new version" })); + await waitFor(() => expect(setMemory).toHaveBeenCalledTimes(1)); + expect(vi.mocked(setMemory).mock.calls[0][2]).toBe('{"milk": "oat"'); + }); + it("holds the redirect on a no_delete row, which a rename without one would delete", async () => { seed("writer"); vi.mocked(getMemory).mockResolvedValue({ ...LIVE, lock_mode: "no_delete" }); diff --git a/frontend/src/components/MemoryInspector.tsx b/frontend/src/components/MemoryInspector.tsx index 2f9e462d66..6e6e025009 100644 --- a/frontend/src/components/MemoryInspector.tsx +++ b/frontend/src/components/MemoryInspector.tsx @@ -64,7 +64,7 @@ import { keepOpenOnToasts, toast, toastError, toastWithId } from "./Toast"; import { committedAnyway, errorLine, toastCommitted } from "../lib/errorWords"; import { IconButton } from "./IconButton"; import { SkeletonText } from "./Skeleton"; -import { Chip, ExternalLink, Loading, LoadingSkeleton, Tip, Unavailable } from "./ui"; +import { Chip, ExternalLink, fieldError, Loading, LoadingSkeleton, Tip, Unavailable } from "./ui"; import { AnchoredPopover } from "./ui/AnchoredPopover"; import { CHIP_OUTLINE_CLASS } from "./ui/Chip"; import { confirmAction } from "./ConfirmDialog"; @@ -166,6 +166,21 @@ interface InspectorProps { onInspectMemory?: (key: string) => void; } +/** The editor's field error for text that is no JSON over a stored object. */ +const NOT_JSON = + "This memory holds an object and the text is not valid JSON, so it was not saved. Correct it, or cancel to keep the stored value."; + +const isStoredObject = (value: unknown) => typeof value === "object" && value !== null && !Array.isArray(value); + +function parsesAsJson(text: string) { + try { + JSON.parse(text); + return true; + } catch { + return false; + } +} + /** * Right-edge drawer showing one memory: value, metadata, tags, provenance, * related rows, history and lineage. The footer holds Edit, Ask about this, a More menu with @@ -209,6 +224,8 @@ export function MemoryInspector({ const [restoring, setRestoring] = useState(false); const [editing, setEditing] = useState(false); const [draft, setDraft] = useState(""); + // Save refused the draft as no JSON over a stored object; cleared by the next keystroke. + const [draftRefused, setDraftRefused] = useState(false); const [diffVersion, setDiffVersion] = useState(null); const [expanded, setExpanded] = useState(false); const [copyOpen, setCopyOpen] = useState(false); @@ -823,6 +840,7 @@ export function MemoryInspector({ if (!detail || setReason) return; formSession.current += 1; setDraft(formatValue(detail.value)); + setDraftRefused(false); setEditing(true); }; @@ -882,6 +900,12 @@ export function MemoryInspector({ const onSaveEdit = async () => { if (!detail || setReason) return; const session = formSession.current; + // Over a stored object, text that is no JSON is refused: saved as it is, it would + // replace the object with a string. + if (isStoredObject(detail.value) && !parsesAsJson(draft)) { + setDraftRefused(true); + return; + } try { // Parse JSON if it looks like an object/array; else keep the string. let nextValue: unknown = draft; @@ -1159,9 +1183,13 @@ export function MemoryInspector({ setDraft(v)} + onChange={(v) => { + setDraft(v); + setDraftRefused(false); + }} rows={Math.min(12, Math.max(3, draft.split("\n").length))} autoFocus + {...fieldError("memory-value-error", draftRefused && NOT_JSON)} />
-
+
Applies to: {appliesTo(claim.applies_to)}
+
+ + +
); } +// The longest team or product name the server reads, in characters: a longer one would be +// saved and then read as not declared. +const APPLIES_TO_MAX = 64; +const TOO_LONG = `Use at most ${fmtInt(APPLIES_TO_MAX)} characters.`; +const MOVED = "This definition changed after the list was read, so nothing was saved. Close this and open it again."; +const GOVERNED = + "This definition is governed. Saving edits it, so it stops being governed until an admin shares it again."; +const MAY_BE_GOVERNED = + "Saving edits this definition. If it is governed, it stops being governed until an admin shares it again."; + +/** The definition is not the one the claim was read from: edited since, or no longer an object. */ +const moved = (e: unknown) => + e instanceof NotADefinition || (e instanceof ApiError && e.status === 409 && e.code === "PRECONDITION_FAILED"); + +/** + * The dialog that declares the team and product a definition applies to. Save writes them + * into the definition's stored value under the hash the claim was read with, which is an edit + * of the definition: `governed` says before Save whether that ends its governed status (true), + * leaves none to end (false) or cannot be told (null: the shared list is not read). A saved + * change bumps the store's version, so both sections read again. + */ +function AppliesToDialog({ + claim, + governed, + onClose, +}: { + claim: DefinitionClaim; + governed: boolean | null; + onClose: () => void; +}) { + const identity = useIdentity(); + const bumpMemoriesVersion = useStore((s) => s.bumpMemoriesVersion); + const id = useId(); + const [team, setTeam] = useState(claim.applies_to?.team ?? ""); + const [product, setProduct] = useState(claim.applies_to?.product ?? ""); + const [busy, setBusy] = useState(false); + const [refusal, setRefusal] = useState(null); + const tooLong = (name: string) => (name.trim().length > APPLIES_TO_MAX ? TOO_LONG : null); + + const save = async () => { + if (busy || tooLong(team) || tooLong(product)) return; + setBusy(true); + setRefusal(null); + try { + await declareAppliesTo(identity, claim, { team: team.trim(), product: product.trim() }); + toast("Saved", "ok"); + } catch (e) { + // Saved, with only lists and search behind: closed as after a success, not sent again. + if (!isPublicationPending(e)) { + setRefusal(moved(e) ? MOVED : `Couldn't save what it applies to: ${errorLine(e)}`); + setBusy(false); + // The list behind the dialog shows the definition as it was: read it again. + if (moved(e)) bumpMemoriesVersion(); + return; + } + toastCommitted(e); + } + bumpMemoriesVersion(); + onClose(); + }; + + return ( + !open && !busy && onClose()} + title="What this definition applies to" + description="Two definitions of one name are shown as alternatives when both name a different team, or both name a different product. Leave a field empty to name none." + className="w-full max-w-[520px]" + > +
{ + e.preventDefault(); + void save(); + }} + > +
{claim.memory_key}
+ + + {governed !== false && } + {refusal && } + + + + + +
+ ); +} + +/** Whether a dispute's definitions are alternatives. Any other state, one this build does not + * hold and none (a server that tells none apart) need review. */ +const isAlternatives = (dispute: DefinitionDispute) => dispute.state === "alternatives"; + +/** A dispute's badge. A memo over the flag: Click UI's Badge measures its text on every render. */ +const StateBadge = memo(function StateBadge({ alternatives }: { alternatives: boolean }) { + return alternatives ? ( + + ) : ( + + ); +}); + const plural = (n: number, one: string, many: string) => `${fmtInt(n)} ${n === 1 ? one : many}`; /** * The names whose current definitions differ, above the shared list: one panel per dispute, - * its definitions side by side in key order. Read when the panel opens and after every change - * the drawer makes; it writes nothing. `reason` is why the caller cannot read it; with one - * the section shows it and reads nothing. A server without the read shows no section. + * those that need review first, its definitions side by side in key order. Read when the + * panel opens and after every change the drawer or the Applies to dialog makes. `reason` is + * why the caller cannot read it; with one the section shows it and reads nothing. A server + * without the read shows no section. `setReason` is why the caller cannot edit a definition, + * and `governed` says whether the definition under a key is governed (null: not known). * `onAnswered` gets the store's version each read that answered, or failed, was started at. */ function DisputesSection({ reason, + setReason, + governed, onOpen, onAnswered, }: { reason: string | null; + setReason: string | null; + governed: (key: string) => boolean | null; onOpen: (key: string) => void; onAnswered: (version: number) => void; }) { @@ -261,7 +423,14 @@ function DisputesSection({ const [error, setError] = useState(null); const [absent, setAbsent] = useState(false); const [reload, setReload] = useState(0); + // The claim whose Applies to dialog is open. + const [scoping, setScoping] = useState(null); const heading = useId(); + // Those that need review first; each group keeps the server's order. + const disputes = useMemo( + () => [...(read?.disputes ?? [])].sort((a, b) => Number(isAlternatives(a)) - Number(isAlternatives(b))), + [read], + ); useAbortableEffect( (signal, live) => { @@ -310,16 +479,21 @@ function DisputesSection({

) : (
- {read.disputes.map((d) => ( + {disputes.map((d) => ( {d.names.join(" · ")}
} + header={ +
+
{d.names.join(" · ")}
+ +
+ } >
    {d.claims.map((c) => ( - + ))}
@@ -332,9 +506,14 @@ function DisputesSection({ under its own name is not compared.

{found > 0 && ( -

- A name leaves this list when its definitions say the same: edit or delete one of them. -

+ <> +

+ A name leaves this list when its definitions say the same: edit or delete one of them. +

+

+ Definitions meant for different teams or products are alternatives once each says which it applies to. +

+ )} {read.capped && (

@@ -356,6 +535,10 @@ function DisputesSection({

)} + {/* Outside the read's states: a read that fails behind the open dialog keeps it, with what was typed. */} + {scoping && ( + setScoping(null)} /> + )} ); } @@ -365,8 +548,9 @@ function DisputesSection({ * definitions, the most recently shared first, each with whether it is governed, why a lapsed * one lapsed and what brings it back, and the names another definition serves. A row or a * differing definition opens in the memory drawer, where an admin edits it, shares it or stops - * sharing it; the panel writes nothing. A row whose definition is deleted or past its expiry - * has no drawer to open: its line says what brings it back. + * sharing it; the panel's one write is what a differing definition applies to, which a writer + * declares in a dialog. A row whose definition is deleted or past its expiry has no drawer to + * open: its line says what brings it back. * * `listReason` is why the caller cannot read the list (the role it needs, or that the role is * not known yet); with one the list shows it and reads nothing. The differing names are a @@ -383,6 +567,8 @@ export function DefinitionsPanel({ listReason }: { listReason: string | null }) const whoami = useStore((s) => s.whoami); const roleRead = useNamespaceRoleRead(identity.namespace); const disputesReason = callReason("memory.definitions.disputes", roleRead, whoami, identity.namespace); + // Declaring what a definition applies to is an edit of it: a writer's. + const setReason = callReason("memory.set", roleRead, whoami, identity.namespace); const [list, setList] = useState(null); const [error, setError] = useState(null); const [reload, setReload] = useState(0); @@ -437,6 +623,15 @@ export function DefinitionsPanel({ listReason }: { listReason: string | null }) () => definitions.some((d) => winnersOf(d, terms, repeated).length > 1), [definitions, terms, repeated], ); + // Whether the definition under a key is governed, as the shared list on screen says; null + // when it does not say: the list is not read, or holds the key unchecked or not at all + // while more are shared than it lists. + const governed = (key: string) => { + if (listReason || error || list === null) return null; + const entry = definitions.find((d) => d.memory_key === key); + if (!entry) return list.count > definitions.length ? null : false; + return entry.capped ? null : entry.verdict === "governed"; + }; // The row whose control opened the drawer. Once the drawer is closed and both sections are // read, a control that is gone (a winner's link, the menu, the row itself, a differing @@ -462,7 +657,13 @@ export function DefinitionsPanel({ listReason }: { listReason: string | null })

{listReason}

) : ( <> - open(key, key)} onAnswered={setCompared} /> + open(key, key)} + onAnswered={setCompared} + /> , #[serde(default = "default_definition_claim_body")] pub body: Option, + #[serde(default = "default_definition_claim_applies_to")] + pub applies_to: std::collections::HashMap, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum DefinitionDisputeState { + #[serde(rename = "suspected")] + Suspected, + #[serde(rename = "alternatives")] + Alternatives, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -38021,6 +38032,8 @@ pub struct DefinitionClaim { pub struct DefinitionDispute { pub names: Vec, pub claims: Vec, + #[serde(default = "default_definition_dispute_state")] + pub state: DefinitionDisputeState, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -72987,6 +73000,12 @@ fn default_definition_claim_aliases() -> Vec { fn default_definition_claim_body() -> Option { serde_json::from_str("null").expect("schema default") } +fn default_definition_claim_applies_to() -> std::collections::HashMap { + serde_json::from_str("{}").expect("schema default") +} +fn default_definition_dispute_state() -> DefinitionDisputeState { + serde_json::from_str("\"suspected\"").expect("schema default") +} fn default_memory_definitions_disputes_output_unread_names() -> Vec { serde_json::from_str("[]").expect("schema default") } diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 836c63ef3e..d60147840a 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -6891,6 +6891,7 @@ export interface MemoryDefinitionsDisputesInput { export interface DefinitionDispute { names: string[]; claims: DefinitionClaim[]; + state?: "suspected" | "alternatives"; } export interface DefinitionClaim { @@ -6901,6 +6902,7 @@ export interface DefinitionClaim { term: string; aliases?: string[]; body?: string | null; + applies_to?: Record; } export interface MemoryDefinitionsDisputesOutput { diff --git a/server/memory/api/models_lifecycle.py b/server/memory/api/models_lifecycle.py index 94f1b51868..4b466466e1 100644 --- a/server/memory/api/models_lifecycle.py +++ b/server/memory/api/models_lifecycle.py @@ -131,7 +131,8 @@ class MemoryDefinitionsDisputesInput(BaseModel): Each name comes with the definitions that disagree. Only live definitions saved for the whole namespace (agent, user and session `-`) under a `definition/` key are - compared. The read writes nothing.""" + compared. A dispute whose `state` is `alternatives` holds definitions that declare + different teams or products in `applies_to`. The read writes nothing.""" org: str namespace: str @@ -153,6 +154,11 @@ class DefinitionClaim(BaseModel): # The definition's `body`; None when it is not a string, and the definition is then # compared by its whole value. body: str | None = None + # The team or product the definition says it applies to: the `team` and `product` of + # its value's `applies_to`, as written, trimmed; a blank one is left out. Empty when it + # declares none, and when `applies_to` is not an object of those two keys with string + # values of at most 64 characters. + applies_to: dict[str, str] = Field(default_factory=dict) class DefinitionDispute(BaseModel): @@ -161,6 +167,11 @@ class DefinitionDispute(BaseModel): names: list[str] # Two or more, by key; the order prefers none. claims: list[DefinitionClaim] + # `alternatives` when every two claims whose texts differ both declare one `applies_to` + # key with different values (case and spacing folded): definitions for different teams + # or products, so ask which applies. `suspected` otherwise, and when the request's + # bound ended before every pair was checked: the definitions may contradict each other. + state: Literal["suspected", "alternatives"] = "suspected" class MemoryDefinitionsDisputesOutput(BaseModel): diff --git a/server/memory/app/definition_disputes.py b/server/memory/app/definition_disputes.py index 27d70e2cd1..8d09c50013 100644 --- a/server/memory/app/definition_disputes.py +++ b/server/memory/app/definition_disputes.py @@ -3,7 +3,8 @@ A dispute is derived when it is read (`server.memory.domain.definition_disputes`): no row is marked or written. One statement locates the live namespace-wide definitions and their names; only the definitions that share a name are read, from the memory authority, and -every field served about one comes from that head. +every field served about one comes from that head. A served dispute's state comes from +checking its claims' declared scopes two at a time, inside the request's work bound. """ from __future__ import annotations @@ -29,8 +30,10 @@ from server.memory.domain.definition_disputes import ( Claim, Dispute, + State, claim_of, dispute_candidates, + dispute_state, name_groups, ) from server.memory.domain.definitions import definition_names, fold_name @@ -41,6 +44,9 @@ # Charged per located definition before its names, so a row with none still costs work. _ROW_CHARS = 32 +# Charged per pair of claims whose scopes are checked: the whole bound pays for +# `ON_LOOP_CHARS` checks, the most that run between two turns of the loop. +_PAIR_CHARS = DEFINITION_WORK_CHARS // ON_LOOP_CHARS async def handle_memory_definitions_disputes( @@ -109,7 +115,15 @@ async def _disputes(org: str, namespace: str, only: str | None) -> MemoryDefinit claims = await _claims(org, namespace, list(keys), now) # A located key whose head is gone or is no claim was not compared. moved = len(keys) - len(claims) - disputes, late = _served(dispute_candidates(claims, only=only), unread) + served, late = _served(dispute_candidates(claims, only=only), unread) + disputes = [] + for read_names, dispute in served: + # A dispute's pair checks walk its claims on the loop: a turn before each. A pair + # the bound does not pay for is not checked, and its dispute stays suspected. + await asyncio.sleep(0) + state, checked = dispute_state(dispute.claims, checks=left // _PAIR_CHARS) + left -= checked * _PAIR_CHARS + disputes.append(_wire(read_names, dispute, state)) return MemoryDefinitionsDisputesOutput( disputes=disputes, compared=len(held) - moved, @@ -181,12 +195,15 @@ def _claim(head: MemoryRow, now: Any) -> Claim | None: ) -def _served(disputes: list[Dispute], unread: set[str]) -> tuple[list[DefinitionDispute], set[str]]: - """The disputes as served, and the names of those left out. A name whose text was not - read stays out of a dispute (its other holders were not fetched), and disputes are - kept in order while the text they serve fits the request's bound: a value rewritten - larger between the two statements is not served past it.""" - out: list[DefinitionDispute] = [] +def _served( + disputes: list[Dispute], unread: set[str] +) -> tuple[list[tuple[list[str], Dispute]], set[str]]: + """The disputes to serve, each with the names it is served under, and the names of + those left out. A name whose text was not read stays out of a dispute (its other + holders were not fetched), and disputes are kept in order while the text they serve + fits the request's bound: a value rewritten larger between the two statements is not + served past it.""" + out: list[tuple[list[str], Dispute]] = [] late: set[str] = set() left = DEFINITION_WORK_CHARS for dispute in disputes: @@ -198,21 +215,25 @@ def _served(disputes: list[Dispute], unread: set[str]) -> tuple[list[DefinitionD late.update(names) continue left -= cost - out.append( - DefinitionDispute( - names=names, - claims=[ - DefinitionClaim( - memory_key=c.memory_key, - memory_id=c.memory_id, - version=c.version, - content_sha256=c.content_sha256, - term=c.term, - aliases=list(c.aliases), - body=c.body, - ) - for c in dispute.claims - ], - ) - ) + out.append((names, dispute)) return out, late + + +def _wire(names: list[str], dispute: Dispute, state: State) -> DefinitionDispute: + return DefinitionDispute( + names=names, + claims=[ + DefinitionClaim( + memory_key=c.memory_key, + memory_id=c.memory_id, + version=c.version, + content_sha256=c.content_sha256, + term=c.term, + aliases=list(c.aliases), + body=c.body, + applies_to=dict(c.applies_to), + ) + for c in dispute.claims + ], + state=state, + ) diff --git a/server/memory/domain/definition_disputes.py b/server/memory/domain/definition_disputes.py index 239cf883ad..6e48dba411 100644 --- a/server/memory/domain/definition_disputes.py +++ b/server/memory/domain/definition_disputes.py @@ -4,14 +4,20 @@ names and not labelled `high`, shared or not. A dispute is two or more claims that hold a name and whose text is not all equal: the folded `body` when it is a string, else the served hash of the whole value. Case, spacing, aliases and any other field make none. + +A claim may declare the scope it applies to: its value's `applies_to`, an object of +`team`, `product` or both. Two claims are separated when both declare one of those keys +with different values, and a dispute whose differing claims are all separated reads as +`alternatives`: definitions for different teams or products, with none to correct. """ from __future__ import annotations -from collections.abc import Iterable, Mapping, Set +from collections.abc import Iterable, Mapping, Sequence, Set from dataclasses import dataclass from datetime import datetime -from typing import Any +from itertools import combinations +from typing import Any, Literal from server.core.hashing import served_content_sha256 from server.memory.domain.definition_check import liveness_lapse @@ -24,6 +30,16 @@ from server.memory.domain.memory_types import DEFINITION from server.memory.domain.sensitivity import HIGH +# The keys of `applies_to` that are read, in the order a claim serves them. +SCOPE_KEYS = ("team", "product") +# The longest `applies_to` value that is read, in characters as written. +SCOPE_VALUE_CHARS = 64 + +# A dispute's states. `suspected`: its definitions may contradict each other. +State = Literal["suspected", "alternatives"] +SUSPECTED: State = "suspected" +ALTERNATIVES: State = "alternatives" + @dataclass(frozen=True) class Claim: @@ -38,6 +54,11 @@ class Claim: names: frozenset[str] # folded # What two claims are compared on: the folded body, or the hash of a value without one. text: tuple[str, str] + # The scope the definition declares: each of `SCOPE_KEYS` its `applies_to` holds, with + # the value as written, trimmed. Empty when it declares none. + applies_to: tuple[tuple[str, str], ...] + # The same keys with each value folded as a name is: what two scopes are compared on. + scope: tuple[tuple[str, str], ...] @dataclass(frozen=True) @@ -76,6 +97,7 @@ def claim_of( term, *aliases = written_names(value) body = value.get("body") sha256 = served_content_sha256(value) + declared = _declared_scope(value.get("applies_to")) return Claim( memory_key=memory_key, memory_id=memory_id, @@ -86,9 +108,46 @@ def claim_of( body=body if isinstance(body, str) else None, names=frozenset(names), text=("body", fold_name(body)) if isinstance(body, str) else ("value", sha256), + applies_to=tuple((key, written) for key, written, _ in declared), + scope=tuple((key, folded) for key, _, folded in declared), ) +def _declared_scope(applies_to: Any) -> list[tuple[str, str, str]]: + """The scope an `applies_to` declares, as `(key, written, folded)` in the order of + `SCOPE_KEYS`. Empty when it is not an object of those keys alone with string values of + at most `SCOPE_VALUE_CHARS` characters, so a misspelled key separates nothing; a value + that folds to nothing declares nothing for its key.""" + if not isinstance(applies_to, dict) or not set(applies_to) <= set(SCOPE_KEYS): + return [] + values = applies_to.values() + if not all(isinstance(v, str) and len(v) <= SCOPE_VALUE_CHARS for v in values): + return [] + read = [(key, applies_to[key]) for key in SCOPE_KEYS if key in applies_to] + return [(key, v.strip(), folded) for key, v in read if (folded := fold_name(v))] + + +def separated(a: Claim, b: Claim) -> bool: + """Whether both claims declare one scope key with different values. A key only one + of them declares separates nothing.""" + theirs = dict(b.scope) + return any(key in theirs and theirs[key] != value for key, value in a.scope) + + +def dispute_state(claims: Sequence[Claim], *, checks: int) -> tuple[State, int]: + """A dispute's state and the pair checks it took, at most `checks`: `ALTERNATIVES` + when every two of `claims` whose text differs are separated, `SUSPECTED` at the first + two that are not, and when `checks` end before the last pair is looked at.""" + spent = 0 + for a, b in combinations(claims, 2): + if spent == checks: + return SUSPECTED, spent + spent += 1 + if a.text != b.text and not separated(a, b): + return SUSPECTED, spent + return ALTERNATIVES, spent + + def name_groups( held: Mapping[str, Set[str]], *, only: str | None = None ) -> list[tuple[tuple[str, ...], tuple[str, ...]]]: diff --git a/tests/integration/test_definition_disputes.py b/tests/integration/test_definition_disputes.py index 1371beef5c..de6dccf5ec 100644 --- a/tests/integration/test_definition_disputes.py +++ b/tests/integration/test_definition_disputes.py @@ -1,7 +1,8 @@ """memory.definitions.disputes through the server: two definitions of one name that say different things are listed with both texts, a viewer reads them and another namespace -reads none, the read changes no row, and the names the locate reads in SQL are the names -the rule reads from a head.""" +reads none, the read changes no row, the names the locate reads in SQL are the names +the rule reads from a head, and declaring the team a definition applies to is an edit of +it that turns the dispute into alternatives once both sides declare one.""" from __future__ import annotations @@ -215,6 +216,81 @@ async def written() -> list[tuple[int, int]] | None: assert (entry["memory_key"], entry["verdict"]) == (key, "governed") +@pytest.mark.asyncio +async def test_declaring_a_scope_lapses_the_governed_copy_as_changed( + control_plane_url: str, mint_test_token +) -> None: + """Declaring a scope is a `memory.set` of the definition under its claim's hash: the + governed copy lapses as changed until the edited text is promoted, a dispute reads as + alternatives once both definitions declare another team, and the name stays with the + one shared definition.""" + from loom import Agent + from loom.errors import LoomError + + org, ns = _space("dispute-scope") + tok = mint_test_token(org=org, namespaces=["*"], roles=["admin", "writer"], subject="lead") + key, other = "definition/active-user", "definition/active-user-finance" + async with Agent( + org=org, namespace=ns, agent="analyst", base_url=control_plane_url, api_key=tok + ) as a: + read = a.client.memory.definitions_disputes + + async def governed() -> tuple[str, str | None]: + (entry,) = (await a.client.memory.definitions_list())["definitions"] + assert entry["memory_key"] == key + return entry["verdict"], entry["lapse_reason"] + + await _define(a, key, THIRTY) + got = await a.memory.get(key, agent_id="-") + await a.memory.promote(key, agent_id="-", approved_sha256=got["content_sha256"]) + await _define(a, other, NINETY) + (dispute,) = (await read())["disputes"] + assert dispute["state"] == "suspected" + assert [c["applies_to"] for c in dispute["claims"]] == [{}, {}] + assert await governed() == ("governed", None) + + # The scope is written into the stored value, under the hash the claim carries. + first, second = dispute["claims"] + growth = {**THIRTY, "applies_to": {"team": "Growth"}} + await _define(a, key, growth, if_match_sha256=first["content_sha256"]) + edited = await a.memory.get(key, agent_id="-") + assert edited["value"] == growth and edited["version"] > first["version"] + assert await governed() == ("lapsed", "changed") + # The hash of the text before the edit no longer admits a write. + with pytest.raises(LoomError) as stale: + await _define(a, key, THIRTY, if_match_sha256=first["content_sha256"]) + assert stale.value.code == "PRECONDITION_FAILED" + assert (await a.memory.get(key, agent_id="-"))["version"] == edited["version"] + + # One side declares a team: the definitions may still contradict each other. + (dispute,) = (await read())["disputes"] + assert dispute["state"] == "suspected" + assert [c["applies_to"] for c in dispute["claims"]] == [{"team": "Growth"}, {}] + + finance = {**NINETY, "applies_to": {"team": "Finance", "product": "Cloud"}} + await _define(a, other, finance, if_match_sha256=second["content_sha256"]) + (dispute,) = (await read())["disputes"] + assert dispute["state"] == "alternatives" + assert [c["applies_to"] for c in dispute["claims"]] == [ + {"team": "Growth"}, + {"team": "Finance", "product": "Cloud"}, + ] + assert dispute["claims"][0]["version"] == edited["version"] + assert dispute["claims"][1]["version"] > second["version"] + + # The name has one governed definition: the second stays an ordinary row. + with pytest.raises(LoomError) as taken: + await a.memory.promote( + other, agent_id="-", approved_sha256=dispute["claims"][1]["content_sha256"] + ) + assert taken.value.code == "DEFINITION_NAME_TAKEN" + assert taken.value.detail["conflicting_keys"] == [key] + # Sharing the edited text governs it again. + await a.memory.promote(key, agent_id="-", approved_sha256=edited["content_sha256"]) + assert await governed() == ("governed", None) + assert (await read())["disputes"][0]["state"] == "alternatives" + + @pytest.mark.asyncio async def test_the_locate_and_the_rule_agree_on_odd_name_values( control_plane_url: str, mint_test_token diff --git a/tests/unit/test_definition_disputes.py b/tests/unit/test_definition_disputes.py index 194f3e6e3d..c4877f4059 100644 --- a/tests/unit/test_definition_disputes.py +++ b/tests/unit/test_definition_disputes.py @@ -20,6 +20,7 @@ from server.memory.api.models_lifecycle import MemoryDefinitionsDisputesInput from server.memory.app import definition_disputes as disputes from server.memory.app.sensitivity_level import ON_LOOP_CHARS +from server.memory.domain import definition_disputes as domain from server.memory.domain.definition_disputes import Claim, dispute_candidates, name_groups from server.memory.store import MemoryRow, definition_claims from server.observability.event_args import IDENTIFIER_KEYS, TEXT_KEYS, project_args @@ -446,6 +447,176 @@ async def test_a_key_in_two_disputes_is_charged_twice( assert out.unread_names == [] +# ---- the scope a definition declares + +FINANCE = {**THIRTY, "applies_to": {"team": "Finance"}} +GROWTH = {**NINETY, "applies_to": {"team": "Growth"}} +WEEK = {"term": "Active user", "body": "Signed in this week."} + + +def _state(*values: Any, checks: int = 99) -> tuple[str, int]: + """The state of a dispute among `values`, saved under `definition/0`, `definition/1`…""" + claims = _claims(*((f"definition/{i}", v) for i, v in enumerate(values))) + return domain.dispute_state(claims, checks=checks) + + +async def test_a_key_both_declare_with_different_values_reads_as_alternatives( + namespace: dict[str, Any], +) -> None: + assert _state(FINANCE, GROWTH) == ("alternatives", 1) + # Either key separates, whatever the other says. + cloud = {**THIRTY, "applies_to": {"team": "Finance", "product": "Cloud"}} + local = {**NINETY, "applies_to": {"team": "finance", "product": "Self-managed"}} + assert _state(cloud, local) == ("alternatives", 1) + # A value is compared as a name is: one team written in another case or spacing + # separates nothing. + spaced = {**NINETY, "applies_to": {"team": " FINANCE "}} + assert _state(FINANCE, spaced) == ("suspected", 1) + # A blank value declares nothing for its key alone: the other key still separates. + half = {**THIRTY, "applies_to": {"team": "Finance", "product": " "}} + assert _state(half, GROWTH) == ("alternatives", 1) + assert _claims(("definition/a", half))[0].applies_to == (("team", "Finance"),) + + _put(namespace, ("definition/a", FINANCE), ("definition/b", {**GROWTH, "aliases": ["AU"]})) + (dispute,) = (await _read()).disputes + assert dispute.state == "alternatives" + # Each claim serves the scope its definition wrote, trimmed. + assert [c.applies_to for c in dispute.claims] == [{"team": "Finance"}, {"team": "Growth"}] + padded = {**NINETY, "applies_to": {"product": " Cloud ", "team": "Growth"}} + assert _claims(("definition/b", padded))[0].applies_to == ( + ("team", "Growth"), + ("product", "Cloud"), + ) + + +async def test_a_scope_on_one_side_only_is_suspected(namespace: dict[str, Any]) -> None: + assert _state(FINANCE, NINETY) == ("suspected", 1) + assert _state(THIRTY, GROWTH) == ("suspected", 1) + assert _state(THIRTY, NINETY) == ("suspected", 1), "no scope at all: what every dispute was" + + _put(namespace, ("definition/a", FINANCE), ("definition/b", NINETY)) + (dispute,) = (await _read()).disputes + assert dispute.state == "suspected" + assert [c.applies_to for c in dispute.claims] == [{"team": "Finance"}, {}] + + +@pytest.mark.parametrize( + ("one", "other"), + [ + ({"team": "Finance"}, {"product": "Cloud"}), + ({"region": "EU"}, {"region": "US"}), + # A scope with a key that is neither `team` nor `product` declares nothing. + ({"team": "Finance", "region": "EU"}, {"team": "Growth"}), + ({"team": 7}, {"team": "Growth"}), + ({"team": "F" * 65}, {"team": "Growth"}), + ({"team": " ​ "}, {"team": "Growth"}), + ("Finance", {"team": "Growth"}), + (["Finance"], {"team": "Growth"}), + ], + ids=[ + "disjoint", + "unknown", + "unknown-beside-known", + "number", + "too-long", + "blank", + "text", + "list", + ], +) +def test_disjoint_or_unknown_scope_keys_are_suspected(one: Any, other: Any) -> None: + a, b = {**THIRTY, "applies_to": one}, {**NINETY, "applies_to": other} + assert _state(a, b) == ("suspected", 1) + assert _state(b, a) == ("suspected", 1) + # The longest value that is read does separate. + edge = {**THIRTY, "applies_to": {"team": "F" * 64}} + assert _state(edge, GROWTH) == ("alternatives", 1) + + +def test_alternatives_needs_every_differing_pair_separated() -> None: + support = {**WEEK, "applies_to": {"team": "Support"}} + assert _state(FINANCE, GROWTH, support) == ("alternatives", 3) + # The first and the third differ and both say finance: one pair is not separated. + also_finance = {**WEEK, "applies_to": {"team": "finance"}} + assert _state(FINANCE, GROWTH, also_finance) == ("suspected", 2) + undeclared = _state(FINANCE, GROWTH, WEEK) + assert undeclared == ("suspected", 2) + # Two claims that say the same need no separation from each other, only from the rest. + copy = {**THIRTY, "term": "ACTIVE USER", "applies_to": {"team": "Finance"}} + assert _state(FINANCE, copy, GROWTH) == ("alternatives", 3) + assert _state(FINANCE, {**THIRTY, "term": "ACTIVE USER"}, GROWTH) == ("suspected", 3) + + +async def test_a_pair_past_the_work_bound_stays_suspected( + namespace: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + support = {**WEEK, "applies_to": {"team": "Support"}} + assert _state(FINANCE, GROWTH, support, checks=2) == ("suspected", 2) + assert _state(FINANCE, GROWTH, support, checks=3) == ("alternatives", 3) + + _put( + namespace, + ("definition/a", FINANCE), + ("definition/b", GROWTH), + ("definition/c", support), + ("definition/y", {"term": "Churn", "body": "Left.", "applies_to": {"product": "Cloud"}}), + ("definition/z", {"term": "churn", "body": "Gone.", "applies_to": {"product": "Local"}}), + ) + located = [_located(h) for h in namespace["heads"].values()] + read = sum(32 + len(r["term"]) + len(r["aliases_raw"]) + r["value_len"] for r in located) + pair = disputes._PAIR_CHARS + # The names and the text are paid for, and three of the four pair checks: the second + # dispute's one pair is past the bound. + monkeypatch.setattr(disputes, "DEFINITION_WORK_CHARS", read + 4 * pair - 1) + out = await _read() + assert [(d.names, d.state) for d in out.disputes] == [ + (["active user"], "alternatives"), + (["churn"], "suspected"), + ] + assert (out.capped, out.unread_names) == (False, []), "both disputes are served whole" + monkeypatch.setattr(disputes, "DEFINITION_WORK_CHARS", read + 4 * pair) + assert [d.state for d in (await _read()).disputes] == ["alternatives", "alternatives"] + # Past the bound inside a dispute: its third pair is not checked. + monkeypatch.setattr(disputes, "DEFINITION_WORK_CHARS", read + 3 * pair - 1) + assert [d.state for d in (await _read()).disputes] == ["suspected", "suspected"] + + +async def test_another_task_runs_before_each_disputes_pairs_are_checked( + namespace: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """A dispute's pair checks walk its claims on the loop.""" + _put( + namespace, + ("definition/a", FINANCE), + ("definition/b", GROWTH), + ("definition/y", {"term": "Churn", "body": "Left."}), + ("definition/z", {"term": "churn", "body": "Gone."}), + ) + turns = [0] + done = asyncio.Event() + + async def other() -> None: + while not done.is_set(): + turns[0] += 1 + await asyncio.sleep(0) + + seen: list[int] = [] + state = disputes.dispute_state + monkeypatch.setattr( + disputes, + "dispute_state", + lambda claims, *, checks: seen.append(turns[0]) or state(claims, checks=checks), + ) + task = asyncio.create_task(other()) + try: + out = await _read() + finally: + done.set() + await task + assert [d.state for d in out.disputes] == ["alternatives", "suspected"] + assert len(seen) == 2 and seen == sorted(set(seen)), "a turn before each dispute" + + # ---- the filter and the order