From 05ae3bb99d57f8c4a0299694391edc87d0a4b3ff Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 07:57:21 +0000 Subject: [PATCH 1/3] skill.usage reports which revisions of a namespace's skills were fetched `skill.usage` is a new experimental read that needs viewer on the namespace it names. It folds the acts of the namespace's skills and one grouped statement over the request ledger's answered `skill.get` rows. For each skill the caller can list it answers the published revision, one entry for each fetched revision (sessions, principals, the last fetch, and the looks of the dashboard, the assistant and a command that shows a skill), the stale codes `draft_waiting` and `unknown_operation`, and a statement in words. Every count is a lower bound, and the report's statement says what the ledger cannot show. `by_subject` names who fetched each revision and needs admin on the namespace. `loom skill usage [/]` prints the report. A skill's page gains a Fetches tab, and the Skills list and a skill's page label a stale skill. The five generated SDKs carry the op. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/skills.md | 25 + docs/features/dashboard.md | 22 +- docs/features/skills.md | 45 +- docs/guides/without-the-dashboard.md | 1 + docs/reference/cli.md | 2 +- docs/reference/operations.md | 3 +- docs/reference/operations/skill.md | 20 + docs/reference/status.md | 4 +- frontend/e2e/fixtures.ts | 3 + frontend/e2e/skills.spec.ts | 4 +- frontend/src/api/skills.ts | 76 +++ frontend/src/lib/callReason.ts | 1 + frontend/src/views/Skills.test.tsx | 77 ++- frontend/src/views/Skills.tsx | 88 +++- frontend/src/views/skills/FetchesTab.test.tsx | 163 ++++++ frontend/src/views/skills/FetchesTab.tsx | 155 ++++++ frontend/src/views/skills/stale.tsx | 44 ++ sdk/go/client.gen.go | 28 + sdk/go/wire/models.gen.go | 52 ++ sdk/python/loom/cli_skill.py | 23 +- sdk/python/loom/cli_skill_usage.py | 110 ++++ sdk/python/loom/client.py | 6 + sdk/python/loom/ops.py | 69 +++ sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 10 +- sdk/rust/src/blocking_operations.rs | 17 + sdk/rust/src/operations.rs | 18 + sdk/rust/src/wire_models.rs | 166 ++++++ sdk/rust/tests/registry_contracts.rs | 16 + sdk/typescript/src/generated/ops.ts | 48 +- server/cli/login.py | 4 +- server/identity/api/models_skills.py | 96 ++++ server/identity/api/ops_skills.py | 15 + server/identity/app/skill_usage.py | 156 ++++++ server/identity/app/skills.py | 9 +- server/identity/domain/skill_usage.py | 251 +++++++++ server/identity/store/skill_fetches.py | 69 +++ server/identity/store/skills.py | 16 + server/operations/reach_manifest.py | 4 + server/settings/catalog.py | 5 + tests/analyzer/cases/planes.py | 16 +- tests/analyzer/shapes.txt | 2 + .../test_cross_principal_leakage.py | 98 ++++ .../test_skill_independent_review.py | 79 ++- tests/unit/skill_store.py | 80 ++- tests/unit/snapshots/cli_help.json | 2 +- tests/unit/snapshots/cli_tree.json | 2 +- tests/unit/snapshots/sdk_public_api.json | 4 + tests/unit/test_sdk_skill_usage_command.py | 186 +++++++ tests/unit/test_skill_usage.py | 493 ++++++++++++++++++ 49 files changed, 2844 insertions(+), 39 deletions(-) create mode 100644 frontend/src/views/skills/FetchesTab.test.tsx create mode 100644 frontend/src/views/skills/FetchesTab.tsx create mode 100644 frontend/src/views/skills/stale.tsx create mode 100644 sdk/python/loom/cli_skill_usage.py create mode 100644 server/identity/app/skill_usage.py create mode 100644 server/identity/domain/skill_usage.py create mode 100644 server/identity/store/skill_fetches.py create mode 100644 tests/unit/test_sdk_skill_usage_command.py create mode 100644 tests/unit/test_skill_usage.py diff --git a/docs/architecture/skills.md b/docs/architecture/skills.md index 140374b7cc..83d2236d80 100644 --- a/docs/architecture/skills.md +++ b/docs/architecture/skills.md @@ -344,6 +344,30 @@ A published skill reaches a session unasked as one line of the `skills` section - **Tenant isolation.** The read scopes by `org` and by the namespaces the fan-out resolved for the caller's token, so it holds no namespace the caller may not read. `tests/integration/test_cross_principal_leakage.py` holds the case of a namespace granted and never opened. - **Rolling upgrade.** [Rolling upgrades](rolling-upgrades.md), rule 98. +### The usage report + +`skill.usage` answers which revisions of a namespace's skills were fetched, and which skills are stale. It is a read of two things Loom already holds, and stores nothing. + +| Loom knows | Loom does not know | +| --------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| Which revision is published and when: the `publish` rows of `loom.skills` | Which sessions were shown a [listing line](#the-session-listing): a line is no row | +| Each answered `skill.get`: a request ledger row with the content hash it answered | Whether a copy pulled to a folder is read: the pull is one fetch, a later read none | +| Who asked, in which session, over which transport and under which consumer: the same row | What a session did with the text it asked for | +| That the dashboard, the assistant and a command that shows a skill looked: the row's consumer | A request whose ledger row was dropped | + +So the report says "fetched", gives every count as a lower bound, and never says a skill is installed, active or adopted. + +- **Two reads and a row.** One read of `loom.skills` by `(org, namespace)` for the acts of every skill, without `content` or `files` (`usage_acts`); one statement over the request ledger (`FETCHES` in `server/identity/store/skill_fetches.py`); and the namespace's registry row, for the days it keeps its ledger. The acts are read with sequential consistency ([what that covers](clickhouse.md#read-your-writes)), so no reader is reported a skill an archive on another replica stopped. +- **What counts as a fetch.** A ledger row of a successful `skill.get`, not a worker's, whose `out_content_sha256` is the hash of a revision that the fold calls published, superseded or withdrawn, and whose time is past the second of that revision's first `publish` row. A `publish` row keeps whole seconds, so a read in that second may be a writer's read of the draft and is not counted. The ledger keeps the hash a read answered and never the number: of two published revisions with one hash, the higher is named. A draft's hash, a rejected revision's and a void one's are not in the statement's parameters, so no row of theirs is read. +- **The statement.** It filters by `org`, `namespace`, the window and the operation, keeps the rows whose hash is one of the published hashes from that hash's time on (two bound arrays), and groups by hash, session, principal, consumer and transport with a count and the first and the last time. It returns the most recent 10,000 groups and one more (`FETCH_GROUPS_MAX`): the extra group tells a cut read from a whole one, and the report's statement says when the read was cut. The ledger is sorted by `(org, namespace, agent, ts)` and partitioned by month, so the read prunes to the namespace's rows of the window's months. The window is at most 90 days, and never longer than the days the namespace keeps its ledger. +- **The counts.** `server/identity/domain/skill_usage.py` makes one entry a revision of the groups: the distinct sessions (a row with no session counts its principal only), the distinct principals, and the last fetch. A group whose consumer is an inspector's (`INSPECTOR_CONSUMERS`) counts in neither and is summed as `inspector_fetches`. `loom skill pull` names no consumer, so a pull is a fetch. +- **The sentences.** The report's `statement` and each skill's are built in that one module from the counts: that counts are lower bounds, that a listing shown to a session is not recorded, how many of the namespace's skills a listing can carry and in what order, whether the window or the ledger read was cut, and for each skill the revisions fetched or that none was. The command and the dashboard print them and write none of their own for a count. +- **Stale codes.** A closed set of strings, each proven by rows the skill holds: `draft_waiting` (the open draft's `save` row is more than 14 days old, `DRAFT_WAITING_DAYS`) and `unknown_operation` (a stored `op_names` entry of the served revision that the answering build's registry does not hold). Both thresholds are constants, so a code means the same on every deployment. No fetch is no code: a pulled copy is read without one. +- **Tenant isolation.** The op needs `viewer` on the namespace it names. The caller is reported the skills `skill.list` lists to it (`listed_row`): a writer every skill, any other reader the ones that serve a revision, and `draft_waiting` is a writer's as the draft is. The published hashes of a skill the caller is not reported are not in the ledger statement's parameters. A name the caller cannot list answers no skill, as a name that does not exist does. `by_subject` names principals, so it needs `admin` on the namespace and is refused with 403 to anyone else: the refusal confirms nothing, since the namespace is the one the caller named. `tests/integration/test_cross_principal_leakage.py` holds the case. +- **A failed read fails the op.** An error of the ledger statement is the op's error. A skill is never answered as not fetched because the ledger could not be read. +- **Rolling upgrade.** The op adds no table, column or stored value. A replica one release behind answers 404 for it: the command exits 2 and says the server does not serve it, and the dashboard shows no stale label and one line on the **Fetches** tab. +- **Cost.** `OP_BUDGETS_P99_MS` holds the op's budget. The acts read is the one `skill.list` makes for one namespace. The ledger statement reads the namespace's ledger rows of the window; the dashboard's list asks a one-day window, because it shows the codes and no count. + ### Erasure and retention `loom.skills` holds memory content. A namespace erasure deletes the namespace's rows in the step `skills.delete`, and its census counts what is left (`server/erasure/store/census.py`). A user erasure has no step for the table: every row's `user_id` is `-`, and a skill names no end user. The table has no TTL, so a revision is kept until an administrator deletes it or its namespace is erased. @@ -399,6 +423,7 @@ These hold for `skill.check`. The ones of a save are [above](#invariants-of-a-sa - Tests of a decision and the published reads: `tests/unit/test_skill_decide.py`, `tests/unit/test_skill_reads_published.py`, `tests/unit/test_inspector_consumers.py`, `tests/unit/test_sdk_skill_review_commands.py`, `tests/integration/test_skill_independent_review.py`, `tests/integration/test_skill_decide.py`, and the published case of `tests/integration/test_cross_principal_leakage.py`. - Tests of the namespace token: `tests/unit/test_skill_binding.py`, `tests/unit/test_skill_literal_namespace_finding.py`, `tests/integration/test_skill_binding.py`, and the token cases of `tests/unit/test_sdk_skill_commands.py` and `frontend/src/views/Skills.test.tsx`. - The session listing: `server/identity/domain/skill_format.py` (`listing_line`, `listing`), `server/identity/app/skills.py` (`session_listing`), `server/memory/app/context_pack.py` (`_pack_skills`), `server/transport/mcp_primer.py` (the sentence). Tests: `tests/unit/test_skill_listing.py`, `tests/unit/test_context_pack_skills.py`, `tests/unit/test_mcp_primer_order.py`, and the listing cases of `tests/unit/test_sdk_skill_commands.py`, `tests/integration/test_cross_principal_leakage.py` and `frontend/src/views/Skills.test.tsx`. +- The usage report: `server/identity/app/skill_usage.py` (`handle_skill_usage`), `server/identity/domain/skill_usage.py` (`published`, `hash_times`, `counts`, `subjects`, `stale_codes`, `skill_statement`, `report_statement`), `server/identity/store/skill_fetches.py` (`FETCHES`, `fetch_groups`), `sdk/python/loom/cli_skill_usage.py` (the command), `frontend/src/views/skills/FetchesTab.tsx`. Tests: `tests/unit/test_skill_usage.py`, `tests/unit/test_sdk_skill_usage_command.py`, `frontend/src/views/skills/FetchesTab.test.tsx`, and the usage cases of `tests/integration/test_skill_independent_review.py`, `tests/integration/test_cross_principal_leakage.py` and `frontend/src/views/Skills.test.tsx`. - Tests of a delete: `tests/unit/test_skill_delete.py`, `tests/unit/test_skill_delete_statement.py`, `tests/unit/test_hidden_op_says_why.py`, and the delete cases of `tests/unit/test_sdk_skill_save_command.py`, `tests/integration/test_skill_drafts.py` and `tests/integration/test_cross_principal_leakage.py`. ## Related diff --git a/docs/features/dashboard.md b/docs/features/dashboard.md index 495dcb5dc8..c66ff53aac 100644 --- a/docs/features/dashboard.md +++ b/docs/features/dashboard.md @@ -102,7 +102,7 @@ The account menu names the organization. Every page has a shareable URL. | **Recall** (tab of Memories) | `/recall` | "Why did this rank here": the rows the Memories list shows for a query with no filters set, in its order (keyword matches newest first, then `memory.search` hits with their ranking terms), and read past searches with every key and score they returned (`memory.search_trace_log`). | | **Copy rules** | `/copy-rules` | A tab of Memories: the namespace's [copy rules](namespaces-and-sharing.md#copy-rules), its saved criteria for copying memories into it from another namespace, each with what it selects, its owner and its revision. A rule's owner adds, revises, enables, pauses, runs and deletes it; a writer previews what a run would propose, and the page lists the past previews and runs. See [Copy rules](#copy-rules). | | **Library** | `/library` | Knowledge documents: add (a file, which is uploaded for the server's extractor, badged beforehand with the format `knowledge.formats` says it is read as, and whose ingest is followed to the revision it publishes, with **Stop ingestion** while it runs, `knowledge.ingest_cancel`; several files at once, picked or dropped, each its own document followed in a list with **Retry failed** and **Stop** ([many files](knowledge.md#many-files-from-the-dashboard)); a folder, which becomes a collection with its folders nested inside it (on My files or a namespace, the person picks a top-level collection or files kept with their folder paths) ([a folder](knowledge.md#a-folder-from-the-dashboard)); or pasted text), preview, download, edit metadata, move (**Move to…** on a row or a selection, `knowledge.move`, to a collection the person adds to, My files or the namespace at the top: [moving documents](knowledge.md#moving-documents); beside the tree, a row dragged onto a place, with the selection when it is in one, opens **Move to…** set to that place, and only the places **Move to…** lists take the drop), delete (the notice it raises carries **Undo**, `knowledge.restore`, which restores the document's last deleted revision, whichever delete retired it; a bulk delete's notice has none), review the typed tables a document's file became from its preview's **Tables** and approve their column types (`knowledge.dataset_get`, `knowledge.dataset_approve`), and find a passage inside the documents (**Find a passage**, `knowledge.search`; each hit is cited by its revision and place, in lines, a key, pages or slides, or rows, and opens its document). Where the page is at least 1036 px wide (from a 1280 px window with the sidebar open; **Ask AI** beside the page narrows it), a tree beside the documents lists where they can be: **All documents**, the namespace picked at the top, **My files**, the person's [collections](../architecture/sharing.md) nested as they sit (a button before each one that holds others shows or hides them, which the browser remembers per person and org; the one shown and its parents open by themselves), and **Shared with you** (`collection.list`); **New collection** at its foot turns into a title field that says where the collection goes: inside the collection shown when it is pressed, if the person writes there, else at the top level. Narrower, a select above the list shows **All documents**, the namespace or one of the collections, as a tree with each one's title and description (its `col-…` address in **About this place**; a title shown twice carries its address); `?collection=` names it (`?place=all` names All documents). At every width the browser tab names the place shown. **All documents** is one list of the documents of every place the person reads in the Library (the namespace at the top, **My files** and the collections, in the tree's order), read in one `knowledge.list` call that names them in `namespaces`, up to the 101 places one call takes; the rest are said to be left out. Each row says where it lives, as a link to that place, and takes its writes from that place's role: a row of a collection the person only reads has no checkbox and its writes say why, and **Move to…** takes a selection from one place at a time. What the read left out is said above the rows, never as part of the whole: when the read is refused, each place is read alone to name the ones refused (and any whose own read then failed, with **Read again**), and the rest are listed; a place refused is left out of later reads, still named, until the collections answer again (they are read again the first time a place is refused, and a grant that had not reached the reading replica yet is then read); any other failure is the list's error, with **Retry**. The figures line counts the places read ("4 of 5 places"), or only those read ("3 places read") while the collections could not be loaded or their list stops early. From a server a release behind that reads one place per call, the page says only the first is shown, and a **Load more** that server cannot continue reads the list again from the top. Its **Add document** adds to the namespace at the top, else to **My files**. Elsewhere, while something is searched, a choice under the search bar keeps the search in **This collection** (**This namespace** on a namespace) or takes it **Everywhere**, which reads every place, for the list and for **Find a passage** (the places the list read, saying how many it leaves out; the panel stays open and asks again when the scope changes), each row saying where it lives; All documents always searches everywhere. A collection's path from the top runs on one line above the list (beside the tree, it ends with the collection's title): the place above, the ones above the parent folded into a dots button, and the parent, each a link (a parent the person cannot read shows as a dots button, which gives its address when tapped). From 640 px wide the collections inside the one shown sit as a row of folder chips above its documents (on a phone the select lists them), and, where the tree is not shown, on **My files** and on a namespace, below the documents **Collections** lists the person's own top-level ones (and their own whose parent they cannot read), with **Shared with you** below them: the collections the person reads or writes but does not administer (one inside another shared with them shows inside it), each list naming the parents of a collection inside another, in words for a parent missing from the list (`collection.list` names no owner, so one shared as admin sits with the person's own, and the role is the token's: a token capped below admin lists the person's own here too). Each list of places in the tree shows its first fifty (the way to the place shown always among them), the chips and each list below the documents their first six, and each Show more adds fifty; on a phone the path is one back button beside the select, and the select, a tree, lists the collections inside. On a code or tracker namespace, or none, the select lists only collections; with no namespace at the top, the Library opens **My files** (a token that is not a person's has no files of its own: it stays on the top level, which lists the collections). Under the path, a collection's header says who can see it, in words: the grants on it and on the parents it inherits from, as far as the person can read them (`grants.list`, [inheritance](../architecture/sharing.md#the-model)); **My files** say they are the person's alone. **Share**, beside **Add document** (its icon alone on a phone), opens its members in place for its admins (`grants.*`), with who else can see it through each parent listed beneath them, read-only and linked to the parent; anyone else gets **See who**, the same dialog with its controls unavailable. Its menu holds **Budget…**; its admins move it under another collection or to the top (`collection.move`; beside the tree, dragging it onto a collection it may go inside, or onto **Drop here for the top level**, opens that move set to it) and delete it, which erases what it holds (`collection.delete`); **New collection** creates one from a title, inside the one shown when the person writes there; the server derives its address, and a title already used inside the same collection (at the top level, one of the person's own) opens that one (with **Choose the address myself**, the title is kept as given) ([names and titles](../architecture/sharing.md)). The header's **New** adds to the header's namespace, so while the Library shows a collection, or a namespace that holds no documents, it offers no **Document**: the Library's own **Add document** adds where the Library shows. The select finds a collection by its title, address or description as you type. See [knowledge](knowledge.md). **Sources**, in the header's actions and counting them (its icon alone on a phone), opens the document sources of the shared namespace or collection in view below the header, with their last sync; the [sources table](knowledge.md#document-sources) says who changes them. | -| **Skills** | `/skills` | The skills the server and your namespaces hold (`skill.list`), each on its own page with its text and files (`skill.get`), a check of a folder against the package rules (`skill.check`), a draft saved from the editor or a folder (`skill.save`), a delete (`skill.delete`), and an administrator's review of a draft: publish, send back or archive (`skill.decide`). See [Skills](#skills). | +| **Skills** | `/skills` | The skills the server and your namespaces hold (`skill.list`), each on its own page with its text and files (`skill.get`), a check of a folder against the package rules (`skill.check`), a draft saved from the editor or a folder (`skill.save`), a delete (`skill.delete`), and an administrator's review of a draft: publish, send back or archive (`skill.decide`), and which revisions of a skill were fetched (`skill.usage`). See [Skills](#skills). | | **Conversations** | `/conversations` | Stored conversation threads, replayed turn by turn (a writer renames a thread, an admin deletes one), and the saved session briefs, which a writer forgets. See [conversations and sessions](conversations-and-sessions.md). | | **Runs** | `/runs` | The run ledger: goal, how it ended, what it relied on and wrote, and in the replay what it recalled, observed and cost, and what it read: the revision of each item and what the agent reported relying on; a writer grades a closed run by whether it held up. The address carries the open run (`?run=`), so a link, a reload and Back reopen it ([a link to a run](runs.md#a-link-to-a-run)). See [runs](runs.md). | | **Tasks** | `/tasks` | The task inbox board. Tiles count what needs a person (triage, blocked on a person, failed, leases about to end); rows group as Triage, To do, In progress, Waiting, Closed, as a list or a board, with Accept / Won't do inline; the panel's buttons or a drag onto another group move a task. See [tasks and decisions](tasks-and-decisions.md). | @@ -292,6 +292,26 @@ skills folder and does not load Loom's context gets the files from the address of the server that served the page and the skill's name. The tab says that Loom does not see which skills a client loads, and to use one route per client. +The **Fetches** tab shows [which revisions were fetched](skills.md#see-which-revisions-were-fetched) +from the server (`skill.usage`), for a published skill to every reader and for any other +skill to its writers. It prints the server's own sentences: what the skill's counts say, +then what every count means and what Loom cannot see. Between them a table has one row a +revision that was fetched: the sessions and the principals that fetched it, each as "at +least" a number, when it was last fetched, and its looks. A look is a read from the +dashboard, the assistant or a command that shows a skill; it is shown and never counted +as a fetch. For an administrator of the namespace the tab adds **Who fetched**: each +principal that read a revision, between which times, over MCP or over HTTP (the command, +an SDK or a job), and under which consumer. That read is made for an administrator alone. +The tab says "fetched" throughout: Loom does not know whether a session followed the text. + +A skill that is stale carries a label, on its row of the list and beside its name on its +page, with one line that says what the label means. **Long wait for review**: a draft has +waited for review for more than 14 days, shown to a writer. **Names an unknown +operation**: the published revision names an operation this server does not serve. The +list reads the labels of the header namespace's skills in one request, only while it shows +a skill of that namespace; rows of your other namespaces carry none. On a server that does +not serve `skill.usage` the tab says so in one line and no label shows. + To a writer of the namespace the page is also the review of the revision it shows. It adds the last decision on that revision (who decided, when, and the note they left) and three tabs beside **Files**: diff --git a/docs/features/skills.md b/docs/features/skills.md index b45d9023ab..f49cdfcff6 100644 --- a/docs/features/skills.md +++ b/docs/features/skills.md @@ -100,10 +100,11 @@ A session with a token narrowed to one user or one session is listed nothing. [S | [`skill.save`](../reference/operations/skill.md#skillsave) | Saves a folder as a namespace's next draft | `POST /v1/skill.save` | `loom_op` with `op: "skill.save"` | `skill.save` method | `loom skill save ` | The editor, the import | | [`skill.delete`](../reference/operations/skill.md#skilldelete) | Deletes a revision or a whole skill | `POST /v1/skill.delete` | Not served | `skill.delete` method | `loom skill delete /` | **Delete…** | | [`skill.decide`](../reference/operations/skill.md#skilldecide) | Publishes, rejects or archives | `POST /v1/skill.decide` | Not served | `skill.decide` method | `loom skill publish`, `reject`, `archive` | A skill page's review | +| [`skill.usage`](../reference/operations/skill.md#skillusage) | Reports which revisions were fetched | `POST /v1/skill.usage` | `loom_op` with `op: "skill.usage"` | `skill.usage` method | `loom skill usage ` | The **Fetches** tab | -The three reads need `viewer` on the namespace the call names, also for a built-in skill, `skill.save` needs `writer`, and `skill.delete` and `skill.decide` need `admin`: a caller outside the namespace is refused as on any op. A token bounded below its namespace, to one user or one session, is refused. No MCP toolset lists the reads and the save as tools; `loom_op` calls them by name. MCP does not serve `skill.delete` or `skill.decide`: a session must not remove a team's reviewed text, and a session that read a draft must not publish it, so `loom_op` refuses both and names no other operation. Every generated SDK carries the six, at the same names. The [status page](../reference/status.md) gives their maturity. +The four reads need `viewer` on the namespace the call names, also for a built-in skill, `skill.save` needs `writer`, and `skill.delete` and `skill.decide` need `admin`: a caller outside the namespace is refused as on any op. `skill.usage` with `by_subject` also needs `admin`. A token bounded below its namespace, to one user or one session, is refused. No MCP toolset lists the reads and the save as tools; `loom_op` calls them by name. MCP does not serve `skill.delete` or `skill.decide`: a session must not remove a team's reviewed text, and a session that read a draft must not publish it, so `loom_op` refuses both and names no other operation. Every generated SDK carries the seven, at the same names. The [status page](../reference/status.md) gives their maturity. -The dashboard's [Skills page](dashboard.md#skills) lists the built-in skills and the skills of your namespaces: to a writer with their drafts, to any other reader the published ones. It opens each skill on its own page, checks a folder picked in the browser, saves a draft from its editor or from a picked folder, and deletes a revision or a whole skill for an administrator. A writer's page of a skill is its review: what changed against the published revision, what a check finds, and the skill's history. On it an administrator publishes a draft, sends it back with a note, or archives the skill. The [Review queue](dashboard.md#the-admin-drawer) lists the drafts that wait in the namespace picked in the header on its **Skills** tab, for an administrator, and counts them in its badge; a row there, and a row of the Skills page whose draft waits, opens the draft on what it changes. +The dashboard's [Skills page](dashboard.md#skills) lists the built-in skills and the skills of your namespaces: to a writer with their drafts, to any other reader the published ones. It opens each skill on its own page, checks a folder picked in the browser, saves a draft from its editor or from a picked folder, and deletes a revision or a whole skill for an administrator. A writer's page of a skill is its review: what changed against the published revision, what a check finds, and the skill's history. On it an administrator publishes a draft, sends it back with a note, or archives the skill. A skill's **Fetches** tab shows [which revisions were fetched](#see-which-revisions-were-fetched), and the list and the page label a skill that is stale. The [Review queue](dashboard.md#the-admin-drawer) lists the drafts that wait in the namespace picked in the header on its **Skills** tab, for an administrator, and counts them in its badge; a row there, and a row of the Skills page whose draft waits, opens the draft on what it changes. ## List the skills @@ -418,6 +419,46 @@ The command sends one `skill.list` for each namespace the locks name, for that n An archive or a delete on the server does not reach a pulled folder. Pulled copies stay where they are, and `status` reports them as no longer served. +## See which revisions were fetched + +`skill.usage` reports which revisions of a namespace's skills were fetched from the server, and which skills are stale. `loom skill usage` prints the report, and a skill's page shows it on its **Fetches** tab. + +```bash +loom skill usage team # every skill of the namespace you can list +loom skill usage team/deploy-notes --days 90 # one skill, over 90 days +loom skill usage team --by-subject --json # who fetched each revision: admin +``` + +```text +Counts cover the last 30 days and are lower bounds: the request ledger can drop a row, so each number reads as at least that many. Loom does not record which sessions were shown the listing: a fetch counts a session that asked for the skill's text. A session's listing can carry 2 skills of this namespace: it takes one skill of each namespace in turn, each namespace's by name. + +team/deploy-notes revision 2 is published + Revision 2 was fetched by at least 3 sessions of at least 2 principals in the last 30 days. + revision 2 sessions >= 3 principals >= 2 last fetched 2026-01-05T10:00:00 looks 4 +``` + +Every sentence is the server's (`statement` of the report and of each skill), so the command, the dashboard and an SDK caller read the same words. `--days` takes 1 to 90 and defaults to 30. The command exits 0 when the report was printed and 2 when the server does not serve `skill.usage`. + +| What Loom records | What the report says of it | +| --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| Which revision is published, and when | `published_revision`, `published_at` | +| Each answered `skill.get` of a revision that is or was published, in the request ledger | `fetches`: the sessions and principals that fetched each revision, and the last one | +| The reads the dashboard, the assistant and a command that shows a skill made | `inspector_fetches`: looks, shown beside the counts and never counted in them | +| A draft that waits, and the operations a published revision names | `stale` | + +| What Loom does not record | What follows | +| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | +| Which sessions were shown a listing line | The report counts fetches, and says how many skills of the namespace a listing can carry | +| A read of a copy pulled to a folder | The pull is one fetch, over HTTP. Later reads of the folder are none, so a skill with no fetch may still be read | +| What a session did with the text it asked | No count says a session followed a skill | +| A ledger row the server dropped | Every count is a lower bound | + +- **A fetch.** An answered `skill.get` whose content hash is that of a revision that is or was published, made from the second after that revision was published. A read of a draft, of a rejected revision and of a revision that was never published is no fetch. A session is counted once a revision, whatever the transport; a request that named no session counts its principal only. +- **The window.** `window_days` is `days`, or the days the namespace keeps its request ledger when that is fewer; the statement says when the window was cut. One report folds at most 10,000 ledger groups, the most recent, and the statement says when the read stopped there. +- **Stale codes.** `stale` holds codes from a closed set, each proven by rows the skill holds. `draft_waiting`: the skill's draft has waited for review for more than 14 days; answered to a caller who may write to the namespace, as the draft is. `unknown_operation`: the published revision names an operation the answering build does not serve. A skill nobody fetched has no code for that. A client shows a code it does not know by its name. +- **Who sees what.** The caller is reported the skills `skill.list` lists to it: a writer every skill of the namespace, any other reader the ones that serve a revision. A name the caller cannot list answers no skill, as a name that does not exist does. `by_subject` adds `subjects`, one entry a principal, revision, transport and consumer with the first and the last read; it needs `admin` on the namespace and is refused with 403 to anyone else. +- **A failed read.** When the ledger cannot be read the op fails. It never answers a skill as not fetched in place of an error. + ## Delete a revision or a skill ```bash diff --git a/docs/guides/without-the-dashboard.md b/docs/guides/without-the-dashboard.md index 263fbf006a..dea76a9705 100644 --- a/docs/guides/without-the-dashboard.md +++ b/docs/guides/without-the-dashboard.md @@ -95,6 +95,7 @@ are on `agent.account` and `agent.deployment`. | Skills: save a draft, delete | `loom skill save `, `loom skill delete /` ([skills](../features/skills.md)) | `agent.client.skill.save(...)`, `.delete(...)` | | Skills: review a draft, archive | `loom skill diff`, `loom skill publish`, `reject`, `archive` ([skills](../features/skills.md#review-a-draft)) | `agent.client.skill.decide(...)` | | Skills: pull to a folder, compare | `loom skill pull / --to `, `loom skill status ` ([skills](../features/skills.md#pull-a-skill-to-a-folder)) | `loom.skills.write_skill(...)`, `.read_lock(...)`, `.served_state(...)` | +| Skills: fetches of a revision | `loom skill usage [/]`, `--by-subject` for an administrator ([skills](../features/skills.md#see-which-revisions-were-fetched)) | `agent.client.skill.usage(...)` | | Code index | `code.index_status`, `code.repo.add`, … | `agent.code.*` | | Erasure, forgetting | `erasure.request`, `erasure.status`, `erasure.list`, `erasure.export`, `memory.clear` | `agent.erasure.*` | | Tasks and inbox | `task.create`, `task.pull`, `task.updates`, `inbox.*` | `agent.tasks.*` | diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 816a0920be..5e6e317f69 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -382,7 +382,7 @@ python scripts/codegen/docs_reference.py | `loom connect` | Print the dashboard link to connect your own Google, Notion or Linear account. | | | `loom pointers` | Print the code pointer block for the task prompt on standard input. | | | `loom curator` | Report what in a namespace needs a person, and set its curator mode (`loom curator --help`). | | -| `loom skill` | List and read the server's skills, check a skill folder, save one as a draft, publish, reject, archive or delete it, and write a published skill to a folder (`loom skill --help`). | | +| `loom skill` | List and read the server's skills, check a skill folder, save one as a draft, publish, reject, archive or delete it, write a published skill to a folder, and report which revisions were fetched… | | | `loom copy-rule` | Preview a namespace's copy rule, or run it to propose each new match (`loom copy-rule --help`). | | | `loom proposals` | List a namespace's pending proposals, read one whole, and accept or reject by the hash of the text that was read (`loom proposals --help`). | | diff --git a/docs/reference/operations.md b/docs/reference/operations.md index 91e85fb152..f9f6a15aa2 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -124,7 +124,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal -421 operations in 46 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). +422 operations in 46 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). Columns: **Role** is the minimum role (`viewer` < `writer` < `admin` < `org_admin` < `platform_admin`); **Kind** is `read` (idempotent, viewer, unaudited, writes nothing — MCP `readOnlyHint`), `idempotent` (safe to retry) or `write`; **Listed under `all`** says whether an MCP connection on the `all` toolset lists the op in `tools/list` (`code.*` ops only with `LOOM_MCP_CODE_TOOLS=true`); an op marked `no` is still callable by name or through `loom_op`, unless it is hidden from MCP; **Audit** marks ops that leave an `audit_log` row. @@ -775,6 +775,7 @@ Fields for every `skill` op: [operations/skill.md](operations/skill.md). | [`skill.get`](operations/skill.md#skillget) | Read one skill: its `SKILL.md`, its frontmatter and the files beside it. | viewer | read | no | | | [`skill.list`](operations/skill.md#skilllist) | List skills: the ones the caller's namespaces hold, then the ones built into the server image. | viewer | read | no | | | [`skill.save`](operations/skill.md#skillsave) | Save a skill folder as the next draft revision of the namespace's skill. | writer | idempotent | no | yes | +| [`skill.usage`](operations/skill.md#skillusage) | Report which revisions of a namespace's skills were fetched, and which skills are stale. | viewer | read | no | | ### stewardship diff --git a/docs/reference/operations/skill.md b/docs/reference/operations/skill.md index 179c6056c0..caee9e2786 100644 --- a/docs/reference/operations/skill.md +++ b/docs/reference/operations/skill.md @@ -182,4 +182,24 @@ Save a skill folder as the next draft revision of the namespace's skill. | `operations` | `list[SkillOperation]` | The operations and MCP tools the text names, as `skill.check` reports them. | | `current` | `SkillCurrent \| None` | On a conflict, the skill's latest revision; otherwise None. | +## `skill.usage` + +Report which revisions of a namespace's skills were fetched, and which skills are stale. + +`POST /v1/skill.usage` · MCP `loom_skill_usage` · role `viewer` · read · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The tenant (first element of the identity tuple). | +| `namespace` | `str` | required | The namespace the op reads or writes. | +| `name` | `str` | `''` | The skill to report; empty (the default) reports every skill of the namespace the caller can list. | +| `days` | `int` | `30` | How many days back fetches are counted, 1 to 90; default 30. | +| `by_subject` | `bool` | `False` | Fill `subjects` with who fetched each revision; needs admin on the namespace, else 403. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `window_days` | `int` | The days the counts cover: `days`, or the days the request ledger is kept when that is fewer. | +| `statement` | `str` | What every count means and what the report cannot see: the counts are lower bounds, which sessions were shown a listing is not recorded, how many of the namespace's skills a listing can carry and in what order, and whether the window or… | +| `skills` | `list[SkillUsage]` | The namespace's skills the caller can list, by name; with `name`, that skill alone, and none when the caller cannot list it. | + diff --git a/docs/reference/status.md b/docs/reference/status.md index 38dd161e52..e1f6500425 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). -421 operations, 307 of them experimental. +422 operations, 308 of them experimental. | Group | Stable | Experimental | | --- | --- | --- | @@ -68,7 +68,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). | `run` | 4 | [`run.grade`](operations/run.md#rungrade), [`run.reliance`](operations/run.md#runreliance), [`run.retract_credit`](operations/run.md#runretract_credit) | | `search` | 0 | [`search.query`](operations/search.md#searchquery) | | `session` | 0 | [`session.brief_delete`](operations/session.md#sessionbrief_delete), [`session.brief_get`](operations/session.md#sessionbrief_get), [`session.brief_list`](operations/session.md#sessionbrief_list), [`session.brief_save`](operations/session.md#sessionbrief_save) | -| `skill` | 0 | [`skill.check`](operations/skill.md#skillcheck), [`skill.decide`](operations/skill.md#skilldecide), [`skill.delete`](operations/skill.md#skilldelete), [`skill.get`](operations/skill.md#skillget), [`skill.list`](operations/skill.md#skilllist), [`skill.save`](operations/skill.md#skillsave) | +| `skill` | 0 | [`skill.check`](operations/skill.md#skillcheck), [`skill.decide`](operations/skill.md#skilldecide), [`skill.delete`](operations/skill.md#skilldelete), [`skill.get`](operations/skill.md#skillget), [`skill.list`](operations/skill.md#skilllist), [`skill.save`](operations/skill.md#skillsave), [`skill.usage`](operations/skill.md#skillusage) | | `stewardship` | 0 | [`stewardship.assign`](operations/stewardship.md#stewardshipassign), [`stewardship.get`](operations/stewardship.md#stewardshipget), [`stewardship.list`](operations/stewardship.md#stewardshiplist), [`stewardship.review`](operations/stewardship.md#stewardshipreview) | | `task` | 0 | [`task.accept`](operations/task.md#taskaccept), [`task.block`](operations/task.md#taskblock), [`task.cancel`](operations/task.md#taskcancel), [`task.claim`](operations/task.md#taskclaim), [`task.complete`](operations/task.md#taskcomplete), [`task.counts`](operations/task.md#taskcounts), [`task.create`](operations/task.md#taskcreate), [`task.defer`](operations/task.md#taskdefer), [`task.fail`](operations/task.md#taskfail), [`task.get`](operations/task.md#taskget), [`task.heartbeat`](operations/task.md#taskheartbeat), [`task.history`](operations/task.md#taskhistory), [`task.list`](operations/task.md#tasklist), [`task.progress`](operations/task.md#taskprogress), [`task.pull`](operations/task.md#taskpull), [`task.reassign`](operations/task.md#taskreassign), [`task.reopen`](operations/task.md#taskreopen), [`task.resume`](operations/task.md#taskresume), [`task.unblock`](operations/task.md#taskunblock), [`task.update`](operations/task.md#taskupdate), [`task.updates`](operations/task.md#taskupdates), [`task.wont_do`](operations/task.md#taskwont_do) | | `tracker` | 0 | [`tracker.answer`](operations/tracker.md#trackeranswer), [`tracker.binding`](operations/tracker.md#trackerbinding), [`tracker.component`](operations/tracker.md#trackercomponent), [`tracker.contract`](operations/tracker.md#trackercontract), [`tracker.duplicate_check`](operations/tracker.md#trackerduplicate_check), [`tracker.flaky`](operations/tracker.md#trackerflaky), [`tracker.item`](operations/tracker.md#trackeritem), [`tracker.links`](operations/tracker.md#trackerlinks), [`tracker.release`](operations/tracker.md#trackerrelease), [`tracker.similar`](operations/tracker.md#trackersimilar), [`tracker.source.add`](operations/tracker.md#trackersourceadd), [`tracker.source.check`](operations/tracker.md#trackersourcecheck), [`tracker.source.inspect`](operations/tracker.md#trackersourceinspect), [`tracker.source.list`](operations/tracker.md#trackersourcelist), [`tracker.source.remove`](operations/tracker.md#trackersourceremove), [`tracker.source.rotate`](operations/tracker.md#trackersourcerotate), [`tracker.source.set_mapping`](operations/tracker.md#trackersourceset_mapping), [`tracker.test_signal`](operations/tracker.md#trackertest_signal) | diff --git a/frontend/e2e/fixtures.ts b/frontend/e2e/fixtures.ts index bab0b4066d..12b4c896c1 100644 --- a/frontend/e2e/fixtures.ts +++ b/frontend/e2e/fixtures.ts @@ -1193,6 +1193,9 @@ export async function installApi(page: Page, options: InstallOptions = {}): Prom total: 3, next_cursor: "", }); + case "/v1/skill.usage": + // The built-in skills are no namespace's: the report names none. + return json({ window_days: 30, statement: "", skills: [] }); case "/v1/knowledge.suites.list": return json({ suites: SUITES }); case "/v1/knowledge.suites.get": diff --git a/frontend/e2e/skills.spec.ts b/frontend/e2e/skills.spec.ts index 10a6014c40..62cc151e3c 100644 --- a/frontend/e2e/skills.spec.ts +++ b/frontend/e2e/skills.spec.ts @@ -377,7 +377,7 @@ test("a second administrator publishes the draft its author cannot, and a viewer await expect(listing.getByTestId("skill-listing-line")).toHaveText(LINE); await expect(decision(viewer)).toHaveCount(0); const tabs = viewer.getByRole("tablist", { name: "Skill sections" }); - await expect(tabs.getByRole("tab")).toHaveText(["Files", "Get it"]); + await expect(tabs.getByRole("tab")).toHaveText(["Files", "Fetches", "Get it"]); // The published skill's page says how a client that reads a folder gets it: the command // names the server that served the page, and this skill. await tabs.getByRole("tab", { name: "Get it" }).click(); @@ -466,7 +466,7 @@ for (const width of [1400, 375]) { expect(await violations(page)).toEqual([]); const tabs = page.getByRole("tablist", { name: "Skill sections" }); - await expect(tabs.getByRole("tab")).toHaveText(["Files", "Checks", "History"]); + await expect(tabs.getByRole("tab")).toHaveText(["Files", "Checks", "History", "Fetches"]); await tabs.getByRole("tab", { name: "Checks" }).click(); await expect(page.getByText("Nothing to look at.")).toBeVisible(); expect(await violations(page)).toEqual([]); diff --git a/frontend/src/api/skills.ts b/frontend/src/api/skills.ts index d44fbee94a..ea1557916c 100644 --- a/frontend/src/api/skills.ts +++ b/frontend/src/api/skills.ts @@ -414,3 +414,79 @@ export async function decideSkill( opts.signal, ); } + +/** The fetches of one revision that is or was published. Each count is a lower bound. */ +export interface SkillFetches { + revision: number; + content_sha256: string; + sessions: number; + /** How many principals fetched it. */ + subjects: number; + /** Null when only inspectors read the revision. */ + last_at: string | null; + /** Reads by the dashboard, the assistant and the command line's inspection: looks, + * counted in neither `sessions` nor `subjects`. */ + inspector_fetches: number; +} + +/** One principal's reads of one revision over one transport, under one consumer. */ +export interface SkillFetchSubject { + subject: string; + revision: number; + /** `mcp` or `http`. */ + transport: string; + consumer: string; + first_at: string; + last_at: string; +} + +export interface SkillUsage { + namespace: string; + name: string; + published_revision: number; + published_at: string | null; + /** One entry for each revision fetched in the window, highest revision first. */ + fetches: SkillFetches[]; + /** What needs attention: `draft_waiting`, `unknown_operation`, or a code a later build + * answers. */ + stale: string[]; + /** The counts in the server's words. */ + statement: string; + /** Who read each revision; answered only to a read that asked `bySubject`. */ + subjects?: SkillFetchSubject[]; +} + +export interface SkillUsageResponse { + window_days: number; + /** What every count means and what the report cannot see, in the server's words. */ + statement: string; + skills: SkillUsage[]; +} + +export interface SkillUsageOpts { + /** Report this skill alone. */ + name?: string; + /** How many days back fetches are counted; the server's default without one. */ + days?: number; + /** Also answer who fetched each revision: an administrator's read. */ + bySubject?: boolean; +} + +/** POST /v1/skill.usage: which revisions of the skills of `id.namespace` were fetched, and + * which skills are stale. */ +export async function skillUsage( + id: Pick, + opts: SkillUsageOpts & RequestOpts = {}, +): Promise { + return post( + "/v1/skill.usage", + { + org: id.org, + namespace: id.namespace, + ...(opts.name ? { name: opts.name } : {}), + ...(opts.days ? { days: opts.days } : {}), + ...(opts.bySubject ? { by_subject: true } : {}), + }, + opts.signal, + ); +} diff --git a/frontend/src/lib/callReason.ts b/frontend/src/lib/callReason.ts index beab231800..a0342c7d4d 100644 --- a/frontend/src/lib/callReason.ts +++ b/frontend/src/lib/callReason.ts @@ -101,6 +101,7 @@ export const PAGE_OP_MIN_ROLE = { "skill.list": "viewer", "skill.get": "viewer", "skill.check": "viewer", + "skill.usage": "viewer", // The Audit log's Exposure tab reads on open; the Agents page's "Forget its memories". "memory.exposure_summary": "admin", "memory.clear": "admin", diff --git a/frontend/src/views/Skills.test.tsx b/frontend/src/views/Skills.test.tsx index a2ed278231..c4773f4da1 100644 --- a/frontend/src/views/Skills.test.tsx +++ b/frontend/src/views/Skills.test.tsx @@ -11,6 +11,7 @@ import { listGrants, listSkills, saveSkill, + skillUsage, type MyNamespaceEntry, type SkillDetail, type SkillRow, @@ -36,6 +37,7 @@ vi.mock("../api", async (importOriginal) => ({ saveSkill: vi.fn(), deleteSkill: vi.fn(), decideSkill: vi.fn(), + skillUsage: vi.fn(), listGrants: vi.fn(), })); vi.mock("../lib/download", () => ({ saveJson: vi.fn(), saveText: vi.fn() })); @@ -196,6 +198,7 @@ describe("Skills", () => { ); vi.mocked(listGrants).mockResolvedValue({ rows: [] }); vi.mocked(countListedSkills).mockResolvedValue(3); + vi.mocked(skillUsage).mockResolvedValue({ window_days: 30, statement: "", skills: [] }); at("/skills"); }); afterEach(() => { @@ -600,7 +603,7 @@ describe("Skills", () => { const user = userEvent.setup(); const { container } = render(); await screen.findByRole("heading", { level: 1, name: "deploy-notes" }); - expect(screen.getAllByRole("tab").map((t) => t.textContent)).toEqual(["Files", "Get it"]); + expect(screen.getAllByRole("tab").map((t) => t.textContent)).toEqual(["Files", "Fetches", "Get it"]); await user.click(screen.getByRole("tab", { name: "Get it" })); expect(new URLSearchParams(window.location.search).get("tab")).toBe("get"); @@ -1118,6 +1121,7 @@ describe("Skills", () => { "Changes", "Checks", "History", + "Fetches", "Get it", ]); expect(vi.mocked(checkSkill)).not.toHaveBeenCalled(); @@ -1155,6 +1159,77 @@ describe("Skills", () => { ]); }); + /** What `skill.usage` answers of `ns/deploy-notes` with these stale codes. */ + const stale = (codes: string[], statement = "") => ({ + window_days: 30, + statement: "Counts cover the last 30 days and are lower bounds.", + skills: [ + { + namespace: "ns", + name: "deploy-notes", + published_revision: 2, + published_at: "2026-01-01 01:00:00", + fetches: [], + stale: codes, + statement, + }, + ], + }); + + // Fails if a row shows a stale code without what it means, labels a row of another + // namespace, reads usage for each row, or reads it for a list that shows no skill of + // the header's namespace. + it("labels what is stale on the header namespace's rows from one read", async () => { + render(); + await screen.findByRole("list", { name: "Built into this server" }); + expect(vi.mocked(skillUsage)).not.toHaveBeenCalled(); + cleanup(); + + listed([...TEAM, ...BUILTINS]); + vi.mocked(skillUsage).mockResolvedValue(stale(["draft_waiting", "later_code"])); + render(); + const [own, other] = within(await screen.findByRole("list", { name: "Skills" })).getAllByRole("listitem"); + expect(await within(own).findByText("Long wait for review")).toBeVisible(); + expect( + within(own).getByText("Long wait for review: A draft has waited for review for more than 14 days."), + ).toBeVisible(); + // A code this build has no words for shows by its name, with no meaning made up. + expect(within(own).getByText("Later code")).toBeVisible(); + expect(within(other).queryByText(/wait for review/)).toBeNull(); + expect(vi.mocked(skillUsage)).toHaveBeenCalledTimes(1); + expect(vi.mocked(skillUsage).mock.calls[0][0]).toMatchObject({ org: "dev", namespace: "ns" }); + expect(vi.mocked(skillUsage).mock.calls[0][1]).toMatchObject({ days: 1 }); + }); + + // Fails if a skill's page reads usage more than once to open, shows a stale code + // without what it means, or draws the Fetches tab in words that are not the server's. + it("labels what is stale on a skill's page and opens Fetches from the same read", async () => { + const said = "Not fetched from Loom in the last 30 days."; + vi.mocked(getSkill).mockImplementation(async (_id, _skill, opts = {}) => (opts.revision === 3 ? DRAFT : SERVED)); + vi.mocked(skillUsage).mockResolvedValue(stale(["unknown_operation"], said)); + grants([grant("ns", "writer")]); + at("/skills?skill=ns/deploy-notes"); + const user = userEvent.setup(); + render(); + await screen.findByRole("heading", { level: 1, name: "deploy-notes" }); + expect(await screen.findByText("Names an unknown operation")).toBeVisible(); + expect( + screen.getByText( + "Names an unknown operation: The published revision names an operation this server does not serve.", + ), + ).toBeVisible(); + + await user.click(screen.getByRole("tab", { name: "Fetches" })); + expect(await screen.findByText(said)).toBeVisible(); + expect(screen.getByText("Counts cover the last 30 days and are lower bounds.")).toBeVisible(); + expect(new URLSearchParams(window.location.search).get("tab")).toBe("fetches"); + // One read of this skill, in its namespace; a writer's page asks nobody's name. + expect(vi.mocked(skillUsage)).toHaveBeenCalledTimes(1); + expect(vi.mocked(skillUsage).mock.calls[0][0]).toEqual({ org: "dev", namespace: "ns" }); + expect(vi.mocked(skillUsage).mock.calls[0][1]).toMatchObject({ name: "deploy-notes" }); + expect(vi.mocked(skillUsage).mock.calls[0][1]).not.toHaveProperty("bySubject"); + }); + // Fails if an archived skill's page has a control that serves it again without a review, // offers no review of its latest revision, or offers one to a person who wrote it. it("an archived skill offers a review, not a restore", async () => { diff --git a/frontend/src/views/Skills.tsx b/frontend/src/views/Skills.tsx index 3585861bb4..6dfeeb5c58 100644 --- a/frontend/src/views/Skills.tsx +++ b/frontend/src/views/Skills.tsx @@ -3,7 +3,7 @@ // namespace's skill (a draft written or imported, and a delete) and its review: what // changed, what the checks found, and the decision. Every name, description, count and // state shown is the server's: the page keeps no record of its own. -import { useEffect, useState } from "react"; +import { lazy, Suspense, useEffect, useState } from "react"; import { Badge } from "@clickhouse/click-ui/Badge"; import { Button } from "@clickhouse/click-ui/Button"; import { ButtonGroup } from "@clickhouse/click-ui/ButtonGroup"; @@ -19,6 +19,7 @@ import { listSkills, revisionText, savedAt, + skillUsage, type SkillDetail, type SkillFileEntry, type SkillKind, @@ -68,6 +69,7 @@ import { ChangesTab } from "./skills/ChangesTab"; import { CheckFolder } from "./skills/CheckFolder"; import { ChecksTab } from "./skills/ChecksTab"; import { DeleteSkillButton, DeleteSkillDialog, type DeleteTarget } from "./skills/DeleteSkill"; +import type { UsageRead } from "./skills/FetchesTab"; import { DownloadFile, GetItTab } from "./skills/GetIt"; import { HistoryTab } from "./skills/HistoryTab"; import { ImportFolder } from "./skills/ImportFolder"; @@ -86,6 +88,10 @@ import { import { DECISION_HEADING_ID, hasDecision, ReviewBar } from "./skills/ReviewBar"; import { hasListing, NotListedNamespaces, SessionListing } from "./skills/SessionListing"; import { SkillEditor } from "./skills/SkillEditor"; +import { StaleBadges, StaleMeanings } from "./skills/stale"; + +// Loaded when the tab is opened: a skill's page loads none of it before that. +const FetchesTab = lazy(() => import("./skills/FetchesTab").then((m) => ({ default: m.FetchesTab }))); const SEARCH_DEBOUNCE_MS = 250; /** The longest search the server takes. */ @@ -129,6 +135,12 @@ export function Skills() { return address === null ? : ; } +/** The stale codes of the header namespace's skills, by name, with the namespace asked. */ +interface StaleRead { + scope: string; + codes: Record; +} + /** One answer of the list read, or its failure, with what was asked. */ interface ListRead { scope: string; @@ -202,6 +214,28 @@ function SkillList() { const current = here?.key === key ? here : null; const error = current?.error ?? null; const shown = error === null && here && here.error === null ? here : null; + + // What needs attention on the header namespace's skills: one read, made only while the + // list shows a skill of that namespace. It asks the shortest window, because a row + // shows the codes and no count. The labels are an addition to the rows: without an + // answer the rows stand as the list read drew them. + const [stale, setStale] = useState(null); + const listsOwn = !!shown?.skills.some((r) => r.kind !== "builtin" && r.namespace === identity.namespace); + useAbortableEffect( + async (signal, live) => { + if (!listsOwn) return; + try { + const answer = await skillUsage(identity, { days: 1, signal }); + const codes = Object.fromEntries((answer.skills ?? []).map((s) => [s.name, s.stale ?? []])); + if (live()) setStale({ scope, codes }); + } catch { + if (live()) setStale(null); + } + }, + [identity.org, identity.namespace, listsOwn, reads], + ); + const staleOf = (row: SkillRow): string[] => + stale?.scope === scope && row.namespace === identity.namespace ? (stale.codes[row.name] ?? []) : []; const filtering = builtinOnly || within !== "all_mine" || state !== "all" || draftOnly || query !== ""; const clearFilters = () => { setQuery(""); @@ -398,7 +432,7 @@ function SkillList() { )} {shown && shown.skills.length > 0 && (
- {held.length > 0 && } + {held.length > 0 && } {builtin.length > 0 && (
@@ -460,17 +494,20 @@ function countText(shown: number, total: number): string { } /** The rows of one group. A namespace's skill also shows its state, the revision that is - * served, a mark for a draft the read answered, when it last changed, and its menu. */ + * served, a mark for a draft the read answered, a label for each stale code with what it + * means, when it last changed, and its menu. */ function SkillRows({ label, rows, onOpen, menu, + staleOf, }: { label: string; rows: SkillRow[]; onOpen: (row: SkillRow) => void; menu?: (row: SkillRow) => RowMenuItem[]; + staleOf?: (row: SkillRow) => string[]; }) { return (
    @@ -503,6 +540,7 @@ function SkillRows({ )} {/* Only where the read answered a draft: the page infers none. */} {row.open_draft && } + {!!row.published_revision && ( revision {row.published_revision} )} @@ -511,6 +549,7 @@ function SkillRows({ )}
{row.description &&

{row.description}

} + ))} @@ -525,13 +564,14 @@ interface SkillRead { error: unknown; } -const SKILL_TABS = ["files", "changes", "checks", "history", "get"] as const; +const SKILL_TABS = ["files", "changes", "checks", "history", "fetches", "get"] as const; type SkillTab = (typeof SKILL_TABS)[number]; const TAB_LABEL: Record = { files: "Files", changes: "Changes", checks: "Checks", history: "History", + fetches: "Fetches", get: "Get it", }; @@ -578,6 +618,25 @@ function SkillPage({ address }: { address: string }) { [identity.org, namespace, skill?.kind, skill?.name, asked, reads], ); const now = read?.key === key ? read : null; + // What the request ledger holds of a namespace's skill: the header's stale labels and + // the Fetches tab are drawn from this one read. A decision changes what is stale, so + // it is made again with each read of the skill. + const [usageReads, setUsageReads] = useState(0); + const [usageRead, setUsageRead] = useState<(UsageRead & { key: string }) | null>(null); + const usageKey = `${identity.org}/${namespace}/${skill?.name}/${reads}/${usageReads}`; + useAbortableEffect( + async (signal, live) => { + if (skill?.kind !== "team") return; + try { + const answer = await skillUsage({ org: identity.org, namespace }, { name: skill.name, signal }); + if (live()) setUsageRead({ key: usageKey, answer, error: null }); + } catch (e) { + if (live()) setUsageRead({ key: usageKey, answer: null, error: e }); + } + }, + [identity.org, namespace, skill?.kind, skill?.name, reads, usageReads], + ); + const usage = usageRead?.key === usageKey ? usageRead : null; // A press in the Decision section redraws it, most often from a new read, and the // control pressed is gone with what it was drawn from. The focus then goes to the // section's heading once it is drawn again, or to the page's when the answer has none. @@ -614,8 +673,11 @@ function SkillPage({ address }: { address: string }) { : null; // The routes to a skill are those to its published revision: a skill that serves none has no tab for them. const served = team && detail?.state === "published"; + // The server reports the fetches of the skills it lists to the caller: a served one to + // every reader, any other to a writer alone. + const counted = served || reviewable; const offered = (t: SkillTab) => - t === "files" || (t === "changes" ? sides !== null : t === "get" ? served : reviewable); + t === "files" || (t === "changes" ? sides !== null : t === "get" ? served : t === "fetches" ? counted : reviewable); const shown = offered(tab) ? tab : "files"; const selectTab = (t: SkillTab) => { setTab(t); @@ -624,6 +686,7 @@ function SkillPage({ address }: { address: string }) { const state = detail?.revision_state ? revisionState(detail.revision_state) : null; const decision = detail && reviewable ? lastDecision(detail, revision) : null; const source = team ? sourceLine(detail?.origin?.source) : ""; + const staleCodes = (detail && (usage?.answer?.skills ?? []).find((s) => s.name === detail.name)?.stale) || []; const readAgain = () => setReads((n) => n + 1); // Opens another revision of the skill on this page. A refusal was of the revision left. const openRevision = (n: number) => { @@ -686,7 +749,9 @@ function SkillPage({ address }: { address: string }) { > {detail && !team && Built into this server} {detail && team && {namespace}} + + {/* One state for a skill that is not there and one the caller may not read, and nothing of the address in it. */} {missing && } @@ -815,6 +880,7 @@ function SkillPage({ address }: { address: string }) { {sides && {TAB_LABEL.changes}} {reviewable && {TAB_LABEL.checks}} {reviewable && {TAB_LABEL.history}} + {counted && {TAB_LABEL.fetches}} {served && {TAB_LABEL.get}} @@ -849,6 +915,18 @@ function SkillPage({ address }: { address: string }) { /> )} + {counted && ( + + + setUsageReads((n) => n + 1)} + /> + + + )} {served && ( diff --git a/frontend/src/views/skills/FetchesTab.test.tsx b/frontend/src/views/skills/FetchesTab.test.tsx new file mode 100644 index 0000000000..406c075995 --- /dev/null +++ b/frontend/src/views/skills/FetchesTab.test.tsx @@ -0,0 +1,163 @@ +import { cleanup, render, screen, waitFor, within } from "../../test/rtl"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ApiError, skillUsage, type SkillUsageResponse } from "../../api"; +import { resetNamespaceRoleCache } from "../../lib/namespaceRole"; +import { useStore } from "../../lib/state"; +import { axeViolations } from "../../test/axe"; +import { FetchesTab } from "./FetchesTab"; + +// The Fetches tab: the server's sentences for one skill's counts, a row for each revision +// that was fetched, and who fetched it for an administrator of the namespace alone. + +vi.mock("../../api", async (importOriginal) => ({ + ...(await importOriginal()), + skillUsage: vi.fn(), +})); + +const REPORT = + "Counts cover the last 30 days and are lower bounds: the request ledger can drop a row, so each number reads as at least that many."; +const SKILL = "Revision 2 was fetched by at least 3 sessions of at least 2 principals in the last 30 days."; + +/** What the page's read answered: one revision fetched, and one that only inspectors read. */ +const ANSWER: SkillUsageResponse = { + window_days: 30, + statement: REPORT, + skills: [ + { + namespace: "ns", + name: "deploy-notes", + published_revision: 2, + published_at: "2026-01-02 10:00:00", + fetches: [ + { + revision: 2, + content_sha256: "a".repeat(64), + sessions: 3, + subjects: 2, + last_at: "2026-01-05 10:00:00.000", + inspector_fetches: 4, + }, + { revision: 1, content_sha256: "b".repeat(64), sessions: 0, subjects: 0, last_at: null, inspector_fetches: 1 }, + ], + stale: [], + statement: SKILL, + }, + ], +}; + +/** The same skill as the read that names who fetched answers it. */ +const WITH_SUBJECTS: SkillUsageResponse = { + ...ANSWER, + skills: [ + { + ...ANSWER.skills[0], + subjects: [ + { + subject: "sa:deploy-bot", + revision: 2, + transport: "mcp", + consumer: "agent-host", + first_at: "2026-01-03 10:00:00.000", + last_at: "2026-01-05 10:00:00.000", + }, + { + subject: "alice", + revision: 2, + transport: "http", + consumer: "loom-cli", + first_at: "2026-01-04 10:00:00.000", + last_at: "2026-01-04 11:00:00.000", + }, + ], + }, + ], +}; + +const usage = { answer: ANSWER, error: null }; + +/** Signs in `alice` with one role on `ns`. */ +function signIn(role: "admin" | "viewer") { + useStore.setState({ + authed: true, + identity: { org: "dev", namespace: "other", agent: "loom-ui" }, + whoami: { authenticated: true, subject: "alice", org: "dev", roles: [role], namespaces: ["ns"] }, + myNamespaces: [ + { + namespace: "ns", + role, + status: "active", + visibility: "private", + description: "", + joined_at: null, + is_new: false, + kind: "memory", + }, + ], + }); + resetNamespaceRoleCache(); +} + +describe("The Fetches tab", () => { + beforeEach(() => { + vi.mocked(skillUsage).mockResolvedValue(WITH_SUBJECTS); + }); + afterEach(() => { + cleanup(); + vi.clearAllMocks(); + }); + + // Fails if the tab writes a sentence of its own for the counts, drops the server's + // statement of what they cannot see, or words a fetch as an install or a use. + it("says fetched, never installed", async () => { + signIn("viewer"); + const { container } = render( {}} />); + expect(screen.getByText(SKILL)).toBeVisible(); + expect(screen.getByText(REPORT)).toBeVisible(); + const table = screen.getByRole("table", { name: "Fetches of each revision" }); + const rows = within(table).getAllByRole("row"); + expect(rows.map((row) => row.textContent)).toEqual([ + "RevisionSessionsPrincipalsLast fetchedLooks", + expect.stringMatching(/^2at least 3at least 2.+4$/), + "1at least 0at least 0—1", + ]); + expect(container.textContent).toMatch(/fetch/i); + expect(container.textContent).not.toMatch(/install|in use|active|adopt/i); + expect(await axeViolations(container)).toEqual([]); + }); + + // Fails if the read that names who fetched is made for a caller the server refuses it + // to, or if an administrator's tab does not make it or draws its rows in other words. + it("shows who fetched only to an administrator", async () => { + signIn("viewer"); + render( {}} />); + expect(screen.getByText(SKILL)).toBeVisible(); + expect(screen.queryByRole("heading", { name: "Who fetched" })).toBeNull(); + expect(vi.mocked(skillUsage)).not.toHaveBeenCalled(); + cleanup(); + + signIn("admin"); + render( {}} />); + const who = await screen.findByRole("list", { name: "Who fetched" }); + const lines = within(who) + .getAllByRole("listitem") + .map((li) => li.textContent ?? ""); + expect(lines[0]).toMatch(/^sa:deploy-botfetched revision 2 between.+and.+, over MCP, as agent-host$/); + expect(lines[1]).toMatch( + /^alicefetched revision 2 between.+, over HTTP \(the command, an SDK or a job\), as loom-cli$/, + ); + // One read, in the skill's namespace, that asks who fetched this skill. + expect(vi.mocked(skillUsage)).toHaveBeenCalledTimes(1); + expect(vi.mocked(skillUsage).mock.calls[0][0]).toEqual({ org: "dev", namespace: "ns" }); + expect(vi.mocked(skillUsage).mock.calls[0][1]).toMatchObject({ name: "deploy-notes", bySubject: true }); + }); + + // Fails if a server that does not serve the read draws an error with a Retry. + it("says one line on a server without the read", async () => { + signIn("admin"); + const absent = { answer: null, error: new ApiError({ status: 404, message: "no such op" }) }; + render( {}} />); + expect(screen.getByText("Fetch counts are not available on this deployment yet.")).toBeVisible(); + expect(screen.queryByRole("button", { name: /retry/i })).toBeNull(); + await waitFor(() => expect(vi.mocked(skillUsage)).not.toHaveBeenCalled()); + }); +}); diff --git a/frontend/src/views/skills/FetchesTab.tsx b/frontend/src/views/skills/FetchesTab.tsx new file mode 100644 index 0000000000..63f0d9f6df --- /dev/null +++ b/frontend/src/views/skills/FetchesTab.tsx @@ -0,0 +1,155 @@ +// A skill's Fetches tab: what the request ledger holds of the skill, in the server's own +// sentences, one row a revision that was fetched and, for an administrator of the +// namespace, who fetched it. A fetch is an answered read of the skill's text: the tab +// says "fetched", and nothing about what a session did with it. +import { useId, useState } from "react"; +import { skillUsage, type SkillFetchSubject, type SkillUsageResponse } from "../../api"; +import { ListTime, Loading, SectionHeading } from "../../components/ui"; +import { ListState } from "../../components/ui/ListState"; +import { useAbortableEffect } from "../../lib/hooks"; +import { isOpAbsent } from "../../lib/opAbsent"; +import { useIdentity } from "../../lib/state"; +import { useOpReason } from "../../lib/useOpReason"; + +/** The page's read of one skill's usage: the answer, or the failure. */ +export interface UsageRead { + answer: SkillUsageResponse | null; + error: unknown; +} + +/** How a fetch reached the server, in the words the command prints. */ +const OVER: Record = { + mcp: "over MCP", + http: "over HTTP (the command, an SDK or a job)", +}; + +/** `usage` is the read the skill's page made when it opened, null while it is in flight. */ +export function FetchesTab({ + namespace, + name, + usage, + onRetry, +}: { + namespace: string; + name: string; + usage: UsageRead | null; + onRetry: () => void; +}) { + if (usage === null) return ; + if (usage.answer === null) { + return isOpAbsent(usage.error) ? ( +

Fetch counts are not available on this deployment yet.

+ ) : ( + + ); + } + const skill = (usage.answer.skills ?? []).find((s) => s.name === name) ?? null; + const fetches = skill?.fetches ?? []; + return ( +
+ {skill &&

{skill.statement}

} + {fetches.length > 0 && ( +
+ + + + + + + + + + + + + {fetches.map((f) => ( + + + + + + + + ))} + +
Fetches of each revision
RevisionSessionsPrincipalsLast fetchedLooks
+ {f.revision} + at least {f.sessions.toLocaleString()}at least {f.subjects.toLocaleString()}{f.last_at ? : "—"}{f.inspector_fetches.toLocaleString()}
+
+ )} + {fetches.length > 0 && ( +

+ A look is a read from this dashboard, the assistant or a command that shows a skill. It is shown here and is + not counted as a fetch. +

+ )} +

{usage.answer.statement}

+ {skill && } +
+ ); +} + +/** One read of who fetched the skill, or its failure, with what was asked. */ +interface SubjectsRead { + key: string; + subjects: SkillFetchSubject[]; + error: unknown; +} + +/** Who fetched each revision. The request is an administrator's: nobody else's page makes + * it, and the server refuses it to anyone else. */ +function WhoFetched({ namespace, name }: { namespace: string; name: string }) { + const identity = useIdentity(); + const heading = useId(); + // `by_subject` takes the role a decision takes: admin on the namespace. + const administers = useOpReason("skill.decide", namespace) === null; + const [reads, setReads] = useState(0); + const [read, setRead] = useState(null); + const key = `${identity.org}/${namespace}/${name}/${reads}`; + useAbortableEffect( + async (signal, live) => { + if (!administers) return; + try { + const answer = await skillUsage({ org: identity.org, namespace }, { name, bySubject: true, signal }); + const subjects = (answer.skills ?? []).find((s) => s.name === name)?.subjects ?? []; + if (live()) setRead({ key, subjects, error: null }); + } catch (e) { + if (live()) setRead({ key, subjects: [], error: e }); + } + }, + [administers, identity.org, namespace, name, reads], + ); + if (!administers) return null; + const now = read?.key === key ? read : null; + return ( +
+ + {now === null && } + {now !== null && now.error !== null && ( + setReads((n) => n + 1)} /> + )} + {now !== null && now.error === null && now.subjects.length === 0 && ( +

The ledger holds no read of a published revision in this window.

+ )} + {now !== null && now.subjects.length > 0 && ( +
    + {now.subjects.map((s) => ( +
  • + {s.subject || "no sign-in"} + fetched revision {s.revision} between + + and + + + , {OVER[s.transport] ?? `over ${s.transport}`}, as {s.consumer} + +
  • + ))} +
+ )} +
+ ); +} diff --git a/frontend/src/views/skills/stale.tsx b/frontend/src/views/skills/stale.tsx new file mode 100644 index 0000000000..b4c2d1c34c --- /dev/null +++ b/frontend/src/views/skills/stale.tsx @@ -0,0 +1,44 @@ +// What `skill.usage` says needs attention on a skill, as labels. The codes are the +// server's; the page keeps a short label and the one-line meaning of each. +import { Badge } from "@clickhouse/click-ui/Badge"; +import { sentenceCase } from "../../lib/format"; + +/** The label of each stale code and what it means, in the server's own sentence for it. */ +const STALE: Record = { + draft_waiting: { label: "Long wait for review", means: "A draft has waited for review for more than 14 days." }, + unknown_operation: { + label: "Names an unknown operation", + means: "The published revision names an operation this server does not serve.", + }, +}; + +/** The label of a stale code; a code a later build answers shows by its name, in words. */ +export function staleLabel(code: string): { label: string; means?: string } { + return STALE[code] ?? { label: sentenceCase(code.replaceAll("_", " ")) }; +} + +/** One label a code. */ +export function StaleBadges({ codes }: { codes: string[] }) { + return ( + <> + {codes.map((code) => ( + + ))} + + ); +} + +/** What each code means, one line a code that this build has words for. */ +export function StaleMeanings({ codes, className = "" }: { codes: string[]; className?: string }) { + const known = codes.map(staleLabel).filter((s) => s.means); + if (known.length === 0) return null; + return ( +
+ {known.map((s) => ( +

+ {s.label}: {s.means} +

+ ))} +
+ ); +} diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go index efbda1a37d..3541fc389a 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -3167,6 +3167,12 @@ type SkillDeleteInput = wire.SkillDeleteInput // SkillDeleteOutput is the response from skill.delete. type SkillDeleteOutput = wire.SkillDeleteOutput +// SkillFetchSubject is a model used by Loom operations. +type SkillFetchSubject = wire.SkillFetchSubject + +// SkillFetches is a model used by Loom operations. +type SkillFetches = wire.SkillFetches + // SkillFile is a model used by Loom operations. type SkillFile = wire.SkillFile @@ -3212,6 +3218,15 @@ type SkillSaveOutput = wire.SkillSaveOutput // SkillSource is a model used by Loom operations. type SkillSource = wire.SkillSource +// SkillUsage is a model used by Loom operations. +type SkillUsage = wire.SkillUsage + +// SkillUsageInput is the request to skill.usage. +type SkillUsageInput = wire.SkillUsageInput + +// SkillUsageOutput is the response from skill.usage. +type SkillUsageOutput = wire.SkillUsageOutput + // SnapshotAuditRow is a model used by Loom operations. type SnapshotAuditRow = wire.SnapshotAuditRow @@ -9030,6 +9045,19 @@ func (s SkillService) Save(ctx context.Context, in SkillSaveInput) (*SkillSaveOu return callOperation[SkillSaveOutput](s.client, ctx, "skill.save", in) } +// Usage calls skill.usage. +// Use WithInput to supply additional request fields. +func (s SkillService) Usage(ctx context.Context, opts ...Option[SkillUsageInput]) (*SkillUsageOutput, error) { + in := applyOptions(opts) + if in.Namespace == "" { + in.Namespace = s.client.identity.Namespace + } + if in.Org == "" { + in.Org = s.client.identity.Org + } + return callOperation[SkillUsageOutput](s.client, ctx, "skill.usage", in) +} + // Assign calls stewardship.assign. // Use WithInput to supply additional request fields. func (s StewardshipService) Assign(ctx context.Context, targetKind string, opts ...Option[StewardshipAssignInput]) (*StewardshipAssignOutput, error) { diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 7b586769f4..c192dc3c6c 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -12851,6 +12851,26 @@ type SkillDeleteOutput struct { TextRemoved bool `json:"text_removed"` } +// SkillFetchSubject is a model used by Loom operations. +type SkillFetchSubject struct { + Subject string `json:"subject"` + Revision int64 `json:"revision"` + Transport string `json:"transport"` + Consumer string `json:"consumer"` + FirstAt string `json:"first_at"` + LastAt string `json:"last_at"` +} + +// SkillFetches is a model used by Loom operations. +type SkillFetches struct { + Revision int64 `json:"revision"` + ContentSHA256 string `json:"content_sha256"` + Sessions *int64 `json:"sessions,omitempty"` + Subjects *int64 `json:"subjects,omitempty"` + LastAt Optional[string] `json:"last_at,omitempty"` + InspectorFetches *int64 `json:"inspector_fetches,omitempty"` +} + // SkillFile is a model used by Loom operations. type SkillFile struct { Path string `json:"path"` @@ -13034,6 +13054,38 @@ type SkillSource struct { Commit *string `json:"commit,omitempty"` } +// SkillUsage is a model used by Loom operations. +type SkillUsage struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + PublishedRevision *int64 `json:"published_revision,omitempty"` + PublishedAt Optional[string] `json:"published_at,omitempty"` + Fetches *[]SkillFetches `json:"fetches,omitempty"` + Stale *[]string `json:"stale,omitempty"` + Statement *string `json:"statement,omitempty"` + Subjects *[]SkillFetchSubject `json:"subjects,omitempty"` +} + +// SkillUsageInput is the request to skill.usage. +type SkillUsageInput struct { + Org string `json:"org"` + Namespace string `json:"namespace"` + Name *string `json:"name,omitempty"` + Days *int64 `json:"days,omitempty"` + BySubject *bool `json:"by_subject,omitempty"` +} + +// SkillUsageOutput is the response from skill.usage. +type SkillUsageOutput struct { + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` + WindowDays int64 `json:"window_days"` + Statement string `json:"statement"` + Skills *[]SkillUsage `json:"skills,omitempty"` +} + // SnapshotAuditRow is a model used by Loom operations. type SnapshotAuditRow struct { Ts string `json:"ts"` diff --git a/sdk/python/loom/cli_skill.py b/sdk/python/loom/cli_skill.py index 8243756af5..1bf1c44c6d 100644 --- a/sdk/python/loom/cli_skill.py +++ b/sdk/python/loom/cli_skill.py @@ -1,6 +1,7 @@ """`loom skill list | show | diff | check | save | publish | reject | archive | delete | -pull | status`: read the skills a server holds, check a folder, save one as a draft, -decide a revision, delete a revision or a whole skill, and write a skill to a folder. +pull | status | usage`: read the skills a server holds, check a folder, save one as a +draft, decide a revision, delete a revision or a whole skill, write a skill to a folder, +and report which revisions were fetched. `list` prints the catalog `skill.list` answers. `show` prints one skill as `skill.get` answers it: the server's notice, `SKILL.md`, then the files beside it. Exit 0 when the @@ -46,6 +47,9 @@ server answers it, and `list` names the namespaces whose skills no session of the caller is listed. A server that answers neither field prints neither. +`usage` prints which revisions of a namespace's skills were fetched and which skills +are stale, in the server's sentences (`loom.cli_skill_usage`). + `pull` writes a revision to a folder beside a lock file and `status` compares such folders with what the server serves (`loom.cli_skill_pull`). `check`, `save` and `diff` refuse a pulled folder whose namespace token was replaced, before any request: its text @@ -84,7 +88,8 @@ _GROUP_HELP = """List and read the skills a Loom server holds, check a skill folder against its package rules, save one as a draft, publish, reject or archive it, delete a -revision or a whole skill, and write a published skill to a folder. +revision or a whole skill, write a published skill to a folder, and report which +revisions were fetched. loom skill list loom skill show loom --builtin @@ -95,6 +100,7 @@ loom skill delete team/deploy-notes --revision 2 loom skill pull team/deploy-notes --to skills loom skill status skills + loom skill usage team """ _LIST_HELP = """List skills: the ones your namespaces hold, then the ones built into the @@ -278,7 +284,8 @@ def _caller_flags(p: Any) -> None: def add_parser(sub: Any) -> None: p = sub.add_parser( "skill", - help="list and read the server's skills, check a folder, save, decide, delete and pull", + help="list and read the server's skills, check a folder, save, decide, delete, pull " + "and report fetches", description=_GROUP_HELP, formatter_class=argparse.RawDescriptionHelpFormatter, ) @@ -338,10 +345,11 @@ def add_parser(sub: Any) -> None: delete.add_argument("--apply", action="store_true", help="delete (default: only read)") _caller_flags(delete) _add_review_parsers(actions) - # Imported here: the module takes its helpers from this one. - from loom import cli_skill_pull + # Imported here: the modules take their helpers from this one. + from loom import cli_skill_pull, cli_skill_usage cli_skill_pull.add_parsers(actions) + cli_skill_usage.add_parsers(actions) def _add_review_parsers(actions: Any) -> None: @@ -1141,7 +1149,7 @@ def _decide(args: argparse.Namespace, server: str | None) -> int: def run(args: argparse.Namespace, server: str | None) -> int: """Run `loom skill `; a request that fails raises, as every command's does.""" - from loom import cli_skill_pull + from loom import cli_skill_pull, cli_skill_usage actions = { "list": _list, @@ -1155,5 +1163,6 @@ def run(args: argparse.Namespace, server: str | None) -> int: "delete": _delete, "pull": cli_skill_pull.pull, "status": cli_skill_pull.status, + "usage": cli_skill_usage.usage, } return actions[args.action](args, server) diff --git a/sdk/python/loom/cli_skill_usage.py b/sdk/python/loom/cli_skill_usage.py new file mode 100644 index 0000000000..317aceab93 --- /dev/null +++ b/sdk/python/loom/cli_skill_usage.py @@ -0,0 +1,110 @@ +"""`loom skill usage [/]`: which revisions of a namespace's skills were +fetched from the server, and which skills are stale. + +The command prints what `skill.usage` answers. Every sentence is the server's: the +statement of what the counts mean and what the report cannot see, then for each skill +its own statement. Under it come the numbers the sentences are built from, one line a +revision, and the stale codes. `--by-subject` adds who fetched each revision, which the +server answers to an administrator of the namespace and refuses to anyone else. + +A count is a lower bound, and a fetch is a request for the skill's text: the command +never says what a session did with it. + +Exit 0 when the report was printed, 2 when the server does not serve `skill.usage`. +""" + +from __future__ import annotations + +import argparse +import json +from typing import Any + +from loom.cli_skill import _action, _ask, _caller_flags, _shown + +USAGE_OP = "skill.usage" + +_USAGE_HELP = """Report which revisions of a namespace's skills were fetched from the server, +and which skills are stale. + + loom skill usage team + loom skill usage team/deploy-notes --days 90 + loom skill usage team --by-subject --json + +A fetch is a request for a published revision's text that the server's request ledger +holds. Every count is a lower bound: the ledger can drop a row, and a copy pulled to a +folder is read without a fetch. A look from the dashboard, the assistant or +`loom skill show` is counted apart. The report lists the skills you can list in the +namespace; --by-subject names who fetched each revision and needs admin on it. + +Exit 0 when the report was printed, 2 when the server does not serve skill.usage. +""" + +# How a fetch reached the server, in the words every surface uses. +_OVER = {"mcp": "over MCP", "http": "over HTTP (the command, an SDK or a job)"} + + +def add_parsers(actions: Any) -> None: + usage = _action(actions, "usage", "report which revisions were fetched", _USAGE_HELP) + usage.add_argument("skills", metavar="namespace[/name]", help="a namespace, or one skill of it") + usage.add_argument( + "--days", type=int, metavar="N", help="count fetches of the last N days, 1 to 90" + ) + usage.add_argument( + "--by-subject", action="store_true", help="name who fetched each revision (admin)" + ) + _caller_flags(usage) + + +def _revision_line(entry: dict[str, Any]) -> str: + """The numbers of one revision's sentence. `>=` marks a lower bound.""" + last = entry.get("last_at") or "never" + return ( + f" revision {entry.get('revision')} sessions >= {entry.get('sessions', 0)} " + f"principals >= {entry.get('subjects', 0)} last fetched {last} " + f"looks {entry.get('inspector_fetches', 0)}" + ) + + +def _subject_line(entry: dict[str, Any]) -> str: + who = entry.get("subject") or "(no principal)" + transport = str(entry.get("transport") or "") + over = _OVER.get(transport, f"over {transport}") + return ( + f" {who} fetched revision {entry.get('revision')} between {entry.get('first_at')} " + f"and {entry.get('last_at')}, {over}, as {entry.get('consumer')}" + ) + + +def render_usage(answer: dict[str, Any]) -> str: + """The report as text: the server's statement, then each skill under its own.""" + parts = [_shown(answer.get("statement", ""))] + for skill in answer.get("skills") or []: + served = skill.get("published_revision") + state = f"revision {served} is published" if served else "nothing is published" + parts += ["", _shown(f"{skill.get('namespace')}/{skill.get('name')} {state}")] + parts.append(_shown(f" {skill.get('statement', '')}")) + parts += [_shown(_revision_line(entry)) for entry in skill.get("fetches") or []] + if skill.get("stale"): + parts.append(_shown(f" stale: {', '.join(skill['stale'])}")) + if skill.get("subjects"): + parts.append(" who fetched:") + parts += [_shown(_subject_line(entry)) for entry in skill["subjects"]] + if not answer.get("skills"): + parts += ["", "no skill to report"] + return "\n".join(parts) + + +def usage(args: argparse.Namespace, server: str | None) -> int: + namespace, _, name = args.skills.rpartition("/") + if not namespace: + namespace, name = name, "" + fields: dict[str, Any] = {"name": name} + if args.days is not None: + fields["days"] = args.days + if args.by_subject: + fields["by_subject"] = True + answer, _ = _ask(args, server, USAGE_OP, fields, namespace) + if answer is None: + return 2 + print(json.dumps(answer, indent=2) if args.json else render_usage(answer)) + return 0 diff --git a/sdk/python/loom/client.py b/sdk/python/loom/client.py index 4173c56fa0..6dfd0ddb00 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -3480,6 +3480,12 @@ async def save( """`skill.save`.""" return cast("_ops.SkillSaveOutput", await self._agent.call("skill.save", body, **options)) + async def usage( + self, body: _ops.SkillUsageBody | None = None, /, **options: Any + ) -> _ops.SkillUsageOutput: + """`skill.usage`.""" + return cast("_ops.SkillUsageOutput", await self._agent.call("skill.usage", body, **options)) + class StewardshipOps: """The `stewardship.*` operations.""" diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 078e438baf..f2246472c1 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -405,6 +405,7 @@ class OpSpec: "skill.get", "skill.list", "skill.save", + "skill.usage", "stewardship.assign", "stewardship.get", "stewardship.list", @@ -829,6 +830,7 @@ class OpSpec: "skill.get", "skill.list", "skill.save", + "skill.usage", "stewardship.assign", "stewardship.get", "stewardship.list", @@ -5279,6 +5281,18 @@ class OpSpec: True, False, ), + "skill.usage": OpSpec( + "skill.usage", + "SkillUsageInput", + "SkillUsageBody", + "SkillUsageOutput", + True, + "viewer", + "experimental", + 1000, + False, + True, + ), "stewardship.assign": OpSpec( "stewardship.assign", "StewardshipAssignInput", @@ -22259,6 +22273,61 @@ class SkillCurrent(TypedDict, total=False): content_sha256: Required[str] +class SkillUsageInput(TypedDict, total=False): + "Report which revisions of a namespace's skills were fetched, and which skills" + + org: Required[str] + namespace: Required[str] + name: NotRequired[str] + days: NotRequired[int] + by_subject: NotRequired[bool] + + +class SkillUsageBody(TypedDict, total=False): + "Report which revisions of a namespace's skills were fetched, and which skills" + + org: NotRequired[str] + namespace: NotRequired[str] + name: NotRequired[str] + days: NotRequired[int] + by_subject: NotRequired[bool] + + +class SkillUsageOutput(TypedDict, total=False): + window_days: Required[int] + statement: Required[str] + skills: NotRequired[list["SkillUsage"]] + + +class SkillUsage(TypedDict, total=False): + namespace: Required[str] + name: Required[str] + published_revision: NotRequired[int] + published_at: NotRequired[Optional[str]] + fetches: NotRequired[list["SkillFetches"]] + stale: NotRequired[list[str]] + statement: NotRequired[str] + subjects: NotRequired[list["SkillFetchSubject"]] + + +class SkillFetches(TypedDict, total=False): + revision: Required[int] + content_sha256: Required[str] + sessions: NotRequired[int] + subjects: NotRequired[int] + last_at: NotRequired[Optional[str]] + inspector_fetches: NotRequired[int] + + +class SkillFetchSubject(TypedDict, total=False): + subject: Required[str] + revision: Required[int] + transport: Required[str] + consumer: Required[str] + first_at: Required[str] # date-time as ISO-8601 text + last_at: Required[str] # date-time as ISO-8601 text + + class StewardshipAssignInput(TypedDict, total=False): "Name who answers for a shared memory or a document and how often it is reviewed," diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 446963af22..37f09d3e55 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -8,7 +8,7 @@ module Loom # Every served operation: its spec in OPS, and one method per op on the class # of its group (`client.memory.set(...)` is `memory.set`). module Generated - OP_COUNT = 421 + OP_COUNT = 422 # The declared spec of every served op, by name; the HTTP path is /v1/. OPS = { @@ -378,6 +378,7 @@ module Generated "skill.get" => OpSpec.new("skill.get", "skill", "get", true, true, "viewer", "experimental", %w[org namespace name kind include_files path revision history].freeze, %w[org namespace name].freeze), "skill.list" => OpSpec.new("skill.list", "skill", "list", true, true, "viewer", "experimental", %w[org namespace namespace_scope kind state open_draft_only query limit cursor count_only].freeze, %w[org namespace].freeze), "skill.save" => OpSpec.new("skill.save", "skill", "save", true, false, "writer", "experimental", %w[org namespace files expected_revision note source source_class].freeze, %w[org namespace files].freeze), + "skill.usage" => OpSpec.new("skill.usage", "skill", "usage", true, true, "viewer", "experimental", %w[org namespace name days by_subject].freeze, %w[org namespace].freeze), "stewardship.assign" => OpSpec.new("stewardship.assign", "stewardship", "assign", true, false, "admin", "experimental", %w[org namespace target_kind target_key agent steward review_every_days].freeze, %w[org namespace target_kind].freeze), "stewardship.get" => OpSpec.new("stewardship.get", "stewardship", "get", true, true, "viewer", "experimental", %w[org namespace target_kind target_key agent].freeze, %w[org namespace target_kind].freeze), "stewardship.list" => OpSpec.new("stewardship.list", "stewardship", "list", true, true, "viewer", "experimental", %w[org namespace state problems_only mine limit fields].freeze, %w[org namespace].freeze), @@ -2937,6 +2938,13 @@ def list(body = nil, request_options: nil, **fields) def save(body = nil, request_options: nil, **fields) call_op("skill.save", body, fields, request_options) end + + # `skill.usage` (viewer, read-only, experimental). + # Report which revisions of a namespace's skills were fetched, and which skills + # Required: org, namespace. + def usage(body = nil, request_options: nil, **fields) + call_op("skill.usage", body, fields, request_options) + end end # The `stewardship.*` operations. diff --git a/sdk/rust/src/blocking_operations.rs b/sdk/rust/src/blocking_operations.rs index faaed5c3d6..014f6b5641 100644 --- a/sdk/rust/src/blocking_operations.rs +++ b/sdk/rust/src/blocking_operations.rs @@ -6978,6 +6978,23 @@ impl crate::blocking::Client { ) -> Result, crate::CallFailure> { self.call("skill.decide", &request, options) } + /// Call `skill.usage`. + pub fn skill_usage( + &self, + request: crate::SkillUsageInput, + ) -> Result { + self.skill_usage_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `skill.usage` with per-request options and metadata. + pub fn skill_usage_with_options( + &self, + request: crate::SkillUsageInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("skill.usage", &request, options) + } /// Call `stewardship.assign`. pub fn stewardship_assign( &self, diff --git a/sdk/rust/src/operations.rs b/sdk/rust/src/operations.rs index 5402d284b6..4d8bcef4e1 100644 --- a/sdk/rust/src/operations.rs +++ b/sdk/rust/src/operations.rs @@ -7455,6 +7455,24 @@ impl crate::Client { ) -> Result, crate::CallFailure> { self.call("skill.decide", &request, options).await } + /// Call `skill.usage`. + pub async fn skill_usage( + &self, + request: crate::SkillUsageInput, + ) -> Result { + self.skill_usage_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `skill.usage` with per-request options and metadata. + pub async fn skill_usage_with_options( + &self, + request: crate::SkillUsageInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("skill.usage", &request, options).await + } /// Call `stewardship.assign`. pub async fn stewardship_assign( &self, diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index 4c0135bc70..bdda35ed37 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -2118,6 +2118,7 @@ pub(crate) const OP_POLICIES: &[OperationPolicy] = &[ ("skill.save", true, false, &["namespace", "org"], &[]), ("skill.delete", true, false, &["namespace", "org"], &[]), ("skill.decide", true, false, &["namespace", "org"], &[]), + ("skill.usage", true, true, &["namespace", "org"], &[]), ( "stewardship.assign", true, @@ -61278,6 +61279,138 @@ impl SkillSaveInput { } } +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct SkillFetches { + pub revision: Integer, + pub content_sha256: String, + #[serde(default = "default_skill_fetches_sessions")] + pub sessions: Integer, + #[serde(default = "default_skill_fetches_subjects")] + pub subjects: Integer, + #[serde(default = "default_skill_fetches_last_at")] + pub last_at: Option, + #[serde(default = "default_skill_fetches_inspector_fetches")] + pub inspector_fetches: Integer, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct SkillFetchSubject { + pub subject: String, + pub revision: Integer, + pub transport: String, + pub consumer: String, + pub first_at: String, + pub last_at: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct SkillUsage { + pub namespace: String, + pub name: String, + #[serde(default = "default_skill_usage_published_revision")] + pub published_revision: Integer, + #[serde(default = "default_skill_usage_published_at")] + pub published_at: Option, + #[serde(default = "default_skill_usage_fetches")] + pub fetches: Vec, + #[serde(default = "default_skill_usage_stale")] + pub stale: Vec, + #[serde(default = "default_skill_usage_statement")] + pub statement: String, + #[serde(default = "default_skill_usage_subjects")] + pub subjects: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct SkillUsageOutput { + pub window_days: Integer, + pub statement: String, + #[serde(default = "default_skill_usage_output_skills")] + pub skills: Vec, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct SkillUsageInput { + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub org: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub namespace: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub name: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub days: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub by_subject: Option, +} +impl Default for SkillUsageInput { + fn default() -> Self { + Self::new() + } +} +impl SkillUsageInput { + pub fn new() -> Self { + Self { + org: None, + namespace: None, + name: None, + days: None, + by_subject: None, + } + } + pub fn org(mut self, org: impl Into) -> Self { + self.org = Some(org.into()); + self + } + pub fn namespace(mut self, namespace: impl Into) -> Self { + self.namespace = Some(namespace.into()); + self + } + pub fn name(mut self, name: impl Into) -> Self { + self.name = Some(name.into()); + self + } + pub fn days(mut self, days: impl Into) -> Self { + self.days = Some(days.into()); + self + } + pub fn by_subject(mut self, by_subject: bool) -> Self { + self.by_subject = Some(by_subject); + self + } + pub async fn send( + self, + client: &crate::Client, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + client.call("skill.usage", &self, options).await + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[non_exhaustive] pub enum StewardshipItemTargetKind { @@ -75132,6 +75265,39 @@ fn default_skill_save_output_operations() -> Vec { fn default_skill_save_output_current() -> Option { serde_json::from_str("null").expect("schema default") } +fn default_skill_usage_published_revision() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_skill_usage_published_at() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_skill_fetches_sessions() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_skill_fetches_subjects() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_skill_fetches_last_at() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_skill_fetches_inspector_fetches() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_skill_usage_fetches() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_skill_usage_stale() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_skill_usage_statement() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_skill_usage_subjects() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_skill_usage_output_skills() -> Vec { + serde_json::from_str("[]").expect("schema default") +} fn default_stewardship_assign_output_item() -> Option { serde_json::from_str("null").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index afb7ec2126..3b7fc468ab 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -14069,6 +14069,22 @@ fn skill_decide() { ); } #[test] +fn skill_usage() { + let value: clickhouse_loom::SkillUsageInput = + serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\"}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::SkillUsageOutput = + serde_json::from_str("{\"window_days\":1,\"statement\":\"sample\"}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + assert_eq!( + encoded["skills"], + serde_json::from_str::("[]").unwrap(), + "skill.usage:skills" + ); +} +#[test] fn stewardship_assign() { let value: clickhouse_loom::StewardshipAssignInput = serde_json::from_str( "{\"org\":\"sample\",\"namespace\":\"sample\",\"target_kind\":\"memory\"}", diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 0eecae5a92..2d11086656 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -11246,6 +11246,49 @@ export interface SkillSaveOutput { current?: SkillCurrent | null; } +export interface SkillUsageInput { + org: string; + namespace: string; + name?: string; + days?: number; + by_subject?: boolean; +} + +export interface SkillUsage { + namespace: string; + name: string; + published_revision?: number; + published_at?: string | null; + fetches?: SkillFetches[]; + stale?: string[]; + statement?: string; + subjects?: SkillFetchSubject[]; +} + +export interface SkillFetches { + revision: number; + content_sha256: string; + sessions?: number; + subjects?: number; + last_at?: string | null; + inspector_fetches?: number; +} + +export interface SkillFetchSubject { + subject: string; + revision: number; + transport: string; + consumer: string; + first_at: string; // date-time + last_at: string; // date-time +} + +export interface SkillUsageOutput { + window_days: number; + statement: string; + skills?: SkillUsage[]; +} + export interface StewardshipAssignInput { org: string; namespace: string; @@ -12623,6 +12666,7 @@ export type OpName = | "skill.get" | "skill.list" | "skill.save" + | "skill.usage" | "stewardship.assign" | "stewardship.get" | "stewardship.list" @@ -13047,6 +13091,7 @@ export interface OpMap { "skill.get": { input: SkillGetInput; output: SkillGetOutput }; "skill.list": { input: SkillListInput; output: SkillListOutput }; "skill.save": { input: SkillSaveInput; output: SkillSaveOutput }; + "skill.usage": { input: SkillUsageInput; output: SkillUsageOutput }; "stewardship.assign": { input: StewardshipAssignInput; output: StewardshipAssignOutput }; "stewardship.get": { input: StewardshipGetInput; output: StewardshipGetOutput }; "stewardship.list": { input: StewardshipListInput; output: StewardshipListOutput }; @@ -13471,6 +13516,7 @@ export const OPS: readonly OpSpec[] = [ { name: "skill.get", group: "skill", method: "get", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 300, audit: false, readOnly: true }, { name: "skill.list", group: "skill", method: "list", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 200, audit: false, readOnly: true }, { name: "skill.save", group: "skill", method: "save", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 600, audit: true, readOnly: false }, + { name: "skill.usage", group: "skill", method: "usage", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 1000, audit: false, readOnly: true }, { name: "stewardship.assign", group: "stewardship", method: "assign", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 800, audit: true, readOnly: false }, { name: "stewardship.get", group: "stewardship", method: "get", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 300, audit: false, readOnly: true }, { name: "stewardship.list", group: "stewardship", method: "list", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 1500, audit: false, readOnly: true }, @@ -13532,4 +13578,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 421; +export const GENERATED_OP_COUNT = 422; diff --git a/server/cli/login.py b/server/cli/login.py index a91fdb7350..9282482cea 100644 --- a/server/cli/login.py +++ b/server/cli/login.py @@ -21,8 +21,8 @@ "curator": "Report what in a namespace needs a person, and set its curator mode " "(`loom curator --help`).", "skill": "List and read the server's skills, check a skill folder, save one as a draft, " - "publish, reject, archive or delete it, and write a published skill to a folder " - "(`loom skill --help`).", + "publish, reject, archive or delete it, write a published skill to a folder, and " + "report which revisions were fetched (`loom skill --help`).", "copy-rule": "Preview a namespace's copy rule, or run it to propose each new match " "(`loom copy-rule --help`).", "proposals": "List a namespace's pending proposals, read one whole, and accept or reject " diff --git a/server/identity/api/models_skills.py b/server/identity/api/models_skills.py index fdd0ad9dd5..415ba9f6a3 100644 --- a/server/identity/api/models_skills.py +++ b/server/identity/api/models_skills.py @@ -493,3 +493,99 @@ class SkillDecideOutput(BaseModel): revision_state: RevisionState = "" # The served revision's number after the call; 0 when none is served. published_revision: int = 0 + + +class SkillUsageInput(BaseModel): + """Report which revisions of a namespace's skills were fetched, and which skills + are stale. + + A fetch is an answered `skill.get` the request ledger holds for a revision that is + or was published; a read by the dashboard, the assistant or a command that shows a + skill is counted apart. Every count is a lower bound, and `statement` says what the + report cannot see: a copy pulled to a folder is read without a fetch, and no count + says what a session did with the text. The caller is answered the skills + `skill.list` lists to it; a name it cannot list answers `skills: []`.""" + + org: str + namespace: str + # The skill to report; empty (the default) reports every skill of the namespace + # the caller can list. + name: str = Field(default="", max_length=512) + # How many days back fetches are counted, 1 to 90; default 30. + days: int = Field(default=30, ge=1, le=90) + # Fill `subjects` with who fetched each revision; needs admin on the namespace, + # else 403. Default false. + by_subject: bool = False + + +class SkillFetches(BaseModel): + # The revision fetched. The ledger keeps the hash a read answered: of two published + # revisions with one hash, the higher number. + revision: int + # The hash of that revision's files. + content_sha256: str + # How many sessions fetched it, at least. A fetch that named no session counts in + # `subjects` only. + sessions: int = 0 + # How many principals fetched it, at least. + subjects: int = 0 + # When it was last fetched; None when only inspectors read it. + last_at: datetime | None = None + # How many reads of it the dashboard, the assistant and a command that shows a skill + # made: looks, counted in neither `sessions` nor `subjects`. + inspector_fetches: int = 0 + + +class SkillFetchSubject(BaseModel): + # The token subject that read the revision; empty when sign-in is off. + subject: str + # The revision read. + revision: int + # `mcp` or `http` (the command, an SDK or a job). + transport: str + # The consumer the reads named; `loom-ui`, `loom-assistant` and `loom-cli-inspect` + # are looks, which `fetches` counts apart. + consumer: str + # The first and the last read in the window. + first_at: datetime + last_at: datetime + + +class SkillUsage(BaseModel): + # The namespace that holds the skill. + namespace: str + # The skill's name. + name: str + # The served revision's number; 0 when none is served. + published_revision: int = 0 + # When the served revision was published; None when none is served. + published_at: datetime | None = None + # One entry for each revision that is or was published and was read in the window, + # highest revision first. A revision that was never published has none. + fetches: list[SkillFetches] = Field(default_factory=list) + # What needs attention, each proven by rows the skill holds: `draft_waiting` (the + # open draft has waited more than 14 days; answered to a caller who may write to + # the namespace) and `unknown_operation` (the published revision names an operation + # this build does not serve). A later build may answer a code not named here. A + # skill nobody fetched has no code for that. + stale: list[str] = Field(default_factory=list) + # The counts in words: a sentence for each fetched revision, or that the skill was + # not fetched in the window, then a sentence for each code of `stale`. + statement: str = "" + # With `by_subject`, who read each revision: one entry a principal, revision, + # transport and consumer, highest revision first. + subjects: list[SkillFetchSubject] = Field(default_factory=list) + + +class SkillUsageOutput(BaseModel): + # The days the counts cover: `days`, or the days the request ledger is kept when + # that is fewer. + window_days: int + # What every count means and what the report cannot see: the counts are lower + # bounds, which sessions were shown a listing is not recorded, how many of the + # namespace's skills a listing can carry and in what order, and whether the window + # or the ledger read was cut. + statement: str + # The namespace's skills the caller can list, by name; with `name`, that skill + # alone, and none when the caller cannot list it. + skills: list[SkillUsage] = Field(default_factory=list) diff --git a/server/identity/api/ops_skills.py b/server/identity/api/ops_skills.py index d5a095efd0..d123fba643 100644 --- a/server/identity/api/ops_skills.py +++ b/server/identity/api/ops_skills.py @@ -15,10 +15,13 @@ SkillListOutput, SkillSaveInput, SkillSaveOutput, + SkillUsageInput, + SkillUsageOutput, ) from server.identity.app.skill_decide import handle_skill_decide from server.identity.app.skill_delete import handle_skill_delete from server.identity.app.skill_save import handle_skill_save, save_audit_subject +from server.identity.app.skill_usage import handle_skill_usage from server.identity.app.skills import handle_skill_check, handle_skill_get, handle_skill_list from server.operations.base import Operation, Role @@ -98,6 +101,17 @@ audit=False, ) +skill_usage = Operation( + name="skill.usage", + maturity="experimental", + input_model=SkillUsageInput, + output_model=SkillUsageOutput, + handler=handle_skill_usage, + idempotent=True, + required_role=Role.VIEWER, + audit=False, +) + OPERATIONS: list[Operation] = [ skill_check, skill_list, @@ -105,4 +119,5 @@ skill_save, skill_delete, skill_decide, + skill_usage, ] diff --git a/server/identity/app/skill_usage.py b/server/identity/app/skill_usage.py new file mode 100644 index 0000000000..2abdcabac9 --- /dev/null +++ b/server/identity/app/skill_usage.py @@ -0,0 +1,156 @@ +"""`skill.usage`: which revisions of a namespace's skills were fetched, and which +skills are stale. + +Loom holds one record of a skill being loaded: the request ledger's row of a +`skill.get` that answered its text. The op reads the acts of the namespace's skills +(`repo.usage_acts`, without text) and one statement over the ledger +(`skill_fetches.fetch_groups`), and answers what `server.identity.domain.skill_usage` +makes of them: a count a revision, the stale codes, and the sentences that say what +the numbers mean. + +The caller is answered the skills `skill.list` lists to it (`skills.listed_row`): a +writer of the namespace every skill, any other reader the ones that serve a revision. +Who fetched what is an administrator's to read. A ledger read that fails fails the op: +it is never answered as no fetch. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta + +from server.core.ch import own_write_reads +from server.core.datetimes import naive_utc_now +from server.core.errors import AuthInsufficientError +from server.identity.api.models_skills import ( + SkillFetches, + SkillFetchSubject, + SkillUsage, + SkillUsageInput, + SkillUsageOutput, +) +from server.identity.app import skills +from server.identity.app.registration import namespace_retention_days +from server.identity.domain import skill_usage as usage +from server.identity.domain.skill_drafts import by_skill +from server.identity.domain.skill_format import listing_line +from server.identity.domain.skill_state import SkillState, fold +from server.identity.store import skill_fetches +from server.identity.store import skills as repo +from server.observability.consumer import INSPECTOR_CONSUMERS +from server.settings import settings + + +async def _administers(org: str, namespace: str) -> bool: + """Whether the caller holds ADMIN on the namespace. With sign-in off every + namespace is the one user's.""" + # Lazy: server.auth.context pulls in authz, which imports the op modules. + from server.auth.authz import CachedGate + from server.auth.context import current_auth + from server.operations.base import Role + + auth = current_auth() + if auth is None: + return not settings.auth_actually_required() + return await CachedGate(auth, org).admits(namespace, Role.ADMIN) + + +def _names_unknown_operation(state: SkillState) -> bool: + """Whether the served revision's stored names hold one this build's registry does + not serve. The names are the ones its save took from the text.""" + served = state.revisions.get(state.served.revision) if state.served else None + if served is None: + return False + return any(not op.known for op in skills.stored_operations(served.row["op_names"])) + + +def _listed(namespace: str, name: str, state: SkillState) -> bool: + """Whether a session's listing may carry the skill: it serves a revision that asks + to be listed.""" + served = state.served + return served is not None and bool( + listing_line( + namespace, name, str(served.row["description"]), listed=bool(served.row["listed"]) + ) + ) + + +def _usage( + input: SkillUsageInput, + name: str, + state: SkillState, + revisions: list[usage.Published], + groups: dict[str, list[usage.Group]], + *, + writer: bool, + window: int, + now: datetime, +) -> SkillUsage: + fetches = usage.counts(groups, revisions, INSPECTOR_CONSUMERS) + codes = usage.stale_codes( + state, writer=writer, unknown_operation=_names_unknown_operation(state), now=now + ) + who = usage.subjects(groups, revisions) if input.by_subject else [] + return SkillUsage( + namespace=input.namespace, + name=name, + published_revision=state.served.revision if state.served else 0, + published_at=state.served.row["at"] if state.served else None, + fetches=[SkillFetches(**f._asdict()) for f in fetches], + stale=codes, + statement=usage.skill_statement(fetches, codes, window), + subjects=[SkillFetchSubject(**s._asdict()) for s in who], + ) + + +async def handle_skill_usage(input: SkillUsageInput) -> SkillUsageOutput: + readable, writable = await skills._reach(input.org, [input.namespace]) + if input.by_subject and not await _administers(input.org, input.namespace): + raise AuthInsufficientError( + f"`by_subject` names who fetched a skill: it needs admin on {input.namespace!r}" + ) + kept = await namespace_retention_days(input.org, input.namespace) or int( + settings.retention_agent_events_days + ) + window = usage.window_days(input.days, kept) + now = naive_utc_now() + # No reader is reported a skill an archive stopped, on any replica. + with own_write_reads(): + acts = await repo.usage_acts(input.org, input.namespace) if readable else [] + writer = bool(writable) + listed = 0 + reported: dict[str, tuple[SkillState, list[usage.Published]]] = {} + since: dict[str, datetime] = {} + for (_, name), rows in by_skill(acts).items(): + state = fold(rows) + listed += _listed(input.namespace, name, state) + # After the fold and the caller's reach, as a listing filters: never in the + # statement that feeds them. + if input.name and name != input.name: + continue + if skills.listed_row(input.namespace, name, rows, writer=writer) is None: + continue + revisions = usage.published(rows, state) + reported[name] = (state, revisions) + since |= usage.hash_times(revisions) + # One more than a report folds, so a read the limit cut is told from a whole one. + found = await skill_fetches.fetch_groups( + input.org, + input.namespace, + now - timedelta(days=window), + since, + usage.FETCH_GROUPS_MAX + 1, + ) + groups = usage.by_hash(found[: usage.FETCH_GROUPS_MAX]) + return SkillUsageOutput( + window_days=window, + statement=usage.report_statement( + days=input.days, + kept_days=kept, + listed=listed, + cut=len(found) > usage.FETCH_GROUPS_MAX, + ), + skills=[ + _usage(input, name, *reported[name], groups, writer=writer, window=window, now=now) + for name in sorted(reported) + ], + ) diff --git a/server/identity/app/skills.py b/server/identity/app/skills.py index 3595938df1..8c2495d8f5 100644 --- a/server/identity/app/skills.py +++ b/server/identity/app/skills.py @@ -403,6 +403,13 @@ def _served_row(namespace: str, name: str, rows: Sequence[Row]) -> SkillRow | No ) +def listed_row(namespace: str, name: str, rows: Sequence[Row], *, writer: bool) -> SkillRow | None: + """One skill as its caller lists it, None for a skill the caller is not listed: the + one rule of who lists which skill, for the listing and for every report that + names the skills of a namespace.""" + return (_team_row if writer else _served_row)(namespace, name, rows) + + async def _team_rows(input: SkillListInput) -> _Team: split = await namespaces_to_search(input.org, input.namespace, input.namespace_scope) readable, writable = await _reach(input.org, split.read) @@ -411,7 +418,7 @@ async def _team_rows(input: SkillListInput) -> _Team: with own_write_reads(): acts = await repo.namespace_acts(input.org, readable) found = [ - (_team_row if ns in writable else _served_row)(ns, name, rows) + listed_row(ns, name, rows, writer=ns in writable) for (ns, name), rows in by_skill(acts).items() ] rows = [r for r in found if r] diff --git a/server/identity/domain/skill_usage.py b/server/identity/domain/skill_usage.py new file mode 100644 index 0000000000..cf621d5291 --- /dev/null +++ b/server/identity/domain/skill_usage.py @@ -0,0 +1,251 @@ +"""What `skill.usage` reports of a namespace's skills: which fetches count, what is +stale, and the sentences that say what the numbers mean. + +A fetch is one answered `skill.get` whose hash is that of a revision that is or was +published, made after that revision's first `publish` row. `published` names those +revisions and `hash_times` the time each counts from; the store's statement keeps the +ledger rows of their hashes from that time on and answers them in groups, and `counts` +makes one entry a revision of them. A read by an inspector (the dashboard, the +assistant, a command that shows a skill) is a look: it is shown beside the fetches and +never counted as one. + +Every sentence of a report is built here, from the counts, so a command and a page +print the server's words. A count is a lower bound, because the ledger can drop a +row, and no sentence says what a session did with the text it fetched. Pure, no I/O. +""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping, Sequence +from datetime import datetime, timedelta +from typing import Any, NamedTuple + +from server.identity.domain.skill_state import ( + PUBLISH, + PUBLISHED, + SUPERSEDED, + WITHDRAWN, + Row, + SkillState, +) + +# not a setting: the wire refuses a longer window, and the SDKs carry the bound +DAYS_MAX = 90 +# not a setting: a stale code means the same age on every deployment that answers it +DRAFT_WAITING_DAYS = 14 +# not a setting: the most groups one report folds; a read cut here says so in its statement +FETCH_GROUPS_MAX = 10_000 + +# The stale codes, a closed set: each is proven by rows the skill holds. +DRAFT_WAITING = "draft_waiting" # the open draft has waited past DRAFT_WAITING_DAYS +UNKNOWN_OPERATION = "unknown_operation" # the published text names an op this build lacks + +# The session a ledger row carries when its request named none. +NO_SESSION = "-" +# The states of a revision whose text a reader was served at some time. +_WAS_PUBLISHED = (PUBLISHED, SUPERSEDED, WITHDRAWN) + +_STALE_SENTENCE = { + DRAFT_WAITING: f"A draft has waited for review for more than {DRAFT_WAITING_DAYS} days.", + UNKNOWN_OPERATION: "The published revision names an operation this server does not serve.", +} + +# One group of the ledger's rows: `content_sha256`, `session_id`, `subject`, `consumer`, +# `transport`, `fetches`, `first_at` and `last_at`. +Group = Mapping[str, Any] + + +class Published(NamedTuple): + """A revision that is or was published: its number, its hash, and when its first + `publish` row was recorded.""" + + revision: int + content_sha256: str + at: datetime + + +class Fetches(NamedTuple): + """The fetches of one revision. `last_at` is None when only inspectors read it.""" + + revision: int + content_sha256: str + sessions: int + subjects: int + last_at: datetime | None + inspector_fetches: int + + +class SubjectFetches(NamedTuple): + """One principal's reads of one revision over one transport, under one consumer.""" + + subject: str + revision: int + transport: str + consumer: str + first_at: datetime + last_at: datetime + + +def window_days(days: int, kept_days: int) -> int: + """The days a report covers: `days`, or the days the ledger is kept when that is + fewer. `kept_days` is 0 for a ledger kept forever.""" + return min(days, kept_days) if kept_days else days + + +def published(rows: Sequence[Row], state: SkillState) -> list[Published]: + """The revisions of one skill that are or were published, lowest number first. + Which revisions those are is the fold's answer (`state`); the time is the earliest + `publish` row that names the revision's number and hash. A draft, a rejected + revision and a void one are not answered, so no fetch is counted for them.""" + first: dict[tuple[int, str], datetime] = {} + for row in rows: + if row["act"] == PUBLISH: + key = (int(row["revision"]), str(row["content_sha256"])) + first[key] = min(first.get(key, row["at"]), row["at"]) + found = [] + for number, revision in sorted(state.revisions.items()): + at = first.get((number, revision.content_sha256)) + if revision.state in _WAS_PUBLISHED and at is not None: + found.append(Published(number, revision.content_sha256, at)) + return found + + +def hash_times(revisions: Sequence[Published]) -> dict[str, datetime]: + """Each published hash and the time a fetch of it counts from: the second after + the earliest `publish` of any revision that holds it. A `publish` row keeps its + time in whole seconds, so a read in that second may be a writer's read of the + draft; it is not counted, which keeps every count a lower bound.""" + since: dict[str, datetime] = {} + for revision in revisions: + counted_from = revision.at + timedelta(seconds=1) + since[revision.content_sha256] = min( + since.get(revision.content_sha256, counted_from), counted_from + ) + return since + + +def by_hash(groups: Sequence[Group]) -> dict[str, list[Group]]: + """The ledger's groups under the hash each one answered.""" + found: dict[str, list[Group]] = {} + for group in groups: + found.setdefault(str(group["content_sha256"]), []).append(group) + return found + + +def _revision_of(revisions: Sequence[Published]) -> dict[str, int]: + # Lowest number first, so of two revisions that hold one hash the higher names it: + # the ledger keeps the hash a read answered, never the number. + return {revision.content_sha256: revision.revision for revision in revisions} + + +def counts( + groups: Mapping[str, Sequence[Group]], + revisions: Sequence[Published], + inspectors: Collection[str], +) -> list[Fetches]: + """One entry for each of `revisions` whose hash a group names, highest number + first. A session and a principal are counted once a revision, whatever the + transport; a row with no session counts its principal only. An inspector's reads + are summed apart and count neither.""" + found = [] + for sha, number in _revision_of(revisions).items(): + rows = groups.get(sha, ()) + if not rows: + continue + counted = [g for g in rows if g["consumer"] not in inspectors] + found.append( + Fetches( + revision=number, + content_sha256=sha, + sessions=len({g["session_id"] for g in counted} - {NO_SESSION}), + subjects=len({g["subject"] for g in counted}), + last_at=max((g["last_at"] for g in counted), default=None), + inspector_fetches=sum( + int(g["fetches"]) for g in rows if g["consumer"] in inspectors + ), + ) + ) + return sorted(found, key=lambda f: -f.revision) + + +def subjects( + groups: Mapping[str, Sequence[Group]], revisions: Sequence[Published] +) -> list[SubjectFetches]: + """Who read each of `revisions`, one entry a principal, revision, transport and + consumer, with the first and the last read. An inspector's reads are entries too, + told apart by `consumer`. Highest revision first, then by principal.""" + spans: dict[tuple[str, int, str, str], tuple[datetime, datetime]] = {} + for sha, number in _revision_of(revisions).items(): + for g in groups.get(sha, ()): + key = (str(g["subject"]), number, str(g["transport"]), str(g["consumer"])) + first, last = spans.get(key, (g["first_at"], g["last_at"])) + spans[key] = (min(first, g["first_at"]), max(last, g["last_at"])) + ordered = sorted(spans.items(), key=lambda kv: (-kv[0][1], kv[0][0], kv[0][2], kv[0][3])) + return [SubjectFetches(*key, *span) for key, span in ordered] + + +def stale_codes( + state: SkillState, *, writer: bool, unknown_operation: bool, now: datetime +) -> list[str]: + """The stale codes of one skill. `draft_waiting` is a writer's to read, as the + draft is. A skill nobody fetched has no code for that: a copy pulled to disk is + read without a fetch.""" + codes = [] + if writer and state.open_draft: + saved = state.revisions[state.open_draft].row["at"] + if now - saved > timedelta(days=DRAFT_WAITING_DAYS): + codes.append(DRAFT_WAITING) + if unknown_operation: + codes.append(UNKNOWN_OPERATION) + return codes + + +def _count(n: int, noun: str) -> str: + return f"{n:,} {noun}" if n == 1 else f"{n:,} {noun}s" + + +def skill_statement(fetches: Sequence[Fetches], codes: Sequence[str], window: int) -> str: + """What the counts of one skill say: a sentence for each revision that was fetched, + or the one sentence of a skill that was not, then a sentence for each stale code + this build has words for.""" + within = f"in the last {_count(window, 'day')}" + said = [] + for f in fetches: + if not f.subjects: + continue + by = f"at least {_count(f.subjects, 'principal')}" + if f.sessions: + by = f"at least {_count(f.sessions, 'session')} of {by}" + said.append(f"Revision {f.revision} was fetched by {by} {within}.") + if not said: + said.append( + f"Not fetched from Loom {within}. A copy pulled to a folder is read without a " + "fetch, so the skill may still be read from one." + ) + said += [_STALE_SENTENCE[code] for code in codes if code in _STALE_SENTENCE] + return " ".join(said) + + +def report_statement(*, days: int, kept_days: int, listed: int, cut: bool) -> str: + """What every count of a report means, and what the report cannot see. `listed` is + how many of the namespace's skills a session's listing may carry; `cut` says the + ledger read stopped at `FETCH_GROUPS_MAX`.""" + window = window_days(days, kept_days) + said = [ + f"Counts cover the last {_count(window, 'day')} and are lower bounds: the request " + "ledger can drop a row, so each number reads as at least that many.", + "Loom does not record which sessions were shown the listing: a fetch counts a " + "session that asked for the skill's text.", + f"A session's listing can carry {_count(listed, 'skill')} of this namespace: it " + "takes one skill of each namespace in turn, each namespace's by name.", + ] + if window < days: + said.append( + f"Fetches are kept for {_count(kept_days, 'day')}, so older ones are not counted." + ) + if cut: + said.append( + f"The ledger read stopped at {FETCH_GROUPS_MAX:,} rows, the most recent, so " + "older fetches in the window are not counted." + ) + return " ".join(said) diff --git a/server/identity/store/skill_fetches.py b/server/identity/store/skill_fetches.py new file mode 100644 index 0000000000..12c8f59ad1 --- /dev/null +++ b/server/identity/store/skill_fetches.py @@ -0,0 +1,69 @@ +"""The fetches of a namespace's skills, read from the request ledger. + +One statement over the masked ledger rows (`MASKED_EVENTS`): the answered `skill.get` +calls of one namespace in a window whose answer carried one of the hashes given, each +from the time given for its hash. The rows are grouped so one report costs a bounded +answer however many fetches the window holds: a group is one hash, session, principal, +consumer and transport. No column holds skill text: the ledger keeps the hash a read +answered, never the text. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from datetime import datetime +from typing import Any + +from server.core.repo_base import _CHClient, _default_client +from server.observability.store.event_reads import MASKED_EVENTS + +# The scope leads with the ledger's key prefix `(org, namespace)` and bounds `ts`, which +# the table is partitioned by. A worker's row is no request. A row of a restricted +# namespace is masked to `success = false` with no `args`, so it is not counted. +FETCHES = ( + "SELECT content_sha256, session_id, subject, consumer, transport, " + "count() AS fetches, min(ts) AS first_at, max(ts) AS last_at " + "FROM (SELECT ts, session_id, subject, consumer, transport, " + "args['out_content_sha256'] AS content_sha256 " + f"FROM {MASKED_EVENTS} " + "WHERE org = {org:String} AND namespace = {ns:String} " + "AND ts >= {since:DateTime64(3)} " + "AND operation = 'skill.get' AND kind != 'worker' AND success) " + "WHERE has({hashes:Array(String)}, content_sha256) " + "AND ts >= arrayElement({published:Array(DateTime)}, " + "indexOf({hashes:Array(String)}, content_sha256)) " + "GROUP BY content_sha256, session_id, subject, consumer, transport " + "ORDER BY last_at DESC, content_sha256, session_id, subject, consumer, transport " + "LIMIT {limit:UInt32}" +) + + +async def fetch_groups( + org: str, + namespace: str, + since: datetime, + published: Mapping[str, datetime], + limit: int, + *, + ch: _CHClient | None = None, +) -> list[dict[str, Any]]: + """The fetches of `namespace` since `since`, grouped, the group read last first, at + most `limit` groups. `published` maps each hash that counts to the time a read of + it counts from; a read of any other hash, and an earlier read, is no fetch. With no + hash there is nothing to read. A failed read raises: it is never answered as no + fetch.""" + if not published: + return [] + ch = ch or _default_client() + rows: list[dict[str, Any]] = await ch.query_all( + FETCHES, + params={ + "org": org, + "ns": namespace, + "since": since, + "hashes": list(published), + "published": list(published.values()), + "limit": limit, + }, + ) + return rows diff --git a/server/identity/store/skills.py b/server/identity/store/skills.py index d9a2a4fc8e..6f1c328d2d 100644 --- a/server/identity/store/skills.py +++ b/server/identity/store/skills.py @@ -64,6 +64,22 @@ async def namespace_acts( return rows +async def usage_acts( + org: str, namespace: str, *, ch: _CHClient | None = None +) -> list[dict[str, Any]]: + """Every act on every skill of one namespace as a usage report folds it: what a + listing reads, and the operation names each row stored. Without text, by name and + `seq`.""" + ch = ch or _default_client() + rows: list[dict[str, Any]] = await ch.query_all( + f"SELECT {_LIST_COLUMNS}, op_names FROM loom.skills " + "WHERE org = {org:String} AND namespace = {ns:String} " + "ORDER BY name, seq", + params={"org": org, "ns": namespace}, + ) + return rows + + async def last_acts_but( org: str, namespaces: list[str], diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py index b2e4610def..029b3f0dc9 100644 --- a/server/operations/reach_manifest.py +++ b/server/operations/reach_manifest.py @@ -1187,6 +1187,10 @@ "sdk_method", "dashboard", ), + "skill.usage": ( + "sdk_method", + "dashboard", + ), "stewardship.assign": ( "sdk_method", "dashboard", diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 8124074436..c7b7b040ee 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -7089,6 +7089,11 @@ class TrackerSettings(BaseModel): # The package check (at most 400,000 bytes of text, off the event loop), the claim # on the namespace's skills, two reads and one waited insert. "skill.save": 600, + # One read of the namespace's skill rows without text, one of its retention, and one + # grouped read of the request ledger's `skill.get` rows of the window, by the ledger's + # key prefix: it reads the namespace's ledger rows of the window, 3,000,000 of them in + # about 125 ms on a local ClickHouse. + "skill.usage": 1000, # The fleet read, the target's rows, then for an item put under stewardship the # namespace's state and one head, the steward's grant, one insert and the read back: # about ten statements. diff --git a/tests/analyzer/cases/planes.py b/tests/analyzer/cases/planes.py index 402799b81c..1cf0dabb47 100644 --- a/tests/analyzer/cases/planes.py +++ b/tests/analyzer/cases/planes.py @@ -1080,9 +1080,10 @@ async def _skill_reads(ch: RecordingCH, c: dict[str, Any]) -> None: namespaces, the `delete` rows and last deciding acts a pack's listing folds, one skill's acts, and the text of one revision; and what `skill.delete` issues: the check for its unfinished removal and the removal of one revision's rows and of a - whole skill's.""" + whole skill's; and the acts of one namespace's skills that `skill.usage` folds.""" from server.identity.store import skills as skills_repo + await skills_repo.usage_acts(ORG, NS, ch=ch) await skills_repo.namespace_acts(ORG, [NS, "n2"], ch=ch) await skills_repo.last_acts_but( ORG, [NS, "n2"], ("save", "reject", "delete"), every=("delete",), ch=ch @@ -1096,6 +1097,18 @@ async def _skill_reads(ch: RecordingCH, c: dict[str, Any]) -> None: await skills_repo.remove_below(ORG, NS, "deploy-notes", 4, ch=ch) +async def _skill_fetches(ch: RecordingCH, c: dict[str, Any]) -> None: + """The request ledger's answered `skill.get` rows of one published hash, which + `skill.usage` counts.""" + from datetime import datetime + + from server.identity.store import skill_fetches + + await skill_fetches.fetch_groups( + ORG, NS, datetime(2030, 1, 1), {"0" * 64: datetime(2030, 1, 2)}, 10_001, ch=ch + ) + + async def _grants_repo(ch: RecordingCH, c: dict[str, Any]) -> None: """The grants `collection.create` reads to find another holder of the name, and the member count `namespace.inventory` takes over a collection's lineage; `grants.list` @@ -1458,6 +1471,7 @@ def cases() -> list[Case]: Case("namespace_in_use", "server.identity.store.namespace_census", _namespace_in_use, {}) ) out.append(Case("skills", "server.identity.store.skills", _skill_reads, {})) + out.append(Case("skill_fetches", "server.identity.store.skill_fetches", _skill_fetches, {})) out.append(Case("curator_status", "server.memory.store.curator", _curator_reads, {})) out.append(Case("copy_rules", "server.memory.store.copy_rules", _copy_rules, {})) out.append( diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index ba74a79c29..cd539cd949 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -773,6 +773,7 @@ 536826142a9e SELECT count() AS n FROM loom.events WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 537db1eef44c ALTER TABLE loom.memory_reinforcement DELETE WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 537dfcb5d9ff SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, version, value, toString(value_json) AS object_text FROM loom.memory FINAL WHERE tombstoned_at IS NULL AND sensitivity = ? AND +537eda01b49c SELECT content_sha256, session_id, subject, consumer, transport, count() AS fetches, min(ts) AS first_at, max(ts) AS last_at FROM (SELECT ts, session_id, subject, consumer, transport, args[?] AS conte 538a7fd3c1a1 SELECT source_uri, title, description, ingestion_id, artifact_sha256, doc_format, chars, if(cut AND sum(if(cut, chars, ?)) OVER ( ORDER BY cityHash64(source_uri), source_uri ROWS UNBOUNDED PRECEDING) 53a13a7270aa SELECT count() AS n FROM loom.memory_chunks WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND parent_memory_key = {k:String} AND content_sha256 N 53d24506ef23 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist @@ -1996,6 +1997,7 @@ cc115227ad18 SELECT count() AS n FROM loom.namespace_guides WHERE org = {org:Str cc216db24930 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user cc23f4e1f7d2 SELECT count() AS n FROM loom.memory_chunks FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} cc63d1a2772c SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} +cc6fb21a8392 SELECT namespace, name, seq, act, revision, content_sha256, description, listed, actor, source_class, at, op_names FROM loom.skills WHERE org = {org:String} AND namespace = {ns:String} ORDER BY name, cc7a1e0e6cae SELECT count() AS n FROM loom.conflict_allowlist FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL cc814212d2f9 SELECT agent, user_id, session_id, memory_key, version FROM loom.memory_embeddings WHERE org = {org:String} AND namespace = {ns:String} AND (agent, user_id, session_id, memory_key, version) IN {ids:Ar cc8b705f6161 SELECT version, status, toString(created_at) AS created_at FROM loom.memory_versions WHERE org = {o:String} AND namespace = {n:String} AND memory_key = {k:String} ORDER BY version DESC LIMIT {lim:UInt diff --git a/tests/integration/test_cross_principal_leakage.py b/tests/integration/test_cross_principal_leakage.py index 775d3fe2ee..bf7d9da806 100644 --- a/tests/integration/test_cross_principal_leakage.py +++ b/tests/integration/test_cross_principal_leakage.py @@ -3194,3 +3194,101 @@ def decide(skill: str, decision: str, saved: dict[str, Any] | None = None) -> No assert refused.status_code == 403, f"{op}: {refused.status_code}" assert not any(n in refused.text for n in nonces.values()), op assert ok(viewer, "skill.get", name=name)["revision"] == 2 + + +def test_a_viewers_skill_usage_names_no_draft_and_no_unpublished_revision( + control_plane_url, mint_test_token, ch_client +) -> None: + """One skill serves revision 1 and holds a draft saved 15 days ago; a second holds a + draft alone; a third was published and archived. A writer's `skill.usage` lists the + three and `draft_waiting` on the first. A viewer's lists the first alone, with no + code of its draft and no entry for the draft's hash, and for the draft-only and the + archived name the answer of a name that does not exist. Who fetched is refused to + the viewer and the writer, and the whole op to a principal outside the namespace.""" + from datetime import UTC, datetime, timedelta + + from server.auth.jwt import mint_token + + org, ns = unique_org("skill-usage"), f"skills-{uuid.uuid4().hex[:8]}" + name, drafted, gone = (f"{label}-{uuid.uuid4().hex[:8]}" for label in ("notes", "wip", "old")) + at = {"org": org, "namespace": ns} + writer = mint_test_token(org=org, namespaces=[ns], roles=["writer"], subject="sa:w") + viewer = mint_test_token(org=org, namespaces=[ns], roles=["viewer"], subject="sa:v") + outsider = mint_test_token(org=org, namespaces=["elsewhere"], roles=["admin"], subject="sa:o") + reviewer = mint_token( + subject="reviewer@example.test", + org=org, + namespaces=[ns], + roles=["admin"], + ttl_seconds=600, + is_service_account=False, + ) + nonce = _canary() + + def ok(token: str, op: str, **body: Any) -> dict[str, Any]: + r = _post(control_plane_url, token, op, {**at, **body}) + assert r.status_code == 200, f"{op}: {r.text[:300]}" + return r.json() + + def save(skill: str, body: str, after: int = 0) -> dict[str, Any]: + text = f"---\nname: {skill}\ndescription: Deploys.\n---\n\n{body}\n" + files = [{"path": "SKILL.md", "text": text}] + saved = ok(writer, "skill.save", files=files, expected_revision=after) + assert saved["written"] is True, saved + return saved + + def publish(skill: str, saved: dict[str, Any]) -> None: + approved = {"revision": saved["revision"], "approved_sha256": saved["content_sha256"]} + ok(reviewer, "skill.decide", name=skill, decision="publish", **approved) + + live = save(name, "Run the served text.") + publish(name, live) + draft = save(name, f"Run {nonce}.", 1) + # A later draft saved 15 days ago: the one fact no op can write. + aged = datetime.now(UTC) - timedelta(days=15) + ch_client.insert( + "loom.skills", + [[org, ns, name, 9, "save", 3, "e" * 64, "Deploys.", "process:sa:w", "asserted", aged]], + column_names=[ + "org", + "namespace", + "name", + "seq", + "act", + "revision", + "content_sha256", + "description", + "actor", + "source_class", + "at", + ], + ) + save(drafted, f"Draft {nonce}.") + publish(gone, save(gone, "Retired text.")) + ok(reviewer, "skill.decide", name=gone, decision="archive") + # The writer reads a draft: its hash was never published, so it is no fetch. + assert ok(writer, "skill.get", name=name, revision=2)["revision_state"] == "draft" + + # Positive control: the writer is reported the three skills and the waiting draft. + seen = {s["name"]: s for s in ok(writer, "skill.usage", days=90)["skills"]} + assert sorted(seen) == sorted([name, drafted, gone]) + assert seen[name]["stale"] == ["draft_waiting"], seen[name] + + whole = ok(viewer, "skill.usage", days=90) + [reported] = whole["skills"] + assert (reported["name"], reported["published_revision"]) == (name, 1) + assert reported["stale"] == [] and reported["subjects"] == [] + assert {f["content_sha256"] for f in reported["fetches"]} <= {live["content_sha256"]} + secrets = (nonce, draft["content_sha256"], "e" * 64, drafted, gone, "draft") + assert not any(s in json.dumps(whole["skills"]) for s in secrets) + absent = ok(viewer, "skill.usage", name="no-such-skill") + assert absent["skills"] == [] + for skill in (drafted, gone): + assert ok(viewer, "skill.usage", name=skill) == absent, skill + for who, token in (("viewer", viewer), ("writer", writer)): + named = _post(control_plane_url, token, "skill.usage", {**at, "by_subject": True}) + assert named.status_code == 403, f"{who}: {named.status_code} {named.text[:200]}" + for body in ({}, {"name": name}, {"by_subject": True}): + refused = _post(control_plane_url, outsider, "skill.usage", {**at, **body}) + assert refused.status_code == 403, f"{body}: {refused.status_code}" + assert not any(s in refused.text for s in (nonce, live["content_sha256"])) diff --git a/tests/integration/test_skill_independent_review.py b/tests/integration/test_skill_independent_review.py index 69c71935dd..3d06fc9223 100644 --- a/tests/integration/test_skill_independent_review.py +++ b/tests/integration/test_skill_independent_review.py @@ -6,9 +6,10 @@ reader below WRITER is served a draft or anything but the published revision; when an administrator publishes a draft that a token they minted or a child of that token saved, before or after that token is revoked; when a draft no person saved is not -published by one administrator; or when the folder `loom skill pull` writes for a +published by one administrator; when the folder `loom skill pull` writes for a reader is not the published revision, or `loom skill status` calls it current after a -second publish. +second publish; or when `skill.usage` counts a look as a fetch, misses a fetch the +ledger holds, or tells who fetched to a caller below ADMIN. Runs against a real Control Plane + ClickHouse (LOOM_BASE_URL, LOOM_CH_*). """ @@ -25,7 +26,7 @@ import pytest from server.settings import settings -from tests.integration._eventually import acl_change_adopted +from tests.integration._eventually import acl_change_adopted, wait_until from tests.integration._skills import Space, folder, manifest_sha @@ -284,3 +285,75 @@ def test_a_reader_pulls_the_published_revision_and_status_follows_the_server( assert cli.main(["skill", "status", str(to), *scope]) == 1 assert f"{skill} revision 2 unchanged, no longer served" in capsys.readouterr().out assert (to / name / "SKILL.md").is_file() + + +def test_a_fetch_is_counted_once_it_is_flushed( + space: Space, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """A viewer's read of a published skill appears in `fetches` once the ledger holds + its row, and the command's `show` appears only in `inspector_fetches`. A writer's + read of the draft before it was published is no fetch, and who fetched is told to + an administrator alone.""" + from loom import cli + + name = space.name() + author, reviewer = space.token("sa:skill-author"), space.person("reviewer@example.test") + reader = space.token("sa:skill-reader", "viewer") + saved = space.save(author, folder(name)) + # The author reads the draft: the hash is not published yet, so this is no fetch. + assert space.ok("skill.get", author, name=name, revision=1)["revision_state"] == "draft" + assert space.publish(reviewer, name, saved).status_code == 200 + # A publish is recorded in whole seconds, and a fetch counts from the next one. + time.sleep(1.1) + + # The reader fetches twice in one session, then looks with the command. + for _ in range(2): + got = space.ok("skill.get", reader, name=name, session_id="usage-session") + assert got["content_sha256"] == saved["content_sha256"] + monkeypatch.setenv("LOOM_API_KEY", reader) + monkeypatch.delenv("LOOM_PROFILE", raising=False) + monkeypatch.setattr("loom.credentials.CREDENTIALS_FILE", tmp_path / "credentials") + skill, scope = f"{space.ns}/{name}", ["--org", space.org, "--server", space.base] + assert cli.main(["skill", "show", skill, *scope]) == 0 + capsys.readouterr() + + def counted() -> dict[str, Any] | None: + [reported] = space.ok("skill.usage", reader, name=name)["skills"] + fetches = reported["fetches"] + flushed = fetches and fetches[0]["sessions"] and fetches[0]["inspector_fetches"] + return reported if flushed else None + + reported = wait_until(counted, max_wait=30, interval=0.5, description="the ledger to flush") + [fetched] = reported["fetches"] + assert fetched["last_at"] is not None + assert {k: v for k, v in fetched.items() if k != "last_at"} == { + "revision": 1, + "content_sha256": saved["content_sha256"], + "sessions": 1, + "subjects": 1, + "inspector_fetches": 1, + } + assert (reported["published_revision"], reported["stale"], reported["subjects"]) == (1, [], []) + assert reported["statement"] == ( + "Revision 1 was fetched by at least 1 session of at least 1 principal in the last 30 days." + ) + + # The command prints the server's sentences. + assert cli.main(["skill", "usage", skill, *scope]) == 0 + out = capsys.readouterr().out + assert reported["statement"] in out and "Counts cover the last 30 days" in out + + # Who fetched is an administrator's to read: the reader and the author are refused. + for token in (reader, author): + refused = space.post("skill.usage", token, name=name, by_subject=True) + assert refused.status_code == 403, refused.text + assert "sa:skill-reader" not in refused.text + [named] = space.ok("skill.usage", reviewer, name=name, by_subject=True)["skills"] + who = {(s["subject"], s["revision"], s["transport"], s["consumer"]) for s in named["subjects"]} + assert who == { + ("sa:skill-reader", 1, "http", "service-account"), + ("sa:skill-reader", 1, "http", "loom-cli-inspect"), + } diff --git a/tests/unit/skill_store.py b/tests/unit/skill_store.py index 7d78484dee..d97d2b56c0 100644 --- a/tests/unit/skill_store.py +++ b/tests/unit/skill_store.py @@ -6,10 +6,11 @@ assert [r["revision"] for r in store.rows] == [1] `install` replaces the repository's statements with reads of `Skills.rows`, and the -seams of a save, a delete, a decision or a listing that reach other stores: the fleet -gate, the namespace kinds, the namespace's claim, the role gate, the alias directory, -the namespaces the caller took up and the audit log. The role gate answers from the -token's role claims, as `tests/unit/test_reviewer_rule.py` does. +seams of a save, a delete, a decision, a listing or a usage report that reach other +stores: the fleet gate, the namespace kinds, the namespace's claim, the role gate, the +alias directory, the namespaces the caller took up, the audit log, the request ledger +and the namespace's retention. The role gate answers from the token's role claims, as +`tests/unit/test_reviewer_rule.py` does. A removal a delete starts stays in `Skills.running` until `finish()` applies it, as ClickHouse finishes a mutation nobody waits for. @@ -17,7 +18,7 @@ from __future__ import annotations -from collections.abc import AsyncIterator, Sequence +from collections.abc import AsyncIterator, Mapping, Sequence from contextlib import asynccontextmanager from datetime import datetime, timedelta from typing import Any @@ -27,7 +28,14 @@ from server.auth import aliases, authz from server.auth.fanout import Split from server.identity.api.models_skills import SkillFile, SkillSaveInput -from server.identity.app import namespace_membership, skill_delete, skill_save, skills +from server.identity.app import ( + namespace_membership, + skill_delete, + skill_save, + skill_usage, + skills, +) +from server.identity.store import skill_fetches from server.identity.store import skills as repo from server.operations.base import Role from tests.unit.principals import NAMESPACE, ORG @@ -112,6 +120,12 @@ def __init__(self) -> None: # read fails. self.aliases: dict[str, list[str]] = {} self.alias_read_fails = False + # The request ledger's answered `skill.get` rows, what its read was asked, + # whether it fails, and the days the namespace keeps its ledger (0: forever). + self.ledger: list[dict[str, Any]] = [] + self.ledger_asked: list[dict[str, Any]] = [] + self.ledger_fails = False + self.retention_days = 0 def add(self, name: str, seq: int, act: str, revision: int, sha: str, **fields: Any) -> None: """A row another call, or a later build, wrote.""" @@ -141,6 +155,54 @@ def add(self, name: str, seq: int, act: str, revision: int, sha: str, **fields: } self.rows.append({**row, **fields}) + def fetched(self, sha: str, ts: datetime, **fields: Any) -> None: + """A `skill.get` the ledger holds: it answered the hash `sha` at `ts`.""" + row = { + "org": ORG, + "namespace": NAMESPACE, + "ts": ts, + "content_sha256": sha, + "session_id": "-", + "subject": "", + "consumer": "user", + "transport": "mcp", + } + self.ledger.append({**row, **fields}) + + async def fetch_groups( + self, + org: str, + namespace: str, + since: datetime, + published: Mapping[str, datetime], + limit: int, + *, + ch: Any = None, + ) -> list[dict[str, Any]]: + """The ledger statement's answer over `ledger`: the rows of a hash of + `published` from its time on, grouped, the group read last first.""" + if self.ledger_fails: + raise RuntimeError("the ledger read failed") + self.ledger_asked.append({"since": since, "published": dict(published), "limit": limit}) + names = ("content_sha256", "session_id", "subject", "consumer", "transport") + groups: dict[tuple[str, ...], dict[str, Any]] = {} + for r in self.ledger: + sha = r["content_sha256"] + if (r["org"], r["namespace"]) != (org, namespace) or r["ts"] < since: + continue + if sha not in published or r["ts"] < published[sha]: + continue + key = tuple(r[name] for name in names) + start = {**dict(zip(names, key, strict=True)), "fetches": 0} + group = groups.setdefault(key, {**start, "first_at": r["ts"], "last_at": r["ts"]}) + group["fetches"] += 1 + group["first_at"] = min(group["first_at"], r["ts"]) + group["last_at"] = max(group["last_at"], r["ts"]) + return sorted(groups.values(), key=lambda g: g["last_at"], reverse=True)[:limit] + + async def usage_acts(self, org: str, namespace: str, *, ch: Any = None) -> list[dict[str, Any]]: + return [{c: r[c] for c in (*_LIST, "op_names")} for r in self._of(org, [namespace])] + def _of(self, org: str, namespaces: Sequence[str]) -> list[dict[str, Any]]: kept = [r for r in self.rows if r["org"] == org and r["namespace"] in namespaces] return sorted(kept, key=lambda r: (r["namespace"], r["name"], r["seq"])) @@ -260,6 +322,7 @@ def install(monkeypatch: pytest.MonkeyPatch) -> Skills: "body", "removal_unfinished", "remove_below", + "usage_acts", ) for name in statements: monkeypatch.setattr(repo, name, getattr(store, name)) @@ -300,6 +363,11 @@ async def read_aliases(org: str, subject: str, ch: Any) -> list[str]: raise RuntimeError("the alias read failed") return list(store.aliases.get(subject, [])) + async def retention_days(org: str, namespace: str, **_: Any) -> int: + return store.retention_days + + monkeypatch.setattr(skill_fetches, "fetch_groups", store.fetch_groups) + monkeypatch.setattr(skill_usage, "namespace_retention_days", retention_days) monkeypatch.setattr(aliases, "read_aliases", read_aliases) monkeypatch.setattr(skill_delete.audit, "emit_strict", emit_strict) monkeypatch.setattr(skill_save.machines, "fleet_at", fleet_at) diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index 8fe14e3ac5..dfce21183e 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -2,7 +2,7 @@ "loom": [ "usage: loom [-h] [--version] {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect,pointers,curator,skill,copy-rule,proposals} ...", "Loom — vendor-neutral agent memory plane on ClickHouse.", - "positional arguments: {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect,pointers,curator,skill,copy-rule,proposals} code Code intelligence plane operations. decisions Decision records mined from documents. knowledge Knowledge documents and their sources. export-okf Render a namespace as an OKF v0.2 bundle (Markdown + frontmatter) — the git-reviewable projection of Loom memory. import-okf Write the concepts of an OKF v0.2 bundle into a namespace via memory.set. okf-lint Lint an OKF bundle directory offline — the compile gate a mirror repository's CI runs. Exit 2 critical, 1 warnings, 0 clean. up Boot the local stack (Loom, its document extractor and ClickHouse) and print how to connect: creates .env and the ClickHouse config from their templates, runs docker compose up --build, waits for /v1/health, then prints the dashboard URL and the first memory.set (curl + Python SDK) and `claude mcp add` snippets — minting a writer token first when auth is on. Re-run any time. down Stop the local stack while preserving data; --delete-data performs a confirmed reset. ch-setup Prepare a self-managed ClickHouse or a ClickHouse Cloud service for Loom: create the loom database and the read-only reader user, or print the SQL for an admin. participant The Loom processes a provider change waits for. deployment The configuration every replica checks itself against. settings Every setting's value in force, and overrides of the live ones. secrets Credentials and signing keys stored sealed in ClickHouse. signing-key The token signing keys beside LOOM_JWT_SECRET, kept in ClickHouse. provider-lock The provider configuration lock. export-analytics Write one UTC day of usage and a namespace snapshot to S3 as Parquet, names hashed under LOOM_ANALYTICS_EXPORT_NAME_KEY. Never replaces an object, so a repeated run is safe. sql-access Make, rescope or drop a ClickHouse user that reads a tenant's memory, conversations and request ledger through the sql_v1_* views. reembed Re-embed vectors whose embedding_model != the configured embedder (run after changing LOOM_EMBEDDING_MODEL — Loom does not auto-re-embed). Covers memory, entity, and conversation vectors. Coded vector tables keep their width: change a model of another width in Settings → Models & keys, which rebuilds them. reextract Replay a namespace's raw evidence (memory.set_from_messages turns) through a running server's write path into ANOTHER namespace — the current extractor over the stored transcripts; the source is never written. deploy-delta What a colour swap changed: the deployment's ledger rows (volume, errors, p50/p95, upstream spend per operation) and its ClickHouse statement shapes (runs, bytes, seconds) for a window on each side of the swap, with flags for what moved past a coarse threshold. entity-export Export a namespace's entity graph (co-occurrence edges + triples) to GraphML or JSON-LD for an external graph or RDF tool. Read-only; every edge carries its provenance and a note that a path is declared, not proven. audit-namespace How a namespace is being used (namespace.audit): exact-key reads vs searches, hash keys, double-encoded and oversized values, hand-rolled index rows, leases stored as memories, version churn. Read-only; prints a table (code, severity, kind, count, share, first sample) or --json. Exit 1 on a critical finding. mentor The store's advice to one agent (mentor.brief): what it called, the planes its namespace offers, the hints with their evidence, and how often past hints were followed. Read-only; prints a table or --json. Exit 1 when a warning-level hint fires. serve Boot the control plane (uvicorn). migrate Apply schema migrations against the configured CH. reconcile-status Re-emit memory_embeddings rows whose status diverged from loom.memory (superseded / conflicted / duplicate marks the pool never saw), compared and re-emitted per identity row (org, namespace, agent, user_id, session_id, key). Dry run by default (counts by status, the rows it would write); --apply writes. period-digest Write period digests — one derived semantic memory over K consecutive session digests of each identity in one namespace. Additive and idempotent. Dry run by default (plans only); --apply writes. demote-activity-narration Find a namespace's extracted facts that narrate tool activity ('User read lines 1-1000 of X', 'Claude ran a command on …') with no durable outcome and demote (confidence x0.25) or label them through memory.apply. Dry run by default; keys an agent read by name in the last --days are left alone. Never deletes. recalibrate Re-probe the embedder + run per-NS calibration immediately (otherwise this runs weekly via the recalibration worker). import-clickgap Import a ClickGap (Detector→Validator→Reviewer) SQLite export into Loom (lessons + typed entities + categories). Reembed-only; preserves kind→memory_type, per-row TTL, recall_count (→ ranking via reinforcement_count), suppression polarity, and provenance. Idempotent via deterministic keys + per-run version. import-recall Import an external vector-recall agent-memory SQLite export into Loom. Introspects the DB at runtime (schema not assumed): tables are classified by column heuristics into memories (→ memory.set) or conversation transcripts (→ conversation.append, grouped by conversation id); unmatched tables/rows are skipped, never crash. Idempotent via deterministic keys. import-brain Import a markdown agent 'brain' directory into Loom: MEMORY.md (always- injected HOT layer) → profile.set sections; memory/contexts/*.md (read-on- demand WARM layer) → knowledge.add docs. Completes the migration alongside import-recall (the deep vector layer). Missing files are skipped, never crash. claim-release Release a self-signup claim: revoke its grants, clear the owner, deactivate it. The name stays reserved. mint-token Mint a JWT locally (requires LOOM_JWT_SECRET and verified stores). revoke-token Revoke one token by jti or subject (writes loom.revoked_tokens through the revocation module; needs the configured ClickHouse). sso Carry password accounts over to single sign-on. bot Bots and CI jobs that sign in with a key or their CI's identity. doctor Diagnose pre-boot misconfig (Python version, settings, JWT, CH reachability) and print the problem list /v1/health carries, each with its fix. With --client, also examine this machine as a coding-agent client. report Print the bug form's Environment field: versions and the `loom doctor` checks. drops Print the memory ingest drop ledger (loom.memory_drops) for a namespace, by stage/reason — what the pipeline discarded, truncated or gave up on. namespaces-gc List (default) or erase throwaway namespaces — finished bench runs under the bench prefixes that nobody registered and nobody has written to for --idle-hours — in one list-scoped erasure saga per batch. erasure-re-verify Re-verify failed erasure sagas: print each one's last step-named reason and a fresh residue census (default, read-only); --resume re-runs them from their checkpoint past the recovery worker's attempts budget; --orphan-graph lists namespaces whose entity graph outlived their memories and, with --erase, purges them. reconcile After a restore of ClickHouse or Postgres, run again in the restored store the erasures and redactions the other records past the restore point, and (after a ClickHouse restore) publish again every revision committed after it. Stop every server and worker first. Dry run by default. router The router in front of a deployment's cells. cell Operate a deployment's cells through the router's directory. tracker-probe Read-only first contact with the tracker source: counts and newest timestamps per upstream table per credential, breaker states, the configured tracker namespaces. tracker-contract-check Read-only: does each tracker source's schema meet the record contract (docs/features/tracker/record-contract.md)? Names missing tables / columns, optional tables present, feature columns. Exit 0 when every checked source meets it. tracker-dupcheck-fit Refit tracker.duplicate_check's calibrated confidence for one tracker namespace now: replays the duplicate gold at filing time, fits, stores the fit. tracker-embed-reset Clear the tracker_embed pass cursors of one tracker namespace so the next pass re-walks the window and re-embeds every item whose text recipe changed. Dry run by default (prints the cursors); --apply clears them. tracker-feed Maintain a team's GitHub or Linear tracker record namespaces-adopt Give namespaces that hold live memory and no registry row an owner row: kind=bench under the bench prefixes, else memory; retention_days 0, no TTL. Dry run unless --apply. sensitivity-sweep Label live rows the sensitivity detector would have labelled on write but a path skipped. Dry run by default: counts by level, probe shape and namespace. --apply writes one new version per row, tombstones a high row's embedding rows and tags a medium row's. The closing line is the high- sensitivity invariant (high rows with a live embedding). integrity-repair Read the row-level integrity gauges (dim-0 rows holding a vector, tombstoned_at/status drift, active rows past valid_to) and, with --apply, re-emit the dim-0 rows with their true dimension so search can return them again. Drift and valid_to are listed, not repaired. rechunk Re-chunk and re-embed a namespace's knowledge documents from stored content through the current chunker, so every document carries section metadata, chunk context and document frequency. Idempotent; one embedding per new chunk. Dry run by default (counts the documents and chunks); --apply re-chunks. export-actions Export the action schema derived from the operation registry — an MCP tools/list manifest with loom extras (json) or the Cedar schema (cedar) a policy gateway governs the surface with. lexical-stats-rebuild Recompute BM25 document frequency for a namespace from its live rows (the term-frequency views only see inserts; supersession and tombstones leave stale vocabulary behind). version Print installed Loom version. install Wire Loom into a local AI client's config. Writes the MCP server block into Claude Desktop / Cursor / VS Code's config file, atomically, merging with anything already there; for Claude Code it runs (or prints) `claude mcp add` and for Codex `codex mcp add`. Restart the client afterwards. demo The first five minutes: ingest this repo's AGENTS.md (or --file) into the knowledge plane the way `make ingest` does, ask it a question, and print the answer with its evidence rows. On the stock fake-LLM stack it prints the top knowledge.search hits and says what a real answer needs. init Create an identity on a Loom server. `--agent NAME` signs an agent up by itself (server needs LOOM_SELF_SIGNUP=open): mints a writer token on a fresh agent- namespace, saves it to ~/.loom/token, and prints the claim code a person enters once, with a password of their own, to claim the namespace. ingest-transcript Pipe a chat-history file (markdown / JSON) into Loom's conversation table as one thread. Generic ingest for tools without an MCP integration (Aider, Continue.dev, JetBrains AI, anything else): export the chat → run this command → the thread shows in the dashboard's Conversations. memory-search Run a memory.search from the shell. Default human output; --json-agent emits a structured envelope agents can pipe through (a `{command, results}` JSON shape). set-host Designate the Loom host(s) for this deployment. Writes the given login handle(s) or email(s) to LOOM_PLATFORM_ADMINS in the .env (--env-file, default ./.env): a handle promotes that password account to platform_admin, an email promotes an SSO sign-in with that verified email. Multiple OK (on-call rotation, co-operators, etc.). Re-login required after to pick up the role. login Sign in to a Loom server on any browser with a one-time code. logout End the stored session on the server and forget it here. whoami Show who the stored session signs you in as. call Call any operation or API route with the stored session (`loom call --help`). token Make, list and revoke your own tokens for CI and agents (`loom token --help`). connect Print the dashboard link to connect your own Google, Notion or Linear account. pointers Print the code pointer block for the task prompt on standard input. curator Report what in a namespace needs a person, and set its curator mode (`loom curator --help`). skill List and read the server's skills, check a skill folder, save one as a draft, publish, reject, archive or delete it, and write a published skill to a folder (`loom skill --help`). copy-rule Preview a namespace's copy rule, or run it to propose each new match (`loom copy-rule --help`). proposals List a namespace's pending proposals, read one whole, and accept or reject by the hash of the text that was read (`loom proposals --help`).", + "positional arguments: {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect,pointers,curator,skill,copy-rule,proposals} code Code intelligence plane operations. decisions Decision records mined from documents. knowledge Knowledge documents and their sources. export-okf Render a namespace as an OKF v0.2 bundle (Markdown + frontmatter) — the git-reviewable projection of Loom memory. import-okf Write the concepts of an OKF v0.2 bundle into a namespace via memory.set. okf-lint Lint an OKF bundle directory offline — the compile gate a mirror repository's CI runs. Exit 2 critical, 1 warnings, 0 clean. up Boot the local stack (Loom, its document extractor and ClickHouse) and print how to connect: creates .env and the ClickHouse config from their templates, runs docker compose up --build, waits for /v1/health, then prints the dashboard URL and the first memory.set (curl + Python SDK) and `claude mcp add` snippets — minting a writer token first when auth is on. Re-run any time. down Stop the local stack while preserving data; --delete-data performs a confirmed reset. ch-setup Prepare a self-managed ClickHouse or a ClickHouse Cloud service for Loom: create the loom database and the read-only reader user, or print the SQL for an admin. participant The Loom processes a provider change waits for. deployment The configuration every replica checks itself against. settings Every setting's value in force, and overrides of the live ones. secrets Credentials and signing keys stored sealed in ClickHouse. signing-key The token signing keys beside LOOM_JWT_SECRET, kept in ClickHouse. provider-lock The provider configuration lock. export-analytics Write one UTC day of usage and a namespace snapshot to S3 as Parquet, names hashed under LOOM_ANALYTICS_EXPORT_NAME_KEY. Never replaces an object, so a repeated run is safe. sql-access Make, rescope or drop a ClickHouse user that reads a tenant's memory, conversations and request ledger through the sql_v1_* views. reembed Re-embed vectors whose embedding_model != the configured embedder (run after changing LOOM_EMBEDDING_MODEL — Loom does not auto-re-embed). Covers memory, entity, and conversation vectors. Coded vector tables keep their width: change a model of another width in Settings → Models & keys, which rebuilds them. reextract Replay a namespace's raw evidence (memory.set_from_messages turns) through a running server's write path into ANOTHER namespace — the current extractor over the stored transcripts; the source is never written. deploy-delta What a colour swap changed: the deployment's ledger rows (volume, errors, p50/p95, upstream spend per operation) and its ClickHouse statement shapes (runs, bytes, seconds) for a window on each side of the swap, with flags for what moved past a coarse threshold. entity-export Export a namespace's entity graph (co-occurrence edges + triples) to GraphML or JSON-LD for an external graph or RDF tool. Read-only; every edge carries its provenance and a note that a path is declared, not proven. audit-namespace How a namespace is being used (namespace.audit): exact-key reads vs searches, hash keys, double-encoded and oversized values, hand-rolled index rows, leases stored as memories, version churn. Read-only; prints a table (code, severity, kind, count, share, first sample) or --json. Exit 1 on a critical finding. mentor The store's advice to one agent (mentor.brief): what it called, the planes its namespace offers, the hints with their evidence, and how often past hints were followed. Read-only; prints a table or --json. Exit 1 when a warning-level hint fires. serve Boot the control plane (uvicorn). migrate Apply schema migrations against the configured CH. reconcile-status Re-emit memory_embeddings rows whose status diverged from loom.memory (superseded / conflicted / duplicate marks the pool never saw), compared and re-emitted per identity row (org, namespace, agent, user_id, session_id, key). Dry run by default (counts by status, the rows it would write); --apply writes. period-digest Write period digests — one derived semantic memory over K consecutive session digests of each identity in one namespace. Additive and idempotent. Dry run by default (plans only); --apply writes. demote-activity-narration Find a namespace's extracted facts that narrate tool activity ('User read lines 1-1000 of X', 'Claude ran a command on …') with no durable outcome and demote (confidence x0.25) or label them through memory.apply. Dry run by default; keys an agent read by name in the last --days are left alone. Never deletes. recalibrate Re-probe the embedder + run per-NS calibration immediately (otherwise this runs weekly via the recalibration worker). import-clickgap Import a ClickGap (Detector→Validator→Reviewer) SQLite export into Loom (lessons + typed entities + categories). Reembed-only; preserves kind→memory_type, per-row TTL, recall_count (→ ranking via reinforcement_count), suppression polarity, and provenance. Idempotent via deterministic keys + per-run version. import-recall Import an external vector-recall agent-memory SQLite export into Loom. Introspects the DB at runtime (schema not assumed): tables are classified by column heuristics into memories (→ memory.set) or conversation transcripts (→ conversation.append, grouped by conversation id); unmatched tables/rows are skipped, never crash. Idempotent via deterministic keys. import-brain Import a markdown agent 'brain' directory into Loom: MEMORY.md (always- injected HOT layer) → profile.set sections; memory/contexts/*.md (read-on- demand WARM layer) → knowledge.add docs. Completes the migration alongside import-recall (the deep vector layer). Missing files are skipped, never crash. claim-release Release a self-signup claim: revoke its grants, clear the owner, deactivate it. The name stays reserved. mint-token Mint a JWT locally (requires LOOM_JWT_SECRET and verified stores). revoke-token Revoke one token by jti or subject (writes loom.revoked_tokens through the revocation module; needs the configured ClickHouse). sso Carry password accounts over to single sign-on. bot Bots and CI jobs that sign in with a key or their CI's identity. doctor Diagnose pre-boot misconfig (Python version, settings, JWT, CH reachability) and print the problem list /v1/health carries, each with its fix. With --client, also examine this machine as a coding-agent client. report Print the bug form's Environment field: versions and the `loom doctor` checks. drops Print the memory ingest drop ledger (loom.memory_drops) for a namespace, by stage/reason — what the pipeline discarded, truncated or gave up on. namespaces-gc List (default) or erase throwaway namespaces — finished bench runs under the bench prefixes that nobody registered and nobody has written to for --idle-hours — in one list-scoped erasure saga per batch. erasure-re-verify Re-verify failed erasure sagas: print each one's last step-named reason and a fresh residue census (default, read-only); --resume re-runs them from their checkpoint past the recovery worker's attempts budget; --orphan-graph lists namespaces whose entity graph outlived their memories and, with --erase, purges them. reconcile After a restore of ClickHouse or Postgres, run again in the restored store the erasures and redactions the other records past the restore point, and (after a ClickHouse restore) publish again every revision committed after it. Stop every server and worker first. Dry run by default. router The router in front of a deployment's cells. cell Operate a deployment's cells through the router's directory. tracker-probe Read-only first contact with the tracker source: counts and newest timestamps per upstream table per credential, breaker states, the configured tracker namespaces. tracker-contract-check Read-only: does each tracker source's schema meet the record contract (docs/features/tracker/record-contract.md)? Names missing tables / columns, optional tables present, feature columns. Exit 0 when every checked source meets it. tracker-dupcheck-fit Refit tracker.duplicate_check's calibrated confidence for one tracker namespace now: replays the duplicate gold at filing time, fits, stores the fit. tracker-embed-reset Clear the tracker_embed pass cursors of one tracker namespace so the next pass re-walks the window and re-embeds every item whose text recipe changed. Dry run by default (prints the cursors); --apply clears them. tracker-feed Maintain a team's GitHub or Linear tracker record namespaces-adopt Give namespaces that hold live memory and no registry row an owner row: kind=bench under the bench prefixes, else memory; retention_days 0, no TTL. Dry run unless --apply. sensitivity-sweep Label live rows the sensitivity detector would have labelled on write but a path skipped. Dry run by default: counts by level, probe shape and namespace. --apply writes one new version per row, tombstones a high row's embedding rows and tags a medium row's. The closing line is the high- sensitivity invariant (high rows with a live embedding). integrity-repair Read the row-level integrity gauges (dim-0 rows holding a vector, tombstoned_at/status drift, active rows past valid_to) and, with --apply, re-emit the dim-0 rows with their true dimension so search can return them again. Drift and valid_to are listed, not repaired. rechunk Re-chunk and re-embed a namespace's knowledge documents from stored content through the current chunker, so every document carries section metadata, chunk context and document frequency. Idempotent; one embedding per new chunk. Dry run by default (counts the documents and chunks); --apply re-chunks. export-actions Export the action schema derived from the operation registry — an MCP tools/list manifest with loom extras (json) or the Cedar schema (cedar) a policy gateway governs the surface with. lexical-stats-rebuild Recompute BM25 document frequency for a namespace from its live rows (the term-frequency views only see inserts; supersession and tombstones leave stale vocabulary behind). version Print installed Loom version. install Wire Loom into a local AI client's config. Writes the MCP server block into Claude Desktop / Cursor / VS Code's config file, atomically, merging with anything already there; for Claude Code it runs (or prints) `claude mcp add` and for Codex `codex mcp add`. Restart the client afterwards. demo The first five minutes: ingest this repo's AGENTS.md (or --file) into the knowledge plane the way `make ingest` does, ask it a question, and print the answer with its evidence rows. On the stock fake-LLM stack it prints the top knowledge.search hits and says what a real answer needs. init Create an identity on a Loom server. `--agent NAME` signs an agent up by itself (server needs LOOM_SELF_SIGNUP=open): mints a writer token on a fresh agent- namespace, saves it to ~/.loom/token, and prints the claim code a person enters once, with a password of their own, to claim the namespace. ingest-transcript Pipe a chat-history file (markdown / JSON) into Loom's conversation table as one thread. Generic ingest for tools without an MCP integration (Aider, Continue.dev, JetBrains AI, anything else): export the chat → run this command → the thread shows in the dashboard's Conversations. memory-search Run a memory.search from the shell. Default human output; --json-agent emits a structured envelope agents can pipe through (a `{command, results}` JSON shape). set-host Designate the Loom host(s) for this deployment. Writes the given login handle(s) or email(s) to LOOM_PLATFORM_ADMINS in the .env (--env-file, default ./.env): a handle promotes that password account to platform_admin, an email promotes an SSO sign-in with that verified email. Multiple OK (on-call rotation, co-operators, etc.). Re-login required after to pick up the role. login Sign in to a Loom server on any browser with a one-time code. logout End the stored session on the server and forget it here. whoami Show who the stored session signs you in as. call Call any operation or API route with the stored session (`loom call --help`). token Make, list and revoke your own tokens for CI and agents (`loom token --help`). connect Print the dashboard link to connect your own Google, Notion or Linear account. pointers Print the code pointer block for the task prompt on standard input. curator Report what in a namespace needs a person, and set its curator mode (`loom curator --help`). skill List and read the server's skills, check a skill folder, save one as a draft, publish, reject, archive or delete it, write a published skill to a folder, and report which revisions were fetched (`loom skill --help`). copy-rule Preview a namespace's copy rule, or run it to propose each new match (`loom copy-rule --help`). proposals List a namespace's pending proposals, read one whole, and accept or reject by the hash of the text that was read (`loom proposals --help`).", "options: -h, --help show this help message and exit --version show program's version number and exit" ], "loom code": [ diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 4371fc4b76..f6d1d27b8a 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -19705,7 +19705,7 @@ }, { "dest": "skill", - "help": "List and read the server's skills, check a skill folder, save one as a draft, publish, reject, archive or delete it, and write a published skill to a folder (`loom skill --help`).", + "help": "List and read the server's skills, check a skill folder, save one as a draft, publish, reject, archive or delete it, write a published skill to a folder, and report which revisions were fetched (`loom skill --help`).", "metavar": "skill" }, { diff --git a/tests/unit/snapshots/sdk_public_api.json b/tests/unit/snapshots/sdk_public_api.json index e674d3e9d1..972c01e34a 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -1895,6 +1895,10 @@ "save": [ "body", "options" + ], + "usage": [ + "body", + "options" ] } }, diff --git a/tests/unit/test_sdk_skill_usage_command.py b/tests/unit/test_sdk_skill_usage_command.py new file mode 100644 index 0000000000..aea055224c --- /dev/null +++ b/tests/unit/test_sdk_skill_usage_command.py @@ -0,0 +1,186 @@ +"""`loom skill usage`, against the handler. + +The command prints the server's sentences and the numbers under them. These tests fail +when it writes a sentence of its own for a count, sends a window or `by_subject` nobody +asked for, names a principal in a report that did not ask who fetched, prints a refused +`--by-subject` as a report, or exits 0 on a server that does not serve the op. +""" + +from __future__ import annotations + +import json +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any + +import httpx +import pytest +from loom import cli + +from server.auth.jwt import AuthInfo +from server.core.errors import LoomServerError +from server.identity.api.models_skills import SkillUsageInput +from server.identity.app import skill_usage +from server.identity.app.skill_usage import handle_skill_usage +from server.observability.consumer import CLI_INSPECT_CONSUMER +from server.settings import settings +from tests.unit import skill_store +from tests.unit.principals import NAMESPACE, ORG, acting_as, principal +from tests.unit.skill_store import Skills + +WRITER = principal("writer", subject="alice@example.com", service_account=False) +ADMIN = principal("admin", subject="bob@example.com", service_account=False) +NOW = datetime(2030, 3, 1, 12, 0, 0) +A = "a" * 64 +REPORT = ( + "Counts cover the last 30 days and are lower bounds: the request ledger can drop a " + "row, so each number reads as at least that many. Loom does not record which " + "sessions were shown the listing: a fetch counts a session that asked for the " + "skill's text. A session's listing can carry 1 skill of this namespace: it takes " + "one skill of each namespace in turn, each namespace's by name." +) + + +class _Server: + """A deployment that serves `skill.usage` to `caller`, or does not serve it.""" + + def __init__(self, store: Skills) -> None: + self.store = store + self.caller: AuthInfo = WRITER + self.serves = True + self.calls: list[dict[str, Any]] = [] + + async def __call__(self, request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + op = request.url.path.removeprefix("/v1/") + if op == "ops.capabilities": + ops = [{"name": "skill.usage", "required_role": "VIEWER"}] if self.serves else [] + return httpx.Response( + 200, json={"build_commit": "abc1234", "schema_version": "1", "ops": ops} + ) + assert op == "skill.usage", op + self.calls.append(body) + try: + with acting_as(self.caller): + answer = await handle_skill_usage(SkillUsageInput(**body)) + except LoomServerError as refused: + return httpx.Response(refused.status_code, json={"detail": refused.to_detail()}) + return httpx.Response(200, content=answer.model_dump_json()) + + +@pytest.fixture +def server(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> _Server: + monkeypatch.setattr(skill_usage, "naive_utc_now", lambda: NOW) + monkeypatch.setattr(settings, "retention_agent_events_days", 0) + store = skill_store.install(monkeypatch) + # Revision 1 published ten days ago: two sessions of one principal fetched it, and + # a command that shows a skill looked at it once. + store.add("runbook", 1, "save", 1, A, at=NOW - timedelta(days=11), description="How we deploy.") + store.add( + "runbook", 2, "publish", 1, A, at=NOW - timedelta(days=10), description="How we deploy." + ) + for session, days in (("s1", 3), ("s2", 2)): + store.fetched(A, NOW - timedelta(days=days), session_id=session, subject="sa:deploy-bot") + store.fetched( + A, + NOW - timedelta(days=1), + subject="carol@example.com", + consumer=CLI_INSPECT_CONSUMER, + transport="http", + ) + wire = _Server(store) + for name in ("LOOM_PROFILE", "LOOM_MENTOR_BRIEF", "LOOM_AUTO_RUN"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("LOOM_BASE_URL", "http://example.invalid") + monkeypatch.setenv("LOOM_API_KEY", "private-pipeline-bearer") + monkeypatch.setattr("loom.credentials.CREDENTIALS_FILE", tmp_path / "credentials") + monkeypatch.setattr("loom.transport.TOKEN_FILE", tmp_path / "token") + real_client = httpx.AsyncClient + + def client(*args: Any, **kwargs: Any) -> httpx.AsyncClient: + kwargs["transport"] = httpx.MockTransport(wire) + kwargs.pop("http2", None) + return real_client(*args, **kwargs) + + monkeypatch.setattr("loom.transport.httpx.AsyncClient", client) + return wire + + +def _asked(body: dict[str, Any]) -> dict[str, Any]: + """What a request asked of the op, without the caller's identity fields.""" + return {k: body[k] for k in ("namespace", "name", "days", "by_subject") if k in body} + + +def _run(*argv: str) -> int: + """`loom skill usage` under the org that holds the skills.""" + return cli.main(["skill", "usage", *argv, "--org", ORG]) + + +def test_usage_prints_the_servers_sentences_over_the_numbers( + server: _Server, capsys: pytest.CaptureFixture[str] +) -> None: + """Fails when the report's or the skill's sentence is not the server's, a look is + counted as a fetch, or the request carries a window or `by_subject` nobody asked.""" + assert _run(NAMESPACE) == 0 + assert capsys.readouterr().out == ( + f"{REPORT}\n" + "\n" + f"{NAMESPACE}/runbook revision 1 is published\n" + " Revision 1 was fetched by at least 2 sessions of at least 1 principal in the " + "last 30 days.\n" + " revision 1 sessions >= 2 principals >= 1 last fetched 2030-02-27T12:00:00 " + "looks 1\n" + ) + assert [_asked(body) for body in server.calls] == [{"namespace": NAMESPACE, "name": ""}] + + +def test_usage_names_one_skill_and_its_window( + server: _Server, capsys: pytest.CaptureFixture[str] +) -> None: + """Fails when `/` is not split at the last slash, `--days` is not + sent, or a name the namespace does not hold prints a skill.""" + assert _run(f"{NAMESPACE}/runbook", "--days", "7", "--json") == 0 + answer = json.loads(capsys.readouterr().out) + assert answer["window_days"] == 7 + assert [s["name"] for s in answer["skills"]] == ["runbook"] + assert _asked(server.calls[0]) == {"namespace": NAMESPACE, "name": "runbook", "days": 7} + + assert _run(f"{NAMESPACE}/absent") == 0 + assert capsys.readouterr().out.endswith("\n\nno skill to report\n") + + +def test_who_fetched_is_printed_for_an_administrator_alone( + server: _Server, capsys: pytest.CaptureFixture[str] +) -> None: + """Fails when a report that did not ask names a principal, when a writer's + `--by-subject` prints a report, or when an administrator's lacks who fetched, over + which transport and under which consumer.""" + assert _run(NAMESPACE) == 0 + assert "deploy-bot" not in capsys.readouterr().out + + assert _run(NAMESPACE, "--by-subject") == 1 + printed = capsys.readouterr() + assert "it needs admin on 'shop'" in printed.err and printed.out == "" + + server.caller = ADMIN + assert _run(NAMESPACE, "--by-subject") == 0 + assert capsys.readouterr().out.endswith( + " who fetched:\n" + " carol@example.com fetched revision 1 between 2030-02-28T12:00:00 and " + "2030-02-28T12:00:00, over HTTP (the command, an SDK or a job), as " + f"{CLI_INSPECT_CONSUMER}\n" + " sa:deploy-bot fetched revision 1 between 2030-02-26T12:00:00 and " + "2030-02-27T12:00:00, over MCP, as user\n" + ) + assert _asked(server.calls[-1]) == {"namespace": NAMESPACE, "name": "", "by_subject": True} + + +def test_usage_on_a_server_without_the_op_exits_2( + server: _Server, capsys: pytest.CaptureFixture[str] +) -> None: + """Fails when a server that does not serve the op is asked, or the run exits 0.""" + server.serves = False + assert _run(NAMESPACE) == 2 + printed = capsys.readouterr() + assert "loom skill usage: this server does not serve skill.usage" in printed.err + assert printed.out == "" and server.calls == [] diff --git a/tests/unit/test_skill_usage.py b/tests/unit/test_skill_usage.py new file mode 100644 index 0000000000..ae6ade76fe --- /dev/null +++ b/tests/unit/test_skill_usage.py @@ -0,0 +1,493 @@ +"""What `skill.usage` counts as a fetch, what it calls stale, and what its sentences say. + +The handler runs over the in-memory skills and ledger of `tests/unit/skill_store.py`, +whose ledger read applies the hashes and times it is given as the statement does; the +statement itself is read as text here and run on clickhouse-local. Each test says in +its docstring which defect fails it. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from typing import Any + +import pydantic +import pytest + +from server.auth.jwt import AuthInfo +from server.core.errors import AuthInsufficientError +from server.core.paths import REPO_ROOT +from server.identity.api.models_skills import SkillUsageInput +from server.identity.app import skill_usage +from server.identity.domain import skill_usage as usage +from server.identity.store import skill_fetches +from server.identity.store import skills as repo +from server.observability.consumer import ( + ASSISTANT_CONSUMER, + CLI_INSPECT_CONSUMER, + INSPECTOR_CONSUMERS, + UI_CONSUMER, +) +from server.settings import settings +from tests.unit import skill_store +from tests.unit.clickhouse_local import CLICKHOUSE, ddl, run +from tests.unit.principals import NAMESPACE, ORG, acting_as, principal +from tests.unit.skill_store import Skills + +WRITER = principal("writer", subject="alice@example.com", service_account=False) +ADMIN = principal("admin", subject="bob@example.com", service_account=False) +VIEWER = principal("viewer", subject="vera@example.com", service_account=False) +NAME = "runbook" +NOW = datetime(2030, 3, 1, 12, 0, 0) +A, B, C, D = (letter * 64 for letter in "abcd") +needs_clickhouse = pytest.mark.skipif(CLICKHOUSE is None, reason="needs the clickhouse binary") + + +def _ago(**span: float) -> datetime: + return NOW - timedelta(**span) + + +@pytest.fixture() +def store(monkeypatch: pytest.MonkeyPatch) -> Skills: + monkeypatch.setattr(skill_usage, "naive_utc_now", lambda: NOW) + monkeypatch.setattr(settings, "retention_agent_events_days", 0) + return skill_store.install(monkeypatch) + + +def _history(store: Skills, name: str = NAME) -> None: + """Revision 1 published 20 days ago and superseded by 2 ten days ago, 3 rejected, + 4 an open draft saved a day ago.""" + store.add(name, 1, "save", 1, A, at=_ago(days=21)) + store.add(name, 2, "publish", 1, A, at=_ago(days=20)) + store.add(name, 3, "save", 2, B, at=_ago(days=11)) + store.add(name, 4, "publish", 2, B, at=_ago(days=10)) + store.add(name, 5, "save", 3, C, at=_ago(days=5)) + store.add(name, 6, "reject", 3, C, at=_ago(days=4)) + store.add(name, 7, "save", 4, D, at=_ago(days=1)) + + +async def _usage(auth: AuthInfo | None, **fields: Any) -> dict[str, Any]: + with acting_as(auth): + out = await skill_usage.handle_skill_usage( + SkillUsageInput(org=ORG, namespace=NAMESPACE, **fields) + ) + return out.model_dump() + + +async def test_skill_usage_counts(store: Skills) -> None: + """Fails when rows are grouped by anything but the hash, an inspector read is + counted as a fetch or dropped from `inspector_fetches`, a `-` session counts as a + session, a read before the revision's publish counts, or a revision that was never + published has an entry.""" + _history(store) + # Revision 1: one session twice over MCP, the same session once over HTTP, a second + # session, a read that named no session, three looks, and a read before its publish. + store.fetched(A, _ago(days=19), session_id="s1", subject="alice") + store.fetched(A, _ago(days=18), session_id="s1", subject="alice") + store.fetched(A, _ago(days=17), session_id="s1", subject="alice", transport="http") + store.fetched(A, _ago(days=16), session_id="s2", subject="bob", transport="http") + store.fetched(A, _ago(days=15), subject="carol", transport="http") + for consumer in INSPECTOR_CONSUMERS: + store.fetched(A, _ago(days=2), session_id="looking", subject="dana", consumer=consumer) + store.fetched(A, _ago(days=20, hours=1), session_id="early", subject="erin") + # A publish row's time is in whole seconds: a read in its second may be of the draft. + store.fetched(A, _ago(days=20) + timedelta(milliseconds=400), session_id="e2", subject="erin") + # Revision 2: one session. Revisions 3 and 4 were never published. + store.fetched(B, _ago(days=3), session_id="s3", subject="alice") + store.fetched(C, _ago(days=3), session_id="s4", subject="frank") + store.fetched(D, _ago(hours=2), session_id="s5", subject="gina") + + answer = await _usage(WRITER) + + [skill] = answer["skills"] + assert (skill["namespace"], skill["name"]) == (NAMESPACE, NAME) + assert (skill["published_revision"], skill["published_at"]) == (2, _ago(days=10)) + assert skill["fetches"] == [ + { + "revision": 2, + "content_sha256": B, + "sessions": 1, + "subjects": 1, + "last_at": _ago(days=3), + "inspector_fetches": 0, + }, + { + "revision": 1, + "content_sha256": A, + "sessions": 2, + "subjects": 3, + "last_at": _ago(days=15), + "inspector_fetches": 3, + }, + ] + assert skill["statement"] == ( + "Revision 2 was fetched by at least 1 session of at least 1 principal in the last " + "30 days. Revision 1 was fetched by at least 2 sessions of at least 3 principals " + "in the last 30 days." + ) + # The read was asked for the published hashes alone, each from the second after + # its publish. + [asked] = store.ledger_asked + second = timedelta(seconds=1) + assert asked["published"] == {A: _ago(days=20) + second, B: _ago(days=10) + second} + assert asked["since"] == _ago(days=30) + + +async def test_only_looks_are_shown_and_never_counted(store: Skills) -> None: + """Fails when a skill only inspectors read is said to be fetched, or when its looks + are left out of the answer.""" + store.add(NAME, 1, "save", 1, A, at=_ago(days=3)) + store.add(NAME, 2, "publish", 1, A, at=_ago(days=2)) + store.fetched(A, _ago(days=1), session_id="s", subject="dana", consumer=UI_CONSUMER) + store.fetched(A, _ago(hours=5), subject="dana", consumer=CLI_INSPECT_CONSUMER) + store.fetched(A, _ago(hours=4), subject="dana", consumer=ASSISTANT_CONSUMER) + + [skill] = (await _usage(VIEWER))["skills"] + + assert skill["fetches"] == [ + { + "revision": 1, + "content_sha256": A, + "sessions": 0, + "subjects": 0, + "last_at": None, + "inspector_fetches": 3, + } + ] + assert skill["statement"].startswith("Not fetched from Loom in the last 30 days.") + + +async def test_skill_usage_window_and_statement( + store: Skills, monkeypatch: pytest.MonkeyPatch +) -> None: + """Fails when `window_days` exceeds the kept days, the cut sentence is missing, + `days=91` is accepted, or a skill with no fetch lacks its sentence or gains a stale + code for it.""" + store.add(NAME, 1, "save", 1, A, at=_ago(days=40), description="How we deploy.") + store.add(NAME, 2, "publish", 1, A, at=_ago(days=39), description="How we deploy.") + store.add("quiet", 1, "save", 1, B, at=_ago(days=40), listed=0, description="By name.") + store.add("quiet", 2, "publish", 1, B, at=_ago(days=39), listed=0, description="By name.") + + whole = await _usage(VIEWER) + assert whole["window_days"] == 30 + assert whole["statement"] == ( + "Counts cover the last 30 days and are lower bounds: the request ledger can drop a " + "row, so each number reads as at least that many. Loom does not record which " + "sessions were shown the listing: a fetch counts a session that asked for the " + "skill's text. A session's listing can carry 1 skill of this namespace: it takes " + "one skill of each namespace in turn, each namespace's by name." + ) + not_fetched = ( + "Not fetched from Loom in the last 30 days. A copy pulled to a folder is read " + "without a fetch, so the skill may still be read from one." + ) + assert [(s["name"], s["statement"], s["stale"]) for s in whole["skills"]] == [ + ("quiet", not_fetched, []), + (NAME, not_fetched, []), + ] + + # The namespace's own retention cuts the window, and the statement says so. + store.retention_days = 7 + cut = await _usage(VIEWER, days=30) + assert cut["window_days"] == 7 + assert cut["statement"].endswith("Fetches are kept for 7 days, so older ones are not counted.") + assert store.ledger_asked[-1]["since"] == _ago(days=7) + assert "in the last 7 days" in cut["skills"][0]["statement"] + # A window inside the kept days is not cut. + assert "are kept for" not in (await _usage(VIEWER, days=7))["statement"] + # With no retention of its own, the namespace's ledger is kept as the table is. + store.retention_days = 0 + monkeypatch.setattr(settings, "retention_agent_events_days", 1) + table = await _usage(VIEWER, days=90) + assert table["window_days"] == 1 + assert table["statement"].endswith("Fetches are kept for 1 day, so older ones are not counted.") + + for days in (0, 91): + with pytest.raises(pydantic.ValidationError): + SkillUsageInput(org=ORG, namespace=NAMESPACE, days=days) + assert SkillUsageInput(org=ORG, namespace=NAMESPACE, days=90).days == usage.DAYS_MAX + + +async def test_an_empty_namespace_answers_no_skill_and_the_statement(store: Skills) -> None: + """Fails when a namespace with no skill answers an error, no statement, or a read + of the ledger with no hash to look for.""" + answer = await _usage(VIEWER) + assert answer["skills"] == [] and answer["window_days"] == 30 + assert "can carry 0 skills of this namespace" in answer["statement"] + assert store.ledger_asked == [{"since": _ago(days=30), "published": {}, "limit": 10_001}] + assert await skill_fetches.fetch_groups(ORG, NAMESPACE, NOW, {}, 5, ch=object()) == [] + + +async def test_a_cut_ledger_read_says_so(store: Skills, monkeypatch: pytest.MonkeyPatch) -> None: + """Fails when a read the limit cut is answered as a whole one: the statement must + name the limit, and the row past it must not be counted.""" + monkeypatch.setattr(usage, "FETCH_GROUPS_MAX", 2) + store.add(NAME, 1, "save", 1, A, at=_ago(days=3)) + store.add(NAME, 2, "publish", 1, A, at=_ago(days=2)) + for n in range(3): + store.fetched(A, _ago(hours=n + 1), session_id=f"s{n}", subject=f"p{n}") + + cut = await _usage(VIEWER) + + assert store.ledger_asked[-1]["limit"] == 3 + assert cut["statement"].endswith( + "The ledger read stopped at 2 rows, the most recent, so older fetches in the " + "window are not counted." + ) + assert cut["skills"][0]["fetches"][0]["sessions"] == 2 + # A read that fits is not said to be cut. + store.ledger.pop() + assert "stopped at" not in (await _usage(VIEWER))["statement"] + + +async def test_a_failed_ledger_read_fails_the_op(store: Skills) -> None: + """Fails when a ledger read that raised is answered as no fetch.""" + store.add(NAME, 1, "save", 1, A, at=_ago(days=3)) + store.add(NAME, 2, "publish", 1, A, at=_ago(days=2)) + store.ledger_fails = True + with pytest.raises(RuntimeError, match="the ledger read failed"): + await _usage(VIEWER) + + +async def test_skill_usage_stale_codes(store: Skills) -> None: + """Fails when a code is missing for its case, a viewer gets `draft_waiting`, a draft + inside the bound is called stale, or a code names anything but a waiting draft and + an unknown operation.""" + # `runbook`: published text that names an operation no build serves, and a draft + # saved 15 days ago. `notes`: a known operation and a draft saved 13 days ago. + store.add(NAME, 1, "save", 1, A, at=_ago(days=30), op_names=["memory.search", "memory.gone"]) + store.add(NAME, 2, "publish", 1, A, at=_ago(days=29)) + store.add(NAME, 3, "save", 2, B, at=_ago(days=15)) + store.add("notes", 1, "save", 1, C, at=_ago(days=30), op_names=["memory.search", "loom_op"]) + store.add("notes", 2, "publish", 1, C, at=_ago(days=29)) + store.add("notes", 3, "save", 2, D, at=_ago(days=13)) + + as_writer = {s["name"]: s for s in (await _usage(WRITER))["skills"]} + assert as_writer[NAME]["stale"] == ["draft_waiting", "unknown_operation"] + assert as_writer["notes"]["stale"] == [] + assert as_writer[NAME]["statement"].endswith( + "A draft has waited for review for more than 14 days. The published revision " + "names an operation this server does not serve." + ) + # A draft is its writers' to read: a viewer learns the published text's code alone. + as_viewer = {s["name"]: s for s in (await _usage(VIEWER))["skills"]} + assert as_viewer[NAME]["stale"] == ["unknown_operation"] + assert "draft" not in as_viewer[NAME]["statement"] + assert as_viewer["notes"]["stale"] == [] + # The closed set of this build. + assert {usage.DRAFT_WAITING, usage.UNKNOWN_OPERATION} == {"draft_waiting", "unknown_operation"} + assert usage.DRAFT_WAITING_DAYS == 14 + + +async def test_a_reader_is_reported_only_the_skills_it_lists(store: Skills) -> None: + """Fails when a caller below WRITER is answered a skill with nothing published, an + archived one, or a revision that was never published, or when a writer loses one.""" + _history(store) + store.add("draft-only", 1, "save", 1, C, at=_ago(days=2)) + store.add("stopped", 1, "save", 1, D, at=_ago(days=20)) + store.add("stopped", 2, "publish", 1, D, at=_ago(days=19)) + store.add("stopped", 3, "archive", 1, D, at=_ago(days=18)) + store.fetched(D, _ago(days=18, hours=12), session_id="s", subject="alice") + + assert [s["name"] for s in (await _usage(VIEWER))["skills"]] == [NAME] + for name in ("draft-only", "stopped", "no-such-skill"): + named = await _usage(VIEWER, name=name) + assert named["skills"] == [], name + assert named["statement"] == (await _usage(VIEWER))["statement"] + [named] = (await _usage(VIEWER, name=NAME))["skills"] + assert named["name"] == NAME and named["published_revision"] == 2 + # A viewer's read asks the ledger for no hash of a skill it is not listed. + assert set(store.ledger_asked[-1]["published"]) == {A, B} + + as_writer = {s["name"]: s for s in (await _usage(WRITER))["skills"]} + assert sorted(as_writer) == ["draft-only", NAME, "stopped"] + assert as_writer["draft-only"]["fetches"] == [] and not as_writer["draft-only"]["stale"] + assert as_writer["draft-only"]["published_revision"] == 0 + # An archived skill serves nothing; its fetches while it was served are a writer's. + assert as_writer["stopped"]["published_at"] is None + assert [f["revision"] for f in as_writer["stopped"]["fetches"]] == [1] + + +async def test_skill_usage_by_subject(store: Skills, monkeypatch: pytest.MonkeyPatch) -> None: + """Fails when a caller below ADMIN gets subjects, when they are answered unasked, + or when an inspector's rows are left out of them.""" + _history(store) + store.fetched(A, _ago(days=19), session_id="s1", subject="alice") + store.fetched(A, _ago(days=12), session_id="s2", subject="alice") + store.fetched(B, _ago(days=3), session_id="s3", subject="alice", transport="http") + store.fetched(B, _ago(days=2), session_id="s4", subject="dana", consumer=UI_CONSUMER) + + for auth in (VIEWER, WRITER): + with pytest.raises(AuthInsufficientError, match="needs admin"): + await _usage(auth, by_subject=True) + assert (await _usage(ADMIN))["skills"][0]["subjects"] == [] + + [skill] = (await _usage(ADMIN, by_subject=True))["skills"] + assert skill["subjects"] == [ + { + "subject": "alice", + "revision": 2, + "transport": "http", + "consumer": "user", + "first_at": _ago(days=3), + "last_at": _ago(days=3), + }, + { + "subject": "dana", + "revision": 2, + "transport": "mcp", + "consumer": UI_CONSUMER, + "first_at": _ago(days=2), + "last_at": _ago(days=2), + }, + { + "subject": "alice", + "revision": 1, + "transport": "mcp", + "consumer": "user", + "first_at": _ago(days=19), + "last_at": _ago(days=12), + }, + ] + # With sign-in off every namespace is the one user's; with it on, no principal is + # nobody's administrator. + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: False) + assert (await _usage(None, by_subject=True))["skills"][0]["subjects"] + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) + with pytest.raises(AuthInsufficientError): + await _usage(None, by_subject=True) + + +class _Recording: + """A client that keeps what it was sent and answers no row.""" + + def __init__(self) -> None: + self.sent: list[tuple[str, dict[str, Any]]] = [] + + async def query_all(self, sql: str, params: dict[str, Any] | None = None, **_: Any) -> Any: + self.sent.append((sql, params or {})) + return [] + + +async def test_skill_usage_statement_shape() -> None: + """Fails when the ledger statement lacks the `(org, namespace)` prefix, the `ts` + bound or the `LIMIT`, formats a value into its text, or when either read selects + skill text.""" + ch = _Recording() + since, at = NOW - timedelta(days=30), NOW - timedelta(days=2) + await skill_fetches.fetch_groups(ORG, NAMESPACE, since, {A: at}, 7, ch=ch) + await repo.usage_acts(ORG, NAMESPACE, ch=ch) + (ledger, ledger_params), (acts, acts_params) = ch.sent + + assert ( + "WHERE org = {org:String} AND namespace = {ns:String} AND ts >= {since:DateTime64(3)} " + "AND operation = 'skill.get' AND kind != 'worker' AND success" in ledger + ) + assert ledger.endswith("LIMIT {limit:UInt32}") + assert "has({hashes:Array(String)}, content_sha256)" in ledger + assert "loom.agent_events" in ledger and "loom.skills" not in ledger + assert not any(value in ledger for value in (ORG, NAMESPACE, A)) + assert ledger_params == { + "org": ORG, + "ns": NAMESPACE, + "since": since, + "hashes": [A], + "published": [at], + "limit": 7, + } + # The ledger keeps the hash a read answered, never its text. + selected = ledger.split(" FROM ", 1)[0] + assert selected == ( + "SELECT content_sha256, session_id, subject, consumer, transport, " + "count() AS fetches, min(ts) AS first_at, max(ts) AS last_at" + ) + + columns = acts.split(" FROM ", 1)[0].removeprefix("SELECT ").split(", ") + assert "op_names" in columns and not {"content", "files", "origin", "note"} & set(columns) + assert "WHERE org = {org:String} AND namespace = {ns:String} " in acts + assert acts_params == {"org": ORG, "ns": NAMESPACE} and NAMESPACE not in acts + + +def _event(ts: datetime, sha: str, **fields: Any) -> str: + row: dict[str, Any] = { + "org": ORG, + "namespace": NAMESPACE, + "session_id": "-", + "subject": "alice", + "consumer": "user", + "transport": "mcp", + "operation": "skill.get", + "kind": "", + "success": 1, + } + row |= fields + plain = ", ".join(f"'{row[name]}'" for name in sorted(row) if name != "success") + names = ", ".join(name for name in sorted(row) if name != "success") + args = f"map('out_content_sha256', '{sha}', 'out_found', 'true')" + return ( + f"INSERT INTO loom.agent_events (ts, {names}, success, agent, user_id, request_id, " + f"latency_ms, args) VALUES ('{ts:%Y-%m-%d %H:%M:%S}', {plain}, {row['success']}, " + f"'a', '-', 'r', 1, {args})" + ) + + +@needs_clickhouse +def test_the_ledger_statement_counts_a_fetch_from_its_publish_on() -> None: + """Fails when the statement answers a read before the hash's publish or the + window, a read of a hash not asked for, a failed call, a worker's row, another + operation or another namespace, or when it groups two sessions as one.""" + since, at = NOW - timedelta(days=30), NOW - timedelta(days=10) + setup = [ + ddl("agent_events"), + ddl("agent_events_private"), + _event(NOW - timedelta(days=9), A, session_id="s1"), + _event(NOW - timedelta(days=8), A, session_id="s1"), + _event(NOW - timedelta(days=7), A, session_id="s2", transport="http"), + _event(NOW - timedelta(days=6), A, session_id="s3", subject="dana", consumer=UI_CONSUMER), + # None of these is a fetch of `A`. + _event(NOW - timedelta(days=11), A, session_id="before-publish"), + _event(NOW - timedelta(days=5), B, session_id="other-hash"), + _event(NOW - timedelta(days=5), A, session_id="failed", success=0), + _event(NOW - timedelta(days=5), A, session_id="worker", kind="worker"), + _event(NOW - timedelta(days=5), A, session_id="other-op", operation="skill.check"), + _event(NOW - timedelta(days=5), A, session_id="other-ns", namespace="elsewhere"), + _event(NOW - timedelta(days=5), A, session_id="other-org", org="other"), + ] + params = { + "org": ORG, + "ns": NAMESPACE, + "since": since, + "hashes": [A], + "published": [at], + "limit": 10, + } + rows = run(setup, skill_fetches.FETCHES, params) + assert [(r["session_id"], r["consumer"], r["transport"], int(r["fetches"])) for r in rows] == [ + ("s3", UI_CONSUMER, "mcp", 1), + ("s2", "user", "http", 1), + ("s1", "user", "mcp", 2), + ] + assert {r["content_sha256"] for r in rows} == {A} + # The window bounds the read whatever the publish time, and the limit cuts it. + late = run(setup, skill_fetches.FETCHES, {**params, "since": NOW - timedelta(days=7, hours=1)}) + assert [r["session_id"] for r in late] == ["s3", "s2"] + assert len(run(setup, skill_fetches.FETCHES, {**params, "limit": 1})) == 1 + + +def test_the_dashboard_says_what_a_stale_code_means_in_the_servers_sentence() -> None: + """Fails when the dashboard's meaning of a stale code is not the sentence the server + appends to a skill's statement for it, or a code has no label there.""" + labels = (REPO_ROOT / "frontend/src/views/skills/stale.tsx").read_text(encoding="utf-8") + for code, sentence in usage._STALE_SENTENCE.items(): + assert f" {code}: {{" in labels, code + assert sentence in labels, code + + +def test_the_op_is_a_read_of_the_namespace_and_experimental() -> None: + """Fails when the op is declared a write, audited, stable, or below VIEWER.""" + from server.operations.base import Role + from server.operations.registry import OPERATIONS_BY_NAME + + op = OPERATIONS_BY_NAME["skill.usage"] + assert op.read_only and op.idempotent and not op.audit + assert op.maturity == "experimental" and op.required_role is Role.VIEWER From d72bfc945aabd0cbd48dabab7cc11b59ab703bd6 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 09:15:34 +0000 Subject: [PATCH 2/3] skill.usage says when a cut ledger read may hide a skill's fetches A skill with no fetch among the groups of a cut ledger read is said to have none among the rows read, and that an older fetch in the window may exist. The read keeps the 10,000 most recent groups, so a skill whose groups are all older got the sentence of a skill that was not fetched. A skill that never published keeps that sentence: the read asked for no hash of it. - A fetch whose request sent a blank `session_id` counts its principal only, as one that named no session does. The ledger stores a blank id as the empty string, which counted as one session. - The report reads the registry once, over the operation names of every served revision. It built the registry's facts once for each skill. - `skills.reach` is public and answers the `by_subject` admin check from the gate that answers the reader and writer checks. The report built a second gate through a copy of the helper. - `loom skill usage --by-subject` prints `no sign-in` for a read with no subject, the dashboard's words. - The ledger statement's test holds the guard against a read with no hash. The assertion ran the in-memory ledger, so removing the guard failed no test. - `DAYS_MAX` had no caller and is removed. The comment on the masked ledger rows names the mark that masks a row, and the architecture page says which stale code depends on the answering build. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/skills.md | 6 +- docs/features/skills.md | 2 +- sdk/python/loom/cli_skill_usage.py | 5 +- server/identity/api/models_skills.py | 3 +- server/identity/app/skill_usage.py | 66 ++++++++++--------- server/identity/app/skills.py | 27 ++++---- server/identity/domain/skill_usage.py | 27 +++++--- server/identity/store/skill_fetches.py | 5 +- tests/unit/test_sdk_skill_usage_command.py | 22 ++++++- tests/unit/test_skill_usage.py | 77 ++++++++++++++++------ 10 files changed, 159 insertions(+), 81 deletions(-) diff --git a/docs/architecture/skills.md b/docs/architecture/skills.md index 83d2236d80..2fa4d3e9c5 100644 --- a/docs/architecture/skills.md +++ b/docs/architecture/skills.md @@ -360,9 +360,9 @@ So the report says "fetched", gives every count as a lower bound, and never says - **Two reads and a row.** One read of `loom.skills` by `(org, namespace)` for the acts of every skill, without `content` or `files` (`usage_acts`); one statement over the request ledger (`FETCHES` in `server/identity/store/skill_fetches.py`); and the namespace's registry row, for the days it keeps its ledger. The acts are read with sequential consistency ([what that covers](clickhouse.md#read-your-writes)), so no reader is reported a skill an archive on another replica stopped. - **What counts as a fetch.** A ledger row of a successful `skill.get`, not a worker's, whose `out_content_sha256` is the hash of a revision that the fold calls published, superseded or withdrawn, and whose time is past the second of that revision's first `publish` row. A `publish` row keeps whole seconds, so a read in that second may be a writer's read of the draft and is not counted. The ledger keeps the hash a read answered and never the number: of two published revisions with one hash, the higher is named. A draft's hash, a rejected revision's and a void one's are not in the statement's parameters, so no row of theirs is read. - **The statement.** It filters by `org`, `namespace`, the window and the operation, keeps the rows whose hash is one of the published hashes from that hash's time on (two bound arrays), and groups by hash, session, principal, consumer and transport with a count and the first and the last time. It returns the most recent 10,000 groups and one more (`FETCH_GROUPS_MAX`): the extra group tells a cut read from a whole one, and the report's statement says when the read was cut. The ledger is sorted by `(org, namespace, agent, ts)` and partitioned by month, so the read prunes to the namespace's rows of the window's months. The window is at most 90 days, and never longer than the days the namespace keeps its ledger. -- **The counts.** `server/identity/domain/skill_usage.py` makes one entry a revision of the groups: the distinct sessions (a row with no session counts its principal only), the distinct principals, and the last fetch. A group whose consumer is an inspector's (`INSPECTOR_CONSUMERS`) counts in neither and is summed as `inspector_fetches`. `loom skill pull` names no consumer, so a pull is a fetch. -- **The sentences.** The report's `statement` and each skill's are built in that one module from the counts: that counts are lower bounds, that a listing shown to a session is not recorded, how many of the namespace's skills a listing can carry and in what order, whether the window or the ledger read was cut, and for each skill the revisions fetched or that none was. The command and the dashboard print them and write none of their own for a count. -- **Stale codes.** A closed set of strings, each proven by rows the skill holds: `draft_waiting` (the open draft's `save` row is more than 14 days old, `DRAFT_WAITING_DAYS`) and `unknown_operation` (a stored `op_names` entry of the served revision that the answering build's registry does not hold). Both thresholds are constants, so a code means the same on every deployment. No fetch is no code: a pulled copy is read without one. +- **The counts.** `server/identity/domain/skill_usage.py` makes one entry a revision of the groups: the distinct sessions (a row with no session, `-` or blank, counts its principal only), the distinct principals, and the last fetch. A group whose consumer is an inspector's (`INSPECTOR_CONSUMERS`) counts in neither and is summed as `inspector_fetches`. `loom skill pull` names no consumer, so a pull is a fetch. +- **The sentences.** The report's `statement` and each skill's are built in that one module from the counts: that counts are lower bounds, that a listing shown to a session is not recorded, how many of the namespace's skills a listing can carry and in what order, whether the window or the ledger read was cut, and for each skill the revisions fetched or that none was. A skill with no fetch among the groups of a cut read is said to have none among them, and that an older one may exist. The command and the dashboard print them and write none of their own for a count. +- **Stale codes.** A closed set of strings, each proven by rows the skill holds: `draft_waiting` (the open draft's `save` row is more than 14 days old, `DRAFT_WAITING_DAYS`) and `unknown_operation` (a stored `op_names` entry of the served revision that the answering build's registry does not hold). The 14 days are a constant, so `draft_waiting` means the same on every deployment; `unknown_operation` is the answering build's. No fetch is no code: a pulled copy is read without one. - **Tenant isolation.** The op needs `viewer` on the namespace it names. The caller is reported the skills `skill.list` lists to it (`listed_row`): a writer every skill, any other reader the ones that serve a revision, and `draft_waiting` is a writer's as the draft is. The published hashes of a skill the caller is not reported are not in the ledger statement's parameters. A name the caller cannot list answers no skill, as a name that does not exist does. `by_subject` names principals, so it needs `admin` on the namespace and is refused with 403 to anyone else: the refusal confirms nothing, since the namespace is the one the caller named. `tests/integration/test_cross_principal_leakage.py` holds the case. - **A failed read fails the op.** An error of the ledger statement is the op's error. A skill is never answered as not fetched because the ledger could not be read. - **Rolling upgrade.** The op adds no table, column or stored value. A replica one release behind answers 404 for it: the command exits 2 and says the server does not serve it, and the dashboard shows no stale label and one line on the **Fetches** tab. diff --git a/docs/features/skills.md b/docs/features/skills.md index f49cdfcff6..2dbc2d7d09 100644 --- a/docs/features/skills.md +++ b/docs/features/skills.md @@ -454,7 +454,7 @@ Every sentence is the server's (`statement` of the report and of each skill), so | A ledger row the server dropped | Every count is a lower bound | - **A fetch.** An answered `skill.get` whose content hash is that of a revision that is or was published, made from the second after that revision was published. A read of a draft, of a rejected revision and of a revision that was never published is no fetch. A session is counted once a revision, whatever the transport; a request that named no session counts its principal only. -- **The window.** `window_days` is `days`, or the days the namespace keeps its request ledger when that is fewer; the statement says when the window was cut. One report folds at most 10,000 ledger groups, the most recent, and the statement says when the read stopped there. +- **The window.** `window_days` is `days`, or the days the namespace keeps its request ledger when that is fewer; the statement says when the window was cut. One report folds at most 10,000 ledger groups, the most recent, and the statement says when the read stopped there. A skill with no fetch among them is then said to have none among the rows read, not none in the window. - **Stale codes.** `stale` holds codes from a closed set, each proven by rows the skill holds. `draft_waiting`: the skill's draft has waited for review for more than 14 days; answered to a caller who may write to the namespace, as the draft is. `unknown_operation`: the published revision names an operation the answering build does not serve. A skill nobody fetched has no code for that. A client shows a code it does not know by its name. - **Who sees what.** The caller is reported the skills `skill.list` lists to it: a writer every skill of the namespace, any other reader the ones that serve a revision. A name the caller cannot list answers no skill, as a name that does not exist does. `by_subject` adds `subjects`, one entry a principal, revision, transport and consumer with the first and the last read; it needs `admin` on the namespace and is refused with 403 to anyone else. - **A failed read.** When the ledger cannot be read the op fails. It never answers a skill as not fetched in place of an error. diff --git a/sdk/python/loom/cli_skill_usage.py b/sdk/python/loom/cli_skill_usage.py index 317aceab93..bf31c7de5b 100644 --- a/sdk/python/loom/cli_skill_usage.py +++ b/sdk/python/loom/cli_skill_usage.py @@ -41,6 +41,9 @@ # How a fetch reached the server, in the words every surface uses. _OVER = {"mcp": "over MCP", "http": "over HTTP (the command, an SDK or a job)"} +# Who made a read that carries no subject, as a server with sign-in off records it: the +# dashboard's words. +NO_SUBJECT = "no sign-in" def add_parsers(actions: Any) -> None: @@ -66,7 +69,7 @@ def _revision_line(entry: dict[str, Any]) -> str: def _subject_line(entry: dict[str, Any]) -> str: - who = entry.get("subject") or "(no principal)" + who = entry.get("subject") or NO_SUBJECT transport = str(entry.get("transport") or "") over = _OVER.get(transport, f"over {transport}") return ( diff --git a/server/identity/api/models_skills.py b/server/identity/api/models_skills.py index 415ba9f6a3..382fcaeb02 100644 --- a/server/identity/api/models_skills.py +++ b/server/identity/api/models_skills.py @@ -570,7 +570,8 @@ class SkillUsage(BaseModel): # skill nobody fetched has no code for that. stale: list[str] = Field(default_factory=list) # The counts in words: a sentence for each fetched revision, or that the skill was - # not fetched in the window, then a sentence for each code of `stale`. + # not fetched in the window (when the ledger read was cut, that no fetch is among + # the rows read), then a sentence for each code of `stale`. statement: str = "" # With `by_subject`, who read each revision: one entry a principal, revision, # transport and consumer, highest revision first. diff --git a/server/identity/app/skill_usage.py b/server/identity/app/skill_usage.py index 2abdcabac9..b2bb864abe 100644 --- a/server/identity/app/skill_usage.py +++ b/server/identity/app/skill_usage.py @@ -16,6 +16,7 @@ from __future__ import annotations +from collections.abc import Iterable from datetime import datetime, timedelta from server.core.ch import own_write_reads @@ -40,27 +41,20 @@ from server.settings import settings -async def _administers(org: str, namespace: str) -> bool: - """Whether the caller holds ADMIN on the namespace. With sign-in off every - namespace is the one user's.""" - # Lazy: server.auth.context pulls in authz, which imports the op modules. - from server.auth.authz import CachedGate - from server.auth.context import current_auth - from server.operations.base import Role - - auth = current_auth() - if auth is None: - return not settings.auth_actually_required() - return await CachedGate(auth, org).admits(namespace, Role.ADMIN) +def _served_names(state: SkillState) -> set[str]: + """The operation names the served revision's save took from its text.""" + served = state.revisions.get(state.served.revision) if state.served else None + return set(served.row["op_names"]) if served else set() -def _names_unknown_operation(state: SkillState) -> bool: - """Whether the served revision's stored names hold one this build's registry does - not serve. The names are the ones its save took from the text.""" - served = state.revisions.get(state.served.revision) if state.served else None - if served is None: - return False - return any(not op.known for op in skills.stored_operations(served.row["op_names"])) +def _unknown_operations(states: Iterable[SkillState]) -> set[str]: + """Those of the names the served revisions of `states` hold that this build's + registry does not serve. One read of the registry a report, whatever the number of + skills: a name is known or not whichever skill holds it.""" + names = sorted({name for state in states for name in _served_names(state)}) + if not names: + return set() + return {op.name for op in skills.stored_operations(names) if not op.known} def _listed(namespace: str, name: str, state: SkillState) -> bool: @@ -82,12 +76,14 @@ def _usage( groups: dict[str, list[usage.Group]], *, writer: bool, + unknown: set[str], window: int, + cut: bool, now: datetime, ) -> SkillUsage: fetches = usage.counts(groups, revisions, INSPECTOR_CONSUMERS) codes = usage.stale_codes( - state, writer=writer, unknown_operation=_names_unknown_operation(state), now=now + state, writer=writer, unknown_operation=bool(unknown & _served_names(state)), now=now ) who = usage.subjects(groups, revisions) if input.by_subject else [] return SkillUsage( @@ -97,14 +93,17 @@ def _usage( published_at=state.served.row["at"] if state.served else None, fetches=[SkillFetches(**f._asdict()) for f in fetches], stale=codes, - statement=usage.skill_statement(fetches, codes, window), + # A cut read hides no fetch of a skill that never published: it asked for none. + statement=usage.skill_statement(fetches, codes, window, cut=cut and bool(revisions)), subjects=[SkillFetchSubject(**s._asdict()) for s in who], ) async def handle_skill_usage(input: SkillUsageInput) -> SkillUsageOutput: - readable, writable = await skills._reach(input.org, [input.namespace]) - if input.by_subject and not await _administers(input.org, input.namespace): + readable, writable, administered = await skills.reach( + input.org, [input.namespace], admin=input.by_subject + ) + if input.by_subject and not administered: raise AuthInsufficientError( f"`by_subject` names who fetched a skill: it needs admin on {input.namespace!r}" ) @@ -141,16 +140,23 @@ async def handle_skill_usage(input: SkillUsageInput) -> SkillUsageOutput: usage.FETCH_GROUPS_MAX + 1, ) groups = usage.by_hash(found[: usage.FETCH_GROUPS_MAX]) + cut = len(found) > usage.FETCH_GROUPS_MAX + unknown = _unknown_operations(state for state, _ in reported.values()) return SkillUsageOutput( window_days=window, - statement=usage.report_statement( - days=input.days, - kept_days=kept, - listed=listed, - cut=len(found) > usage.FETCH_GROUPS_MAX, - ), + statement=usage.report_statement(days=input.days, kept_days=kept, listed=listed, cut=cut), skills=[ - _usage(input, name, *reported[name], groups, writer=writer, window=window, now=now) + _usage( + input, + name, + *reported[name], + groups, + writer=writer, + unknown=unknown, + window=window, + cut=cut, + now=now, + ) for name in sorted(reported) ], ) diff --git a/server/identity/app/skills.py b/server/identity/app/skills.py index 8c2495d8f5..2ec98884fd 100644 --- a/server/identity/app/skills.py +++ b/server/identity/app/skills.py @@ -321,11 +321,14 @@ class _Team(NamedTuple): not_listed: list[str] -async def _reach(org: str, namespaces: Sequence[str]) -> tuple[list[str], set[str]]: - """Those of `namespaces` the caller may read, in order, and those of them the caller - may write to. A published revision is its namespace's readers' to read; a draft, its - count and its existence are a writer's. With sign-in off every namespace is the one - user's.""" +async def reach( + org: str, namespaces: Sequence[str], *, admin: bool = False +) -> tuple[list[str], set[str], set[str]]: + """Those of `namespaces` the caller may read, in order, those of them the caller may + write to and, when `admin` asks, those of `namespaces` it administers: empty when it + does not ask. A published revision is its namespace's readers' to read; a draft, its + count and its existence are a writer's. One gate answers every role of a request. + With sign-in off every namespace is the one user's.""" # Lazy: server.auth.context pulls in authz, which imports the op modules. from server.auth.authz import CachedGate from server.auth.context import current_auth @@ -333,11 +336,13 @@ async def _reach(org: str, namespaces: Sequence[str]) -> tuple[list[str], set[st auth = current_auth() if auth is None: - reach = [] if settings.auth_actually_required() else list(namespaces) - return reach, set(reach) + found = [] if settings.auth_actually_required() else list(namespaces) + return found, set(found), set(found) if admin else set() gate = CachedGate(auth, org) readable = [ns for ns in namespaces if await gate.admits(ns, Role.VIEWER)] - return readable, {ns for ns in readable if await gate.admits(ns, Role.WRITER)} + writable = {ns for ns in readable if await gate.admits(ns, Role.WRITER)} + administered = {ns for ns in namespaces if admin and await gate.admits(ns, Role.ADMIN)} + return readable, writable, administered def _open_draft(state: SkillState) -> SkillOpenDraft | None: @@ -412,7 +417,7 @@ def listed_row(namespace: str, name: str, rows: Sequence[Row], *, writer: bool) async def _team_rows(input: SkillListInput) -> _Team: split = await namespaces_to_search(input.org, input.namespace, input.namespace_scope) - readable, writable = await _reach(input.org, split.read) + readable, writable, _ = await reach(input.org, split.read) # A writer lists right after a save, and no reader lists a skill an archive # stopped, on any replica. with own_write_reads(): @@ -673,7 +678,7 @@ async def _team_get(input: SkillGetInput) -> SkillGetOutput: nothing answers the one empty body: an unknown name, a revision that was never saved or is void, a revision whose text the table does not hold, and below WRITER a skill that serves nothing, a revision that was never published, and `history`.""" - readable, writable = await _reach(input.org, [input.namespace]) + readable, writable, _ = await reach(input.org, [input.namespace]) writer = bool(writable) if not readable or (input.history and not writer): return SkillGetOutput() @@ -684,7 +689,7 @@ async def _team_get(input: SkillGetInput) -> SkillGetOutput: state = fold(rows) if not state.latest_revision or not (writer or state.served): return SkillGetOutput() - # The role `_reach` read through the request's gate: no second check, no statement. + # The role `reach` read through the request's gate: no second check, no statement. binding = SkillBinding(namespace=input.namespace, writable=writer) skill: dict[str, Any] = { "found": True, diff --git a/server/identity/domain/skill_usage.py b/server/identity/domain/skill_usage.py index cf621d5291..e1fe13995e 100644 --- a/server/identity/domain/skill_usage.py +++ b/server/identity/domain/skill_usage.py @@ -29,8 +29,6 @@ SkillState, ) -# not a setting: the wire refuses a longer window, and the SDKs carry the bound -DAYS_MAX = 90 # not a setting: a stale code means the same age on every deployment that answers it DRAFT_WAITING_DAYS = 14 # not a setting: the most groups one report folds; a read cut here says so in its statement @@ -40,8 +38,9 @@ DRAFT_WAITING = "draft_waiting" # the open draft has waited past DRAFT_WAITING_DAYS UNKNOWN_OPERATION = "unknown_operation" # the published text names an op this build lacks -# The session a ledger row carries when its request named none. -NO_SESSION = "-" +# The sessions a ledger row carries when its request named none: `-` for a request +# with no `session_id`, the empty string for one that sent it blank. +NO_SESSION = frozenset({"-", ""}) # The states of a revision whose text a reader was served at some time. _WAS_PUBLISHED = (PUBLISHED, SUPERSEDED, WITHDRAWN) @@ -157,7 +156,7 @@ def counts( Fetches( revision=number, content_sha256=sha, - sessions=len({g["session_id"] for g in counted} - {NO_SESSION}), + sessions=len({g["session_id"] for g in counted} - NO_SESSION), subjects=len({g["subject"] for g in counted}), last_at=max((g["last_at"] for g in counted), default=None), inspector_fetches=sum( @@ -204,10 +203,14 @@ def _count(n: int, noun: str) -> str: return f"{n:,} {noun}" if n == 1 else f"{n:,} {noun}s" -def skill_statement(fetches: Sequence[Fetches], codes: Sequence[str], window: int) -> str: +def skill_statement( + fetches: Sequence[Fetches], codes: Sequence[str], window: int, *, cut: bool +) -> str: """What the counts of one skill say: a sentence for each revision that was fetched, or the one sentence of a skill that was not, then a sentence for each stale code - this build has words for.""" + this build has words for. `cut` says the read that looked for the skill's hashes + stopped at `FETCH_GROUPS_MAX`: a skill with no fetch among the groups read may hold + an older one in the window, so it is not said to have none.""" within = f"in the last {_count(window, 'day')}" said = [] for f in fetches: @@ -218,9 +221,15 @@ def skill_statement(fetches: Sequence[Fetches], codes: Sequence[str], window: in by = f"at least {_count(f.sessions, 'session')} of {by}" said.append(f"Revision {f.revision} was fetched by {by} {within}.") if not said: + none = f"Not fetched from Loom {within}." + if cut: + none = ( + f"No fetch is among the {FETCH_GROUPS_MAX:,} ledger rows read, the most " + f"recent, so an older fetch {within} may exist." + ) said.append( - f"Not fetched from Loom {within}. A copy pulled to a folder is read without a " - "fetch, so the skill may still be read from one." + f"{none} A copy pulled to a folder is read without a fetch, so the skill may " + "still be read from one." ) said += [_STALE_SENTENCE[code] for code in codes if code in _STALE_SENTENCE] return " ".join(said) diff --git a/server/identity/store/skill_fetches.py b/server/identity/store/skill_fetches.py index 12c8f59ad1..d37aff5588 100644 --- a/server/identity/store/skill_fetches.py +++ b/server/identity/store/skill_fetches.py @@ -18,8 +18,9 @@ from server.observability.store.event_reads import MASKED_EVENTS # The scope leads with the ledger's key prefix `(org, namespace)` and bounds `ts`, which -# the table is partitioned by. A worker's row is no request. A row of a restricted -# namespace is masked to `success = false` with no `args`, so it is not counted. +# the table is partitioned by. A worker's row is no request. A marked row (a request +# that served a private source) is masked to `success = false` with no `args`; a +# `skill.get` row is never one. FETCHES = ( "SELECT content_sha256, session_id, subject, consumer, transport, " "count() AS fetches, min(ts) AS first_at, max(ts) AS last_at " diff --git a/tests/unit/test_sdk_skill_usage_command.py b/tests/unit/test_sdk_skill_usage_command.py index aea055224c..8c6b1021f8 100644 --- a/tests/unit/test_sdk_skill_usage_command.py +++ b/tests/unit/test_sdk_skill_usage_command.py @@ -3,7 +3,8 @@ The command prints the server's sentences and the numbers under them. These tests fail when it writes a sentence of its own for a count, sends a window or `by_subject` nobody asked for, names a principal in a report that did not ask who fetched, prints a refused -`--by-subject` as a report, or exits 0 on a server that does not serve the op. +`--by-subject` as a report, names a read with no subject in other words than the +dashboard's, or exits 0 on a server that does not serve the op. """ from __future__ import annotations @@ -15,10 +16,11 @@ import httpx import pytest -from loom import cli +from loom import cli, cli_skill_usage from server.auth.jwt import AuthInfo from server.core.errors import LoomServerError +from server.core.paths import REPO_ROOT from server.identity.api.models_skills import SkillUsageInput from server.identity.app import skill_usage from server.identity.app.skill_usage import handle_skill_usage @@ -175,6 +177,22 @@ def test_who_fetched_is_printed_for_an_administrator_alone( assert _asked(server.calls[-1]) == {"namespace": NAMESPACE, "name": "", "by_subject": True} +def test_a_read_with_no_subject_is_named_as_the_dashboard_names_it( + server: _Server, capsys: pytest.CaptureFixture[str] +) -> None: + """Fails when a read that carries no subject, as one made with sign-in off does, is + printed in other words than the dashboard's.""" + server.store.fetched(A, NOW - timedelta(hours=6), session_id="s3") + server.caller = ADMIN + assert _run(NAMESPACE, "--by-subject") == 0 + assert ( + " no sign-in fetched revision 1 between 2030-03-01T06:00:00 and " + "2030-03-01T06:00:00, over MCP, as user\n" + ) in capsys.readouterr().out + page = (REPO_ROOT / "frontend/src/views/skills/FetchesTab.tsx").read_text(encoding="utf-8") + assert f'{{s.subject || "{cli_skill_usage.NO_SUBJECT}"}}' in page + + def test_usage_on_a_server_without_the_op_exits_2( server: _Server, capsys: pytest.CaptureFixture[str] ) -> None: diff --git a/tests/unit/test_skill_usage.py b/tests/unit/test_skill_usage.py index ae6ade76fe..bb7ac72ff8 100644 --- a/tests/unit/test_skill_usage.py +++ b/tests/unit/test_skill_usage.py @@ -8,6 +8,7 @@ from __future__ import annotations +from collections.abc import Sequence from datetime import datetime, timedelta from typing import Any @@ -17,8 +18,8 @@ from server.auth.jwt import AuthInfo from server.core.errors import AuthInsufficientError from server.core.paths import REPO_ROOT -from server.identity.api.models_skills import SkillUsageInput -from server.identity.app import skill_usage +from server.identity.api.models_skills import SkillOperation, SkillUsageInput +from server.identity.app import skill_usage, skills from server.identity.domain import skill_usage as usage from server.identity.store import skill_fetches from server.identity.store import skills as repo @@ -76,17 +77,19 @@ async def _usage(auth: AuthInfo | None, **fields: Any) -> dict[str, Any]: async def test_skill_usage_counts(store: Skills) -> None: """Fails when rows are grouped by anything but the hash, an inspector read is - counted as a fetch or dropped from `inspector_fetches`, a `-` session counts as a - session, a read before the revision's publish counts, or a revision that was never - published has an entry.""" + counted as a fetch or dropped from `inspector_fetches`, a `-` or a blank session + counts as a session, a read before the revision's publish counts, or a revision + that was never published has an entry.""" _history(store) # Revision 1: one session twice over MCP, the same session once over HTTP, a second - # session, a read that named no session, three looks, and a read before its publish. + # session, a read that named no session and one that named a blank one, three looks, + # and a read before its publish. store.fetched(A, _ago(days=19), session_id="s1", subject="alice") store.fetched(A, _ago(days=18), session_id="s1", subject="alice") store.fetched(A, _ago(days=17), session_id="s1", subject="alice", transport="http") store.fetched(A, _ago(days=16), session_id="s2", subject="bob", transport="http") store.fetched(A, _ago(days=15), subject="carol", transport="http") + store.fetched(A, _ago(days=15, hours=1), session_id="", subject="carol", transport="http") for consumer in INSPECTOR_CONSUMERS: store.fetched(A, _ago(days=2), session_id="looking", subject="dana", consumer=consumer) store.fetched(A, _ago(days=20, hours=1), session_id="early", subject="erin") @@ -205,39 +208,59 @@ async def test_skill_usage_window_and_statement( for days in (0, 91): with pytest.raises(pydantic.ValidationError): SkillUsageInput(org=ORG, namespace=NAMESPACE, days=days) - assert SkillUsageInput(org=ORG, namespace=NAMESPACE, days=90).days == usage.DAYS_MAX + assert SkillUsageInput(org=ORG, namespace=NAMESPACE, days=90).days == 90 async def test_an_empty_namespace_answers_no_skill_and_the_statement(store: Skills) -> None: - """Fails when a namespace with no skill answers an error, no statement, or a read - of the ledger with no hash to look for.""" + """Fails when a namespace with no skill answers an error or no statement, or asks + the ledger for a hash.""" answer = await _usage(VIEWER) assert answer["skills"] == [] and answer["window_days"] == 30 assert "can carry 0 skills of this namespace" in answer["statement"] assert store.ledger_asked == [{"since": _ago(days=30), "published": {}, "limit": 10_001}] - assert await skill_fetches.fetch_groups(ORG, NAMESPACE, NOW, {}, 5, ch=object()) == [] async def test_a_cut_ledger_read_says_so(store: Skills, monkeypatch: pytest.MonkeyPatch) -> None: """Fails when a read the limit cut is answered as a whole one: the statement must - name the limit, and the row past it must not be counted.""" + name the limit, the row past it must not be counted, and a skill whose fetches are + all past it must not be said to have none in the window.""" monkeypatch.setattr(usage, "FETCH_GROUPS_MAX", 2) store.add(NAME, 1, "save", 1, A, at=_ago(days=3)) store.add(NAME, 2, "publish", 1, A, at=_ago(days=2)) + store.add("older", 1, "save", 1, B, at=_ago(days=3)) + store.add("older", 2, "publish", 1, B, at=_ago(days=2)) + store.add("draft-only", 1, "save", 1, C, at=_ago(days=1)) + store.fetched(B, _ago(days=1), session_id="old", subject="p") for n in range(3): store.fetched(A, _ago(hours=n + 1), session_id=f"s{n}", subject=f"p{n}") - cut = await _usage(VIEWER) + cut = await _usage(WRITER) assert store.ledger_asked[-1]["limit"] == 3 assert cut["statement"].endswith( "The ledger read stopped at 2 rows, the most recent, so older fetches in the " "window are not counted." ) - assert cut["skills"][0]["fetches"][0]["sessions"] == 2 - # A read that fits is not said to be cut. - store.ledger.pop() - assert "stopped at" not in (await _usage(VIEWER))["statement"] + by_name = {s["name"]: s for s in cut["skills"]} + assert by_name[NAME]["fetches"][0]["sessions"] == 2 + # Every fetch of `older` is past the cut: the read holds none, the window may. + pulled = ( + "A copy pulled to a folder is read without a fetch, so the skill may still be " + "read from one." + ) + assert by_name["older"]["fetches"] == [] + assert by_name["older"]["statement"] == ( + "No fetch is among the 2 ledger rows read, the most recent, so an older fetch in " + f"the last 30 days may exist. {pulled}" + ) + # The read asked for no hash of a skill that never published, so it hides none. + not_fetched = f"Not fetched from Loom in the last 30 days. {pulled}" + assert by_name["draft-only"]["statement"] == not_fetched + # A read that fits is not said to be cut, and a skill with no fetch in it has none. + del store.ledger[:2] + whole = await _usage(WRITER) + assert "stopped at" not in whole["statement"] + assert {s["name"]: s["statement"] for s in whole["skills"]}["older"] == not_fetched async def test_a_failed_ledger_read_fails_the_op(store: Skills) -> None: @@ -249,10 +272,18 @@ async def test_a_failed_ledger_read_fails_the_op(store: Skills) -> None: await _usage(VIEWER) -async def test_skill_usage_stale_codes(store: Skills) -> None: +async def test_skill_usage_stale_codes(store: Skills, monkeypatch: pytest.MonkeyPatch) -> None: """Fails when a code is missing for its case, a viewer gets `draft_waiting`, a draft - inside the bound is called stale, or a code names anything but a waiting draft and - an unknown operation.""" + inside the bound is called stale, a code names anything but a waiting draft and an + unknown operation, or the registry is asked once a skill.""" + asked: list[list[str]] = [] + stored_operations = skills.stored_operations + + def against_registry(names: Sequence[str]) -> list[SkillOperation]: + asked.append(list(names)) + return stored_operations(names) + + monkeypatch.setattr(skills, "stored_operations", against_registry) # `runbook`: published text that names an operation no build serves, and a draft # saved 15 days ago. `notes`: a known operation and a draft saved 13 days ago. store.add(NAME, 1, "save", 1, A, at=_ago(days=30), op_names=["memory.search", "memory.gone"]) @@ -265,6 +296,8 @@ async def test_skill_usage_stale_codes(store: Skills) -> None: as_writer = {s["name"]: s for s in (await _usage(WRITER))["skills"]} assert as_writer[NAME]["stale"] == ["draft_waiting", "unknown_operation"] assert as_writer["notes"]["stale"] == [] + # One read of the registry a report, over the names of every served revision. + assert asked == [["loom_op", "memory.gone", "memory.search"]] assert as_writer[NAME]["statement"].endswith( "A draft has waited for review for more than 14 days. The published revision " "names an operation this server does not serve." @@ -371,10 +404,12 @@ async def query_all(self, sql: str, params: dict[str, Any] | None = None, **_: A async def test_skill_usage_statement_shape() -> None: """Fails when the ledger statement lacks the `(org, namespace)` prefix, the `ts` - bound or the `LIMIT`, formats a value into its text, or when either read selects - skill text.""" + bound or the `LIMIT`, formats a value into its text, is sent with no hash to look + for, or when either read selects skill text.""" ch = _Recording() since, at = NOW - timedelta(days=30), NOW - timedelta(days=2) + assert await skill_fetches.fetch_groups(ORG, NAMESPACE, since, {}, 7, ch=ch) == [] + assert ch.sent == [] await skill_fetches.fetch_groups(ORG, NAMESPACE, since, {A: at}, 7, ch=ch) await repo.usage_acts(ORG, NAMESPACE, ch=ch) (ledger, ledger_params), (acts, acts_params) = ch.sent From 5417c27dec99ec3dbd40a911314adff75bff1dfb Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sun, 6 Dec 2026 09:47:06 +0000 Subject: [PATCH 3/3] The skills pages say which skill a cut ledger read answers as not fetched In a report whose ledger read was cut, `skill.usage` says "no fetch is among the rows read" only for a skill with a revision that is or was published. A skill with no such revision, as one that never published, is answered as not fetched in the window: the read looked for no fetch of it, so the cut hides none. The features page, the architecture page and the comment on the `statement` field of a skill's usage stated the cut sentence for every skill with no fetch. Each now names the condition. No behaviour and no wire field changes. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/skills.md | 2 +- docs/features/skills.md | 2 +- server/identity/api/models_skills.py | 5 +++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/architecture/skills.md b/docs/architecture/skills.md index 2fa4d3e9c5..f8def8714f 100644 --- a/docs/architecture/skills.md +++ b/docs/architecture/skills.md @@ -361,7 +361,7 @@ So the report says "fetched", gives every count as a lower bound, and never says - **What counts as a fetch.** A ledger row of a successful `skill.get`, not a worker's, whose `out_content_sha256` is the hash of a revision that the fold calls published, superseded or withdrawn, and whose time is past the second of that revision's first `publish` row. A `publish` row keeps whole seconds, so a read in that second may be a writer's read of the draft and is not counted. The ledger keeps the hash a read answered and never the number: of two published revisions with one hash, the higher is named. A draft's hash, a rejected revision's and a void one's are not in the statement's parameters, so no row of theirs is read. - **The statement.** It filters by `org`, `namespace`, the window and the operation, keeps the rows whose hash is one of the published hashes from that hash's time on (two bound arrays), and groups by hash, session, principal, consumer and transport with a count and the first and the last time. It returns the most recent 10,000 groups and one more (`FETCH_GROUPS_MAX`): the extra group tells a cut read from a whole one, and the report's statement says when the read was cut. The ledger is sorted by `(org, namespace, agent, ts)` and partitioned by month, so the read prunes to the namespace's rows of the window's months. The window is at most 90 days, and never longer than the days the namespace keeps its ledger. - **The counts.** `server/identity/domain/skill_usage.py` makes one entry a revision of the groups: the distinct sessions (a row with no session, `-` or blank, counts its principal only), the distinct principals, and the last fetch. A group whose consumer is an inspector's (`INSPECTOR_CONSUMERS`) counts in neither and is summed as `inspector_fetches`. `loom skill pull` names no consumer, so a pull is a fetch. -- **The sentences.** The report's `statement` and each skill's are built in that one module from the counts: that counts are lower bounds, that a listing shown to a session is not recorded, how many of the namespace's skills a listing can carry and in what order, whether the window or the ledger read was cut, and for each skill the revisions fetched or that none was. A skill with no fetch among the groups of a cut read is said to have none among them, and that an older one may exist. The command and the dashboard print them and write none of their own for a count. +- **The sentences.** The report's `statement` and each skill's are built in that one module from the counts: that counts are lower bounds, that a listing shown to a session is not recorded, how many of the namespace's skills a listing can carry and in what order, whether the window or the ledger read was cut, and for each skill the revisions fetched or that none was. A skill with a published hash in the statement's parameters and no fetch among the groups of a cut read is said to have none among them, and that an older one may exist. A skill with no such hash, as one that never published, is said to be not fetched: the read asked for no row of it, so the cut hides none. The command and the dashboard print them and write none of their own for a count. - **Stale codes.** A closed set of strings, each proven by rows the skill holds: `draft_waiting` (the open draft's `save` row is more than 14 days old, `DRAFT_WAITING_DAYS`) and `unknown_operation` (a stored `op_names` entry of the served revision that the answering build's registry does not hold). The 14 days are a constant, so `draft_waiting` means the same on every deployment; `unknown_operation` is the answering build's. No fetch is no code: a pulled copy is read without one. - **Tenant isolation.** The op needs `viewer` on the namespace it names. The caller is reported the skills `skill.list` lists to it (`listed_row`): a writer every skill, any other reader the ones that serve a revision, and `draft_waiting` is a writer's as the draft is. The published hashes of a skill the caller is not reported are not in the ledger statement's parameters. A name the caller cannot list answers no skill, as a name that does not exist does. `by_subject` names principals, so it needs `admin` on the namespace and is refused with 403 to anyone else: the refusal confirms nothing, since the namespace is the one the caller named. `tests/integration/test_cross_principal_leakage.py` holds the case. - **A failed read fails the op.** An error of the ledger statement is the op's error. A skill is never answered as not fetched because the ledger could not be read. diff --git a/docs/features/skills.md b/docs/features/skills.md index 2dbc2d7d09..b700c32eb4 100644 --- a/docs/features/skills.md +++ b/docs/features/skills.md @@ -454,7 +454,7 @@ Every sentence is the server's (`statement` of the report and of each skill), so | A ledger row the server dropped | Every count is a lower bound | - **A fetch.** An answered `skill.get` whose content hash is that of a revision that is or was published, made from the second after that revision was published. A read of a draft, of a rejected revision and of a revision that was never published is no fetch. A session is counted once a revision, whatever the transport; a request that named no session counts its principal only. -- **The window.** `window_days` is `days`, or the days the namespace keeps its request ledger when that is fewer; the statement says when the window was cut. One report folds at most 10,000 ledger groups, the most recent, and the statement says when the read stopped there. A skill with no fetch among them is then said to have none among the rows read, not none in the window. +- **The window.** `window_days` is `days`, or the days the namespace keeps its request ledger when that is fewer; the statement says when the window was cut. One report folds at most 10,000 ledger groups, the most recent, and the statement says when the read stopped there. A skill with a revision that is or was published and no fetch among those groups is then said to have none among the rows read, not none in the window. A skill with no such revision, as one that never published, is said to be not fetched: the read looked for no fetch of it. - **Stale codes.** `stale` holds codes from a closed set, each proven by rows the skill holds. `draft_waiting`: the skill's draft has waited for review for more than 14 days; answered to a caller who may write to the namespace, as the draft is. `unknown_operation`: the published revision names an operation the answering build does not serve. A skill nobody fetched has no code for that. A client shows a code it does not know by its name. - **Who sees what.** The caller is reported the skills `skill.list` lists to it: a writer every skill of the namespace, any other reader the ones that serve a revision. A name the caller cannot list answers no skill, as a name that does not exist does. `by_subject` adds `subjects`, one entry a principal, revision, transport and consumer with the first and the last read; it needs `admin` on the namespace and is refused with 403 to anyone else. - **A failed read.** When the ledger cannot be read the op fails. It never answers a skill as not fetched in place of an error. diff --git a/server/identity/api/models_skills.py b/server/identity/api/models_skills.py index 382fcaeb02..eeda014962 100644 --- a/server/identity/api/models_skills.py +++ b/server/identity/api/models_skills.py @@ -570,8 +570,9 @@ class SkillUsage(BaseModel): # skill nobody fetched has no code for that. stale: list[str] = Field(default_factory=list) # The counts in words: a sentence for each fetched revision, or that the skill was - # not fetched in the window (when the ledger read was cut, that no fetch is among - # the rows read), then a sentence for each code of `stale`. + # not fetched in the window (when the ledger read was cut, for a skill with a + # revision that is or was published, that no fetch is among the rows read), then a + # sentence for each code of `stale`. statement: str = "" # With `by_subject`, who read each revision: one entry a principal, revision, # transport and consumer, highest revision first.