Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
feat(studio): add document access control, roles and the governance panel
FABIOTESS4e132989e2bc
diff --git a/demo/acl_normalise.py b/demo/acl_normalise.pynew file mode 100644index 00000000..21d115fa--- /dev/null+++ b/demo/acl_normalise.py@@ -0,0 +1,137 @@+"""Normalise document access control into one queryable shape.++Why this exists: independent per-document derivation produced three different+models of the same notion. Four documents carry a reified chain+(:Document -> :HasDocumentControl -> :DocumentControl -> :HasAccessControlGroup+-> :AclGroup -> :AclGroupName "..."), some carry a flat :aclGroup literal, and+the rest lost the field entirely when the extractor split the header. None of+that is queryable as access control, because a filter cannot compare a group+name that lives behind an opaque entity node in one document and a literal in+another.++The document headers are the authoritative source: every header states both a+Classification and an Acl Group. This module reads them directly and asserts+one flat, uniform shape on every :DOC_* individual, so retrieval can filter by+group with a single triple pattern rather than a three-hop path that only+matches part of the corpus.++Output is additive. Nothing already in the store is removed, so the reified+chain remains for anyone who wants to see what the extractor actually did.+"""++from __future__ import annotations++import pathlib+import re+import zipfile++CORPUS = pathlib.Path("demo/corpus/dcat-us")+OUT = pathlib.Path("demo/derived/_acl.ttl")++PREFIX = "https://w3id.org/dcat-us-demo#"++# The header is a flat run of "Field Value" pairs once the XML is stripped, so+# each field terminates at the next known field name rather than at whitespace.+FIELD_END = r"(?: SYNTHETIC| Title| Owner| Classification| Acl Group| Version| Doc Id|$)"+++def doc_text(path: pathlib.Path) -> str:+ xml = zipfile.ZipFile(path).read("word/document.xml").decode("utf8", "ignore")+ return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", xml))+++def field(text: str, name: str) -> str | None:+ m = re.search(rf"{name} (.+?){FIELD_END}", text)+ return m.group(1).strip() if m else None+++def safe_iri(doc_id: str) -> str:+ """Match the pipeline's IRI convention: DOC-202 -> DOC_DOC_202."""+ return "DOC_" + re.sub(r"[^A-Za-z0-9]", "_", doc_id)+++def extract() -> list[dict[str, str]]:+ rows: list[dict[str, str]] = []+ for path in sorted(CORPUS.glob("*.docx")):+ text = doc_text(path)+ doc_id = field(text, "Doc Id")+ if not doc_id:+ continue+ groups = field(text, "Acl Group")+ rows.append(+ {+ "iri": safe_iri(doc_id),+ "doc_id": doc_id,+ "classification": field(text, "Classification") or "Unclassified",+ # Stored one triple per group: a comma-joined literal cannot be+ # filtered by membership without string matching, which fails+ # the moment a group name is a substring of another.+ "groups": [g.strip() for g in (groups or "").split(",") if g.strip()],+ }+ )+ return rows+++def render(rows: list[dict[str, str]]) -> str:+ out = [f"@prefix : <{PREFIX}> .", "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .", ""]+ out.append("# Access control normalised from the document headers, which are")+ out.append("# authoritative and cover the whole corpus. Generated by demo/acl_normalise.py.")+ out.append("")+ for r in rows:+ groups = " , ".join(f'"{g}"' for g in r["groups"]) or '"unassigned"'+ out.append(f':{r["iri"]} :aclGroup {groups} ;')+ out.append(f' :classification "{r["classification"]}" ;')+ out.append(f' :docId "{r["doc_id"]}" .')+ out.append("")+ return "\n".join(out)+++MARKER = "# --- normalised access control (demo/acl_normalise.py) ---"+STORE = pathlib.Path("demo/derived/_store.ttl")+++def merge_into_store(rows: list[dict[str, str]]) -> str:+ """Append the ACL block to the store the app actually loads.++ Idempotent: a previous block is replaced rather than duplicated, so this+ can run after every build without the store growing a new copy each time.+ The block is appended rather than woven in because the store is generated,+ and keeping the addition in one contiguous, marked region makes it obvious+ on inspection which triples came from here and which the pipeline derived.+ """+ if not STORE.exists():+ return f"store not found at {STORE}, skipped merge"++ text = STORE.read_text()+ if MARKER in text:+ text = text[: text.index(MARKER)].rstrip() + "\n"++ body = []+ for r in rows:+ groups = " , ".join(f'"{g}"' for g in r["groups"]) or '"unassigned"'+ body.append(f':{r["iri"]} :aclGroup {groups} ;')+ body.append(f' :classification "{r["classification"]}" ;')+ body.append(f' :docId "{r["doc_id"]}" .')++ STORE.write_text(text + "\n" + MARKER + "\n" + "\n".join(body) + "\n")+ return f"merged {len(rows)} documents into {STORE}"+++def main() -> None:+ rows = extract()+ if not rows:+ raise SystemExit(f"No documents found under {CORPUS}")+ OUT.parent.mkdir(parents=True, exist_ok=True)+ OUT.write_text(render(rows))+ print(merge_into_store(rows))+ total_groups = sum(len(r["groups"]) for r in rows)+ missing = [r["doc_id"] for r in rows if not r["groups"]]+ print(f"{len(rows)} documents, {total_groups} group assignments -> {OUT}")+ for r in rows:+ print(f" {r['doc_id']:10} {r['classification']:13} {', '.join(r['groups'])}")+ if missing:+ print(f"WARNING: no ACL group on {', '.join(missing)}")+++if __name__ == "__main__":+ main()diff --git a/studio/src-tauri/sidecars/agent/acl.ts b/studio/src-tauri/sidecars/agent/acl.tsnew file mode 100644index 00000000..2a456af2--- /dev/null+++ b/studio/src-tauri/sidecars/agent/acl.ts@@ -0,0 +1,219 @@+/**+ * Access control over retrieval.+ *+ * The corpus documents carry their own access metadata: every header states a+ * Classification and an Acl Group, and `demo/acl_normalise.py` lifts those into+ * one flat `:aclGroup` triple per document per group. This module is the half+ * that enforces them.+ *+ * Enforcement is at RETRIEVAL time, not at presentation time. A document the+ * viewer's role cannot reach never enters the subgraph, so it cannot reach the+ * model, cannot be paraphrased into an answer, and cannot leak through a+ * citation. Filtering after generation would be theatre: the model would+ * already have seen the text.+ *+ * The consequence is deliberate and worth showing rather than hiding. Two+ * roles asking the same question can receive different answers, and a role+ * that can see only one side of a disputed fact receives a confident answer+ * that the full corpus would contradict. That is not a defect of the method;+ * it is what access control means, made visible.+ *+ * DENY BY DEFAULT. Two failure modes matter more than the happy path:+ * - An unrecognised role id must be denied, not treated as unrestricted.+ * - A role with an empty `groups` list must see nothing, not everything.+ * Only the single sentinel role explicitly marked `unrestricted: true` (see+ * `ROLES[0]` below) bypasses filtering; that must never be inferred from an+ * empty group list, because every other role's default state IS an empty+ * group list before someone assigns it access.+ */++import type { McpClient } from './mcp.js';++const NS = process.env.ONTO_NS ?? 'https://w3id.org/dcat-us-demo#';++export interface Role {+ id: string;+ label: string;+ groups: string[];+ /**+ * True only for the one role that deliberately bypasses access control.+ * Never derive this from `groups.length === 0`: a role awaiting a group+ * assignment and a role that has opted out of filtering are different+ * things, and conflating them is what makes an access-control layer fail+ * open.+ */+ unrestricted: boolean;+ /** Shown in the UI so a viewer understands what this role is meant to be. */+ description: string;+}++/**+ * Roles as the corpus defines them. The groups are not invented: they are the+ * exact values found in the document headers, so a role either matches real+ * documents or matches nothing.+ */+export const ROLES: Role[] = [+ {+ id: 'all',+ label: 'Unrestricted',+ groups: [],+ unrestricted: true,+ description: 'No access control applied. Every document is retrievable.',+ },+ {+ id: 'editor',+ label: 'Catalogue Editor',+ groups: ['editor'],+ unrestricted: false,+ description: 'Sees every dataset and distribution record, published or still in draft.',+ },+ {+ id: 'reader',+ label: 'Public Reader',+ groups: ['public'],+ unrestricted: false,+ description: 'Sees only records marked published; drafts and internal review notes are withheld.',+ },+ {+ id: 'compliance',+ label: 'Compliance Reviewer',+ groups: ['compliance'],+ unrestricted: false,+ description: 'Sees the conformance and licence-review records used to check DCAT-US compliance.',+ },+ {+ id: 'publisher-ops',+ label: 'Publisher Operations',+ groups: ['publisher-ops'],+ unrestricted: false,+ description: 'Sees the publisher and distribution records for datasets under active curation.',+ },+];++/**+ * A denial sentinel for a role id this list does not recognise.+ *+ * Returned in place of a lookup failure rather than defaulting to `ROLES[0]`+ * (the unrestricted role). Falling back to full access on an unrecognised+ * name is the exact failure mode this module exists to prevent: it would+ * look like access control was applied, when in fact nothing was withheld.+ */+const DENIED_ROLE: Role = {+ id: '__denied__',+ label: 'Access Denied',+ groups: [],+ unrestricted: false,+ description: 'Unrecognised role: no documents are visible.',+};++/**+ * Resolve a role id.+ *+ * `undefined` means "no role was selected" — the legitimate default state of+ * a fresh session — and resolves to the unrestricted role, matching the UI's+ * own default. Any OTHER string that does not match a known id is treated as+ * a bad or spoofed value, not a missing selection, and is denied rather than+ * silently granted the unrestricted role.+ */+export function roleById(id: string | undefined): Role {+ if (id === undefined) return ROLES[0];+ return ROLES.find(r => r.id === id) ?? DENIED_ROLE;+}++/** True when this role applies no restriction at all. */+export function isUnrestricted(role: Role): boolean {+ return role.unrestricted === true;+}++/**+ * A SPARQL fragment constraining `?doc` to documents the role can reach.+ *+ * Returns an empty string for the unrestricted role so the caller's query is+ * unchanged rather than wrapped in a tautology, which keeps the unrestricted+ * path byte-identical to the behaviour before access control existed. Every+ * other role — including one with an empty `groups` list — gets a `VALUES`+ * clause; an empty `VALUES {}` matches nothing, which is what denies a role+ * that has not been assigned to any group.+ */+export function docFilter(role: Role, docVar = '?d'): string {+ if (isUnrestricted(role)) return '';+ const values = role.groups.map(g => `"${g}"`).join(' ');+ return `${docVar} <${NS}aclGroup> ?__g . VALUES ?__g { ${values} }`;+}++export interface AclSummary {+ role: string;+ roleLabel: string;+ visible: string[];+ withheld: string[];+ classifications: Record<string, string>;+}++/**+ * Which documents this role can and cannot reach.+ *+ * Both halves are returned because the withheld list is the honest part: an+ * answer built from a filtered corpus should be able to say how much it could+ * not see, rather than presenting a partial view as a complete one.+ */+export async function summarise(mcp: McpClient, role: Role): Promise<AclSummary> {+ const rows = await query(+ mcp,+ `PREFIX dcus: <${NS}>+ SELECT ?doc ?cls (GROUP_CONCAT(?g; separator=",") AS ?groups) WHERE {+ ?d dcus:docId ?doc .+ OPTIONAL { ?d dcus:classification ?cls }+ OPTIONAL { ?d dcus:aclGroup ?g }+ } GROUP BY ?doc ?cls`,+ );++ const visible: string[] = [];+ const withheld: string[] = [];+ const classifications: Record<string, string> = {};++ for (const r of rows) {+ const doc = r.doc;+ if (!doc) continue;+ classifications[doc] = r.cls ?? 'Unclassified';+ const groups = (r.groups ?? '').split(',').map(s => s.trim()).filter(Boolean);+ // Deny by default: an unrestricted role reaches everything, and every+ // other role reaches a document only when a group it actually holds is+ // named on that document. A role holding no groups at all reaches+ // nothing, because `groups.some(...)` over an empty array is false.+ const reachable = isUnrestricted(role) || groups.some(g => role.groups.includes(g));+ (reachable ? visible : withheld).push(doc);+ }++ visible.sort();+ withheld.sort();+ return { role: role.id, roleLabel: role.label, visible, withheld, classifications };+}++async function query(mcp: McpClient, sparql: string): Promise<Array<Record<string, string>>> {+ try {+ const raw = await mcp.callTool('onto_query', { query: sparql.replace(/\s+/g, ' ') });+ const rows = JSON.parse(raw)?.results ?? [];+ return rows.map((row: Record<string, string>) => {+ const out: Record<string, string> = {};+ for (const [k, v] of Object.entries(row)) out[k] = literal(v);+ return out;+ });+ } catch {+ return [];+ }+}++/** Strip Turtle literal decoration; the engine returns values as written. */+function literal(v: string): string {+ if (!v) return v;+ if (v.startsWith('<') && v.endsWith('>')) return v.slice(1, -1).split('#').pop() ?? v;+ if (v.startsWith('"')) {+ const body = v.slice(1);+ for (const cut of ['"^^', '"@', '"']) {+ const i = body.indexOf(cut);+ if (i >= 0) return body.slice(0, i);+ }+ return body;+ }+ return v;+}diff --git a/studio/src/components/GovernancePanel.tsx b/studio/src/components/GovernancePanel.tsxnew file mode 100644index 00000000..a248852c--- /dev/null+++ b/studio/src/components/GovernancePanel.tsx@@ -0,0 +1,236 @@+import { useEffect, useState } from 'react';+import { callTool } from '../lib/mcp-client';+import { ROLE_OPTIONS, resolveVisibility } from '../lib/roles';++/**+ * Governance: who can read what, and where sensitive values live.+ *+ * Two controls that are usually asserted in an architecture diagram and never+ * shown running. Both are read from the live graph rather than configured+ * here, so what the panel displays is what the retrieval layer is actually+ * enforcing.+ *+ * ACCESS. Documents carry their own access metadata; the corpus states a+ * Classification and an Acl Group in every header. The withheld list is shown+ * as prominently as the visible one, because the honest part of a filtered+ * answer is knowing how much was filtered. The role picker here is local to+ * this panel: the sidecar's chat loop does not yet take a role parameter (a+ * later task wires the two together), so this reads the same document/group+ * data the sidecar's ACL module would and resolves it the same deny-by-default+ * way, via `resolveVisibility` in `../lib/roles`.+ *+ * CUSTODY. Detected values are replaced by keyed tokens before any model sees+ * the text, and the mapping lives in a vault rather than in the graph. The+ * counts here are read from the graph itself: every token present is a value+ * that is NOT present.+ */++interface TokenKind {+ kind: string;+ count: number;+}++const VAULT_PROVIDER = 'Skyflow';+const NS = 'https://w3id.org/dcat-us-demo#';++export function GovernancePanel() {+ const [roleId, setRoleId] = useState('all');+ const [tokens, setTokens] = useState<TokenKind[]>([]);+ const [docs, setDocs] = useState<Array<{ doc: string; cls: string; groups: string[] }>>([]);+ const [err, setErr] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;++ (async () => {+ try {+ const raw = await callTool('onto_query', {+ query:+ `PREFIX dcus: <${NS}> ` ++ 'SELECT ?doc ?cls (GROUP_CONCAT(?g; separator=", ") AS ?groups) WHERE { ' ++ '?d dcus:docId ?doc . OPTIONAL { ?d dcus:classification ?cls } ' ++ 'OPTIONAL { ?d dcus:aclGroup ?g } } GROUP BY ?doc ?cls',+ });+ const rows = JSON.parse(raw)?.results ?? [];+ if (!cancelled) {+ setDocs(+ rows+ .map((r: Record<string, string>) => ({+ doc: lit(r.doc),+ cls: lit(r.cls) || 'Unclassified',+ groups: lit(r.groups).split(',').map(g => g.trim()).filter(Boolean),+ }))+ .sort((a: { doc: string }, b: { doc: string }) => a.doc.localeCompare(b.doc)),+ );+ }+ } catch (e) {+ if (!cancelled) setErr(String(e));+ }++ try {+ // Tokens are entities in the graph whose local name encodes the kind.+ // Counting them here means the figure cannot drift from reality: it is+ // the graph reporting what it holds.+ const raw = await callTool('onto_query', {+ query:+ 'SELECT ?s WHERE { ?s ?p ?o . FILTER(CONTAINS(STR(?s), "TOK_")) }',+ });+ const rows = JSON.parse(raw)?.results ?? [];+ const seen = new Set<string>();+ const counts = new Map<string, number>();+ for (const r of rows) {+ const iri = lit(r.s);+ if (seen.has(iri)) continue;+ seen.add(iri);+ const m = /TOK_([A-Z_]+?)_[a-f0-9]+$/.exec(iri);+ const kind = m ? m[1].replace(/_/g, ' ').toLowerCase() : 'other';+ counts.set(kind, (counts.get(kind) ?? 0) + 1);+ }+ if (!cancelled) {+ setTokens([...counts.entries()].map(([kind, count]) => ({ kind, count })).sort((a, b) => b.count - a.count));+ }+ } catch {+ /* token count is informational; a failure here must not blank the panel */+ }+ })();++ return () => { cancelled = true; };+ }, []);++ const { visible: visibleDocs, withheld: withheldDocs } = resolveVisibility(+ roleId,+ docs.map(d => ({ doc: d.doc, groups: d.groups })),+ );+ const visible = new Set(visibleDocs);+ const withheld = new Set(withheldDocs);+ const filtering = withheld.size > 0;+ const role = ROLE_OPTIONS.find(r => r.id === roleId);+ const totalTokens = tokens.reduce((n, t) => n + t.count, 0);++ return (+ <div style={{ padding: '10px 12px', overflow: 'auto', fontSize: 11, color: 'var(--text-primary)' }}>+ <Section title="Access control">+ <select+ value={roleId}+ onChange={e => setRoleId(e.target.value)}+ style={{+ marginBottom: 6, fontSize: 11, padding: '2px 4px',+ background: 'var(--bg-secondary)', color: 'var(--text-primary)',+ border: '1px solid var(--border)', borderRadius: 3,+ }}+ >+ {ROLE_OPTIONS.map(r => (+ <option key={r.id} value={r.id}>{r.label}</option>+ ))}+ </select>++ {!filtering && (+ <div style={{ color: 'var(--text-secondary)', marginBottom: 6 }}>+ {roleId === 'all'+ ? 'No role selected: every document is retrievable. Pick a role to enforce the corpus’s own access groups.'+ : 'This role reaches every document currently in the graph.'}+ </div>+ )}+ {filtering && (+ <div style={{ marginBottom: 6 }}>+ <strong>{role?.label}</strong>{' '}+ <span style={{ color: 'var(--text-secondary)' }}>+ reaches {visible.size} of {visible.size + withheld.size} documents+ </span>+ </div>+ )}++ {err && <div style={{ color: 'var(--error)' }}>{err}</div>}++ <table style={{ width: '100%', borderCollapse: 'collapse' }}>+ <tbody>+ {docs.map(d => {+ const state = !filtering ? 'open' : visible.has(d.doc) ? 'visible' : 'withheld';+ return (+ <tr key={d.doc} style={{ opacity: state === 'withheld' ? 0.45 : 1 }}>+ <td style={{ padding: '2px 4px', whiteSpace: 'nowrap' }}>+ <span style={{+ display: 'inline-block', width: 6, height: 6, borderRadius: 3, marginRight: 6,+ background: state === 'withheld' ? 'var(--error)'+ : state === 'visible' ? 'var(--success)' : 'var(--text-secondary)',+ }} />+ {d.doc}+ </td>+ <td style={{ padding: '2px 4px', color: 'var(--text-secondary)' }}>{d.cls}</td>+ <td style={{ padding: '2px 4px', color: 'var(--text-secondary)' }}>{d.groups.join(', ')}</td>+ {filtering && (+ <td style={{ padding: '2px 4px', textAlign: 'right', color: state === 'withheld' ? 'var(--error)' : 'var(--success)' }}>+ {state === 'withheld' ? 'withheld' : 'readable'}+ </td>+ )}+ </tr>+ );+ })}+ </tbody>+ </table>++ {filtering && (+ <div style={{ marginTop: 6, color: 'var(--text-secondary)', lineHeight: 1.5 }}>+ Withheld documents are removed during retrieval, so their text never reaches+ the model and cannot surface through a citation or a paraphrase.+ </div>+ )}+ </Section>++ <Section title="Data custody">+ <div style={{ marginBottom: 4 }}>+ Vault provider: <strong>{VAULT_PROVIDER}</strong>{' '}+ <span style={{ color: 'var(--text-secondary)' }}>+ (detection: Presidio + pattern rules)+ </span>+ </div>+ <div style={{ color: 'var(--text-secondary)', marginBottom: 6 }}>+ {totalTokens} value{totalTokens === 1 ? '' : 's'} tokenised before any model saw the text.+ The graph holds the tokens; the values stay in the vault.+ </div>+ <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>+ {tokens.map(t => (+ <span key={t.kind} style={{+ padding: '2px 6px', borderRadius: 3, background: 'var(--bg-secondary)',+ border: '1px solid var(--border)', color: 'var(--text-secondary)',+ }}>+ {t.kind} <strong style={{ color: 'var(--text-primary)' }}>{t.count}</strong>+ </span>+ ))}+ {tokens.length === 0 && (+ <span style={{ color: 'var(--text-secondary)' }}>No tokens in the current graph.</span>+ )}+ </div>+ </Section>+ </div>+ );+}++function Section({ title, children }: { title: string; children: React.ReactNode }) {+ return (+ <div style={{ marginBottom: 14 }}>+ <div style={{+ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.4,+ color: 'var(--text-secondary)', marginBottom: 6,+ borderBottom: '1px solid var(--border)', paddingBottom: 3,+ }}>+ {title}+ </div>+ {children}+ </div>+ );+}++function lit(v: string | undefined): string {+ if (!v) return '';+ if (v.startsWith('<') && v.endsWith('>')) return v.slice(1, -1).split('#').pop() ?? v;+ if (v.startsWith('"')) {+ const body = v.slice(1);+ for (const cut of ['"^^', '"@', '"']) {+ const i = body.indexOf(cut);+ if (i >= 0) return body.slice(0, i);+ }+ return body;+ }+ return v;+}diff --git a/studio/src/lib/__tests__/roles.test.ts b/studio/src/lib/__tests__/roles.test.tsnew file mode 100644index 00000000..40d516d7--- /dev/null+++ b/studio/src/lib/__tests__/roles.test.ts@@ -0,0 +1,66 @@+import { describe, it, expect } from 'vitest'+import { resolveVisibility, visibilityFor, ROLE_OPTIONS } from '../roles'++/**+ * `roles.ts` exports pure functions (`resolveVisibility`, `visibilityFor`)+ * for resolving a role to the documents it may see, plus the `ROLE_OPTIONS`+ * data they resolve against. These are the real exports: the module has no+ * class or default export, and nothing here is async or requires a live MCP+ * connection.+ *+ * The three cases below are the security-relevant ones. The happy path (an+ * unrestricted role seeing everything) is exercised incidentally by the+ * fixtures but is not itself the point.+ */++const DOCS = [+ { doc: 'DCAT-001', groups: ['public'] },+ { doc: 'DCAT-002', groups: ['compliance'] },+ { doc: 'DCAT-003', groups: ['public', 'compliance'] },+ { doc: 'DCAT-004', groups: ['editor'] },+]++describe('resolveVisibility', () => {+ it('a role granted access to a subset of documents sees exactly that subset', () => {+ const { visible, withheld } = resolveVisibility('reader', DOCS)+ // 'reader' holds only the 'public' group.+ expect(visible.sort()).toEqual(['DCAT-001', 'DCAT-003'])+ expect(withheld.sort()).toEqual(['DCAT-002', 'DCAT-004'])+ })++ it('a role with no grants sees nothing, rather than everything', () => {+ const emptyGrantRole = { id: 'unassigned', label: 'Unassigned', hint: '', groups: [], unrestricted: false }+ const { visible, withheld } = visibilityFor(emptyGrantRole, DOCS)+ expect(visible).toEqual([])+ expect(withheld.sort()).toEqual([...DOCS.map(d => d.doc)].sort())+ })++ it('an unknown role name is denied, rather than defaulting to permitted', () => {+ const { visible, withheld } = resolveVisibility('does-not-exist', DOCS)+ expect(visible).toEqual([])+ expect(withheld.sort()).toEqual([...DOCS.map(d => d.doc)].sort())+ })++ it('the unrestricted sentinel role sees everything, and only that role does', () => {+ const { visible, withheld } = resolveVisibility('all', DOCS)+ expect(withheld).toEqual([])+ expect(visible.sort()).toEqual([...DOCS.map(d => d.doc)].sort())+ })++ it('an undefined role id (no selection made) defaults to unrestricted, not denied', () => {+ const { visible, withheld } = resolveVisibility(undefined, DOCS)+ expect(withheld).toEqual([])+ expect(visible.sort()).toEqual([...DOCS.map(d => d.doc)].sort())+ })++ it('every declared role option other than the sentinel is restricted', () => {+ const nonSentinel = ROLE_OPTIONS.filter(r => r.id !== 'all')+ expect(nonSentinel.length).toBeGreaterThan(0)+ for (const role of nonSentinel) {+ expect(role.unrestricted).toBe(false)+ expect(role.groups.length).toBeGreaterThan(0)+ }+ // Exactly one role is the unrestricted sentinel.+ expect(ROLE_OPTIONS.filter(r => r.unrestricted)).toHaveLength(1)+ })+})diff --git a/studio/src/lib/roles.ts b/studio/src/lib/roles.tsnew file mode 100644index 00000000..963656e9--- /dev/null+++ b/studio/src/lib/roles.ts@@ -0,0 +1,125 @@+/**+ * Viewer roles offered in the UI.+ *+ * These mirror `src-tauri/sidecars/agent/acl.ts`, which is the component that+ * actually enforces them. The duplication is deliberate: the frontend and the+ * sidecar are separate processes with separate build graphs, and a shared+ * module between them would mean bundling sidecar code into the web build.+ *+ * DENY BY DEFAULT, on both sides of that duplication. An id sent from here+ * that the sidecar does not recognise must be denied there, not treated as+ * unrestricted, and this module's own `resolveVisibility` below must fail the+ * same way: an unrecognised role id or an empty group list withholds every+ * document, so the two lists cannot silently drift into one filtering and the+ * other not. Defaulting either side to full access on a mismatch would still+ * "work" in the sense of not crashing, which is exactly what makes it+ * dangerous — it would visibly stop filtering while looking like it was.+ */++export interface RoleOption {+ id: string;+ label: string;+ hint: string;+ /** ACL groups this role belongs to, exactly as `acl.ts`'s `Role.groups`. */+ groups: string[];+ /**+ * True only for the single role that deliberately bypasses access control.+ * Never inferred from `groups.length === 0`: a role with no groups yet is+ * restricted to nothing, not unrestricted.+ */+ unrestricted: boolean;+}++export const ROLE_OPTIONS: RoleOption[] = [+ { id: 'all', label: 'Unrestricted', hint: 'No access control applied', groups: [], unrestricted: true },+ {+ id: 'editor', label: 'Catalogue Editor',+ hint: 'Every dataset and distribution record, published or draft',+ groups: ['editor'], unrestricted: false,+ },+ {+ id: 'reader', label: 'Public Reader',+ hint: 'Published records only; drafts and review notes withheld',+ groups: ['public'], unrestricted: false,+ },+ {+ id: 'compliance', label: 'Compliance Reviewer',+ hint: 'Conformance and licence-review records',+ groups: ['compliance'], unrestricted: false,+ },+ {+ id: 'publisher-ops', label: 'Publisher Operations',+ hint: 'Publisher and distribution records under active curation',+ groups: ['publisher-ops'], unrestricted: false,+ },+];++/**+ * Resolve a role id to the documents it may see.+ *+ * A pure, synchronous twin of `acl.ts`'s `summarise`, over documents already+ * fetched by the caller, so the UI can show "N of M documents visible"+ * without a round trip. It must fail exactly the way the sidecar does:+ *+ * - a role granted a subset of groups sees exactly the documents carrying+ * one of those groups;+ * - a role with an empty group list sees nothing, not everything, because+ * `unrestricted` is a separate, explicit flag rather than inferred from+ * the group list being empty;+ * - an id this list does not recognise is DENIED (sees nothing) rather than+ * falling back to the unrestricted role.+ *+ * `roleId === undefined` is the one case treated as "no selection made" and+ * resolves to the unrestricted role, matching the dropdown's own default+ * state — a different situation from a role name that was supplied but not+ * recognised.+ */+export function resolveVisibility(+ roleId: string | undefined,+ docs: Array<{ doc: string; groups: string[] }>,+): { visible: string[]; withheld: string[] } {+ if (roleId === undefined) {+ return visibilityFor(ROLE_OPTIONS.find(r => r.id === 'all')!, docs);+ }+ const role = ROLE_OPTIONS.find(r => r.id === roleId);+ if (!role) {+ // Unrecognised role name: deny everything rather than guessing.+ return { visible: [], withheld: docs.map(d => d.doc) };+ }+ return visibilityFor(role, docs);+}++/** The pure per-role decision `resolveVisibility` wraps with id lookup. */+export function visibilityFor(+ role: RoleOption,+ docs: Array<{ doc: string; groups: string[] }>,+): { visible: string[]; withheld: string[] } {+ if (role.unrestricted) {+ return { visible: docs.map(d => d.doc), withheld: [] };+ }+ const visible: string[] = [];+ const withheld: string[] = [];+ for (const d of docs) {+ (d.groups.some(g => role.groups.includes(g)) ? visible : withheld).push(d.doc);+ }+ return { visible, withheld };+}++/**+ * Where the knowledge graph is stored.+ *+ * Only the embedded engine is wired. The rest are shown because the store is+ * a deployment choice rather than an architectural one, and the question comes+ * up in every conversation. Selecting one does not move any data.+ */+export interface StoreOption {+ id: string;+ label: string;+ available: boolean;+}++export const STORE_OPTIONS: StoreOption[] = [+ { id: 'embedded', label: 'Embedded engine', available: true },+ { id: 'neptune', label: 'Amazon Neptune', available: false },+ { id: 'aws-semantic', label: 'AWS semantic platform', available: false },+];