diff --git a/docs/features/integrations/librechat.md b/docs/features/integrations/librechat.md index 0bd229a08a..0a5d88f1d1 100644 --- a/docs/features/integrations/librechat.md +++ b/docs/features/integrations/librechat.md @@ -134,9 +134,16 @@ orgs, mints a token per person, revokes one, and scores each answer: inspect or tune case contains the labeled value; a refusal case says access was refused or failed; an abstention case says the fact is not stored. The forbidden text is the other org's canary for the cross-tenant case, the person's own answer (`friday`) for the - revoked-token case, and a stale or wrong value for some others. -- **citation valid:** every memory key the answer names exists in the person's namespace, - and a version written next to it is the row's current version. + revoked-token case, and a stale or wrong value for some others. Through Loom's assistant + route, an answer of any kind that names an op or setting the build neither serves nor + documents (`unknown_names`) is wrong. +- **citation valid:** every memory key the answer cites exists in the person's namespace, + and a version written next to it is the row's current version, or, for a question about + the key's history (`cite_history`), one of its earlier versions. Through Loom's assistant + route a memory citation is `[memory:@v]`; otherwise it is any key-shaped + text outside a `[help:]` citation, so on that path a help answer that quotes the docs' + example key counts it as an invalid memory citation; the help figures below come from + the assistant route. - **tool calls:** the `mcp` rows Loom ledgered under the person's subject during the answer. - **latency and time to first token:** end to end, and to the first streamed delta, which for the harness's own agent (`setup`) is the model's one-line preamble before its first @@ -153,9 +160,10 @@ orgs, mints a token per person, revokes one, and scores each answer: | Tool calls per question | at most 3 | at most 3, 16 in all | | Model cost per answer, every prompt token at list price | at most $0.05 | mean $0.029; max $0.064 (`abstain-cfo`, three searches) misses the target | -The LibreChat numbers are from one run of the 14 memory, inventory, inspect, tune, refusal -and abstention cases, scored against the current `cases.json` with `qualify.py rescore`; -the direct-path numbers are from a later run of that path alone +The LibreChat numbers are from one run of the 14 memory, inventory, inspect, tune and +refusal cases and memory abstentions (`abstain-wifi`, `abstain-cfo`), other than +`data-history` and `data-connected-agents`, scored against the current `cases.json` with +`qualify.py rescore`; the direct-path numbers are from a later run of that path alone (`qualify.py run --native-only`) on a fresh seed. The document cases below were run separately. @@ -212,6 +220,79 @@ breadcrumbs reach the hits, not that retrieval holds up at scale. No citation na revision: the hits of the measured build carry none, and the model read `knowledge.get` only on the two unanswerable questions. +### Use cases + +The case set holds at least one question per use case of Loom: what a namespace holds and +how it is used (the data tools), and how Loom works and how to do something in it (the +help tools, which read the documentation the server ships). Each help case labels the +values its answer must state and the pages that hold them, with a right and a wrong sample +answer the label is tested against. Its answer is scored correct when it states them and +does not deny them (each case's `forbid`), under the unknown-name rule above. For the case +with no answer in the docs, the answer is correct when it says so and writes no `LOOM_` +name that no docs page writes, as a name or as a member of a family a page writes with +placeholders; an answer that names an invented setting only to deny it is scored wrong. +The labels are patterns over the answer's text, so they err both ways: an answer that +states the labeled values beside a wrong claim about them can pass, and a right answer +worded otherwise can fail. A correct score means the answer has what the page says. A help +citation is valid when its page is in the server's documentation (`help.get`) and its +section is one of the page's own, by the rule the server's own check uses. The cases go +through Loom's assistant route (`qualify.py setup-bridge`), so each answer also carries +the question's asker line and the bridge's own citation check. + +| Use case | Cases | Correct | No invalid citation | +| --------------------------------- | ----- | -------- | ------------------- | +| U1 Look up a stored fact | 7 | 7 of 7 | 7 of 7 | +| U2 What a document says | 10 | 9 of 10 | 10 of 10 | +| U3 What the namespace holds | 4 | 4 of 4 | 4 of 4 | +| U4 Usage counts and trends | 3 | 3 of 3 | 3 of 3 | +| U5 Cost and spend | 1 | 1 of 1 | 1 of 1 | +| U6 Write memory better | 4 | 4 of 4 | 2 of 4 | +| U7 History of a fact | 2 | 2 of 2 | 2 of 2 | +| U8 Entity graph | 1 | 1 of 1 | 1 of 1 | +| U9 Code index | 1 | 1 of 1 | 1 of 1 | +| U10 Conflicts and refusal | 1 | 1 of 1 | 1 of 1 | +| U11 Sharing and collections | 1 | 1 of 1 | 1 of 1 | +| U12 My role and who can change it | 1 | 1 of 1 | 1 of 1 | +| U13 Connect a coding agent | 1 | 1 of 1 | 1 of 1 | +| U14 Tokens | 1 | 1 of 1 | 1 of 1 | +| U15 Models and keys | 1 | 1 of 1 | 0 of 1 | +| U16 Health problems | 1 | 1 of 1 | 1 of 1 | +| U17 Why search returned this | 1 | 1 of 1 | 1 of 1 | +| U18 Runs | 1 | 1 of 1 | 1 of 1 | +| U19 Tasks between agents | 1 | 1 of 1 | 1 of 1 | +| U20 Tracker | 1 | 1 of 1 | 1 of 1 | +| U21 Retention and erasure | 1 | 1 of 1 | 1 of 1 | +| U22 Extraction from transcripts | 1 | 1 of 1 | 1 of 1 | +| U23 Working memory | 1 | 1 of 1 | 1 of 1 | +| U24 Integrations | 1 | 1 of 1 | 1 of 1 | +| U25 What a setting does | 1 | 1 of 1 | 1 of 1 | +| U26 Getting started | 1 | 1 of 1 | 1 of 1 | +| U27 Operating a deployment | 1 | 1 of 1 | 1 of 1 | +| U28 Refusals and abstentions | 5 | 5 of 5 | 5 of 5 | +| All | 56 | 55 of 56 | 53 of 56 | + +Measured on v0.8.8 with `claude-haiku-4-5`, on a server running fake embeddings and a fake +LLM for Loom's own model jobs. A full run of the 56 cases costs about $3 at list price +counting every prompt token, a mean of $0.053 per answer. The figures take 14 cases (three +memory, nine document and two help cases) from one run and the other 42 from a full run, +on agent definitions that differ from `integrations/librechat/agent.yaml` in one sentence +on the asker's role, and for the full run also in the wording of the first step's +searches. Twelve answers cite no memory, document or help page: two refusals, three +abstentions, three SQL analyses (which cite their statement instead) and four counts, +which come from tallies with no row to cite; every other answer cites one. The misses: + +- `doc-cache-entries` asks for a value one of the namespace's documents holds + (`config/cache.toml`); the answer searches Loom's own documentation instead and does not + find it: the question and Loom's settings share their words. +- Two recommendation answers cite `mentor.guide`, Loom's writing guide, as a docs page, + which the harness marks invalid (no such page): the guide has no citation form. +- One answer names a section the page does not have. + +Answers vary from run to run at this model. A question about the person's own data that +shares words with Loom's docs (a rate limit, webhook retries) is sometimes answered from +the docs; the agent's instructions ask for the memory, document and help searches together +in its first step for that reason. + ## The deployed assistant Loom can also run LibreChat itself, headless, with one agent it seeds: the shape the @@ -289,8 +370,9 @@ The qualification runs the same cases through Loom's assistant route (`POST /v1/assistant/chat/completions`), each with the person's own token, so Loom delegates each answer's token and runs the agent it seeded. `setup-bridge` grants each person `viewer` on their namespace, since an answer's token is delegated from a live -grant. A run spends about a dollar from each namespace's daily model cost cap, and the -assistant may spend half of it, so raise the cap for the run +grant. A full run spends about $3, most of it from `acme-handbook`'s daily model cost cap +(45 of the 56 cases ask there), and the assistant may spend half of a cap, so raise the cap +for the run (`LOOM_DEFAULT_DAILY_COST_CAP_USD=20` on the server, or the namespace's `daily_cost_cap_usd`); otherwise the last cases are refused with `RATE_LIMITED`: @@ -302,11 +384,11 @@ python $Q revoke python $Q run --cancel-probe ``` -Beside every earlier case it runs three analysis cases (`insights.query` over the -namespace, one asking for every org's counts, whose answer must name no other tenant's -rows) and two recommendation cases over `acme-notes`, a namespace written badly on -purpose (hash-named keys, a JSON value encoded twice, a 6.5 KB runbook stored as a -memory). +Among its cases are three analysis cases (`insights.query` over the namespace, one asking +for every org's counts, whose answer must name no other tenant's rows) and two +recommendation cases over `acme-notes`, a namespace written badly on purpose (hash-named +keys, a JSON value encoded twice, a 6.5 KB runbook stored as a memory). The table measures +the data cases other than `data-history` and `data-connected-agents`. | Measured on v0.8.8, 28 cases, `claude-haiku-4-5`, fake embedder | The deployed agent, asked directly | | ----------------------------------------------------------------- | --------------------------------------------------------------- | diff --git a/docs/features/memory/retention-and-erasure.md b/docs/features/memory/retention-and-erasure.md index e499d68da8..55b695a656 100644 --- a/docs/features/memory/retention-and-erasure.md +++ b/docs/features/memory/retention-and-erasure.md @@ -103,7 +103,11 @@ wins. ## Erasure `erasure.request` erases one scope everywhere Loom keeps it, and returns once it can show -nothing in scope is left. +nothing in scope is left. To erase everything one user id holds across the org, an org +admin requests the `user_id` scope, which erases the user's rows in every namespace of the +org (`purge=true` deletes them rather than tombstoning them; what it leaves is listed +below). `memory.clear` tombstones one agent's or user's memories in one namespace only +([delete is not erase](#delete-is-not-erase)). | `scope_type` | `scope_value` | Who may request it | | ---------------- | --------------------------------------------------------------------------- | -------------------------------------------- | diff --git a/integrations/librechat/qualification/cases.json b/integrations/librechat/qualification/cases.json index 2c6ca539e6..a624cb18f6 100644 --- a/integrations/librechat/qualification/cases.json +++ b/integrations/librechat/qualification/cases.json @@ -12,7 +12,8 @@ "query": "On which day of the week are production deploys frozen?", "top_k": 1 } - } + }, + "use_case": "U1 Look up a stored fact" }, { "id": "memory-db-version", @@ -27,7 +28,8 @@ "query": "Which PostgreSQL version does the orders database run?", "top_k": 1 } - } + }, + "use_case": "U1 Look up a stored fact" }, { "id": "memory-oncall", @@ -42,7 +44,8 @@ "query": "How often does the payments on-call rotation hand over, and on which day?", "top_k": 1 } - } + }, + "use_case": "U1 Look up a stored fact" }, { "id": "memory-webhook-retries", @@ -57,7 +60,8 @@ "query": "How many times is a webhook delivery retried at most?", "top_k": 1 } - } + }, + "use_case": "U1 Look up a stored fact" }, { "id": "memory-backups", @@ -72,7 +76,8 @@ "query": "How long are database backups kept?", "top_k": 1 } - } + }, + "use_case": "U1 Look up a stored fact" }, { "id": "memory-revised-rate-limit", @@ -88,7 +93,8 @@ "top_k": 1 } }, - "forbid": ["\\b300\\b"] + "forbid": ["\\b300\\b"], + "use_case": "U1 Look up a stored fact" }, { "id": "inventory-count", @@ -101,7 +107,8 @@ "args": {}, "path": ["sections", 0, "count"], "equals": 10 - } + }, + "use_case": "U3 What the namespace holds" }, { "id": "inventory-top-agent", @@ -117,7 +124,8 @@ "name": "handbook-bot", "rows": 7 } - } + }, + "use_case": "U3 What the namespace holds" }, { "id": "inspect-agent", @@ -133,7 +141,8 @@ }, "path": ["own", "live_rows"], "equals": 3 - } + }, + "use_case": "U3 What the namespace holds" }, { "id": "tune-drafts", @@ -148,7 +157,8 @@ "count": true, "equals": 0 }, - "forbid": ["\\b([1-9]\\d*|one|two|three|four|five)\\s+(tuning\\s+)?(proposals?|drafts?)\\b"] + "forbid": ["\\b([1-9]\\d*|one|two|three|four|five)\\s+(tuning\\s+)?(proposals?|drafts?)\\b"], + "use_case": "U6 Write memory better" }, { "id": "cross-tenant", @@ -164,7 +174,8 @@ "query": "Project Nightjar launch", "top_k": 1 } - } + }, + "use_case": "U28 Refusals and abstentions" }, { "id": "revoked-token", @@ -178,7 +189,8 @@ "query": "On which day of the week are production deploys frozen?", "top_k": 1 } - } + }, + "use_case": "U28 Refusals and abstentions" }, { "id": "abstain-wifi", @@ -191,7 +203,8 @@ "query": "What is the office Wi-Fi password?", "top_k": 1 } - } + }, + "use_case": "U28 Refusals and abstentions" }, { "id": "abstain-cfo", @@ -204,7 +217,8 @@ "query": "Who is the chief financial officer?", "top_k": 1 } - } + }, + "use_case": "U28 Refusals and abstentions" }, { "id": "doc-release-reviews", @@ -222,7 +236,8 @@ "query": "How many approving reviews does a release need before it joins the release train?", "top_k": 5 } - } + }, + "use_case": "U2 What a document says" }, { "id": "doc-migration-rollback", @@ -240,7 +255,8 @@ "query": "How is a bad database schema migration handled: is it rolled back?", "top_k": 5 } - } + }, + "use_case": "U2 What a document says" }, { "id": "doc-canary", @@ -258,7 +274,8 @@ "query": "What share of production traffic does a canary receive, and for how long?", "top_k": 5 } - } + }, + "use_case": "U2 What a document says" }, { "id": "doc-contract-notice", @@ -276,7 +293,8 @@ "query": "How much notice stops the hosting agreement from renewing?", "top_k": 5 } - } + }, + "use_case": "U2 What a document says" }, { "id": "doc-orders-ttl", @@ -294,7 +312,8 @@ "query": "How long are rows kept in the orders table?", "top_k": 5 } - } + }, + "use_case": "U2 What a document says" }, { "id": "doc-cache-entries", @@ -312,7 +331,8 @@ "query": "What is the maximum number of entries in the session cache?", "top_k": 5 } - } + }, + "use_case": "U2 What a document says" }, { "id": "doc-revised-ack", @@ -331,7 +351,8 @@ "top_k": 5 } }, - "forbid": ["\\b(15|fifteen)\\s*min"] + "forbid": ["\\b(15|fifteen)\\s*min"], + "use_case": "U2 What a document says" }, { "id": "abstain-doc-credit", @@ -344,7 +365,8 @@ "query": "What service credit does Acme get when the hosting provider misses its uptime guarantee?", "top_k": 5 } - } + }, + "use_case": "U2 What a document says" }, { "id": "abstain-doc-phone", @@ -357,7 +379,8 @@ "query": "What is the hosting provider's escalation phone number?", "top_k": 5 } - } + }, + "use_case": "U2 What a document says" }, { "id": "analysis-per-agent", @@ -372,7 +395,8 @@ }, "path": ["rows"], "equals": [["handbook-bot", 7], ["ops-bot", 3]] - } + }, + "use_case": "U4 Usage counts and trends" }, { "id": "analysis-per-scope", @@ -387,7 +411,8 @@ }, "path": ["rows"], "equals": [["infra", 4], ["policy", 3], ["team", 2], ["runbook", 1]] - } + }, + "use_case": "U4 Usage counts and trends" }, { "id": "analysis-other-tenants", @@ -405,7 +430,8 @@ }, "path": ["rows"], "equals": [["acme", "acme-handbook", 10]] - } + }, + "use_case": "U4 Usage counts and trends" }, { "id": "recommend-key-shape", @@ -417,7 +443,8 @@ "op": "namespace.audit", "args": {}, "findings": ["hash_keys", "double_encoded_values"] - } + }, + "use_case": "U6 Write memory better" }, { "id": "recommend-runbook-plane", @@ -434,6 +461,843 @@ }, "path": ["value"], "min_chars": 2048 + }, + "use_case": "U6 Write memory better" + }, + { + "id": "help-ask-vs-search", + "kind": "help", + "use_case": "U1 Look up a stored fact", + "person": "alice", + "question": "What is the difference between memory.search and memory.ask?", + "expect": ["memory\\.search`?[^.]{0,60}(rank|hits)", "memory\\.ask`?[^.]{0,80}(synthesi|answer)"], + "cite_help": ["features/memory/search-and-ask.md", "features/unified-search.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "What is the difference between memory.search and memory.ask?", + "limit": 5 + } + }, + "samples": { + "right": [ + "`memory.search` returns ranked hits for the agent to read; `memory.ask` runs the same retrieval and writes a synthesised, cited answer." + ], + "wrong": [ + "They are the same op and return the same answer.", + "`memory.ask` returns ranked hits; `memory.search` writes a synthesised answer.", + "`memory.search` returns ranked hits; `memory.ask` does not write an answer, it returns the same hits." + ] + }, + "forbid": ["memory\\.ask`?[^.]{0,40}(does ?n[o']t|do not|never) (synthesi|write|return)"] + }, + { + "id": "help-upload-file", + "kind": "help", + "use_case": "U2 What a document says", + "person": "alice", + "question": "How do I add a PDF file to Loom as a document?", + "expect": ["knowledge\\.(upload|ingest)"], + "cite_help": ["features/knowledge.md", "reference/operations/knowledge.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "How do I add a PDF file to Loom as a document?", + "limit": 5 + } + }, + "samples": { + "right": ["Upload it with `knowledge.upload`."], + "wrong": [ + "Save its text with `memory.set`.", + "`knowledge.upload` does not accept a PDF; convert it to text first.", + "There is no `knowledge.upload`; save the text with `memory.set`." + ] + }, + "forbid": [ + "`?knowledge\\.(upload|ingest)`? (does ?n[o']t|cannot|can ?not) (take|accept|read) (a )?PDF", + "\\b(no|there is no|has no) `?knowledge\\.(upload|ingest)" + ] + }, + { + "id": "help-cost-cap", + "kind": "help", + "use_case": "U5 Cost and spend", + "person": "alice", + "question": "What is the default daily spend cap of a namespace, and what does Loom skip once it is spent?", + "expect": ["(\\$\\s?1(\\.0+)?(?!\\.?\\d)|\\b1(\\.0)? ?(USD|dollar)|\\b1\\.0(?!\\.?\\d))", "(synthes|extract)"], + "cite_help": ["features/observability/cost-and-usage.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "What is the default daily spend cap of a namespace, and what does Loom skip once it is spent?", + "limit": 5 + } + }, + "samples": { + "right": [ + "$1.0 a day; once it is spent Loom skips synthesis and entity extraction.", + "The default cap is $1. Once it is spent, Loom skips synthesis.", + "The cap is $1.0. Past it Loom skips entity extraction." + ], + "wrong": [ + "$1.0, and nothing is skipped: the cap only warns.", + "There is no default cap; extraction keeps running.", + "$1.50 a day; once it is spent Loom skips synthesis and extraction.", + "The default cap is $1.0; Loom does not skip synthesis or extraction once it is spent, it only logs." + ] + }, + "forbid": ["\\b(does ?n[o']t|do not|never|won'?t) skip"] + }, + { + "id": "help-key-shape", + "kind": "help", + "use_case": "U6 Write memory better", + "person": "alice", + "question": "What shape should a memory key have?", + "expect": ["?/?///`, readable, like `billing/decision/refund-window`."], + "wrong": [ + "Any string works; a UUID is best.", + "Scope and kind are tags, not part of the key.", + "Keys need not follow `//`; any string works." + ] + }, + "forbid": [ + "\\b(is ?n[o']t|not|need not be|need ?n[o']t be) (required|needed|followed)|\\bany (string|key) (works|is fine)" + ] + }, + { + "id": "help-history", + "kind": "help", + "use_case": "U7 History of a fact", + "person": "alice", + "question": "How do I see every earlier version of a memory?", + "expect": ["memory[._]history"], + "cite_help": ["features/memory/history-and-provenance.md", "concepts/memory.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "How do I see every earlier version of a memory?", + "limit": 5 + } + }, + "samples": { + "right": [ + "Call `memory.history` with the key.", + "`memory.get` returns only the latest version; `memory.history` returns every earlier one." + ], + "wrong": [ + "Loom keeps only the latest version.", + "Loom has no `memory.history` op; it keeps only the latest version.", + "Loom has no `memory.history` op; earlier versions are gone." + ] + }, + "forbid": ["\\b(no|there is no|has no) `?memory\\.history"] + }, + { + "id": "help-graph", + "kind": "help", + "use_case": "U8 Entity graph", + "person": "alice", + "question": "How do entities get into Loom's entity graph?", + "expect": ["memory\\.set|entities` (array|field|list)|`entities`", "extract"], + "cite_help": ["features/entity-graph.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "How do entities get into Loom's entity graph?", + "limit": 5 + } + }, + "forbid": ["\\b(entities|they) (are|is) not extracted|\\b(never|does ?n[o']t|do not|won'?t) extracts?\\b"], + "samples": { + "right": [ + "Pass them in `entities` on `memory.set`; otherwise the extractor worker extracts them from the memory's text.", + "Relations you pass on `memory.set` are not extracted from the text; `memory.set_from_messages` extracts entities and triples." + ], + "wrong": [ + "Entities are not extracted from memories; an admin adds them by hand only.", + "Entities come from `memory.set`; they are not extracted from text.", + "Pass them in `entities` on `memory.set`; Loom never extracts entities from the text." + ] + } + }, + { + "id": "help-add-repo", + "kind": "help", + "use_case": "U9 Code index", + "person": "alice", + "question": "How do I add a repository to Loom's code index?", + "expect": ["code\\.repo\\.add|Add repository|LOOM_CODE_REPOS_JSON|loom code backfill"], + "cite_help": ["features/code-index/repositories.md", "features/code-index/overview.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "How do I add a repository to Loom's code index?", + "limit": 5 + } + }, + "samples": { + "right": [ + "Use **Repositories → Add repository** in the dashboard, or call `code.repo.add`.", + "Add an entry to `LOOM_CODE_REPOS_JSON`, then run `loom code backfill`." + ], + "wrong": [ + "You cannot add a repository; Loom indexes only its own code.", + "You cannot use `code.repo.add`; only Loom's own repository is indexed.", + "There is no `code.repo.add`; Loom indexes only its own repository." + ] + }, + "forbid": [ + "(cannot|can ?not|can't) (call|use) `?code\\.repo\\.add", + "\\b(no|there is no|has no) `?code\\.repo\\.add" + ] + }, + { + "id": "help-conflict", + "kind": "help", + "use_case": "U10 Conflicts and refusal", + "person": "alice", + "question": "What happens when I write a memory that conflicts with one already stored?", + "expect": ["flag|status.{0,5}conflicted|both (stay|rows)", "Review|conflicts\\.resolve"], + "cite_help": ["features/memory/conflicts-and-refusal.md", "concepts/memory.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "What happens when I write a memory that conflicts with one already stored?", + "limit": 5 + } + }, + "samples": { + "right": [ + "The new row is stored and flagged as a conflict; the namespace owner decides in the Review queue or with `conflicts.resolve`.", + "The new row is stored and flagged as a conflict; the owner decides in the Review queue or with `conflicts.resolve`. A pair on the allowlist is not flagged." + ], + "wrong": [ + "The new write overwrites the old one.", + "Loom refuses the write and asks you to resolve the conflict.", + "Loom does not flag it; the new write wins with no Review queue entry or `conflicts.resolve`." + ] + }, + "forbid": ["(Loom|it|the (new )?write)\\s+(does ?n[o']t|do not|never) (flag|mark)"] + }, + { + "id": "help-collection", + "kind": "help", + "use_case": "U11 Sharing and collections", + "person": "alice", + "question": "What is a collection in Loom, and how is one shared?", + "expect": [ + "col-|only grants open|grant-only|opens? only (through|by|via) grants?", + "grants?\\b[^.]{0,40}\\bon it|(by|via|with|through) (a |its )?`?grants?|grant(s|ing)? (a |an )?(user|group|agent|principal|`?everyone)|grants? on (one|it|a collection)" + ], + "cite_help": [ + "concepts/identities-and-namespaces.md", + "architecture/sharing.md", + "features/namespaces-and-sharing.md" + ], + "baseline": { + "op": "help.search", + "args": { + "query": "What is a collection in Loom, and how is one shared?", + "limit": 5 + } + }, + "samples": { + "right": [ + "A collection is a `col-…` namespace that opens only through grants; you share it by creating grants on it.", + "A collection is a namespace that only grants open; no token claim or org admin role reaches it. Share it by granting a user, group, agent or `everyone` a role on it.", + "A collection is a namespace named `col-…` that only grants open; a grant on one can name a `user:`, `group:` or `agent:` principal, or `everyone`." + ], + "wrong": [ + "A collection is a folder of documents; share it with a link.", + "A `col-` namespace is shared by putting it in the token's claims; no grant is needed.", + "A `col-` namespace is shared through its token claims; no grant on it is needed." + ] + }, + "forbid": ["\\bno grants?( on it)? (is |are )?(needed|required)"] + }, + { + "id": "help-my-role", + "kind": "help", + "use_case": "U12 My role and who can change it", + "person": "alice", + "question": "Can I write memories in this namespace? If not, how would I get that?", + "expect": ["viewer", "(admin|grant)"], + "cite_help": [ + "concepts/identities-and-namespaces.md", + "guides/tokens-and-grants.md", + "features/namespaces-and-sharing.md" + ], + "baseline": { + "op": "help.search", + "args": { + "query": "Can I write memories in this namespace? If not, how would I get that?", + "limit": 5 + } + }, + "forbid": ["\\byou (can|may) already write\\b", "\\bviewers? (can|may) write"], + "samples": { + "right": [ + "You are a viewer here, so you cannot write; an admin can grant you writer.", + "No: you are a viewer here. Ask an admin to grant you writer; once granted, you can write here." + ], + "wrong": [ + "Yes, you can write here.", + "You are an admin, so you can write.", + "You can already write here as a viewer.", + "You are a viewer, but you can already write here; an admin can grant more.", + "You are a viewer; viewers can write here, no admin grant needed." + ] } + }, + { + "id": "help-claude-code", + "kind": "help", + "use_case": "U13 Connect a coding agent", + "person": "alice", + "question": "How do I connect Claude Code to Loom?", + "expect": ["claude plugin (marketplace add|install)"], + "cite_help": ["getting-started/connect-a-coding-agent.md", "features/integrations/claude-code.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "How do I connect Claude Code to Loom?", + "limit": 5 + } + }, + "samples": { + "right": ["Run `claude plugin marketplace add ClickHouse/loom`, then install the plugin."], + "wrong": [ + "Install a Loom editor extension and paste your token.", + "`claude plugin install loom` doesn't work; there is no Loom plugin, so paste the token into an editor extension." + ] + }, + "forbid": ["\\b(does ?n[o']t|do not|cannot|can't) (work|connect)\\b|\\bthere is no (Loom )?plugin"] + }, + { + "id": "help-revoke-token", + "kind": "help", + "use_case": "U14 Tokens", + "person": "alice", + "question": "How do I revoke a Loom token?", + "expect": ["revoke-token|service_accounts\\.revoke|Settings\\W+Tokens|revok\\w* it (there|in the dashboard)"], + "cite_help": ["guides/tokens-and-grants.md", "reference/cli.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "How do I revoke a Loom token?", + "limit": 5 + } + }, + "samples": { + "right": [ + "Run `loom revoke-token --jti `.", + "Revoke it under Settings → Tokens in the dashboard; that ends it in every tool at once." + ], + "wrong": [ + "Tokens cannot be revoked; wait for them to expire.", + "There is no `loom revoke-token` command; tokens cannot be revoked, only left to expire." + ] + }, + "forbid": ["\\b(no|there is no) `?(loom )?revoke-token"] + }, + { + "id": "help-models-keys", + "kind": "help", + "use_case": "U15 Models and keys", + "person": "alice", + "question": "Where do I configure the LLM that Loom uses, and its API key?", + "expect": ["(LOOM_LLM_(MODEL|PROVIDER)|Models (&|and) keys)"], + "cite_help": ["getting-started/models-and-keys.md", "reference/configuration.md"], + "baseline": { + "op": "help.search", + "args": { + "query": "Where do I configure the LLM that Loom uses, and its API key?", + "limit": 5 + } + }, + "samples": { + "right": [ + "On the server: set `LOOM_LLM_PROVIDER` and `LOOM_LLM_MODEL`, and the provider's key, or use the dashboard's Models & keys page." + ], + "wrong": [ + "Each namespace picks its model in its profile.", + "There is no `LOOM_LLM_MODEL` or Models & keys page; each namespace picks its model." + ] + }, + "forbid": ["\\b(no|there is no) `?(LOOM_LLM_(MODEL|PROVIDER)|Models (&|and) keys)"] + }, + { + "id": "help-health-assistant", + "kind": "help", + "use_case": "U16 Health problems", + "person": "alice", + "question": "What does the health problem assistant_service_failing mean?", + "expect": [ + "LibreChat", + "(set ?up|setup|regist\\w*|sign-?in|creat\\w*)[^.]{0,80}((? None: (leave it out when the hit has none), for example [guides/setup.md § Setup > Install]. Add the revision, as in [guides/setup.md § Setup > Install, revision 3], only when a tool returned that document's revision number; never write a revision no tool returned. -When the tools return nothing relevant, say it is not stored in Loom. When a tool call -fails, say that it failed and quote the error. Never answer from your own knowledge.""" +For a question about how Loom itself works, search Loom's documentation with +loom_help_search_mcp_loom and read a section with loom_help_get_mcp_loom; cite each passage +as [help: §
], the section as the hit gives it. When the tools return nothing +relevant, say it is not stored in Loom, or, for a question about Loom itself, that Loom's +documentation does not cover it. When a tool call fails, say that it failed and quote the +error. Never answer from your own knowledge.""" def lc_login(lc: httpx.Client, email: str, password: str) -> str: @@ -398,6 +403,9 @@ def ask_assistant(st: dict[str, Any], person: str, question: str) -> dict[str, A text: list[str] = [] usage: dict[str, Any] = {} error = "" + checked: list[dict[str, Any]] = [] + unknown: list[str] = [] + support = "" with httpx.stream("POST", url, json=body, headers=headers, timeout=180) as r: if r.status_code != 200: error = f"HTTP {r.status_code}: {r.read().decode()[:300]}" @@ -406,6 +414,12 @@ def ask_assistant(st: dict[str, Any], person: str, question: str) -> dict[str, A if not line.startswith("data: ") or line == "data: [DONE]": continue chunk = json.loads(line[6:]) + if chunk.get("object") == "loom.citations": + # The bridge's own check of the answer's citations, and its names. + checked = chunk.get("citations") or [] + unknown = chunk.get("unknown_names") or [] + support = str(chunk.get("support") or "") + continue if chunk.get("error"): error = json.dumps(chunk["error"])[:300] usage = chunk.get("usage") or usage @@ -426,6 +440,9 @@ def ask_assistant(st: dict[str, Any], person: str, question: str) -> dict[str, A "first_text_s": first_text, "prompt_tokens": usage.get("prompt_tokens", 0), "completion_tokens": usage.get("completion_tokens", 0), + "server_citations": checked, + "unknown_names": unknown, + "support": support, } @@ -465,10 +482,11 @@ def matches(patterns: tuple[str, ...] | list[str], text: str) -> bool: def check_citations( - st: dict[str, Any], person: dict[str, Any], text: str + st: dict[str, Any], person: dict[str, Any], text: str, history_ok: bool = False ) -> tuple[list[str], list[str]]: """Every memory key the answer names, and those that do not exist in the person's namespace - or name a version other than the row's current one.""" + or name a version other than the row's current one. With `history_ok` (a question about + a key's history), an earlier version the key had is valid too.""" ns = person["namespace"] scorer = st["tokens"][f"scorer:{ns}"] # memory.get over HTTP reads one writer's row; the fixture says who wrote each key. @@ -482,35 +500,70 @@ def check_citations( cited: list[str] = [] invalid: list[str] = [] current: dict[str, int | None] = {} # each key's current version, read once - found = list(KEY_RE.finditer(text)) - for i, m in enumerate(found): - key = m.group(0) + versions: dict[str, set[int]] = {} # each key's every version, read when one is cited + + def body(key: str) -> dict[str, Any]: + return { + "org": person["org"], + "namespace": ns, + "memory_key": key, + "agent": writers.get(key, "-"), + } + + def history(key: str) -> set[int]: + # The key exists: a failed read says nothing about the answer. + if key not in versions: + rows = scorer_read(st, scorer, "memory.history", body(key)).get("rows") or [] + versions[key] = {int(r["version"]) for r in rows if r.get("version")} + return versions[key] + + for key, version in memory_mentions(st, text): if key not in current: cited.append(key) - body = { - "org": person["org"], - "namespace": ns, - "memory_key": key, - "agent": writers.get(key, "-"), - } - code, out, _ = loom_call(st["loom_url"], scorer, "memory.get", body) - ok = code == 200 and out.get("found", True) and out.get("version") + # A key that is not there (found: false) is the answer's fault and is marked + # invalid; a read that fails says nothing about it, so scorer_read waits out a + # 429 and stops the run on anything else. + out = scorer_read(st, scorer, "memory.get", body(key)) + ok = out.get("found", True) and out.get("version") current[key] = int(out["version"]) if ok else None if current[key] is None: invalid.append(key) - if current[key] is None: + if current[key] is None or version is None or version == current[key]: continue - # Every mention is checked: a version belongs to the key before it, up to the next key. - end = min(m.end() + 80, found[i + 1].start() if i + 1 < len(found) else len(text)) - # A bare version, or the deployed agent's `[memory:@v]`. - near = re.search(r"(?:\b|@v)(\d{16,20})\b", text[m.end() : end]) - if near and int(near.group(1)) != current[key]: - stale = f"{key}@{near.group(1)}" - if stale not in invalid: - invalid.append(stale) + # An earlier version cites what the key once held: valid in an answer about its + # history, and stale anywhere else. + if history_ok and version in history(key): + continue + stale = f"{key}@{version}" + if stale not in invalid: + invalid.append(stale) return cited, invalid +# A memory and a code citation as Loom's assistant writes them +# (`server.assistant.domain.citations`). +MEMORY_CITE_RE = re.compile(r"\[memory:(?P[^\]\s]+)@v(?P\d+)\]") +CODE_CITE_RE = re.compile(r"\[code:(?P[^\]\s]+?):(?P\d+)\]") + + +def memory_mentions(st: dict[str, Any], text: str) -> list[tuple[str, int | None]]: + """Each memory key an answer cites, with the version it names (None for none). Through + Loom's assistant a citation is `[memory:@v]`, so a key-shaped example it + quotes from the docs (`scope/kind/id`) is none. Otherwise a key is any key-shaped text + outside a help citation (whose page path is no key), with the version written after it, + up to the next key.""" + if st.get("bridge"): + return [(m["key"], int(m["version"])) for m in MEMORY_CITE_RE.finditer(text)] + keyed = HELP_CITE_RE.sub("", text) + found = list(KEY_RE.finditer(keyed)) + mentions: list[tuple[str, int | None]] = [] + for i, m in enumerate(found): + end = min(m.end() + 80, found[i + 1].start() if i + 1 < len(found) else len(keyed)) + near = re.search(r"(?:\b|@v)(\d{16,20})\b", keyed[m.end() : end]) + mentions.append((m.group(0), int(near.group(1)) if near else None)) + return mentions + + def parse_doc_citations(text: str) -> list[dict[str, Any]]: """The document citations an answer writes, in order: each a source_uri, a section breadcrumb ('' when none is named) and a revision (None when none is named).""" @@ -527,6 +580,151 @@ def parse_doc_citations(text: str) -> list[dict[str, Any]]: return out +# A help citation as the instructions ask for it: `[help: § B>]`, the section +# optional. +HELP_CITE_RE = re.compile(r"\[help:(?P[^\]§\s]+?)(?:\s*§\s*(?P
[^\]]+?))?\s*\]") +# How an answer says the documentation does not cover a question. +HELP_ABSTAIN_PATTERNS = ( + r"\bnot (documented|covered|described|mentioned|listed|in (loom's|the) documentation)\b", + r"\b(documentation|docs) (does|do) ?n[o']t (cover|describe|mention|say|list)\b", + r"\b(there is|there's|\w+ has) no (\w+ ){0,3}(setting|option|feature)s?\b", + r"\bno (\w+ ){0,3}setting (changes|sets|controls|exists|for)\b", + r"\b(is|are) ?n[o']t (configurable|settable)\b", + r"\b(does ?n[o']t|do not) (have|offer|provide|expose) an? (\w+ ){0,3}(setting|option)", + r"\bis ?n[o']t an? (\w+ ){0,3}(setting|option)", + r"\b(could ?n[o']t|did ?n[o']t|can ?not) find\b", + # The sentence the agent ends an abstention with (agent.yaml), after all three searches. + r"\bnothing stored in loom\b", +) + + +DOCS = HERE.parents[2] / "docs" +# A whole name: not the prefix of a family written as `LOOM_RETENTION_*`. +SETTING_RE = re.compile(r"\bLOOM_[A-Z0-9_]*[A-Z0-9](?![A-Z0-9_])") +# A settings family a docs page writes with placeholders (`LOOM_RETENTION__DAYS`, +# `LOOM_RETENTION_*`). +SETTING_FAMILY_RE = re.compile(r"\bLOOM_[A-Z0-9_]*(?:(?:<[A-Z]+>|(?<=_)\*)[A-Z0-9_]*)+") +# The kinds whose right answer is an abstention: from the namespace, or from the docs. +ABSTAIN_KINDS = ("abstain", "help_abstain") + + +@functools.cache +def shipped_docs() -> tuple[str, ...]: + """The text of every docs page the server ships (the help index skips `development/`).""" + return tuple( + page.read_text(encoding="utf-8") + for page in sorted(DOCS.rglob("*.md")) + if not page.relative_to(DOCS).as_posix().startswith("development/") + ) + + +@functools.cache +def documented_settings() -> frozenset[str]: + """Every `LOOM_*` name a shipped docs page writes. Close to the documentation half of + the server's unknown-name check (`server.assistant.domain.names`), not the same rule: + that one reads the help index's identifiers, and has no placeholder families.""" + # A family written with placeholders documents its members, not its bare prefix. + return frozenset( + name + for text in shipped_docs() + for name in SETTING_RE.findall(SETTING_FAMILY_RE.sub("", text)) + ) + + +@functools.cache +def documented_families() -> tuple[re.Pattern[str], ...]: + """Each settings family the docs write with placeholders, as the pattern its members + match: `LOOM_RETENTION_
_DAYS` takes `LOOM_RETENTION_EVENTS_DAYS`, not + `LOOM_RETENTION_THEME`.""" + # A placeholder right after `LOOM_` (`LOOM_`, `LOOM_*`) names the scheme. + families = { + f + for text in shipped_docs() + for f in SETTING_FAMILY_RE.findall(text) + if not f.startswith(("LOOM_<", "LOOM_*")) + } + return tuple( + re.compile( + "".join( + "[A-Z0-9_]+" if part.startswith("<") or part == "*" else re.escape(part) + for part in re.split(r"(<[A-Z]+>|\*)", family) + if part + ) + ) + for family in sorted(families) + ) + + +def undocumented_settings(text: str) -> list[str]: + """The `LOOM_*` names an answer writes that no docs page does, as a name or as a member + of a family it writes with placeholders: a setting the answer made up, even one it + names to deny.""" + names = set(SETTING_RE.findall(text)) - documented_settings() + return sorted(n for n in names if not any(f.fullmatch(n) for f in documented_families())) + + +def is_help_case(case: dict[str, Any]) -> bool: + """A question about Loom itself: its direct path is help.search.""" + return case["baseline"]["op"] == "help.search" + + +def check_help_citations( + st: dict[str, Any], person: dict[str, Any], case: dict[str, Any], text: str +) -> tuple[list[str], list[str], bool]: + """Every help citation the answer writes, those that are not valid, and whether one + of the case's labeled pages is among the valid ones. Valid: the page is in the + server's documentation and a named section is one of its own (help.get with the + scorer's token, no model).""" + scorer = st["tokens"][f"scorer:{person['namespace']}"] + cited: list[str] = [] + invalid: list[str] = [] + pages = set(case.get("cite_help") or []) + expected = False + for m in HELP_CITE_RE.finditer(text): + name = m.group(0)[1:-1] + if name in cited: + continue + cited.append(name) + # The path as cited: help.get strips one `docs/` itself, as the bridge's check does, + # and answers 422 past 300 characters, which would stop the run. + if len(m["path"]) > 300: + invalid.append(f"{name}: no such page") + continue + page = scorer_read(st, scorer, "help.get", {"path": m["path"]}) + if not page.get("available", True): + # A server with no docs cannot check the citation; that says nothing about it. + sys.exit( + "help.get: this server has no documentation, so help citations cannot be checked" + ) + if not page.get("found"): + invalid.append(f"{name}: no such page") + continue + # A section that is only separators (`§ >`) cites the page, as the server reads it. + breadcrumb = help_breadcrumb(m["section"] or "") + if breadcrumb and not names_section( + breadcrumb, [help_breadcrumb(e["section"]) for e in page.get("sections", [])] + ): + invalid.append(f"{name}: no such section") + continue + expected = expected or m["path"].removeprefix("docs/") in pages + return cited, invalid, expected + + +def names_section(cited: tuple[str, ...], sections: list[tuple[str, ...]]) -> bool: + """Whether a cited breadcrumb names one of a page's sections, as the server's check reads + it (`server.help.domain.index.find_section`): equal to one, equal to one without the + page title, or a tail only one section of the page has.""" + if cited in sections or any(s[1:] == cited for s in sections): + return True + return sum(s[-len(cited) :] == cited for s in sections) == 1 + + +def help_breadcrumb(section: str) -> tuple[str, ...]: + """A help breadcrumb as its headings, as the server reads it + (`server.help.domain.index.section_path`): each trimmed, case and inner spacing kept.""" + return tuple(part.strip() for part in section.split(">") if part.strip()) + + def section_key(section: str) -> tuple[str, ...]: """A breadcrumb compared case- and spacing-blind: `A > B` and `a >b` are one section.""" return tuple(" ".join(p.split()).casefold() for p in section.split(">") if p.strip()) @@ -554,7 +752,7 @@ def scorer_read(st: dict[str, Any], token: str, op: str, body: dict[str, Any]) - break time.sleep(retry_after(out)) if code != 200: - sys.exit(f"scorer {op} {body.get('source_uri')}: {code} {out}") + sys.exit(f"scorer {op} {json.dumps(body)}: {code} {out}") return out @@ -619,10 +817,17 @@ def check_doc_citations( def score(case: dict[str, Any], text: str) -> dict[str, Any]: """Score a written answer: the labeled values present, no forbidden text.""" kind = case["kind"] - abstained = matches(ABSTAIN_PATTERNS, text) or ( - is_document_case(case) and matches(DOC_ABSTAIN_PATTERNS, text) - ) - if kind == "abstain": + if is_help_case(case): + # A question about Loom: an abstention says the documentation does not cover it. + abstained = matches(HELP_ABSTAIN_PATTERNS, text) + else: + abstained = matches(ABSTAIN_PATTERNS, text) or ( + is_document_case(case) and matches(DOC_ABSTAIN_PATTERNS, text) + ) + if kind == "help_abstain": + # It says the docs leave it open, and invents no setting for it. + correct = abstained and not undocumented_settings(text) + elif kind == "abstain": correct = abstained elif kind == "refusal": correct = matches(REFUSAL_PATTERNS, text) @@ -632,6 +837,14 @@ def score(case: dict[str, Any], text: str) -> dict[str, Any]: return {"correct": correct, "abstained": abstained} +def score_answer(case: dict[str, Any], got: dict[str, Any]) -> dict[str, Any]: + """Score an answer through LibreChat: its text, and wrong when it names an op or setting + the build neither serves nor documents (the bridge's `unknown_names`).""" + result = score(case, got["answer"] or got["error"]) + result["correct"] = result["correct"] and not got.get("unknown_names") + return result + + # ---------------------------------------------------------------- run @@ -662,9 +875,14 @@ def native_score(case: dict[str, Any], code: int, out: dict[str, Any]) -> dict[s spec = case["baseline"] cited: list[str] = [] abstained = False + expected: bool | None = None # set below where the direct path can cite the labeled source if code != 200: text = f"{code} {out.get('detail', out)}" - correct = case["kind"] == "refusal" + # The direct path of a question the docs leave open is not scored, whatever answered. + correct = None if case["kind"] == "help_abstain" else case["kind"] == "refusal" + # A failed read cites nothing: a source it could have cited counts as not cited. + can_cite = (case.get("cite") and spec["op"] == "memory.search") or case.get("cite_help") + expected = False if can_cite else None elif spec["op"] == "memory.search": hits = out.get("results") or [] abstained = bool(out.get("abstain")) or not hits @@ -675,8 +893,20 @@ def native_score(case: dict[str, Any], code: int, out: dict[str, Any]) -> dict[s cited = [hits[0]["memory_key"]] correct = abstained if case["kind"] == "abstain" else score(case, text)["correct"] correct = correct and case["kind"] != "refusal" + expected = case.get("cite") in cited if case.get("cite") else None elif spec["op"] == "knowledge.search": return native_document_score(case, out) + elif spec["op"] == "help.search": + # The direct path finds the page; it writes no answer, so only that is scored. A + # question the docs leave open has no page to find, and a word search finds some + # page for any question, so that case's direct path is not scored (None). + pages = [h["path"] for h in out.get("hits") or []] + text = json.dumps(pages) + wanted = set(case.get("cite_help") or []) + correct = bool(wanted & set(pages)) if wanted else None + cited = pages[:1] + # The labeled page as its top hit, as the LibreChat side counts the page it cites. + expected = bool(pages) and pages[0] in wanted if wanted else None elif "findings" in spec: # A recommendation's direct path: the audit names each labeled finding on rows. found = {f["code"] for f in out.get("findings", []) if f.get("count")} @@ -701,7 +931,7 @@ def native_score(case: dict[str, Any], code: int, out: dict[str, Any]) -> dict[s "tool_calls": 1, "cited": cited, "invalid_citations": [], - "cited_expected": case.get("cite") in cited if case.get("cite") else None, + "cited_expected": expected, } @@ -739,16 +969,29 @@ def native_document_score(case: dict[str, Any], out: dict[str, Any]) -> dict[str } +def require_docs(st: dict[str, Any], people: dict[str, Any], cases: list[dict[str, Any]]) -> None: + """Stop before the first read when the server ships no docs: any answer may cite a help + page, and a help citation or a help case cannot be checked then.""" + if not cases: + return + # The scorer's token, through scorer_read: a 429 is waited out and any other failure + # stops the run, so a probe that cannot read never lets a no-docs run go on. + scorer = st["tokens"][f"scorer:{people[cases[0]['person']]['namespace']}"] + out = scorer_read(st, scorer, "help.search", {"query": "loom", "limit": 1}) + if not out.get("available", True): + sys.exit("help.search: this server has no documentation, so its help cannot be checked") + + def cmd_run(args: argparse.Namespace) -> None: st = state() people = {p["name"]: p for p in load("fixture.json")["people"]} if args.native_only: run_native_only(st, people, args) return + cases = [c for c in load("cases.json") if not args.only or c["id"] in args.only] + require_docs(st, people, cases) rows = [] - for case in load("cases.json"): - if args.only and case["id"] not in args.only: - continue + for case in cases: person = people[case["person"]] native = baseline(st, case, person) t0 = time.time() @@ -757,11 +1000,12 @@ def cmd_run(args: argparse.Namespace) -> None: time.sleep(2) # the ledger write is asynchronous calls = loom_calls(args.ch_url, case["person"], t0, t1) text = got["answer"] or got["error"] - result = score(case, text) + result = score_answer(case, got) rows.append( { "id": case["id"], "kind": case["kind"], + "use_case": case["use_case"], "documents": is_document_case(case), "librechat": { **got, @@ -779,27 +1023,40 @@ def cmd_run(args: argparse.Namespace) -> None: ) lc = rows[-1]["librechat"] print( - f"{case['id']:<28} librechat {'ok ' if lc['correct'] else 'BAD'} " + f"{case['id']:<28} librechat {verdict(lc['correct'])} " f"{lc['latency_s']:5.1f}s tools={lc['tool_calls']} | " - f"native {'ok ' if native['correct'] else 'BAD'} {native['latency_s']:.2f}s" + f"native {verdict(native['correct'])} {native['latency_s']:.2f}s" ) if args.cancel_probe: rows.append(cancel_probe(st, args)) - Path(args.out).write_text(json.dumps({"model": st.get("model"), "rows": rows}, indent=2)) + # Which path the answers took: through the bridge, a memory citation is `[memory:…]` only. + saved = {"model": st.get("model"), "bridge": bool(st.get("bridge")), "rows": rows} + Path(args.out).write_text(json.dumps(saved, indent=2)) print(report(rows, st.get("model", ""))) def answer_citations( st: dict[str, Any], case: dict[str, Any], person: dict[str, Any], text: str ) -> dict[str, Any]: - """The memory keys and document passages an answer cites, the invalid ones, and whether - the labeled key or section is among them (None when the case labels neither).""" - cited, invalid = check_citations(st, person, text) + """The memory keys, document passages and help pages an answer cites, the invalid ones, + and whether the labeled key, section or page is among them: False for a case that labels + a help page when the answer cites none, None when the case labels nothing.""" + cited, invalid = check_citations(st, person, text, history_ok=bool(case.get("cite_history"))) expected = case.get("cite") in cited if case.get("cite") else None if is_document_case(case): - doc_cited, doc_invalid, doc_expected = check_doc_citations(st, person, case, text) + # Help, memory and code citations (`[help:…]`, `[memory:…]`, `[code:…]`) are not + # documents. + doc_text = CODE_CITE_RE.sub("", MEMORY_CITE_RE.sub("", HELP_CITE_RE.sub("", text))) + doc_cited, doc_invalid, doc_expected = check_doc_citations(st, person, case, doc_text) cited, invalid = cited + doc_cited, invalid + doc_invalid expected = doc_expected if case.get("cite_doc") else None + if HELP_CITE_RE.search(text): + help_cited, help_invalid, help_expected = check_help_citations(st, person, case, text) + cited, invalid = cited + help_cited, invalid + help_invalid + if case.get("cite_help"): + expected = help_expected + elif case.get("cite_help"): + expected = False return {"cited": cited, "invalid_citations": invalid, "cited_expected": expected} @@ -816,14 +1073,15 @@ def run_native_only(st: dict[str, Any], people: dict[str, Any], args: argparse.N sys.exit(f"{out} is missing: --native-only replaces the native side of a saved run") saved = json.loads(out.read_text()) rows = {r["id"]: r for r in saved["rows"]} - for case in load("cases.json"): - if case["id"] in rows and (not args.only or case["id"] in args.only): - rows[case["id"]]["native"] = baseline(st, case, people[case["person"]]) - native = rows[case["id"]]["native"] - print( - f"{case['id']:<28} native {'ok ' if native['correct'] else 'BAD'} " - f"{native['latency_s']:.2f}s" - ) + cases = [ + c for c in load("cases.json") if c["id"] in rows and (not args.only or c["id"] in args.only) + ] + require_docs(st, people, cases) + for case in cases: + rows[case["id"]]["use_case"] = case["use_case"] + rows[case["id"]]["native"] = baseline(st, case, people[case["person"]]) + native = rows[case["id"]]["native"] + print(f"{case['id']:<28} native {verdict(native['correct'])} {native['latency_s']:.2f}s") out.write_text(json.dumps(saved, indent=2)) print(report(saved["rows"], saved.get("model", ""))) @@ -835,13 +1093,17 @@ def cmd_rescore(args: argparse.Namespace) -> None: saved = json.loads(Path(args.out).read_text()) cases = {c["id"]: c for c in load("cases.json")} people = {p["name"]: p for p in load("fixture.json")["people"]} - st = state() if args.citations else {} + # The answers' own path decides how their memory citations read, not the current state. + if args.citations and "bridge" not in saved: + sys.exit(f"{args.out} does not say which path its answers took: run it again") + st = {**state(), "bridge": saved["bridge"]} if args.citations else {} for row in saved["rows"]: if row["kind"] != "cancel": lc = row["librechat"] case = cases[row["id"]] text = lc["answer"] or lc["error"] - lc.update(score(case, text)) + row["use_case"] = case["use_case"] + lc.update(score_answer(case, lc)) if args.citations: lc.update(answer_citations(st, case, people[case["person"]], text)) Path(args.out).write_text(json.dumps(saved, indent=2)) @@ -929,6 +1191,15 @@ def pct(values: list[float], q: float) -> float: return values[min(len(values) - 1, round(q * (len(values) - 1)))] +def verdict(correct: bool | None) -> str: + """A case's line in a run's log: `- ` for a path that is not scored.""" + return "- " if correct is None else "ok " if correct else "BAD" + + +def yes_no(correct: bool | None) -> str: + return "-" if correct is None else "yes" if correct else "no" + + def fmt_s(seconds: float | None, digits: int = 2, unit: str = "") -> str: return "-" if seconds is None else f"{seconds:.{digits}f}{unit}" @@ -947,13 +1218,14 @@ def report(rows: list[dict[str, Any]], model: str) -> str: f"| {r['id']} | {r['kind']} | {'yes' if lc['correct'] else 'no'} | {len(lc['cited'])} " f"({len(lc['invalid_citations'])}) | {lc['tool_calls']} | {lc['latency_s']:.1f} | " f"{ttft} | " - f"{'yes' if nv['correct'] else 'no'} | {nv['latency_s']:.2f} |" + f"{yes_no(nv['correct'])} | {nv['latency_s']:.2f} |" ) # The document cases are reported on their own lines (document_report). others = [r for r in cases if not r.get("documents")] if others: for side in ("librechat", "native"): got = [r[side] for r in others] + scored = [g for g in got if g["correct"] is not None] lat = [g["latency_s"] for g in got] ttft = [g["ttft_s"] for g in got if g["ttft_s"] is not None] cited = sum(len(g["cited"]) for g in got) @@ -961,16 +1233,18 @@ def report(rows: list[dict[str, Any]], model: str) -> str: # The direct path cites the search hit itself, so its citations are not checked. validity = "-" if side == "native" else f"{cited - invalid}/{cited} valid" expected = [g["cited_expected"] for g in got if g["cited_expected"] is not None] - abst = [r for r in others if r["kind"] == "abstain"] + abst = [ + r for r in others if r["kind"] in ABSTAIN_KINDS and r[side]["correct"] is not None + ] false_abst = [ r for r in others - if r["kind"] not in ("abstain", "refusal") and r[side]["abstained"] + if r["kind"] not in (*ABSTAIN_KINDS, "refusal") and r[side]["abstained"] ] lines.append( - f"\n{side}: correct {sum(g['correct'] for g in got)}/{len(got)}; " + f"\n{side}: correct {sum(g['correct'] for g in scored)}/{len(scored)}; " f"citations {validity}, " - f"expected key cited {sum(expected)}/{len(expected)}; " + f"expected source cited {sum(expected)}/{len(expected)}; " f"abstained {sum(r[side]['correct'] for r in abst)}/{len(abst)} where it should, " f"{len(false_abst)} false abstentions; " f"latency p50 {pct(lat, 0.5):.2f}s p95 {pct(lat, 0.95):.2f}s; " @@ -978,6 +1252,7 @@ def report(rows: list[dict[str, Any]], model: str) -> str: f"tool calls {sum(g['tool_calls'] for g in got)}" ) lines.extend(document_report(cases)) + lines.extend(use_case_report(cases)) price_in, price_out = PRICE_PER_MTOK.get(model, (float("nan"), float("nan"))) costs = [ ( @@ -1000,6 +1275,33 @@ def report(rows: list[dict[str, Any]], model: str) -> str: return "\n".join(lines) +def use_case_report(cases: list[dict[str, Any]]) -> list[str]: + """Per use case (cases.json `use_case`): the answers through LibreChat that are + correct, those with no invalid citation, and the unknown names they wrote.""" + by: dict[str, list[dict[str, Any]]] = {} + for r in cases: + by.setdefault(r.get("use_case") or "-", []).append(r) + lines = [ + "\n| use case | correct | no invalid citation | unknown names |", + "| --- | --- | --- | --- |", + ] + for name in sorted(by, key=use_case_order): + got = [r["librechat"] for r in by[name]] + valid = sum(not g["invalid_citations"] for g in got) + unknown = sorted({n for g in got for n in g.get("unknown_names") or []}) + lines.append( + f"| {name} | {sum(g['correct'] for g in got)}/{len(got)} | {valid}/{len(got)} " + f"| {', '.join(unknown) or '-'} |" + ) + return lines + + +def use_case_order(name: str) -> tuple[int, str]: + """`U2` before `U10`: by the use case's number, an unlabeled case last.""" + number = name.split()[0][1:] + return (int(number) if name[:1] == "U" and number.isdigit() else 1_000_000, name) + + def document_report(cases: list[dict[str, Any]]) -> list[str]: """The document cases on their own: recall of the labeled section among the direct path's hits, citation validity, the labeled section cited, and abstention.""" diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py index a1af5c7aeb..9681046813 100644 --- a/server/operations/reach_manifest.py +++ b/server/operations/reach_manifest.py @@ -249,7 +249,11 @@ "sdk_method", "dashboard", ), - "help.get": ("dashboard",), + "help.get": ( + "plugin_hook", + "dashboard", + ), + "help.search": ("plugin_hook",), "inbox.list": ("dashboard",), "inbox.policy_list": ("dashboard",), "inbox.policy_set": ("dashboard",), @@ -410,6 +414,7 @@ "memory.health": ("dashboard",), "memory.history": ( "sdk_method", + "plugin_hook", "dashboard", ), "memory.import_curated": ("dashboard",), diff --git a/tests/unit/test_librechat_integration.py b/tests/unit/test_librechat_integration.py index 6fb340e98a..b22746fa03 100644 --- a/tests/unit/test_librechat_integration.py +++ b/tests/unit/test_librechat_integration.py @@ -178,9 +178,14 @@ def test_native_score_compares_counts_as_numbers(): def test_check_citations_flags_unknown_keys_and_stale_versions(monkeypatch): q = _qualify() rows = {"policy/deploy/freeze": 1793745407448901606} + # An earlier version of a key is a valid citation of what it once held. + history = {"policy/deploy/freeze": [1793745407448901606, 1793745400000000000]} def fake_call(base, token, op, body): - assert op == "memory.get" and token == "viewer-token" + assert op in ("memory.get", "memory.history") and token == "viewer-token" + if op == "memory.history": + versions = history.get(body["memory_key"], []) + return 200, {"rows": [{"version": v} for v in versions]}, 0.0 version = rows.get(body["memory_key"]) return 200, {"found": version is not None, "version": version}, 0.0 @@ -202,6 +207,10 @@ def fake_call(base, token, op, body): ["policy/deploy/freeze"], ["policy/deploy/freeze@1793745407000000000"], ) + earlier = "Before: `policy/deploy/freeze` (version 1793745400000000000)." + assert q.check_citations(st, person, earlier, history_ok=True) == (["policy/deploy/freeze"], []) + # Outside a question about history, an earlier version cited is stale. + assert q.check_citations(st, person, earlier)[1] == ["policy/deploy/freeze@1793745400000000000"] unknown = "See policy/deploy/thaw." assert q.check_citations(st, person, unknown) == ( ["policy/deploy/thaw"], @@ -634,7 +643,7 @@ def side(correct, rank=None, cited=(), invalid=(), expected=None, abstained=Fals ] text = q.report(rows, "m") # Document rows stay out of the memory-key summary line. - assert "\nlibrechat: " not in text and "expected key cited" not in text + assert "\nlibrechat: " not in text and "expected source cited" not in text assert "2 answerable and 1 unanswerable cases; labeled section at rank 1 1/2" in text assert "within the top 5 2/2" in text assert ( @@ -710,7 +719,9 @@ def fake_call(base, token, op, body): row = {"id": "doc-revised-ack", "kind": "document", "documents": True} out = tmp_path / "results.json" out.write_text( - json.dumps({"model": "m", "rows": [{**row, "librechat": side, "native": native}]}) + json.dumps( + {"model": "m", "bridge": False, "rows": [{**row, "librechat": side, "native": native}]} + ) ) q.cmd_rescore(argparse.Namespace(out=str(out), citations=True)) got = json.loads(out.read_text())["rows"][0]["librechat"] @@ -747,3 +758,638 @@ def fake_call(base, token, op, body): # Every document is written before any revision of one. first = {b["source_uri"]: i for i, b in reversed(list(enumerate(docs)))} assert docs.index(next(b for b in docs if b["content"] == writes[-1])) > max(first.values()) + + +_HELP_PAGE = """# Cost and usage + +## Daily spend caps + +Text. + +## Limits + +### Daily spend caps + +More. + +## Webhooks + +### Retries +""" + + +@pytest.mark.parametrize( + "breadcrumb", + [ + "Cost and usage > Webhooks > Retries", # exact + "Webhooks > Retries", # without the page title + "Retries", # a tail one section has + "Daily spend caps", # a tail two sections have + "Limits > Daily spend caps", + "webhooks > retries", # the server compares case + "Web hooks > Retries", + " Webhooks >Retries ", # and trims each heading + "Cost and usage", + ], +) +def test_help_section_rule_is_the_servers(breadcrumb): + from server.help.domain.index import build, find_section, page_sections, section_path + + q = _qualify() + index = build([("features/cost.md", _HELP_PAGE)]) + sections = [s.breadcrumb for s in page_sections(index, "features/cost.md")] + server = find_section(index, "features/cost.md", section_path(breadcrumb)) is not None + assert q.names_section(q.help_breadcrumb(breadcrumb), sections) is server + + +def test_check_help_citations_reads_the_page_and_its_sections(monkeypatch): + q = _qualify() + + def fake_read(st, token, op, body): + assert op == "help.get" and token == "viewer-token" + # help.get strips one `docs/` prefix, as the server does. + if body["path"].removeprefix("docs/") != "features/cost.md": + return {"found": False} + return {"found": True, "sections": [{"section": "Cost and usage > Daily spend caps"}]} + + monkeypatch.setattr(q, "scorer_read", fake_read) + st = {"tokens": {"scorer:acme-handbook": "viewer-token"}} + person = {"namespace": "acme-handbook"} + case = {"cite_help": ["features/cost.md"]} + text = ( + "[help:docs/features/cost.md § Daily spend caps] " + "[help:features/cost.md § daily spend caps] " + "[help:features/other.md] " + "[help:features/cost.md § >] " # only separators: the page itself, as the server reads it + "[help:docs/docs/features/cost.md]" # one prefix is stripped, as the bridge strips it + ) + cited, invalid, expected = q.check_help_citations(st, person, case, text) + assert cited == [ + "help:docs/features/cost.md § Daily spend caps", + "help:features/cost.md § daily spend caps", + "help:features/other.md", + "help:features/cost.md § >", + "help:docs/docs/features/cost.md", + ] + assert invalid == [ + "help:features/cost.md § daily spend caps: no such section", + "help:features/other.md: no such page", + "help:docs/docs/features/cost.md: no such page", + ] + assert expected is True + + +def test_memory_citations_skip_help_pages_and_quoted_examples(monkeypatch): + q = _qualify() + asked = [] + + def fake_call(base, token, op, body): + asked.append(body["memory_key"]) + return 200, {"found": True, "version": 1793745407448901606}, 0.0 + + monkeypatch.setattr(q, "loom_call", fake_call) + st = {"loom_url": "http://loom", "tokens": {"scorer:acme-handbook": "viewer-token"}} + person = {"org": "acme", "namespace": "acme-handbook"} + text = ( + "Keys look like `scope/kind/id` [help:features/memory/writing.md § Keys]. " + "The freeze: [memory:policy/deploy/freeze@v1793745407448901606]." + ) + # A help page's path is no key; straight through LibreChat (no bridge) a quoted example + # still reads as one. + assert q.check_citations(st, person, text)[0] == ["scope/kind/id", "policy/deploy/freeze"] + # Through the bridge only a `[memory:]` citation is a memory citation. + asked.clear() + assert q.check_citations({**st, "bridge": True}, person, text) == ( + ["policy/deploy/freeze"], + [], + ) + assert asked == ["policy/deploy/freeze"] + + +def test_a_help_abstention_and_an_unknown_name_are_scored(): + q = _qualify() + case = {"kind": "help_abstain", "expect": [], "baseline": {"op": "help.search"}} + said = {"answer": "Loom's documentation doesn't cover a colour theme.", "error": ""} + assert q.score_answer(case, said) == {"correct": True, "abstained": True} + guessed = {"answer": "Set LOOM_DASHBOARD_THEME=dark.", "error": ""} + assert q.score_answer(case, guessed)["correct"] is False + # A right answer that names an op the build neither serves nor documents is wrong. + case = {"kind": "fact", "expect": [r"revoke-token"], "baseline": {"op": "help.search"}} + answer = {"answer": "Run `loom revoke-token`.", "error": ""} + assert q.score_answer(case, answer)["correct"] is True + assert q.score_answer(case, {**answer, "unknown_names": ["token.revoke_all"]}) == { + "correct": False, + "abstained": False, + } + + +def test_the_direct_path_does_not_score_a_question_the_docs_leave_open(): + q = _qualify() + case = {"kind": "help_abstain", "cite_help": [], "baseline": {"op": "help.search"}} + hit = {"hits": [{"path": "features/dashboard.md"}]} + assert q.native_score(case, 200, hit)["correct"] is None + case = {"kind": "fact", "cite_help": ["features/dashboard.md"], "baseline": case["baseline"]} + assert q.native_score(case, 200, hit)["correct"] is True + + +def test_report_counts_a_help_abstention_and_orders_the_use_cases(): + q = _qualify() + + def side(correct, abstained=False): + return { + "correct": correct, + "abstained": abstained, + "cited": [], + "invalid_citations": [], + "cited_expected": None, + "tool_calls": 1, + "latency_s": 1.0, + "ttft_s": 0.5, + "prompt_tokens": 0, + "completion_tokens": 0, + } + + rows = [ + { + "id": f"case-{n}", + "kind": "fact", + "use_case": f"U{n} Case {n}", + "librechat": side(True), + "native": side(True), + } + for n in (10, 2, 1) + ] + rows.append( + { + "id": "help-undocumented", + "kind": "help_abstain", + "use_case": "U28 Refusals and abstentions", + "librechat": side(True, abstained=True), + "native": side(None), + } + ) + text = q.report(rows, "m") + assert "librechat: correct 4/4;" in text + assert "abstained 1/1 where it should, 0 false abstentions" in text + # The direct path does not score that case. + assert "native: correct 3/3;" in text and "abstained 0/0 where it should" in text + order = [line.split(" | ")[0][2:] for line in text.splitlines() if line.startswith("| U")] + assert order == ["U1 Case 1", "U2 Case 2", "U10 Case 10", "U28 Refusals and abstentions"] + + +def test_a_help_answer_is_read_for_an_abstention_from_the_docs(): + q = _qualify() + case = {"kind": "help", "expect": [r"revoke-token"], "baseline": {"op": "help.search"}} + left_open = "Loom's documentation doesn't cover revoking every token at once." + assert q.score(case, left_open)["abstained"] is True + # A how-to answer that quotes an error is no abstention. + quoted = "`loom revoke-token` answers `not found` for a token it doesn't have." + assert q.score(case, quoted) == {"correct": True, "abstained": False} + + +def test_the_connected_agents_direct_path_counts_the_agents(): + q = _qualify() + case = _case("data-connected-agents") + + def inventory(agents): + return { + "populations": [{"population": p, "total": 0} for p in ("members",)] + + [{"population": "agents", "total": agents}] + + [{"population": p, "total": 0} for p in ("authors", "subjects")] + } + + assert q.native_score(case, 200, inventory(2))["correct"] is True + assert q.native_score(case, 200, inventory(1))["correct"] is False + + +def _saved_side(answer, **extra): + return { + "answer": answer, + "error": "", + "correct": True, + "abstained": False, + "cited": [], + "invalid_citations": [], + "cited_expected": None, + "tool_calls": 1, + "latency_s": 1.0, + "ttft_s": 0.5, + "prompt_tokens": 0, + "completion_tokens": 0, + **extra, + } + + +def test_rescore_keeps_the_unknown_name_rule_and_takes_the_current_labels(tmp_path): + import argparse + + q = _qualify() + answer = "Run `loom revoke-token `; `token.revoke_all` revokes them all." + side = _saved_side(answer, unknown_names=["token.revoke_all"]) + row = {"id": "help-revoke-token", "kind": "help", "use_case": "-"} + out = tmp_path / "results.json" + out.write_text(json.dumps({"model": "m", "rows": [{**row, "librechat": side, "native": side}]})) + q.cmd_rescore(argparse.Namespace(out=str(out), citations=False)) + got = json.loads(out.read_text())["rows"][0] + assert got["librechat"]["correct"] is False + assert got["use_case"] == _case("help-revoke-token")["use_case"] + + +def test_a_help_answer_that_cites_no_page_misses_the_labeled_one(monkeypatch): + q = _qualify() + monkeypatch.setattr(q, "check_citations", lambda st, person, text, **_: ([], [])) + case = _case("help-revoke-token") + person = {"namespace": "acme-handbook"} + got = q.answer_citations({}, case, person, "Run `loom revoke-token`.") + assert got == {"cited": [], "invalid_citations": [], "cited_expected": False} + # A memory key cited beside the page does not decide it: the labeled page does. + monkeypatch.setattr(q, "check_citations", lambda st, person, text, **_: (["a/b/c"], [])) + monkeypatch.setattr( + q, "check_help_citations", lambda st, person, case, text: (["help:x.md"], [], False) + ) + got = q.answer_citations({}, {**case, "cite": "a/b/c"}, person, "[help:x.md]") + assert got["cited_expected"] is False + + +def test_a_question_the_docs_leave_open_is_held_to_the_documented_settings(): + q = _qualify() + case = _case("help-undocumented") + # A real variable named beside the abstention is fine; an invented one is not, and the + # bridge's unknown names count too. + real = _saved_side("The docs don't cover a theme; `LOOM_COLOUR` picks a deployment.") + assert q.score_answer(case, real)["correct"] is True + assert q.score_answer(case, {**real, "unknown_names": ["LOOM_X"]})["correct"] is False + assert q.undocumented_settings("set LOOM_UI_THEME, not LOOM_COLOUR") == ["LOOM_UI_THEME"] + + +def test_the_history_direct_path_counts_the_keys_versions(): + q = _qualify() + case = _case("data-history") + assert case["baseline"]["op"] == "memory.history" + two = {"rows": [{"version": 2}, {"version": 1}]} + assert q.native_score(case, 200, two)["correct"] is True + assert q.native_score(case, 200, {"rows": [{"version": 1}]})["correct"] is False + + +def _help_cases(): + return [ + c + for c in json.loads((QUAL / "cases.json").read_text()) + if c["baseline"]["op"] == "help.search" + ] + + +@pytest.mark.parametrize("case", _help_cases(), ids=lambda c: c["id"]) +def test_each_help_label_passes_its_right_samples_and_fails_its_wrong_ones(case): + q = _qualify() + samples = case["samples"] + assert samples["right"] and samples["wrong"] + for answer in samples["right"]: + assert q.score_answer(case, {"answer": answer, "error": ""})["correct"], answer + for answer in samples["wrong"]: + assert not q.score_answer(case, {"answer": answer, "error": ""})["correct"], answer + + +def test_a_document_answer_that_cites_a_help_page_checks_it_as_help(monkeypatch): + q = _qualify() + docs_read = [] + monkeypatch.setattr(q, "check_citations", lambda st, person, text, **_: ([], [])) + + def fake_docs(st, person, case, text): + docs_read.append(text) + return [], [], False + + monkeypatch.setattr(q, "check_doc_citations", fake_docs) + monkeypatch.setattr( + q, "check_help_citations", lambda st, person, case, text: (["help:a.md"], [], False) + ) + case = _case("doc-cache-entries") + got = q.answer_citations({}, case, {"namespace": "acme-library"}, "See [help:a.md § A].") + assert docs_read == ["See ."] + assert got["cited"] == ["help:a.md"] and got["invalid_citations"] == [] + + +def test_rescore_reads_memory_citations_by_the_saved_runs_path(monkeypatch, tmp_path): + import argparse + + q = _qualify() + seen = [] + + def fake_citations(st, case, person, text): + seen.append(st.get("bridge")) + return {"cited": [], "invalid_citations": [], "cited_expected": None} + + monkeypatch.setattr(q, "answer_citations", fake_citations) + # The current state is the bridge's; the saved run went straight through LibreChat. + monkeypatch.setattr(q, "state", lambda: {"bridge": True}) + side = _saved_side("The freeze is on Fridays (policy/deploy/freeze).") + out = tmp_path / "results.json" + row = {"id": "memory-freeze", "kind": "memory", "librechat": side, "native": side} + out.write_text(json.dumps({"model": "m", "bridge": False, "rows": [row]})) + q.cmd_rescore(argparse.Namespace(out=str(out), citations=True)) + assert seen == [False] + + +@pytest.mark.parametrize( + "case", [c for c in _help_cases() if c.get("forbid")], ids=lambda c: c["id"] +) +def test_each_help_forbid_is_what_fails_one_wrong_sample(case): + q = _qualify() + # Each pattern has a wrong sample that the label and the other patterns let through. + for pattern in case["forbid"]: + others = [f for f in case["forbid"] if f != pattern] + reached = [ + a + for a in case["samples"]["wrong"] + if q.score({**case, "forbid": others}, a)["correct"] and not q.score(case, a)["correct"] + ] + assert reached, (case["id"], pattern) + + +def test_a_memory_citation_in_a_document_answer_is_no_document(monkeypatch): + q = _qualify() + read = [] + monkeypatch.setattr(q, "check_citations", lambda st, person, text, **_: ([], [])) + monkeypatch.setattr( + q, + "check_doc_citations", + lambda st, person, case, text: read.append(text) or ([], [], False), + ) + q.answer_citations({}, _case("doc-cache-entries"), {}, "A [memory:a/b/c@v1793745407448901606].") + assert read == ["A ."] + + +def test_through_the_bridge_a_memory_citation_is_read_whole(): + q = _qualify() + text = "`user/pref/example` [memory:user/pref/john_doe@v1793745407448901606]" + assert q.memory_mentions({"bridge": True}, text) == [ + ("user/pref/john_doe", 1793745407448901606) + ] + + +def test_rescore_asks_for_a_new_run_when_the_saved_path_is_unknown(tmp_path): + import argparse + + q = _qualify() + out = tmp_path / "results.json" + out.write_text(json.dumps({"model": "m", "rows": []})) + with pytest.raises(SystemExit, match="which path"): + q.cmd_rescore(argparse.Namespace(out=str(out), citations=True)) + + +def test_the_use_case_report_lists_each_use_cases_unknown_names(): + q = _qualify() + rows = [ + { + "use_case": "U14 Tokens", + "librechat": _saved_side("a", unknown_names=["token.revoke_all"]), + }, + {"use_case": "U14 Tokens", "librechat": _saved_side("b", correct=False)}, + {"use_case": "U1 Look up a stored fact", "librechat": _saved_side("c")}, + ] + lines = q.use_case_report(rows) + assert "| U1 Look up a stored fact | 1/1 | 1/1 | - |" in lines + assert "| U14 Tokens | 1/2 | 2/2 | token.revoke_all |" in lines + + +def test_native_only_takes_the_cases_current_use_case_labels(monkeypatch, tmp_path): + import argparse + + q = _qualify() + side = _saved_side("ok") + monkeypatch.setattr(q, "baseline", lambda st, case, person: side) + monkeypatch.setattr(q, "require_docs", lambda st, people, cases: None) + out = tmp_path / "results.json" + row = {"id": "help-revoke-token", "kind": "help", "librechat": side, "native": side} + out.write_text(json.dumps({"model": "m", "bridge": True, "rows": [row]})) + people = {p["name"]: p for p in q.load("fixture.json")["people"]} + q.run_native_only({}, people, argparse.Namespace(out=str(out), only=[])) + saved = json.loads(out.read_text())["rows"][0] + assert saved["use_case"] == _case("help-revoke-token")["use_case"] + + +def test_the_harness_reads_citations_in_the_servers_own_forms(): + from server.assistant.domain import citations + + q = _qualify() + assert q.MEMORY_CITE_RE.pattern == citations._MEMORY.pattern + assert q.CODE_CITE_RE.pattern == citations._CODE.pattern + assert q.HELP_CITE_RE.pattern == citations._HELP.pattern + + +def test_a_documented_settings_family_member_is_documented(): + q = _qualify() + assert q.undocumented_settings("`LOOM_WEBHOOK_SECRET_ACME__HOOK`") == [] + assert q.undocumented_settings("`LOOM_RETENTION_EVENTS_DAYS`") == [] + # A family's prefix alone documents nothing: the placeholder's suffix must be there. + assert q.undocumented_settings("`LOOM_RETENTION_THEME`") == ["LOOM_RETENTION_THEME"] + assert q.undocumented_settings("`LOOM_RETENTION`") == ["LOOM_RETENTION"] + # A family written with a wildcard (`LOOM_CH_*`) documents its members. + assert q.undocumented_settings("`LOOM_CH_HOST`") == [] + assert q.undocumented_settings("`LOOM_UI_THEME`") == ["LOOM_UI_THEME"] + + +def test_a_history_case_takes_an_earlier_version_through_the_bridge(monkeypatch): + q = _qualify() + + def fake_call(base, token, op, body): + if op == "memory.history": + return 200, {"rows": [{"version": 2}, {"version": 1}]}, 0.0 + return 200, {"found": True, "version": 2}, 0.0 + + monkeypatch.setattr(q, "loom_call", fake_call) + st = {"loom_url": "u", "bridge": True, "tokens": {"scorer:acme-handbook": "t"}} + person = {"org": "acme", "namespace": "acme-handbook"} + text = "Before: [memory:policy/api/rate-limit@v1]; now [memory:policy/api/rate-limit@v2]." + assert q.check_citations(st, person, text, history_ok=True) == (["policy/api/rate-limit"], []) + assert q.check_citations(st, person, text)[1] == ["policy/api/rate-limit@1"] + + +@pytest.mark.parametrize( + "case", json.loads((QUAL / "cases.json").read_text()), ids=lambda c: c["id"] +) +def test_every_case_names_its_use_case_and_cites_pages_that_exist(case): + assert re.fullmatch(r"U\d+ \S.*", case.get("use_case", "")), case["id"] + for page in case.get("cite_help") or []: + # The help index skips development/, so a page there can never be cited. + assert (ROOT / "docs" / page).is_file() and not page.startswith("development/"), page + + +def test_a_help_citation_past_help_gets_limit_is_no_page(monkeypatch): + q = _qualify() + monkeypatch.setattr(q, "scorer_read", lambda *a: pytest.fail("help.get was called")) + st = {"tokens": {"scorer:acme-handbook": "t"}} + long = "a/" * 150 + "x.md" + cited, invalid, _ = q.check_help_citations( + st, {"namespace": "acme-handbook"}, {}, f"[help:{long}]" + ) + assert invalid == [f"help:{long}: no such page"] + + +def test_a_failed_direct_read_of_the_no_docs_question_is_not_scored(): + q = _qualify() + case = _case("help-undocumented") + assert q.native_score(case, 503, {"detail": "unavailable"})["correct"] is None + + +def test_ask_assistant_reads_the_bridges_citations_event(monkeypatch): + q = _qualify() + # The event as server.assistant.app.bridge writes it after the answer's text. + event = { + "object": "loom.citations", + "id": "run-1", + "choices": [], + "citations": [{"kind": "help", "text": "[help:a.md]", "verified": True}], + "support": "supported", + "unknown_names": ["token.revoke_all"], + } + lines = [ + 'data: {"choices": [{"delta": {"content": "Answer."}}]}', + f"data: {json.dumps(event)}", + "data: [DONE]", + ] + + class Response: + status_code = 200 + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def iter_lines(self): + return iter(lines) + + monkeypatch.setattr(q, "answer_request", lambda st, person, question: ("u", {}, {})) + monkeypatch.setattr(q.httpx, "stream", lambda *a, **k: Response()) + got = q.ask_assistant({}, "alice", "q") + assert got["answer"] == "Answer." + assert got["server_citations"] == event["citations"] + assert got["unknown_names"] == ["token.revoke_all"] and got["support"] == "supported" + + +def test_the_help_direct_path_counts_its_top_hit_as_the_expected_page(): + q = _qualify() + case = _case("help-revoke-token") + top = {"hits": [{"path": case["cite_help"][0]}, {"path": "other.md"}]} + assert q.native_score(case, 200, top)["cited_expected"] is True + second = {"hits": [{"path": "other.md"}, {"path": case["cite_help"][0]}]} + assert q.native_score(case, 200, second)["cited_expected"] is False + assert q.native_score(_case("help-undocumented"), 200, top)["cited_expected"] is None + + +def test_a_failed_direct_read_cites_no_labeled_source(): + q = _qualify() + assert ( + q.native_score(_case("help-revoke-token"), 503, {"detail": "x"})["cited_expected"] is False + ) + assert q.native_score(_case("memory-freeze"), 503, {"detail": "x"})["cited_expected"] is False + + +def test_a_case_whose_direct_path_cannot_cite_leaves_the_count_either_way(): + q = _qualify() + case = _case("data-history") + assert q.native_score(case, 503, {"detail": "x"})["cited_expected"] is None + two = {"rows": [{"version": 2}, {"version": 1}]} + assert q.native_score(case, 200, two)["cited_expected"] is None + + +def test_a_failed_memory_read_stops_the_check_rather_than_marking_the_key(monkeypatch): + q = _qualify() + calls = [] + + def fake_call(base, token, op, body): + calls.append(op) + return ( + (429, {"detail": {"retry_after_s": 0}}, 0.0) + if len(calls) == 1 + else ( + 200, + {"found": True, "version": 1793745407448901606}, + 0.0, + ) + ) + + monkeypatch.setattr(q, "loom_call", fake_call) + monkeypatch.setattr(q.time, "sleep", lambda s: None) + st = {"loom_url": "u", "tokens": {"scorer:acme-handbook": "t"}} + person = {"org": "acme", "namespace": "acme-handbook"} + text = "`policy/deploy/freeze` (version 1793745407448901606)" + assert q.check_citations(st, person, text) == (["policy/deploy/freeze"], []) + monkeypatch.setattr(q, "loom_call", lambda *a: (503, {"detail": "down"}, 0.0)) + with pytest.raises(SystemExit): + q.check_citations(st, person, "`policy/deploy/other`") + + +def test_markdown_bold_is_no_settings_family(): + q = _qualify() + assert q.SETTING_FAMILY_RE.findall("**LOOM_COLOUR** and LOOM_CH_*") == ["LOOM_CH_*"] + + +@pytest.mark.parametrize("case", _help_cases(), ids=lambda c: c["id"]) +def test_every_help_case_with_a_claim_forbids_its_denial(case): + # The question the docs leave open has no claim to deny; every other help case does. + assert case["kind"] == "help_abstain" or case.get("forbid"), case["id"] + + +@pytest.mark.parametrize( + "case", [c for c in _help_cases() if c.get("forbid")], ids=lambda c: c["id"] +) +def test_no_help_forbid_matches_the_pages_the_case_cites(case): + # An answer that quotes its own page must never trip the case's forbid. + for page in case["cite_help"]: + text = (ROOT / "docs" / page).read_text(encoding="utf-8") + for pattern in case["forbid"]: + assert not re.search(pattern, text, re.IGNORECASE | re.MULTILINE), (page, pattern) + + +@pytest.mark.parametrize("case", _help_cases(), ids=lambda c: c["id"]) +def test_no_help_label_is_met_by_repeating_the_question(case): + # An answer that only echoes the question (a setting or problem name in it) states nothing. + for pattern in case["expect"]: + assert not re.search(pattern, case["question"], re.IGNORECASE), pattern + + +def test_a_server_without_docs_stops_the_help_checks(monkeypatch): + q = _qualify() + monkeypatch.setattr(q, "scorer_read", lambda *a: {"available": False, "found": False}) + st = {"tokens": {"scorer:acme-handbook": "t"}} + with pytest.raises(SystemExit, match="no documentation"): + q.check_help_citations(st, {"namespace": "acme-handbook"}, {}, "[help:a.md]") + monkeypatch.setattr(q, "loom_call", lambda *a: (200, {"available": False, "hits": []}, 0.0)) + st = {"loom_url": "u", "tokens": {"scorer:acme-handbook": "t"}} + people = {p["name"]: p for p in q.load("fixture.json")["people"]} + # A data case can cite a help page too, so even a run of data cases stops first. + with pytest.raises(SystemExit, match="no documentation"): + q.require_docs(st, people, [_case("memory-freeze")]) + + +def test_a_run_checks_for_docs_before_any_answer(monkeypatch): + import argparse + + q = _qualify() + monkeypatch.setattr( + q, "state", lambda: {"loom_url": "u", "tokens": {"scorer:acme-handbook": "t"}} + ) + monkeypatch.setattr(q, "loom_call", lambda *a: (200, {"available": False, "hits": []}, 0.0)) + monkeypatch.setattr(q, "ask_assistant", lambda *a: pytest.fail("a model answer was asked for")) + args = argparse.Namespace(native_only=False, only=["help-revoke-token"], out="unused") + with pytest.raises(SystemExit, match="no documentation"): + q.cmd_run(args) + + +def test_the_docs_probe_stops_the_run_when_it_cannot_read(monkeypatch): + q = _qualify() + sent = [] + + def fake_call(base, token, op, body): + sent.append((token, body)) + return 401, {"detail": "revoked"}, 0.0 + + monkeypatch.setattr(q, "loom_call", fake_call) + st = {"loom_url": "u", "tokens": {"scorer:acme-handbook": "scorer-token"}} + people = {p["name"]: p for p in q.load("fixture.json")["people"]} + with pytest.raises(SystemExit): + q.require_docs(st, people, [_case("revoked-token"), _case("help-revoke-token")]) + assert sent == [("scorer-token", {"query": "loom", "limit": 1})]