From 62933a48d8811aaf43c0719e4ee40372b5b72a46 Mon Sep 17 00:00:00 2001 From: Mark Hazleton Date: Sat, 21 Nov 2026 15:28:21 -0600 Subject: [PATCH 1/3] feat(registry): managed lists and classification domains Clients, projects and applications are chosen from managed lists instead of typed: unknown names are rejected by the API, store and CLI (which gains --create). A Lists tab creates, renames, retires, restores and merges entries and suggests likely duplicates. Domains (Tier, Type, Lifecycle, Stack seeded, all editable) classify repositories singly or in bulk; values in use are retired, not deleted. Classifications are exported to portfolio.json with explicit empty lists. Migration 4 keeps existing names and assignments. Editing a source now validates the client before changing anything. Co-Authored-By: Claude Opus 5.5 --- .documentation/guides/DOCKER_DEPLOYMENT.md | 18 +- .../src/components/Admin/Admin.module.css | 106 +++++ .../src/components/Admin/BulkClassify.jsx | 109 +++++ .../src/components/Admin/DomainsPanel.jsx | 373 +++++++++++++++ frontend/src/components/Admin/ListEntry.jsx | 146 ++++++ frontend/src/components/Admin/ListsPanel.jsx | 253 ++++++++++ .../components/Admin/RepositoriesPanel.jsx | 330 ++++++++----- .../src/components/Admin/RepositoryEditor.jsx | 184 ++++++++ .../src/components/Admin/SourcesPanel.jsx | 25 +- frontend/src/components/Admin/SourcesView.jsx | 21 +- .../src/components/Admin/portfolioOptions.js | 84 ++++ frontend/src/services/adminApi.js | 30 +- frontend/tests/Classification.test.jsx | 426 +++++++++++++++++ frontend/tests/SourcesView.test.jsx | 47 +- src/spark/api/app.py | 71 +-- src/spark/api/catalog_routes.py | 245 ++++++++++ src/spark/registry/__main__.py | 49 +- src/spark/registry/catalog.py | 356 ++++++++++++++ src/spark/registry/db.py | 70 +++ src/spark/registry/domains.py | 446 ++++++++++++++++++ src/spark/registry/export.py | 16 + src/spark/registry/store.py | 204 +++----- tests/unit/test_api.py | 34 +- tests/unit/test_classification.py | 351 ++++++++++++++ tests/unit/test_classification_api.py | 168 +++++++ tests/unit/test_registry.py | 5 +- 26 files changed, 3842 insertions(+), 325 deletions(-) create mode 100644 frontend/src/components/Admin/BulkClassify.jsx create mode 100644 frontend/src/components/Admin/DomainsPanel.jsx create mode 100644 frontend/src/components/Admin/ListEntry.jsx create mode 100644 frontend/src/components/Admin/ListsPanel.jsx create mode 100644 frontend/src/components/Admin/RepositoryEditor.jsx create mode 100644 frontend/src/components/Admin/portfolioOptions.js create mode 100644 frontend/tests/Classification.test.jsx create mode 100644 src/spark/api/catalog_routes.py create mode 100644 src/spark/registry/catalog.py create mode 100644 src/spark/registry/domains.py create mode 100644 tests/unit/test_classification.py create mode 100644 tests/unit/test_classification_api.py diff --git a/.documentation/guides/DOCKER_DEPLOYMENT.md b/.documentation/guides/DOCKER_DEPLOYMENT.md index eb3822da..8b21bd8a 100644 --- a/.documentation/guides/DOCKER_DEPLOYMENT.md +++ b/.documentation/guides/DOCKER_DEPLOYMENT.md @@ -78,7 +78,7 @@ Sources live in a SQLite registry (`/app/config/registry.db`, in the `spark-conf survives container recreation). Manage them from the worker container (uses its `GITHUB_TOKEN`): ```sh -docker compose exec worker python -m spark.registry add org MyOrg --client "Acme" +docker compose exec worker python -m spark.registry add org MyOrg --client "Acme" --create docker compose exec worker python -m spark.registry add repo owner/name docker compose exec worker python -m spark.registry list docker compose exec worker python -m spark.registry exclude owner/name @@ -93,6 +93,9 @@ docker compose exec worker python -m spark.registry disable 3 `python -m spark.registry prune`. - Full per-repository analytics (`data/users//...`, the dashboard) still run for `user` sources. Organization and explicit-repository sources currently appear in `portfolio.json` only. +- Client, project and application names must already exist (create them on the admin **Lists** + tab); an unknown name is rejected so a typo never creates a second client. Pass `--create` to + `add` or `assign` to create a missing name on purpose. - Back up `registry.db` (stop the worker, or use `sqlite3 registry.db ".backup out.db"`). ## Admin UI (sign-in, sources, tokens) @@ -115,7 +118,18 @@ dashboard shows a **Sources** page only when the API answers; on GitHub Pages it - **Sources:** add an organization, user or repository. Access is validated against GitHub first; a source that cannot be read is not saved and the error says what to fix. Disable, re-enable or remove sources; removing never deletes collected repositories. -- **Repositories:** include/exclude and assign to a client, project and application. +- **Repositories:** include/exclude, assign to a client, project and application from dropdowns, and + classify by domain (one repository at a time, or select several and classify them in bulk). The + **Show** filter lists repositories with no client or no value in a domain. +- **Lists:** create, rename, retire, restore and merge clients, projects and applications. A project + with no client is internal. Retiring hides an entry from the dropdowns but keeps it on whatever + already uses it; merging moves every repository and source onto the entry that stays. Likely + duplicates (for example "Acme" and "Acme, Inc.") are suggested, never merged on their own. +- **Domains:** named lists of allowed values. Tier, Type, Lifecycle (one value each) and Stack + (several values) are provided and editable; add your own. A value's key never changes, its label + can. A value or domain in use can only be retired, not deleted. Classifications are written to + `data/portfolio.json` (every active domain is listed per repository, empty when unassigned) on + the worker's next cycle. - **Tokens:** save fine-grained personal access tokens (read-only; one per user or organization), encrypted at rest. A token's expiry is tracked: the page warns when one is within 14 days, and a source whose token has expired reports `connection_unusable` instead of silently using another. diff --git a/frontend/src/components/Admin/Admin.module.css b/frontend/src/components/Admin/Admin.module.css index df71da3e..443889db 100644 --- a/frontend/src/components/Admin/Admin.module.css +++ b/frontend/src/components/Admin/Admin.module.css @@ -134,3 +134,109 @@ .login { max-width: 360px; } + +.inlineForm { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + font-size: 14px; +} + +.inlineForm label { + font-weight: 600; +} + +.fieldset { + display: flex; + flex-wrap: wrap; + gap: 4px 12px; + margin: 0; + padding: 8px 10px; + border: 1px solid var(--color-border); + border-radius: 6px; + font-size: 14px; +} + +.fieldset legend { + font-weight: 600; + padding: 0 4px; +} + +.check { + display: inline-flex; + align-items: center; + gap: 6px; + min-height: 44px; + font-size: 14px; +} + +.bulk { + padding: 10px 12px; + border: 1px solid var(--color-border); + border-radius: 6px; + background: var(--color-surface-alt); +} + +.tags { + display: grid; + gap: 2px; + margin: 0; + font-size: 13px; +} + +.tags div { + display: flex; + gap: 6px; +} + +.tags dt { + color: var(--color-text-secondary); +} + +.tags dd { + margin: 0; +} + +.tree { + list-style: none; + margin: 0; + padding-left: 0; + display: flex; + flex-direction: column; + gap: 6px; +} + +.tree .tree { + padding-left: 20px; + border-left: 1px solid var(--color-border); + margin-top: 6px; +} + +.entry { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.domain { + display: flex; + flex-direction: column; + gap: 8px; + padding-top: 12px; + border-top: 1px solid var(--color-border); +} + +.srOnly { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} diff --git a/frontend/src/components/Admin/BulkClassify.jsx b/frontend/src/components/Admin/BulkClassify.jsx new file mode 100644 index 00000000..f2aa18b5 --- /dev/null +++ b/frontend/src/components/Admin/BulkClassify.jsx @@ -0,0 +1,109 @@ +import { useState } from "react"; +import PropTypes from "prop-types"; +import { Button } from "@/components/Brand"; +import { domainChoices } from "./portfolioOptions"; +import styles from "./Admin.module.css"; + +/** + * Classify every selected repository in one domain at once. A single-choice + * domain sets (or clears) the value; a multi-choice domain can add or remove + * values without touching the others each repository holds. + */ +export default function BulkClassify({ count, domains, onApply, onClear }) { + const choices = domainChoices(domains); + const [domainKey, setDomainKey] = useState(choices[0]?.key || ""); + const [value, setValue] = useState(""); + const [mode, setMode] = useState("add"); + const domain = choices.find((d) => d.key === domainKey); + + const apply = (event) => { + event.preventDefault(); + if (!domain) return; + if (domain.multi) { + if (value) onApply({ domain: domain.key, values: [value], mode }); + } else { + onApply({ + domain: domain.key, + values: value ? [value] : [], + mode: "set", + }); + } + }; + + return ( +
+

+ {count} selected +

+
+ + +
+ {domain?.multi && ( +
+ + +
+ )} +
+ + +
+
+ + +
+
+ ); +} + +BulkClassify.propTypes = { + count: PropTypes.number.isRequired, + domains: PropTypes.arrayOf(PropTypes.object), + onApply: PropTypes.func.isRequired, + onClear: PropTypes.func.isRequired, +}; diff --git a/frontend/src/components/Admin/DomainsPanel.jsx b/frontend/src/components/Admin/DomainsPanel.jsx new file mode 100644 index 00000000..e4f9f1b3 --- /dev/null +++ b/frontend/src/components/Admin/DomainsPanel.jsx @@ -0,0 +1,373 @@ +import { useCallback, useState } from "react"; +import PropTypes from "prop-types"; +import { Button } from "@/components/Brand"; +import { adminApi } from "@/services/adminApi"; +import useAdminResource from "@/hooks/useAdminResource"; +import styles from "./Admin.module.css"; + +const toKey = (label) => + label + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 40); + +function NewEntryForm({ idPrefix, legend, withMulti, onAdd }) { + const [label, setLabel] = useState(""); + const [key, setKey] = useState(""); + const [keyTouched, setKeyTouched] = useState(false); + const [multi, setMulti] = useState(false); + const shownKey = keyTouched ? key : toKey(label); + + return ( +
{ + event.preventDefault(); + const payload = { key: shownKey, label, ...(withMulti && { multi }) }; + if (await onAdd(payload)) { + setLabel(""); + setKey(""); + setKeyTouched(false); + setMulti(false); + } + }} + > + + setLabel(event.target.value)} + maxLength={80} + required + /> + + { + setKeyTouched(true); + setKey(event.target.value); + }} + pattern="[a-z0-9][a-z0-9\-]{0,39}" + title="Lower-case letters, digits and hyphens" + required + /> + {withMulti && ( + + )} + +
+ ); +} + +NewEntryForm.propTypes = { + idPrefix: PropTypes.string.isRequired, + legend: PropTypes.string.isRequired, + withMulti: PropTypes.bool, + onAdd: PropTypes.func.isRequired, +}; + +function Renamable({ id, label, onRename }) { + const [editing, setEditing] = useState(false); + const [value, setValue] = useState(label); + if (!editing) { + return ( + <> + {label}{" "} + + + ); + } + return ( +
{ + event.preventDefault(); + if (await onRename(value)) setEditing(false); + }} + > + + setValue(event.target.value)} + maxLength={80} + required + /> + + +
+ ); +} + +Renamable.propTypes = { + id: PropTypes.string.isRequired, + label: PropTypes.string.isRequired, + onRename: PropTypes.func.isRequired, +}; + +/** + * Classification domains and their allowed values. Keys never change once + * created; labels can. Anything in use is retired rather than deleted. + */ +export default function DomainsPanel({ onUnauthorized, onChanged }) { + const [showRetired, setShowRetired] = useState(false); + const load = useCallback(() => adminApi.domains(showRetired), [showRetired]); + const domains = useAdminResource(load, onUnauthorized); + const [message, setMessage] = useState({ kind: "", text: "" }); + + const run = async (action, success) => { + setMessage({ kind: "", text: "" }); + try { + await action(); + setMessage({ kind: "ok", text: success }); + await domains.reload(); + onChanged?.(); + return true; + } catch (error) { + if (error.status === 401) onUnauthorized(); + setMessage({ kind: "error", text: error.message }); + return false; + } + }; + + return ( +
+

Domains

+

+ A domain is a list of allowed values repositories are classified with. A + single-choice domain holds one value per repository; a multi-choice + domain holds several. +

+ +
+ {message.text && ( +

+ {message.text} +

+ )} +
+ +
+ + run(() => adminApi.createDomain(payload), `Added ${payload.label}.`) + } + /> + +
+ + {domains.loading ? ( +

Loading domains…

+ ) : ( + (domains.data || []).map((domain) => { + const used = domain.values.reduce( + (total, value) => total + value.repository_count, + 0, + ); + return ( +
+

+ + run( + () => adminApi.editDomain(domain.id, { label }), + `Renamed to ${label}.`, + ) + } + /> +

+

+ Key {domain.key} ·{" "} + {domain.multi ? "multi-choice" : "single-choice"} + {domain.retired && " · retired"} + {domain.description && ` · ${domain.description}`} +

+
+ + + {used === 0 && ( + + )} +
+ + + + + + + + + + + + + {domain.values.map((value) => ( + + + + + + + ))} + +
{domain.label} values
ValueKeyRepositoriesActions
+ + run( + () => + adminApi.editDomainValue(value.id, { label }), + `Renamed to ${label}.`, + ) + } + /> + {value.retired && ( + Retired + )} + + {value.key} + {value.repository_count} + + {value.repository_count === 0 && ( + + )} +
+ {!domain.retired && ( + + run( + () => adminApi.addDomainValue(domain.id, payload), + `Added ${payload.label}.`, + ) + } + /> + )} +
+ ); + }) + )} +
+ ); +} + +DomainsPanel.propTypes = { + onUnauthorized: PropTypes.func.isRequired, + onChanged: PropTypes.func, +}; diff --git a/frontend/src/components/Admin/ListEntry.jsx b/frontend/src/components/Admin/ListEntry.jsx new file mode 100644 index 00000000..d4bfda5d --- /dev/null +++ b/frontend/src/components/Admin/ListEntry.jsx @@ -0,0 +1,146 @@ +import { useState } from "react"; +import PropTypes from "prop-types"; +import { Button } from "@/components/Brand"; +import styles from "./Admin.module.css"; + +/** + * One client, project or application: its name and usage, with rename, + * retire/restore, and merge into another entry of the same scope. + */ +export default function ListEntry({ kind, entry, mergeTargets, onChange }) { + const [mode, setMode] = useState("view"); + const [name, setName] = useState(entry.name); + const [target, setTarget] = useState(""); + const fieldId = `${kind}-${entry.id}`; + const usage = `${entry.repository_count} ${entry.repository_count === 1 ? "repository" : "repositories"}${ + entry.source_count ? `, ${entry.source_count} source(s)` : "" + }`; + + const finish = async (action) => { + if (await onChange(action)) setMode("view"); + }; + + if (mode === "rename") { + return ( +
{ + event.preventDefault(); + finish({ type: "edit", id: entry.id, changes: { name } }); + }} + > + + setName(event.target.value)} + maxLength={120} + required + /> + + +
+ ); + } + + if (mode === "merge") { + return ( +
{ + event.preventDefault(); + if (target) + finish({ type: "merge", id: entry.id, intoId: Number(target) }); + }} + > + + + + +
+ ); + } + + return ( +
+ + {entry.name} + {entry.retired && Retired} + · {usage} + + + + + {!entry.retired && mergeTargets.length > 0 && ( + + )} + +
+ ); +} + +ListEntry.propTypes = { + kind: PropTypes.oneOf(["client", "project", "application"]).isRequired, + entry: PropTypes.shape({ + id: PropTypes.number.isRequired, + name: PropTypes.string.isRequired, + retired: PropTypes.bool, + repository_count: PropTypes.number, + source_count: PropTypes.number, + }).isRequired, + mergeTargets: PropTypes.arrayOf(PropTypes.object).isRequired, + onChange: PropTypes.func.isRequired, +}; diff --git a/frontend/src/components/Admin/ListsPanel.jsx b/frontend/src/components/Admin/ListsPanel.jsx new file mode 100644 index 00000000..07f86071 --- /dev/null +++ b/frontend/src/components/Admin/ListsPanel.jsx @@ -0,0 +1,253 @@ +import { useCallback, useState } from "react"; +import PropTypes from "prop-types"; +import { Button } from "@/components/Brand"; +import { adminApi } from "@/services/adminApi"; +import useAdminResource from "@/hooks/useAdminResource"; +import ListEntry from "./ListEntry"; +import styles from "./Admin.module.css"; + +const KIND_LABEL = { + client: "client", + project: "project", + application: "application", +}; + +function AddForm({ id, label, onAdd }) { + const [name, setName] = useState(""); + return ( +
{ + event.preventDefault(); + if (await onAdd(name)) setName(""); + }} + > + + setName(event.target.value)} + maxLength={120} + required + /> + +
+ ); +} + +AddForm.propTypes = { + id: PropTypes.string.isRequired, + label: PropTypes.string.isRequired, + onAdd: PropTypes.func.isRequired, +}; + +const siblings = (list, entry) => + list.filter((other) => other.id !== entry.id && !other.retired); + +/** + * The managed lists repositories and sources are assigned from. Names are + * created only here; retiring hides an entry from the pickers without + * removing it from what already uses it; merging folds a duplicate into the + * entry that stays. + */ +export default function ListsPanel({ onUnauthorized, onChanged }) { + const [showRetired, setShowRetired] = useState(false); + const loadTree = useCallback( + () => adminApi.portfolio(showRetired), + [showRetired], + ); + const tree = useAdminResource(loadTree, onUnauthorized); + const duplicates = useAdminResource(adminApi.duplicates, onUnauthorized); + const [message, setMessage] = useState({ kind: "", text: "" }); + + const run = async (action, success) => { + setMessage({ kind: "", text: "" }); + try { + await action(); + setMessage({ kind: "ok", text: success }); + await Promise.all([tree.reload(), duplicates.reload()]); + onChanged?.(); + return true; + } catch (error) { + if (error.status === 401) onUnauthorized(); + setMessage({ kind: "error", text: error.message }); + return false; + } + }; + + const change = (kind) => (action) => + action.type === "merge" + ? run( + () => adminApi.mergeListEntry(kind, action.id, action.intoId), + `Merged the ${KIND_LABEL[kind]}.`, + ) + : run( + () => adminApi.editListEntry(kind, action.id, action.changes), + `Saved the ${KIND_LABEL[kind]}.`, + ); + + const clients = tree.data || []; + const named = clients.filter((client) => client.id !== null); + const internal = clients.find((client) => client.id === null); + + const projectList = (client) => ( +
    + {client.projects.map((project) => ( +
  • + +
      + {project.applications.map((application) => ( +
    • + +
    • + ))} + {!project.retired && ( +
    • + + run( + () => adminApi.createApplication(project.id, name), + `Added ${name}.`, + ) + } + /> +
    • + )} +
    +
  • + ))} + {!client.retired && ( +
  • + + run( + () => adminApi.createProject(client.id, name), + `Added ${name}.`, + ) + } + /> +
  • + )} +
+ ); + + return ( +
+

Clients, projects and applications

+

+ Repositories and sources are assigned from these lists. A project + without a client is internal work. +

+ +
+ {message.text && ( +

+ {message.text} +

+ )} +
+ + {(duplicates.data || []).length > 0 && ( +
+

Possible duplicates

+
    + {duplicates.data.map((pair) => ( +
  • + {pair.kind[0].toUpperCase() + pair.kind.slice(1)} “{pair.b.name} + ” looks like “{pair.a.name}”.{" "} + +
  • + ))} +
+
+ )} + +
+ + run(() => adminApi.createClient(name), `Added ${name}.`) + } + /> + +
+ + {tree.loading ? ( +

Loading lists…

+ ) : ( +
    +
  • +
    + Internal + · projects with no client +
    + {projectList(internal || { id: null, projects: [] })} +
  • + {named.map((client) => ( +
  • + + {projectList(client)} +
  • + ))} +
+ )} +
+ ); +} + +ListsPanel.propTypes = { + onUnauthorized: PropTypes.func.isRequired, + onChanged: PropTypes.func, +}; diff --git a/frontend/src/components/Admin/RepositoriesPanel.jsx b/frontend/src/components/Admin/RepositoriesPanel.jsx index 3a8a146d..6550989a 100644 --- a/frontend/src/components/Admin/RepositoriesPanel.jsx +++ b/frontend/src/components/Admin/RepositoriesPanel.jsx @@ -1,55 +1,109 @@ -import { useState } from "react"; +import { useCallback, useMemo, useState } from "react"; import PropTypes from "prop-types"; import { Button } from "@/components/Brand"; import { adminApi } from "@/services/adminApi"; import useAdminResource from "@/hooks/useAdminResource"; +import RepositoryEditor from "./RepositoryEditor"; +import BulkClassify from "./BulkClassify"; +import { domainChoices, matchesGap, valueLabels } from "./portfolioOptions"; import styles from "./Admin.module.css"; -export default function RepositoriesPanel({ onUnauthorized, refreshKey }) { +const sameValues = (a = [], b = []) => + a.length === b.length && a.every((key) => b.includes(key)); + +export default function RepositoriesPanel({ + onUnauthorized, + refreshKey, + onEditLists, +}) { // refreshKey changes after sources change, so the list reloads. const repositories = useAdminResource( adminApi.repositories, onUnauthorized, refreshKey, ); + const loadTree = useCallback(() => adminApi.portfolio(true), []); + const loadDomains = useCallback(() => adminApi.domains(true), []); + const tree = useAdminResource(loadTree, onUnauthorized, refreshKey); + const domains = useAdminResource(loadDomains, onUnauthorized, refreshKey); const [editing, setEditing] = useState(null); - const [draft, setDraft] = useState({ - client: "", - project: "", - application: "", - }); + const [selected, setSelected] = useState([]); + const [gap, setGap] = useState(""); const [message, setMessage] = useState({ kind: "", text: "" }); + const active = useMemo(() => domainChoices(domains.data), [domains.data]); + // Labels come from the full list, so a retired value still held reads well. + const everyDomain = useMemo( + () => Object.fromEntries((domains.data || []).map((d) => [d.key, d])), + [domains.data], + ); + const shown = useMemo( + () => (repositories.data || []).filter((repo) => matchesGap(repo, gap)), + [repositories.data, gap], + ); + const run = async (action, success) => { setMessage({ kind: "", text: "" }); try { await action(); setMessage({ kind: "ok", text: success }); await repositories.reload(); + return true; } catch (error) { if (error.status === 401) onUnauthorized(); setMessage({ kind: "error", text: error.message }); + await repositories.reload(); + return false; } }; - const startEdit = (repo) => { - setEditing(repo.full_name); - setDraft({ - client: repo.client || "", - project: repo.project || "", - application: repo.application || "", - }); - }; + const save = (repo) => (place, values) => + run(async () => { + await adminApi.editRepository({ + full_name: repo.full_name, + assign: true, + ...place, + }); + for (const domain of active) { + const next = values[domain.key] || []; + if (!sameValues(next, repo.classifications?.[domain.key])) { + await adminApi.classify({ + full_names: [repo.full_name], + domain: domain.key, + values: next, + mode: "set", + }); + } + } + }, `Saved ${repo.full_name}.`).then((ok) => ok && setEditing(null)); - const field = (name) => (event) => - setDraft((previous) => ({ ...previous, [name]: event.target.value })); + const applyBulk = (change) => + run( + () => adminApi.classify({ full_names: selected, ...change }), + `Updated ${selected.length} repositories.`, + ); + + const toggleSelected = (name) => + setSelected((previous) => + previous.includes(name) + ? previous.filter((n) => n !== name) + : [...previous, name], + ); + const allShown = + shown.length > 0 && shown.every((r) => selected.includes(r.full_name)); + const toggleAll = () => + setSelected(allShown ? [] : shown.map((repo) => repo.full_name)); + + const loading = repositories.loading || tree.loading || domains.loading; return (

Repositories

Each repository appears once, however many sources reach it. Excluded - repositories stay registered but are left out of the portfolio. + repositories stay registered but are left out of the portfolio. Clients, + projects, applications and domain values come from the Lists and Domains + tabs.

@@ -62,127 +116,166 @@ export default function RepositoriesPanel({ onUnauthorized, refreshKey }) { )}
- {repositories.loading ? ( + {loading ? (

Loading repositories…

) : (repositories.data || []).length === 0 ? (

No repositories yet. Add a source first.

) : ( -
- - - - - - - - - - - - {repositories.data.map((repo) => ( - - + ))} + +
Discovered repositories
IncludeRepositoryReached byClient / project / application
+ <> +
+
+ + +
+ + {shown.length} of {repositories.data.length} shown + +
+ + {selected.length > 0 && ( + setSelected([])} + /> + )} + +
+ + + + + - - + + + + + + + + {shown.map((repo) => ( + + + + + + {editing === repo.full_name ? ( + + ) : ( + <> + + )} - - - ))} - -
Discovered repositories
- run( - () => - adminApi.editRepository({ - full_name: repo.full_name, - excluded: !repo.excluded, - }), - `${repo.full_name} ${repo.excluded ? "included" : "excluded"}.`, - ) - } + checked={allShown} + onChange={toggleAll} + aria-label="Select all shown repositories" /> - - - {repo.full_name} -
- {[ - repo.is_fork && "fork", - repo.is_archived && "archived", - repo.is_private && "private", - ] - .filter(Boolean) - .join(" · ")} -
-
- {repo.sources - .map((s) => `${s.type}:${s.identifier}`) - .join(", ")} - - {editing === repo.full_name ? ( -
{ - event.preventDefault(); + +
IncludeRepositoryReached byClient / project / applicationClassification
+ toggleSelected(repo.full_name)} + aria-label={`Select ${repo.full_name}`} + /> + + run( () => adminApi.editRepository({ full_name: repo.full_name, - assign: true, - ...draft, + excluded: !repo.excluded, }), - `Saved ${repo.full_name}.`, - ).then(() => setEditing(null)); - }} - > - {["client", "project", "application"].map((name) => ( -
- - -
- ))} -
- + `${repo.full_name} ${repo.excluded ? "included" : "excluded"}.`, + ) + } + /> +
+ {repo.full_name} +
+ {[ + repo.is_fork && "fork", + repo.is_archived && "archived", + repo.is_private && "private", + ] + .filter(Boolean) + .join(" · ")} +
+
+ {repo.sources + .map((s) => `${s.type}:${s.identifier}`) + .join(", ")} + + setEditing(null)} + onEditLists={onEditLists} + /> + + {[repo.client, repo.project, repo.application] + .filter(Boolean) + .join(" / ") || ( + Unassigned + )}{" "} - - - ) : ( - <> - {[repo.client, repo.project, repo.application] - .filter(Boolean) - .join(" / ") || ( - Unassigned - )}{" "} - + +
+ {active.map((domain) => ( +
+
{domain.label}
+
+ {valueLabels( + everyDomain[domain.key], + repo.classifications?.[domain.key], + ) || ( + + Not set + + )} +
+
+ ))} +
+
-
+
+
+ )}
); @@ -191,4 +284,5 @@ export default function RepositoriesPanel({ onUnauthorized, refreshKey }) { RepositoriesPanel.propTypes = { onUnauthorized: PropTypes.func.isRequired, refreshKey: PropTypes.number, + onEditLists: PropTypes.func, }; diff --git a/frontend/src/components/Admin/RepositoryEditor.jsx b/frontend/src/components/Admin/RepositoryEditor.jsx new file mode 100644 index 00000000..eb59c3b3 --- /dev/null +++ b/frontend/src/components/Admin/RepositoryEditor.jsx @@ -0,0 +1,184 @@ +import { useState } from "react"; +import PropTypes from "prop-types"; +import { Button } from "@/components/Brand"; +import { + applicationOptions, + clientOptions, + domainChoices, + projectOptions, +} from "./portfolioOptions"; +import styles from "./Admin.module.css"; + +function Select({ id, label, value, options, onChange, emptyLabel }) { + return ( +
+ + +
+ ); +} + +Select.propTypes = { + id: PropTypes.string.isRequired, + label: PropTypes.string.isRequired, + value: PropTypes.string.isRequired, + options: PropTypes.arrayOf(PropTypes.object).isRequired, + onChange: PropTypes.func.isRequired, + emptyLabel: PropTypes.string.isRequired, +}; + +/** + * Assign one repository to a client/project/application and classify it. + * Every choice comes from a managed list; nothing is typed. + */ +export default function RepositoryEditor({ + repo, + tree, + domains, + onSave, + onCancel, + onEditLists, +}) { + const [place, setPlace] = useState({ + client: repo.client || "", + project: repo.project || "", + application: repo.application || "", + }); + const [values, setValues] = useState(() => ({ + ...(repo.classifications || {}), + })); + const id = (name) => `${repo.full_name}-${name}`; + const choices = domainChoices(domains, repo.classifications || {}); + + const setClient = (client) => + setPlace({ client, project: "", application: "" }); + const setProject = (project) => + setPlace((previous) => ({ ...previous, project, application: "" })); + const setApplication = (application) => + setPlace((previous) => ({ ...previous, application })); + const setDomain = (key, next) => + setValues((previous) => ({ ...previous, [key]: next })); + const toggle = (key, valueKey) => + setValues((previous) => { + const held = previous[key] || []; + return { + ...previous, + [key]: held.includes(valueKey) + ? held.filter((k) => k !== valueKey) + : [...held, valueKey], + }; + }); + + const submit = (event) => { + event.preventDefault(); + onSave(place, values); + }; + + return ( +
+ + toggle(domain.key, value.key)} + /> + {value.retired ? `${value.label} (retired)` : value.label} + + ))} + + ) : ( + + > + + {clientOptions(tree.data).map((option) => ( + + ))} + + {onEditLists && ( + + )}
@@ -247,4 +265,5 @@ export default function SourcesPanel({ onUnauthorized, onChanged }) { SourcesPanel.propTypes = { onUnauthorized: PropTypes.func.isRequired, onChanged: PropTypes.func, + onEditLists: PropTypes.func, }; diff --git a/frontend/src/components/Admin/SourcesView.jsx b/frontend/src/components/Admin/SourcesView.jsx index b84422d9..e1299dc4 100644 --- a/frontend/src/components/Admin/SourcesView.jsx +++ b/frontend/src/components/Admin/SourcesView.jsx @@ -6,16 +6,21 @@ import LoginForm from "./LoginForm"; import SourcesPanel from "./SourcesPanel"; import RepositoriesPanel from "./RepositoriesPanel"; import ConnectionsPanel from "./ConnectionsPanel"; +import ListsPanel from "./ListsPanel"; +import DomainsPanel from "./DomainsPanel"; import styles from "./Admin.module.css"; const TABS = [ { id: "sources", label: "Sources" }, { id: "repositories", label: "Repositories" }, + { id: "lists", label: "Lists" }, + { id: "domains", label: "Domains" }, { id: "tokens", label: "Tokens" }, ]; /** - * Administration: sign-in, then manage sources, repositories and tokens. + * Administration: sign-in, then manage sources, repositories, the managed + * lists and domains they are classified with, and tokens. * Only offered when the self-hosted admin API is present. */ export default function SourcesView({ onToast }) { @@ -37,6 +42,7 @@ export default function SourcesView({ onToast }) { const signedOut = useCallback(() => setAuth({ state: "out" }), []); const changed = useCallback(() => setChangeCount((count) => count + 1), []); + const openLists = useCallback(() => setTab("lists"), []); const refreshNow = async () => { try { @@ -115,14 +121,25 @@ export default function SourcesView({ onToast }) { aria-labelledby={`admin-tab-${tab}`} > {tab === "sources" && ( - + )} {tab === "repositories" && ( )} + {tab === "lists" && ( + + )} + {tab === "domains" && ( + + )} {tab === "tokens" && ( + !entry.retired || (current && entry.name === current); + +const label = (entry) => + entry.retired ? `${entry.name} (retired)` : entry.name; + +/** Clients for a picker. Internal projects have no client (value ""). */ +export function clientOptions(tree, current = "") { + return (tree || []) + .filter((client) => client.id !== null && offered(client, current)) + .map((client) => ({ value: client.name, label: label(client) })); +} + +function clientEntry(tree, clientName) { + return (tree || []).find((client) => + clientName + ? client.id !== null && client.name === clientName + : client.id === null, + ); +} + +/** Projects under the chosen client, or internal projects when none. */ +export function projectOptions(tree, clientName, current = "") { + const client = clientEntry(tree, clientName); + return (client?.projects || []) + .filter((project) => offered(project, current)) + .map((project) => ({ value: project.name, label: label(project) })); +} + +export function applicationOptions( + tree, + clientName, + projectName, + current = "", +) { + const client = clientEntry(tree, clientName); + const project = (client?.projects || []).find((p) => p.name === projectName); + return (project?.applications || []) + .filter((application) => offered(application, current)) + .map((application) => ({ + value: application.name, + label: label(application), + })); +} + +/** Active domains; each keeps its active values plus any retired value in `held`. */ +export function domainChoices(domains, held = {}) { + return (domains || []) + .filter((domain) => !domain.retired) + .map((domain) => ({ + ...domain, + values: domain.values.filter( + (value) => + !value.retired || (held[domain.key] || []).includes(value.key), + ), + })); +} + +/** "Python, .NET" for a repository's values in one domain. */ +export function valueLabels(domain, keys) { + const byKey = Object.fromEntries( + (domain?.values || []).map((value) => [value.key, value.label]), + ); + return (keys || []).map((key) => byKey[key] || key).join(", "); +} + +/** + * Gap filters for the repository list. "" shows everything; "client" shows + * repositories without a client or project; "domain:" shows those with + * no value in that domain. + */ +export function matchesGap(repo, gap) { + if (!gap) return true; + if (gap === "client") return !repo.client && !repo.project; + if (gap.startsWith("domain:")) { + const key = gap.slice("domain:".length); + return !(repo.classifications?.[key] || []).length; + } + return true; +} diff --git a/frontend/src/services/adminApi.js b/frontend/src/services/adminApi.js index c1494b29..80253c86 100644 --- a/frontend/src/services/adminApi.js +++ b/frontend/src/services/adminApi.js @@ -78,7 +78,35 @@ export const adminApi = { repositories: () => request("GET", "/repositories"), editRepository: (changes) => request("PATCH", "/repositories", changes), - portfolio: () => request("GET", "/portfolio"), + classify: (payload) => request("POST", "/repositories/classify", payload), + + // Managed lists. `kind` is "client", "project" or "application". + portfolio: (includeRetired = false) => + request( + "GET", + `/portfolio${includeRetired ? "?include_retired=true" : ""}`, + ), + duplicates: () => request("GET", "/portfolio/duplicates"), + createClient: (name) => request("POST", "/clients", { name }), + createProject: (clientId, name) => + request("POST", "/projects", { client_id: clientId, name }), + createApplication: (projectId, name) => + request("POST", `/projects/${projectId}/applications`, { name }), + editListEntry: (kind, id, changes) => + request("PATCH", `/${kind}s/${id}`, changes), + mergeListEntry: (kind, id, intoId) => + request("POST", `/${kind}s/${id}/merge`, { into_id: intoId }), + + domains: (includeRetired = false) => + request("GET", `/domains${includeRetired ? "?include_retired=true" : ""}`), + createDomain: (domain) => request("POST", "/domains", domain), + editDomain: (id, changes) => request("PATCH", `/domains/${id}`, changes), + removeDomain: (id) => request("DELETE", `/domains/${id}`), + addDomainValue: (domainId, value) => + request("POST", `/domains/${domainId}/values`, value), + editDomainValue: (id, changes) => + request("PATCH", `/domain-values/${id}`, changes), + removeDomainValue: (id) => request("DELETE", `/domain-values/${id}`), connections: () => request("GET", "/connections"), addConnection: (connection) => request("POST", "/connections", connection), diff --git a/frontend/tests/Classification.test.jsx b/frontend/tests/Classification.test.jsx new file mode 100644 index 00000000..5de69129 --- /dev/null +++ b/frontend/tests/Classification.test.jsx @@ -0,0 +1,426 @@ +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; +import { + render, + screen, + waitFor, + cleanup, + within, +} from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import RepositoriesPanel from "../src/components/Admin/RepositoriesPanel"; +import RepositoryEditor from "../src/components/Admin/RepositoryEditor"; +import ListsPanel from "../src/components/Admin/ListsPanel"; +import DomainsPanel from "../src/components/Admin/DomainsPanel"; +import { + applicationOptions, + clientOptions, + domainChoices, + matchesGap, + projectOptions, +} from "../src/components/Admin/portfolioOptions"; +import { adminApi, ApiError } from "../src/services/adminApi"; + +const tree = [ + { + id: null, + name: "Internal", + retired: false, + repository_count: 0, + source_count: 0, + projects: [ + { + id: 9, + name: "Tools", + retired: false, + repository_count: 0, + applications: [], + }, + ], + }, + { + id: 1, + name: "Contoso", + retired: false, + repository_count: 1, + source_count: 0, + projects: [ + { + id: 2, + name: "Website", + retired: false, + repository_count: 1, + applications: [ + { id: 3, name: "Public site", retired: false, repository_count: 1 }, + { id: 4, name: "Old site", retired: true, repository_count: 0 }, + ], + }, + ], + }, + { + id: 5, + name: "Fabrikam", + retired: false, + repository_count: 0, + source_count: 0, + projects: [], + }, + { + id: 6, + name: "Gone Ltd", + retired: true, + repository_count: 0, + source_count: 0, + projects: [], + }, +]; + +const value = (key, label, extra = {}) => ({ + id: key.length, + key, + label, + retired: false, + repository_count: 0, + ...extra, +}); + +const domains = [ + { + id: 1, + key: "tier", + label: "Tier", + multi: false, + retired: false, + values: [ + value("core", "Core"), + value("archive", "Archive", { retired: true, repository_count: 1 }), + ], + }, + { + id: 4, + key: "stack", + label: "Stack", + multi: true, + retired: false, + values: [value("python", "Python"), value("dotnet", ".NET")], + }, +]; + +const repo = (name, extra = {}) => ({ + full_name: name, + description: null, + is_fork: false, + is_private: false, + is_archived: false, + excluded: false, + client: null, + project: null, + application: null, + sources: [{ id: 1, type: "org", identifier: "Acme" }], + classifications: { tier: [], stack: [] }, + ...extra, +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +describe("portfolio options", () => { + it("cascade from client to project to application", () => { + expect(clientOptions(tree).map((o) => o.value)).toEqual([ + "Contoso", + "Fabrikam", + ]); + expect(projectOptions(tree, "").map((o) => o.value)).toEqual(["Tools"]); + expect(projectOptions(tree, "Contoso").map((o) => o.value)).toEqual([ + "Website", + ]); + expect(projectOptions(tree, "Fabrikam")).toEqual([]); + expect( + applicationOptions(tree, "Contoso", "Website").map((o) => o.value), + ).toEqual(["Public site"]); + }); + + it("offer a retired entry only where it is already used", () => { + expect(clientOptions(tree, "Gone Ltd").map((o) => o.label)).toContain( + "Gone Ltd (retired)", + ); + expect( + applicationOptions(tree, "Contoso", "Website", "Old site").map( + (o) => o.label, + ), + ).toContain("Old site (retired)"); + const tier = domainChoices(domains)[0]; + expect(tier.values.map((v) => v.key)).toEqual(["core"]); + const kept = domainChoices(domains, { tier: ["archive"] })[0]; + expect(kept.values.map((v) => v.key)).toEqual(["core", "archive"]); + }); + + it("find gaps", () => { + const unassigned = repo("a/a"); + const placed = repo("a/b", { + project: "Tools", + classifications: { tier: ["core"], stack: [] }, + }); + expect(matchesGap(unassigned, "client")).toBe(true); + expect(matchesGap(placed, "client")).toBe(false); + expect(matchesGap(placed, "domain:tier")).toBe(false); + expect(matchesGap(placed, "domain:stack")).toBe(true); + expect(matchesGap(placed, "")).toBe(true); + }); +}); + +describe("", () => { + it("offers only managed choices and narrows them as you go", async () => { + const onSave = vi.fn(); + const user = userEvent.setup(); + render( + {}} + />, + ); + expect(screen.queryByRole("textbox")).not.toBeInTheDocument(); + const project = screen.getByLabelText("Project"); + expect( + within(project) + .getAllByRole("option") + .map((o) => o.textContent), + ).toEqual(["No project", "Tools"]); + await user.selectOptions(screen.getByLabelText("Client"), "Contoso"); + await user.selectOptions(screen.getByLabelText("Project"), "Website"); + await user.selectOptions( + screen.getByLabelText("Application"), + "Public site", + ); + await user.selectOptions(screen.getByLabelText("Tier"), "core"); + const stack = screen.getByRole("group", { name: "Stack" }); + await user.click(within(stack).getByLabelText("Python")); + await user.click(within(stack).getByLabelText(".NET")); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(onSave).toHaveBeenCalledWith( + { client: "Contoso", project: "Website", application: "Public site" }, + { tier: ["core"], stack: ["python", "dotnet"] }, + ); + }); + + it("clears the project and application when the client changes", async () => { + const user = userEvent.setup(); + render( + {}} + onCancel={() => {}} + />, + ); + expect(screen.getByLabelText("Project")).toHaveValue("Website"); + await user.selectOptions(screen.getByLabelText("Client"), "Fabrikam"); + expect(screen.getByLabelText("Project")).toHaveValue(""); + expect(screen.getByLabelText("Application")).toHaveValue(""); + }); +}); + +describe("", () => { + beforeEach(() => { + vi.spyOn(adminApi, "repositories").mockResolvedValue([ + repo("Acme/a", { classifications: { tier: ["core"], stack: [] } }), + repo("Acme/b"), + repo("Acme/c"), + ]); + vi.spyOn(adminApi, "portfolio").mockResolvedValue(tree); + vi.spyOn(adminApi, "domains").mockResolvedValue(domains); + }); + + it("classifies exactly the selected repositories in bulk", async () => { + const classify = vi + .spyOn(adminApi, "classify") + .mockResolvedValue({ changed: 2 }); + const user = userEvent.setup(); + render( {}} />); + await user.click(await screen.findByLabelText("Select Acme/a")); + await user.click(screen.getByLabelText("Select Acme/c")); + const bulk = screen.getByRole("form", { + name: "Classify selected repositories", + }); + expect(within(bulk).getByText("2 selected")).toBeInTheDocument(); + await user.selectOptions(within(bulk).getByLabelText("Domain"), "stack"); + await user.selectOptions(within(bulk).getByLabelText("Value"), "python"); + await user.click(within(bulk).getByRole("button", { name: "Apply to 2" })); + await waitFor(() => + expect(classify).toHaveBeenCalledWith({ + full_names: ["Acme/a", "Acme/c"], + domain: "stack", + values: ["python"], + mode: "add", + }), + ); + }); + + it("filters to repositories missing a value", async () => { + const user = userEvent.setup(); + render( {}} />); + await user.selectOptions( + await screen.findByLabelText("Show"), + "domain:tier", + ); + expect(screen.queryByText("Acme/a")).not.toBeInTheDocument(); + expect(screen.getByText("Acme/b")).toBeInTheDocument(); + expect(screen.getByText("2 of 3 shown")).toBeInTheDocument(); + }); + + it("saves the assignment and only the domains that changed", async () => { + const edit = vi.spyOn(adminApi, "editRepository").mockResolvedValue({}); + const classify = vi.spyOn(adminApi, "classify").mockResolvedValue({}); + const user = userEvent.setup(); + render( {}} />); + await user.click( + await screen.findByRole("button", { name: "Edit Acme/b" }), + ); + await user.selectOptions(screen.getByLabelText("Project"), "Tools"); + await user.selectOptions(screen.getByLabelText("Tier"), "core"); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(classify).toHaveBeenCalledTimes(1)); + expect(edit).toHaveBeenCalledWith({ + full_name: "Acme/b", + assign: true, + client: "", + project: "Tools", + application: "", + }); + expect(classify).toHaveBeenCalledWith({ + full_names: ["Acme/b"], + domain: "tier", + values: ["core"], + mode: "set", + }); + }); + + it("shows the API's reason when a save is rejected", async () => { + vi.spyOn(adminApi, "editRepository").mockRejectedValue( + new ApiError(422, { + code: "unknown_name", + message: "unknown client 'X'; add it under Admin > Lists first", + }), + ); + const user = userEvent.setup(); + render( {}} />); + await user.click( + await screen.findByRole("button", { name: "Edit Acme/b" }), + ); + await user.click(screen.getByRole("button", { name: "Save" })); + expect( + await screen.findByText(/add it under Admin > Lists/), + ).toBeInTheDocument(); + }); +}); + +describe("", () => { + beforeEach(() => { + vi.spyOn(adminApi, "portfolio").mockResolvedValue(tree); + vi.spyOn(adminApi, "duplicates").mockResolvedValue([ + { + kind: "client", + a: { id: 1, name: "Contoso" }, + b: { id: 7, name: "Contoso Inc" }, + }, + ]); + }); + + it("adds a client and merges a suggested duplicate", async () => { + const create = vi.spyOn(adminApi, "createClient").mockResolvedValue({}); + const merge = vi.spyOn(adminApi, "mergeListEntry").mockResolvedValue({}); + const user = userEvent.setup(); + render( {}} />); + await user.type(await screen.findByLabelText("New client"), "Northwind"); + await user.click(screen.getAllByRole("button", { name: "Add" })[0]); + await waitFor(() => expect(create).toHaveBeenCalledWith("Northwind")); + await user.click( + screen.getByRole("button", { + name: "Merge “Contoso Inc” into “Contoso”", + }), + ); + await waitFor(() => expect(merge).toHaveBeenCalledWith("client", 7, 1)); + }); + + it("retires an entry and merges within the same scope", async () => { + const edit = vi.spyOn(adminApi, "editListEntry").mockResolvedValue({}); + const merge = vi.spyOn(adminApi, "mergeListEntry").mockResolvedValue({}); + const user = userEvent.setup(); + render( {}} />); + await user.click( + await screen.findByRole("button", { name: "Retire Fabrikam" }), + ); + await waitFor(() => + expect(edit).toHaveBeenCalledWith("client", 5, { retired: true }), + ); + await user.click(screen.getByRole("button", { name: "Merge Fabrikam" })); + const target = screen.getByLabelText("Merge Fabrikam into"); + expect( + within(target) + .getAllByRole("option") + .map((o) => o.textContent), + ).toEqual(["Choose…", "Contoso"]); + await user.selectOptions(target, "1"); + await user.click(screen.getByRole("button", { name: "Confirm merge" })); + await waitFor(() => expect(merge).toHaveBeenCalledWith("client", 5, 1)); + }); +}); + +describe("", () => { + beforeEach(() => { + vi.spyOn(adminApi, "domains").mockResolvedValue(domains); + }); + + it("adds a value with a key derived from its label", async () => { + const add = vi.spyOn(adminApi, "addDomainValue").mockResolvedValue({}); + const user = userEvent.setup(); + render( {}} />); + await user.type(await screen.findByLabelText("New Stack value"), "Go Lang"); + const form = screen + .getByRole("textbox", { name: "New Stack value" }) + .closest("form"); + expect(within(form).getByLabelText("Key")).toHaveValue("go-lang"); + await user.click(within(form).getByRole("button", { name: "Add" })); + await waitFor(() => + expect(add).toHaveBeenCalledWith(4, { key: "go-lang", label: "Go Lang" }), + ); + }); + + it("offers delete only for unused values and retire for all", async () => { + render( {}} />); + const table = await screen.findByRole("table", { name: "Tier values" }); + expect( + within(table).getByRole("button", { name: "Delete Core" }), + ).toBeInTheDocument(); + expect( + within(table).queryByRole("button", { name: "Delete Archive" }), + ).not.toBeInTheDocument(); + expect( + within(table).getByRole("button", { name: "Restore Archive" }), + ).toBeInTheDocument(); + }); + + it("explains a refused change", async () => { + vi.spyOn(adminApi, "editDomain").mockRejectedValue( + new ApiError(422, { + code: "invalid", + message: "2 repositories hold several values in this domain", + }), + ); + const user = userEvent.setup(); + render( {}} />); + await user.click( + await screen.findByRole("button", { name: "Make single-choice" }), + ); + expect(await screen.findByText(/hold several values/)).toBeInTheDocument(); + }); +}); diff --git a/frontend/tests/SourcesView.test.jsx b/frontend/tests/SourcesView.test.jsx index 8990d794..802f7c8f 100644 --- a/frontend/tests/SourcesView.test.jsx +++ b/frontend/tests/SourcesView.test.jsx @@ -27,6 +27,11 @@ beforeEach(() => { vi.spyOn(adminApi, "connections").mockResolvedValue([]); vi.spyOn(adminApi, "sources").mockResolvedValue([source]); vi.spyOn(adminApi, "repositories").mockResolvedValue([]); + vi.spyOn(adminApi, "portfolio").mockResolvedValue([ + { id: 1, name: "Contoso", retired: false, projects: [] }, + { id: 2, name: "Gone Ltd", retired: true, projects: [] }, + ]); + vi.spyOn(adminApi, "domains").mockResolvedValue([]); }); afterEach(() => { @@ -115,6 +120,46 @@ describe("", () => { await waitFor(() => expect(screen.getByLabelText("Name")).toHaveValue("")); }); + it("chooses the client from the managed list, never free text", async () => { + vi.spyOn(adminApi, "session").mockResolvedValue(session); + const add = vi.spyOn(adminApi, "addSource").mockResolvedValue(source); + const user = userEvent.setup(); + render(); + const client = await screen.findByLabelText("Client (optional)"); + expect(client.tagName).toBe("SELECT"); + await waitFor(() => + expect([...client.options].map((option) => option.textContent)).toEqual([ + "No client", + "Contoso", + ]), + ); + await user.selectOptions(client, "Contoso"); + await user.type(screen.getByLabelText("Name"), "Octo"); + await user.click(screen.getByRole("button", { name: "Add source" })); + await waitFor(() => + expect(add).toHaveBeenCalledWith( + expect.objectContaining({ identifier: "Octo", client: "Contoso" }), + ), + ); + }); + + it("offers the Lists and Domains tabs", async () => { + vi.spyOn(adminApi, "session").mockResolvedValue(session); + vi.spyOn(adminApi, "duplicates").mockResolvedValue([]); + const user = userEvent.setup(); + render(); + await user.click(await screen.findByRole("tab", { name: "Lists" })); + expect( + await screen.findByRole("heading", { + name: "Clients, projects and applications", + }), + ).toBeInTheDocument(); + await user.click(screen.getByRole("tab", { name: "Domains" })); + expect( + await screen.findByRole("heading", { name: "Domains" }), + ).toBeInTheDocument(); + }); + it("requires a second click to remove a source", async () => { vi.spyOn(adminApi, "session").mockResolvedValue(session); const remove = vi.spyOn(adminApi, "removeSource").mockResolvedValue(null); @@ -205,7 +250,7 @@ describe("adminApi", () => { }); vi.stubGlobal("fetch", fetchMock); await adminApi.signIn("a", "b"); - await adminApi.portfolio(); + await adminApi.duplicates(); await adminApi.refresh(); const [, read] = fetchMock.mock.calls[1]; const [, write] = fetchMock.mock.calls[2]; diff --git a/src/spark/api/app.py b/src/spark/api/app.py index f11a1b82..a4c7902e 100644 --- a/src/spark/api/app.py +++ b/src/spark/api/app.py @@ -17,7 +17,8 @@ from pydantic import BaseModel, Field from spark.api import security -from spark.registry import Registry, connections +from spark.api.catalog_routes import build_router, http_error +from spark.registry import Registry, connections, domains from spark.registry.discovery import ( ERROR_HINTS, classify_error, @@ -25,7 +26,7 @@ validate_access, ) from spark.registry.secrets import SecretBox, SecretError -from spark.registry.store import RegistryError +from spark.registry.store import RegistryError, normalize_identifier COOKIE = "spark_session" @@ -62,10 +63,6 @@ class RepositoryPatch(BaseModel): application: Optional[str] = Field(default=None, max_length=120) -class NameIn(BaseModel): - name: str = Field(max_length=120) - - class ConnectionIn(BaseModel): name: str = Field(max_length=80) token: str = Field(max_length=300) @@ -235,11 +232,10 @@ def add_source( registry: Registry = Depends(get_registry), ) -> Dict[str, Any]: try: - from spark.registry.store import normalize_identifier - identifier = normalize_identifier(body.type, body.identifier) + registry.client_id_for(body.client) except RegistryError as error: - raise bad_request(error) from error + raise http_error(error) from error existing = registry.find_source(body.type, identifier) if existing: raise HTTPException( @@ -273,6 +269,10 @@ def edit_source( registry: Registry = Depends(get_registry), ) -> Dict[str, Any]: try: + source = registry.get_source(source_id) + # Check the client before changing anything, so a rejected + # request leaves the source as it was. + registry.client_id_for(body.client, current=source["client_id"]) if body.enabled is not None: registry.set_source_enabled(source_id, body.enabled) if ( @@ -288,9 +288,7 @@ def edit_source( ) return present_source(registry, registry.get_source(source_id)) except RegistryError as error: - raise HTTPException( - 404, {"code": "not_found", "message": str(error)} - ) from error + raise http_error(error) from error @app.delete("/api/sources/{source_id}", status_code=204) def remove_source( @@ -323,8 +321,12 @@ def list_repositories( "sources", ) flags = ("is_fork", "is_private", "is_archived", "excluded") + classified = domains.classifications(registry) return [ - {key: bool(repo[key]) if key in flags else repo[key] for key in keep} + { + **{key: bool(repo[key]) if key in flags else repo[key] for key in keep}, + "classifications": classified.get(repo["id"]), + } for repo in registry.list_repositories() ] @@ -345,49 +347,10 @@ def edit_repository( application=body.application or None, ) except RegistryError as error: - raise HTTPException( - 404, {"code": "not_found", "message": str(error)} - ) from error + raise http_error(error) from error return {"ok": True} - @app.get("/api/portfolio") - def portfolio( - session=admin, registry: Registry = Depends(get_registry) - ) -> List[Dict[str, Any]]: - return registry.portfolio_tree() - - @app.post("/api/clients", status_code=201) - def add_client( - body: NameIn, session=admin, registry: Registry = Depends(get_registry) - ) -> Dict[str, Any]: - try: - return registry.create_client(body.name) - except RegistryError as error: - raise bad_request(error) from error - - @app.post("/api/clients/{client_id}/projects", status_code=201) - def add_project( - client_id: int, - body: NameIn, - session=admin, - registry: Registry = Depends(get_registry), - ) -> Dict[str, Any]: - try: - return registry.create_project(client_id, body.name) - except RegistryError as error: - raise bad_request(error) from error - - @app.post("/api/projects/{project_id}/applications", status_code=201) - def add_application( - project_id: int, - body: NameIn, - session=admin, - registry: Registry = Depends(get_registry), - ) -> Dict[str, Any]: - try: - return registry.create_application(project_id, body.name) - except RegistryError as error: - raise bad_request(error) from error + app.include_router(build_router(admin, get_registry)) # -- connections ----------------------------------------------------------- @app.get("/api/connections") diff --git a/src/spark/api/catalog_routes.py b/src/spark/api/catalog_routes.py new file mode 100644 index 00000000..7b7c5962 --- /dev/null +++ b/src/spark/api/catalog_routes.py @@ -0,0 +1,245 @@ +"""Admin routes for managed lists (clients, projects, applications) and +classification domains. Mounted by ``create_app``, which supplies the +registry and signed-in-administrator dependencies.""" + +from __future__ import annotations + +from typing import Any, Callable, Dict, List, Optional + +from fastapi import APIRouter, Depends, HTTPException +from pydantic import BaseModel, Field + +from spark.registry import Registry, catalog, domains +from spark.registry.store import NotFoundError, RegistryError, UnknownNameError + + +class NameIn(BaseModel): + name: str = Field(max_length=120) + + +class ProjectIn(BaseModel): + name: str = Field(max_length=120) + client_id: Optional[int] = None + + +class ListPatch(BaseModel): + name: Optional[str] = Field(default=None, max_length=120) + retired: Optional[bool] = None + + +class MergeIn(BaseModel): + into_id: int + + +class DomainIn(BaseModel): + key: str = Field(max_length=40) + label: str = Field(max_length=80) + description: Optional[str] = Field(default=None, max_length=300) + multi: bool = False + + +class DomainPatch(BaseModel): + label: Optional[str] = Field(default=None, max_length=80) + description: Optional[str] = Field(default=None, max_length=300) + multi: Optional[bool] = None + retired: Optional[bool] = None + sort_order: Optional[int] = None + + +class ValueIn(BaseModel): + key: str = Field(max_length=40) + label: str = Field(max_length=80) + description: Optional[str] = Field(default=None, max_length=300) + + +class ValuePatch(BaseModel): + label: Optional[str] = Field(default=None, max_length=80) + description: Optional[str] = Field(default=None, max_length=300) + retired: Optional[bool] = None + sort_order: Optional[int] = None + + +class ClassifyIn(BaseModel): + full_names: List[str] = Field(min_length=1, max_length=1000) + domain: str = Field(max_length=40) + values: List[str] = Field(default_factory=list, max_length=50) + mode: str = "set" + + +def http_error(error: RegistryError) -> HTTPException: + """Missing record -> 404; unknown name -> 422 ``unknown_name``; any other + invalid input -> 422 ``invalid``.""" + if isinstance(error, NotFoundError): + return HTTPException(404, {"code": "not_found", "message": str(error)}) + code = "unknown_name" if isinstance(error, UnknownNameError) else "invalid" + return HTTPException(422, {"code": code, "message": str(error)}) + + +def build_router(admin: Any, get_registry: Callable[..., Any]) -> APIRouter: + router = APIRouter() + registry_dep = Depends(get_registry) + + def run(action: Callable[[], Any]) -> Any: + try: + return action() + except RegistryError as error: + raise http_error(error) from error + + # -- managed lists ---------------------------------------------------------- + @router.get("/api/portfolio") + def portfolio( + include_retired: bool = False, + session=admin, + registry: Registry = registry_dep, + ) -> List[Dict[str, Any]]: + return catalog.tree(registry, include_retired=include_retired) + + @router.get("/api/portfolio/duplicates") + def duplicates( + session=admin, registry: Registry = registry_dep + ) -> List[Dict[str, Any]]: + return catalog.duplicates(registry) + + @router.post("/api/clients", status_code=201) + def add_client( + body: NameIn, session=admin, registry: Registry = registry_dep + ) -> Dict[str, Any]: + return run(lambda: catalog.create_client(registry, body.name)) + + @router.post("/api/projects", status_code=201) + def add_project( + body: ProjectIn, session=admin, registry: Registry = registry_dep + ) -> Dict[str, Any]: + return run(lambda: catalog.create_project(registry, body.client_id, body.name)) + + @router.post("/api/clients/{client_id}/projects", status_code=201) + def add_client_project( + client_id: int, body: NameIn, session=admin, registry: Registry = registry_dep + ) -> Dict[str, Any]: + try: + return catalog.create_project(registry, client_id, body.name) + except RegistryError as error: # an unknown parent is invalid input here + raise HTTPException( + 422, {"code": "invalid", "message": str(error)} + ) from error + + @router.post("/api/projects/{project_id}/applications", status_code=201) + def add_application( + project_id: int, body: NameIn, session=admin, registry: Registry = registry_dep + ) -> Dict[str, Any]: + try: + return catalog.create_application(registry, project_id, body.name) + except RegistryError as error: + raise HTTPException( + 422, {"code": "invalid", "message": str(error)} + ) from error + + for kind, plural in ( + ("client", "clients"), + ("project", "projects"), + ("application", "applications"), + ): + _list_entry_routes(router, admin, registry_dep, run, kind, plural) + + # -- domains ------------------------------------------------------------------- + @router.get("/api/domains") + def list_domains( + include_retired: bool = False, + session=admin, + registry: Registry = registry_dep, + ) -> List[Dict[str, Any]]: + return domains.list_domains(registry, include_retired=include_retired) + + @router.post("/api/domains", status_code=201) + def add_domain( + body: DomainIn, session=admin, registry: Registry = registry_dep + ) -> Dict[str, Any]: + return run(lambda: domains.create_domain(registry, **body.model_dump())) + + @router.patch("/api/domains/{domain_id}") + def edit_domain( + domain_id: int, + body: DomainPatch, + session=admin, + registry: Registry = registry_dep, + ) -> Dict[str, Any]: + return run( + lambda: domains.update_domain( + registry, domain_id, **body.model_dump(exclude_none=True) + ) + ) + + @router.delete("/api/domains/{domain_id}", status_code=204) + def remove_domain( + domain_id: int, session=admin, registry: Registry = registry_dep + ) -> None: + run(lambda: domains.delete_domain(registry, domain_id)) + + @router.post("/api/domains/{domain_id}/values", status_code=201) + def add_value( + domain_id: int, + body: ValueIn, + session=admin, + registry: Registry = registry_dep, + ) -> Dict[str, Any]: + return run(lambda: domains.add_value(registry, domain_id, **body.model_dump())) + + @router.patch("/api/domain-values/{value_id}") + def edit_value( + value_id: int, + body: ValuePatch, + session=admin, + registry: Registry = registry_dep, + ) -> Dict[str, Any]: + return run( + lambda: domains.update_value( + registry, value_id, **body.model_dump(exclude_none=True) + ) + ) + + @router.delete("/api/domain-values/{value_id}", status_code=204) + def remove_value( + value_id: int, session=admin, registry: Registry = registry_dep + ) -> None: + run(lambda: domains.delete_value(registry, value_id)) + + @router.post("/api/repositories/classify") + def classify( + body: ClassifyIn, session=admin, registry: Registry = registry_dep + ) -> Dict[str, int]: + changed = run( + lambda: domains.classify( + registry, body.full_names, body.domain, body.values, body.mode + ) + ) + return {"changed": changed} + + return router + + +def _list_entry_routes(router, admin, registry_dep, run, kind, plural) -> None: + """Rename/retire/restore and merge for one kind of managed list entry.""" + + def edit( + item_id: int, body: ListPatch, session=admin, registry: Registry = registry_dep + ) -> Dict[str, Any]: + return run( + lambda: catalog.update( + registry, kind, item_id, name=body.name, retired=body.retired + ) + ) + + def merge( + item_id: int, body: MergeIn, session=admin, registry: Registry = registry_dep + ) -> Dict[str, int]: + return run(lambda: catalog.merge(registry, kind, item_id, body.into_id)) + + router.add_api_route( + f"/api/{plural}/{{item_id}}", edit, methods=["PATCH"], name=f"edit_{kind}" + ) + router.add_api_route( + f"/api/{plural}/{{item_id}}/merge", + merge, + methods=["POST"], + name=f"merge_{kind}", + ) diff --git a/src/spark/registry/__main__.py b/src/spark/registry/__main__.py index 4f2c1aca..53f24a0a 100644 --- a/src/spark/registry/__main__.py +++ b/src/spark/registry/__main__.py @@ -1,7 +1,8 @@ """Admin CLI: ``python -m spark.registry ``. -Manages sources until the management UI exists. The database path comes from -``--db`` or ``SPARK_DB_PATH``. +Manages sources until the management UI exists. Client, project and +application names must already exist; pass ``--create`` to add new ones. The +database path comes from ``--db`` or ``SPARK_DB_PATH``. """ from __future__ import annotations @@ -13,6 +14,7 @@ from github import Auth, Github +from spark.registry import catalog from spark.registry.discovery import run_discovery, validate_access from spark.registry.export import write_portfolio from spark.registry.store import Registry, RegistryError @@ -33,6 +35,9 @@ def build_parser() -> argparse.ArgumentParser: add.add_argument("identifier", help="login, or owner/name for a repo") add.add_argument("--client", help="client the source belongs to") add.add_argument("--no-validate", action="store_true") + add.add_argument( + "--create", action="store_true", help="create the client if it is new" + ) sub.add_parser("list", help="show sources and their status") for name in ("enable", "disable", "remove"): @@ -48,6 +53,11 @@ def build_parser() -> argparse.ArgumentParser: assign.add_argument("--client") assign.add_argument("--project") assign.add_argument("--application") + assign.add_argument( + "--create", + action="store_true", + help="create any client, project or application that does not exist yet", + ) export = sub.add_parser("export", help="write portfolio.json") export.add_argument("path", type=Path) @@ -78,6 +88,8 @@ def _run(args, registry: Registry) -> int: file=sys.stderr, ) return 1 + if args.create: + _ensure_names(registry, args.client) source = registry.add_source(args.type, args.identifier, client=args.client) print(f"source {source['id']}: {source['type']} {source['identifier']}") elif cmd == "list": @@ -99,6 +111,8 @@ def _run(args, registry: Registry) -> int: elif cmd in ("exclude", "include"): registry.set_repository_excluded(args.repository, cmd == "exclude") elif cmd == "assign": + if args.create: + _ensure_names(registry, args.client, args.project, args.application) registry.associate_repository( args.repository, client=args.client, @@ -113,5 +127,36 @@ def _run(args, registry: Registry) -> int: return 0 +def _ensure_names(registry: Registry, client, project=None, application=None) -> None: + """Explicitly create the named client/project/application when missing + (``--create``). Without it, unknown names are rejected.""" + tree = catalog.tree(registry, include_retired=True) + by_client = {c["name"].lower(): c for c in tree if c["id"] is not None} + internal = next((c for c in tree if c["id"] is None), None) + client_id = None + projects = internal["projects"] if internal else [] + if client: + found = by_client.get(client.lower()) + if found: + client_id, projects = found["id"], found["projects"] + else: + client_id, projects = catalog.create_client(registry, client)["id"], [] + print(f"created client {client!r}") + if not project: + return + found = next((p for p in projects if p["name"].lower() == project.lower()), None) + if found: + project_id, applications = found["id"], found["applications"] + else: + project_id = catalog.create_project(registry, client_id, project)["id"] + applications = [] + print(f"created project {project!r}") + if application and not any( + a["name"].lower() == application.lower() for a in applications + ): + catalog.create_application(registry, project_id, application) + print(f"created application {application!r}") + + if __name__ == "__main__": sys.exit(main()) diff --git a/src/spark/registry/catalog.py b/src/spark/registry/catalog.py new file mode 100644 index 00000000..4ab86195 --- /dev/null +++ b/src/spark/registry/catalog.py @@ -0,0 +1,356 @@ +"""Managed lists: clients, projects and applications. + +Names are created here, deliberately, and nowhere else. An entry can be +renamed, retired (hidden from pickers but kept on whatever already uses it), +restored, or merged into another entry of the same kind and scope. A project +without a client is an internal project. +""" + +from __future__ import annotations + +import re +import sqlite3 +from difflib import SequenceMatcher +from typing import Any, Dict, List, Optional, Tuple + +from spark.registry.store import ( + NotFoundError, + Registry, + RegistryError, + inserted_id, + now_iso, +) + +KINDS = ("client", "project", "application") +# The column that scopes a name: clients are global, projects belong to a +# client (or none), applications to a project. +_PARENT = {"client": None, "project": "client_id", "application": "project_id"} +_SUFFIXES = {"inc", "llc", "ltd", "corp", "corporation", "co", "company", "the"} +_SIMILAR = 0.85 + + +def _clean_name(kind: str, name: Optional[str]) -> str: + value = " ".join((name or "").split()) + if not value or len(value) > 120: + raise RegistryError(f"{kind} name must be 1-120 characters") + return value + + +def _get(registry: Registry, kind: str, item_id: int) -> sqlite3.Row: + if kind not in KINDS: + raise ValueError(kind) + row = registry.conn.execute( + f"SELECT * FROM {kind} WHERE id = ?", (item_id,) + ).fetchone() + if not row: + raise NotFoundError(f"no {kind} with id {item_id}") + return row + + +def _clash( + registry: Registry, + kind: str, + name: str, + parent: Optional[int], + exclude: Optional[int] = None, +) -> Optional[sqlite3.Row]: + sql = f"SELECT id, retired_at FROM {kind} WHERE name = ? COLLATE NOCASE" + params: List[Any] = [name] + if _PARENT[kind]: + sql += f" AND {_PARENT[kind]} IS ?" + params.append(parent) + if exclude is not None: + sql += " AND id != ?" + params.append(exclude) + return registry.conn.execute(sql, params).fetchone() + + +def _refuse_clash(registry, kind, name, parent, exclude=None) -> None: + found = _clash(registry, kind, name, parent, exclude) + if found: + state = "a retired" if found["retired_at"] else "an existing" + raise RegistryError(f"{name!r} is already {state} {kind} here") + + +# -- create ------------------------------------------------------------------ +def create_client(registry: Registry, name: str) -> Dict[str, Any]: + name = _clean_name("client", name) + _refuse_clash(registry, "client", name, None) + with registry.conn: + new_id = inserted_id( + registry.conn.execute( + "INSERT INTO client (name, created_at) VALUES (?, ?)", (name, now_iso()) + ) + ) + return {"id": new_id, "name": name} + + +def create_project( + registry: Registry, client_id: Optional[int], name: str +) -> Dict[str, Any]: + name = _clean_name("project", name) + if client_id is not None: + _get(registry, "client", client_id) + _refuse_clash(registry, "project", name, client_id) + with registry.conn: + new_id = inserted_id( + registry.conn.execute( + "INSERT INTO project (client_id, name, created_at) VALUES (?, ?, ?)", + (client_id, name, now_iso()), + ) + ) + return {"id": new_id, "client_id": client_id, "name": name} + + +def create_application( + registry: Registry, project_id: int, name: str +) -> Dict[str, Any]: + name = _clean_name("application", name) + project = _get(registry, "project", project_id) + _refuse_clash(registry, "application", name, project_id) + with registry.conn: + new_id = inserted_id( + registry.conn.execute( + "INSERT INTO application (client_id, project_id, name, created_at)" + " VALUES (?, ?, ?, ?)", + (project["client_id"], project_id, name, now_iso()), + ) + ) + return {"id": new_id, "project_id": project_id, "name": name} + + +# -- read -------------------------------------------------------------------- +def tree(registry: Registry, include_retired: bool = False) -> List[Dict[str, Any]]: + """Clients with their projects and applications, for pickers and the list + editor. Internal projects appear under a client with ``id`` None.""" + conn = registry.conn + active = "" if include_retired else " AND retired_at IS NULL" + repo_counts = _counts(conn, "repository") + source_counts = { + row[0]: row[1] + for row in conn.execute( + "SELECT client_id, COUNT(*) FROM source" + " WHERE client_id IS NOT NULL GROUP BY client_id" + ) + } + + def entry(row, kind) -> Dict[str, Any]: + return { + "id": row["id"], + "name": row["name"], + "retired": row["retired_at"] is not None, + "repository_count": repo_counts[kind].get(row["id"], 0), + } + + def projects_for(client_id: Optional[int]) -> List[Dict[str, Any]]: + out = [] + for row in conn.execute( + f"SELECT * FROM project WHERE client_id IS ?{active}" + " ORDER BY name COLLATE NOCASE", + (client_id,), + ): + project = entry(row, "project") + project["applications"] = [ + entry(app, "application") + for app in conn.execute( + f"SELECT * FROM application WHERE project_id = ?{active}" + " ORDER BY name COLLATE NOCASE", + (row["id"],), + ) + ] + out.append(project) + return out + + clients = [] + for row in conn.execute( + f"SELECT * FROM client WHERE 1 = 1{active} ORDER BY name COLLATE NOCASE" + ): + client = entry(row, "client") + client["source_count"] = source_counts.get(row["id"], 0) + client["projects"] = projects_for(row["id"]) + clients.append(client) + internal = projects_for(None) + if internal: + clients.insert( + 0, + { + "id": None, + "name": "Internal", + "retired": False, + "repository_count": 0, + "source_count": 0, + "projects": internal, + }, + ) + return clients + + +def _counts(conn: sqlite3.Connection, table: str) -> Dict[str, Dict[int, int]]: + return { + kind: { + row[0]: row[1] + for row in conn.execute( + f"SELECT {kind}_id, COUNT(*) FROM {table}" + f" WHERE {kind}_id IS NOT NULL GROUP BY {kind}_id" + ) + } + for kind in KINDS + } + + +# -- rename, retire, restore ------------------------------------------------- +def update( + registry: Registry, + kind: str, + item_id: int, + *, + name: Optional[str] = None, + retired: Optional[bool] = None, +) -> Dict[str, Any]: + row = _get(registry, kind, item_id) + column = _PARENT[kind] + parent = row[column] if column else None + with registry.conn: + if name is not None: + name = _clean_name(kind, name) + _refuse_clash(registry, kind, name, parent, exclude=item_id) + registry.conn.execute( + f"UPDATE {kind} SET name = ? WHERE id = ?", (name, item_id) + ) + if retired is not None: + registry.conn.execute( + f"UPDATE {kind} SET retired_at = ? WHERE id = ?", + (now_iso() if retired else None, item_id), + ) + row = _get(registry, kind, item_id) + return {"id": row["id"], "name": row["name"], "retired": bool(row["retired_at"])} + + +# -- merge ------------------------------------------------------------------- +def merge(registry: Registry, kind: str, from_id: int, into_id: int) -> Dict[str, int]: + """Move everything that uses ``from_id`` onto ``into_id`` (same kind and + scope), merging same-named children, then retire ``from_id``. Returns how + many repositories and sources moved. All or nothing.""" + if from_id == into_id: + raise RegistryError(f"choose a different {kind} to merge into") + source = _get(registry, kind, from_id) + target = _get(registry, kind, into_id) + if target["retired_at"]: + raise RegistryError(f"cannot merge into a retired {kind}; restore it first") + column = _PARENT[kind] + if column and source[column] != target[column]: + parent = "client" if kind == "project" else "project" + raise RegistryError(f"only a {kind} under the same {parent} can be merged") + conn = registry.conn + moved = { + "repositories": conn.execute( + f"SELECT COUNT(*) FROM repository WHERE {kind}_id = ?", (from_id,) + ).fetchone()[0], + "sources": ( + conn.execute( + "SELECT COUNT(*) FROM source WHERE client_id = ?", (from_id,) + ).fetchone()[0] + if kind == "client" + else 0 + ), + } + with conn: + _merge(conn, kind, from_id, into_id) + return moved + + +def _merge(conn, kind: str, from_id: int, into_id: int) -> None: + conn.execute( + f"UPDATE repository SET {kind}_id = ? WHERE {kind}_id = ?", (into_id, from_id) + ) + if kind == "client": + conn.execute( + "UPDATE source SET client_id = ? WHERE client_id = ?", (into_id, from_id) + ) + conn.execute( + "UPDATE observation SET client_id = ? WHERE client_id = ?", + (into_id, from_id), + ) + _move_children(conn, "project", "client_id", from_id, into_id) + conn.execute( + "UPDATE application SET client_id = ? WHERE client_id = ?", + (into_id, from_id), + ) + elif kind == "project": + _move_children(conn, "application", "project_id", from_id, into_id) + conn.execute( + f"UPDATE {kind} SET retired_at = COALESCE(retired_at, ?) WHERE id = ?", + (now_iso(), from_id), + ) + + +def _move_children(conn, kind, column, from_id, into_id) -> None: + """Re-parent children. A child whose name already exists under the target + is merged into that one instead (restoring it if it was retired, since it + now carries what the child had); the merged child stays retired under its + old parent, so names stay unique per scope.""" + for child in conn.execute( + f"SELECT id, name, retired_at FROM {kind} WHERE {column} = ?", (from_id,) + ).fetchall(): + twin = conn.execute( + f"SELECT id FROM {kind} WHERE {column} = ? AND name = ? COLLATE NOCASE", + (into_id, child["name"]), + ).fetchone() + if twin: + _merge(conn, kind, child["id"], twin["id"]) + if child["retired_at"] is None: + conn.execute( + f"UPDATE {kind} SET retired_at = NULL WHERE id = ?", (twin["id"],) + ) + else: + conn.execute( + f"UPDATE {kind} SET {column} = ? WHERE id = ?", (into_id, child["id"]) + ) + + +# -- likely duplicates ------------------------------------------------------- +def _normalize(name: str) -> str: + words = re.sub(r"[^a-z0-9]+", " ", name.lower().replace("&", " and ")).split() + while len(words) > 1 and words[-1] in _SUFFIXES: + words.pop() + if len(words) > 1 and words[0] == "the": + words.pop(0) + return " ".join(words) + + +def _similar(a: str, b: str) -> bool: + na, nb = _normalize(a), _normalize(b) + if na == nb: + return True + return min(len(na), len(nb)) >= 5 and SequenceMatcher(None, na, nb).ratio() >= ( + _SIMILAR + ) + + +def duplicates(registry: Registry) -> List[Dict[str, Any]]: + """Pairs of active entries in the same scope whose names look alike, for + the administrator to review. Nothing is merged automatically.""" + out: List[Dict[str, Any]] = [] + for kind in KINDS: + column = _PARENT[kind] + rows = registry.conn.execute( + f"SELECT id, name{', ' + column if column else ''} FROM {kind}" + " WHERE retired_at IS NULL ORDER BY id" + ).fetchall() + groups: Dict[Any, List[Tuple[int, str]]] = {} + for row in rows: + groups.setdefault(row[column] if column else None, []).append( + (row["id"], row["name"]) + ) + for members in groups.values(): + for i, (a_id, a_name) in enumerate(members): + for b_id, b_name in members[i + 1 :]: + if _similar(a_name, b_name): + out.append( + { + "kind": kind, + "a": {"id": a_id, "name": a_name}, + "b": {"id": b_id, "name": b_name}, + } + ) + return out diff --git a/src/spark/registry/db.py b/src/spark/registry/db.py index fc0ac6dd..8e897d03 100644 --- a/src/spark/registry/db.py +++ b/src/spark/registry/db.py @@ -170,6 +170,76 @@ last_success_at TEXT ); """, + # 4: managed lists and classification domains. Clients, projects and + # applications can be retired (hidden from pickers, kept on what already + # uses them). A domain is a named list of allowed values; a repository is + # classified by linking it to values. Keys are stable; labels may change. + """ + ALTER TABLE client ADD COLUMN retired_at TEXT; + ALTER TABLE project ADD COLUMN retired_at TEXT; + ALTER TABLE application ADD COLUMN retired_at TEXT; + CREATE TABLE domain ( + id INTEGER PRIMARY KEY, + key TEXT NOT NULL UNIQUE COLLATE NOCASE, + label TEXT NOT NULL, + description TEXT, + multi INTEGER NOT NULL DEFAULT 0, + sort_order INTEGER NOT NULL DEFAULT 0, + retired_at TEXT, + created_at TEXT NOT NULL + ); + CREATE TABLE domain_value ( + id INTEGER PRIMARY KEY, + domain_id INTEGER NOT NULL REFERENCES domain(id) ON DELETE CASCADE, + key TEXT NOT NULL COLLATE NOCASE, + label TEXT NOT NULL, + description TEXT, + sort_order INTEGER NOT NULL DEFAULT 0, + retired_at TEXT, + created_at TEXT NOT NULL, + UNIQUE (domain_id, key) + ); + CREATE TABLE repository_classification ( + repository_id INTEGER NOT NULL REFERENCES repository(id) ON DELETE CASCADE, + value_id INTEGER NOT NULL REFERENCES domain_value(id), + assigned_at TEXT NOT NULL, + PRIMARY KEY (repository_id, value_id) + ); + CREATE INDEX repository_classification_value + ON repository_classification (value_id); + INSERT INTO domain (key, label, description, multi, sort_order, created_at) + VALUES + ('tier', 'Tier', 'How much the repository matters to the portfolio now.', + 0, 10, strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + ('type', 'Type', 'What the repository is.', + 0, 20, strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + ('lifecycle', 'Lifecycle', 'Where the repository is in its life.', + 0, 30, strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), + ('stack', 'Stack', 'Main technologies; choose all that apply.', + 1, 40, strftime('%Y-%m-%dT%H:%M:%SZ', 'now')); + INSERT INTO domain_value (domain_id, key, label, sort_order, created_at) + SELECT d.id, v.key, v.label, v.sort_order, strftime('%Y-%m-%dT%H:%M:%SZ', 'now') + FROM domain d JOIN ( + SELECT 'tier' AS domain, 'core' AS key, 'Core' AS label, 10 AS sort_order + UNION ALL SELECT 'tier', 'supporting', 'Supporting', 20 + UNION ALL SELECT 'tier', 'archive', 'Archive', 30 + UNION ALL SELECT 'type', 'website', 'Website', 10 + UNION ALL SELECT 'type', 'web-app', 'Web app', 20 + UNION ALL SELECT 'type', 'api', 'API', 30 + UNION ALL SELECT 'type', 'library', 'Library', 40 + UNION ALL SELECT 'type', 'tool', 'Tool', 50 + UNION ALL SELECT 'type', 'docs', 'Docs', 60 + UNION ALL SELECT 'type', 'template', 'Template', 70 + UNION ALL SELECT 'lifecycle', 'active', 'Active', 10 + UNION ALL SELECT 'lifecycle', 'maintenance', 'Maintenance', 20 + UNION ALL SELECT 'lifecycle', 'deprecated', 'Deprecated', 30 + UNION ALL SELECT 'lifecycle', 'experiment', 'Experiment', 40 + UNION ALL SELECT 'stack', 'dotnet', '.NET', 10 + UNION ALL SELECT 'stack', 'python', 'Python', 20 + UNION ALL SELECT 'stack', 'node-react', 'Node/React', 30 + UNION ALL SELECT 'stack', 'static-site', 'Static site', 40 + ) v ON v.domain = d.key; + """, ] diff --git a/src/spark/registry/domains.py b/src/spark/registry/domains.py new file mode 100644 index 00000000..b529d04b --- /dev/null +++ b/src/spark/registry/domains.py @@ -0,0 +1,446 @@ +"""Classification domains: named lists of allowed values for repositories. + +A domain is single-choice (a repository holds at most one of its values) or +multi-choice. Values are retired rather than deleted once anything uses them: +a retired value leaves the pickers but stays on the repositories that carry +it. Keys are stable identifiers; labels are free to change. +""" + +from __future__ import annotations + +import re +import sqlite3 +from typing import Any, Dict, Iterable, List, Optional + +from spark.registry.store import ( + NotFoundError, + Registry, + RegistryError, + inserted_id, + now_iso, +) + +_KEY = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$") +MODES = ("set", "add", "remove") + + +def _key(value: Optional[str]) -> str: + key = (value or "").strip().lower() + if not _KEY.match(key): + raise RegistryError( + "key must be 1-40 lower-case letters, digits or hyphens (got " f"{value!r})" + ) + return key + + +def _label(value: Optional[str], what: str = "label") -> str: + label = " ".join((value or "").split()) + if not label or len(label) > 80: + raise RegistryError(f"{what} must be 1-80 characters") + return label + + +def _description(value: Optional[str]) -> Optional[str]: + text = (value or "").strip() + if len(text) > 300: + raise RegistryError("description must be at most 300 characters") + return text or None + + +def _domain(registry: Registry, domain_id: int) -> sqlite3.Row: + row = registry.conn.execute( + "SELECT * FROM domain WHERE id = ?", (domain_id,) + ).fetchone() + if not row: + raise NotFoundError(f"no domain with id {domain_id}") + return row + + +def _value(registry: Registry, value_id: int) -> sqlite3.Row: + row = registry.conn.execute( + "SELECT * FROM domain_value WHERE id = ?", (value_id,) + ).fetchone() + if not row: + raise NotFoundError(f"no domain value with id {value_id}") + return row + + +def _next_order(registry: Registry, table: str, where: str = "", params=()) -> int: + row = registry.conn.execute( + f"SELECT COALESCE(MAX(sort_order), 0) FROM {table} {where}", params + ).fetchone() + return row[0] + 10 + + +# -- read -------------------------------------------------------------------- +def list_domains( + registry: Registry, include_retired: bool = False +) -> List[Dict[str, Any]]: + """Domains in display order, each with its values and how many + repositories use each value.""" + conn = registry.conn + usage = { + row[0]: row[1] + for row in conn.execute( + "SELECT value_id, COUNT(*) FROM repository_classification GROUP BY value_id" + ) + } + active = "" if include_retired else " WHERE retired_at IS NULL" + out = [] + for row in conn.execute( + f"SELECT * FROM domain{active} ORDER BY sort_order, label COLLATE NOCASE" + ): + values = [ + { + "id": v["id"], + "key": v["key"], + "label": v["label"], + "description": v["description"], + "retired": v["retired_at"] is not None, + "repository_count": usage.get(v["id"], 0), + } + for v in conn.execute( + "SELECT * FROM domain_value WHERE domain_id = ?" + + ("" if include_retired else " AND retired_at IS NULL") + + " ORDER BY sort_order, label COLLATE NOCASE", + (row["id"],), + ) + ] + out.append( + { + "id": row["id"], + "key": row["key"], + "label": row["label"], + "description": row["description"], + "multi": bool(row["multi"]), + "retired": row["retired_at"] is not None, + "values": values, + } + ) + return out + + +class Classifications: + """Every repository's values, by domain key, for the active domains.""" + + def __init__(self, domain_keys: List[str], held: Dict[int, Dict[str, List[str]]]): + self.domain_keys = domain_keys + self._held = held + + def get(self, repository_id: int) -> Dict[str, List[str]]: + """A domain the repository has no value in is present with an empty + list, so "unassigned" is explicit rather than missing.""" + held = self._held.get(repository_id, {}) + return {key: list(held.get(key, [])) for key in self.domain_keys} + + +def classifications(registry: Registry) -> Classifications: + conn = registry.conn + domain_keys = [ + row[0] + for row in conn.execute( + "SELECT key FROM domain WHERE retired_at IS NULL ORDER BY sort_order" + ) + ] + held: Dict[int, Dict[str, List[str]]] = {} + for repo_id, domain_key, value_key in conn.execute( + "SELECT rc.repository_id, d.key, v.key FROM repository_classification rc" + " JOIN domain_value v ON v.id = rc.value_id" + " JOIN domain d ON d.id = v.domain_id" + " WHERE d.retired_at IS NULL" + " ORDER BY rc.repository_id, d.sort_order, v.sort_order" + ): + held.setdefault(repo_id, {}).setdefault(domain_key, []).append(value_key) + return Classifications(domain_keys, held) + + +# -- domains ----------------------------------------------------------------- +def create_domain( + registry: Registry, + *, + key: str, + label: str, + description: Optional[str] = None, + multi: bool = False, +) -> Dict[str, Any]: + key, label = _key(key), _label(label) + if registry.conn.execute("SELECT 1 FROM domain WHERE key = ?", (key,)).fetchone(): + raise RegistryError(f"a domain with key {key!r} already exists") + with registry.conn: + new_id = inserted_id( + registry.conn.execute( + "INSERT INTO domain (key, label, description, multi, sort_order," + " created_at) VALUES (?, ?, ?, ?, ?, ?)", + ( + key, + label, + _description(description), + int(multi), + _next_order(registry, "domain"), + now_iso(), + ), + ) + ) + return _present_domain(registry, new_id) + + +def update_domain( + registry: Registry, + domain_id: int, + *, + label: Optional[str] = None, + description: Optional[str] = None, + multi: Optional[bool] = None, + retired: Optional[bool] = None, + sort_order: Optional[int] = None, +) -> Dict[str, Any]: + _domain(registry, domain_id) + if multi is False: + crowded = registry.conn.execute( + "SELECT COUNT(*) FROM (SELECT rc.repository_id FROM" + " repository_classification rc JOIN domain_value v ON v.id = rc.value_id" + " WHERE v.domain_id = ? GROUP BY rc.repository_id HAVING COUNT(*) > 1)", + (domain_id,), + ).fetchone()[0] + if crowded: + raise RegistryError( + f"{crowded} repositories hold several values in this domain;" + " reduce them to one before making it single-choice" + ) + changes: Dict[str, Any] = {} + if label is not None: + changes["label"] = _label(label) + if description is not None: + changes["description"] = _description(description) + if multi is not None: + changes["multi"] = int(multi) + if retired is not None: + changes["retired_at"] = now_iso() if retired else None + if sort_order is not None: + changes["sort_order"] = int(sort_order) + if changes: + with registry.conn: + registry.conn.execute( + "UPDATE domain SET " + + ", ".join(f"{column} = ?" for column in changes) + + " WHERE id = ?", + (*changes.values(), domain_id), + ) + return _present_domain(registry, domain_id) + + +def delete_domain(registry: Registry, domain_id: int) -> None: + """Only a domain no repository uses can be deleted; retire it otherwise.""" + _domain(registry, domain_id) + if _domain_usage(registry, domain_id): + raise RegistryError("this domain is in use; retire it instead of deleting it") + with registry.conn: + registry.conn.execute("DELETE FROM domain WHERE id = ?", (domain_id,)) + + +def _domain_usage(registry: Registry, domain_id: int) -> int: + return registry.conn.execute( + "SELECT COUNT(*) FROM repository_classification rc" + " JOIN domain_value v ON v.id = rc.value_id WHERE v.domain_id = ?", + (domain_id,), + ).fetchone()[0] + + +def _present_domain(registry: Registry, domain_id: int) -> Dict[str, Any]: + for domain in list_domains(registry, include_retired=True): + if domain["id"] == domain_id: + return domain + raise NotFoundError(f"no domain with id {domain_id}") # pragma: no cover + + +# -- values ------------------------------------------------------------------ +def add_value( + registry: Registry, + domain_id: int, + *, + key: str, + label: str, + description: Optional[str] = None, +) -> Dict[str, Any]: + _domain(registry, domain_id) + key, label = _key(key), _label(label) + if registry.conn.execute( + "SELECT 1 FROM domain_value WHERE domain_id = ? AND key = ?", (domain_id, key) + ).fetchone(): + raise RegistryError(f"this domain already has a value with key {key!r}") + with registry.conn: + new_id = inserted_id( + registry.conn.execute( + "INSERT INTO domain_value (domain_id, key, label, description," + " sort_order, created_at) VALUES (?, ?, ?, ?, ?, ?)", + ( + domain_id, + key, + label, + _description(description), + _next_order( + registry, "domain_value", "WHERE domain_id = ?", (domain_id,) + ), + now_iso(), + ), + ) + ) + return _present_value(registry, new_id) + + +def update_value( + registry: Registry, + value_id: int, + *, + label: Optional[str] = None, + description: Optional[str] = None, + retired: Optional[bool] = None, + sort_order: Optional[int] = None, +) -> Dict[str, Any]: + _value(registry, value_id) + changes: Dict[str, Any] = {} + if label is not None: + changes["label"] = _label(label) + if description is not None: + changes["description"] = _description(description) + if retired is not None: + changes["retired_at"] = now_iso() if retired else None + if sort_order is not None: + changes["sort_order"] = int(sort_order) + if changes: + with registry.conn: + registry.conn.execute( + "UPDATE domain_value SET " + + ", ".join(f"{column} = ?" for column in changes) + + " WHERE id = ?", + (*changes.values(), value_id), + ) + return _present_value(registry, value_id) + + +def delete_value(registry: Registry, value_id: int) -> None: + """Only a value no repository uses can be deleted; retire it otherwise.""" + _value(registry, value_id) + if registry.conn.execute( + "SELECT 1 FROM repository_classification WHERE value_id = ? LIMIT 1", + (value_id,), + ).fetchone(): + raise RegistryError("this value is in use; retire it instead of deleting it") + with registry.conn: + registry.conn.execute("DELETE FROM domain_value WHERE id = ?", (value_id,)) + + +def _present_value(registry: Registry, value_id: int) -> Dict[str, Any]: + row = _value(registry, value_id) + used = registry.conn.execute( + "SELECT COUNT(*) FROM repository_classification WHERE value_id = ?", + (value_id,), + ).fetchone()[0] + return { + "id": row["id"], + "domain_id": row["domain_id"], + "key": row["key"], + "label": row["label"], + "description": row["description"], + "retired": row["retired_at"] is not None, + "repository_count": used, + } + + +# -- classifying repositories ------------------------------------------------ +def classify( + registry: Registry, + full_names: Iterable[str], + domain_key: str, + value_keys: Iterable[str], + mode: str = "set", +) -> int: + """Classify repositories in one domain, all or nothing. + + ``set`` replaces the repository's values in the domain (an empty list + clears it); ``add`` and ``remove`` apply to multi-choice domains only. A + retired value can be kept where it already is but not newly assigned. + Returns the number of repositories changed. + """ + if mode not in MODES: + raise RegistryError(f"mode must be one of {', '.join(MODES)}") + conn = registry.conn + domain = conn.execute( + "SELECT * FROM domain WHERE key = ?", ((domain_key or "").lower(),) + ).fetchone() + if not domain: + raise NotFoundError(f"unknown domain {domain_key!r}") + if domain["retired_at"]: + raise RegistryError(f"domain {domain['label']!r} is retired") + keys = list(dict.fromkeys(k.lower() for k in value_keys)) + if not domain["multi"]: + if mode != "set": + raise RegistryError(f"{domain['label']} is single-choice; use set") + if len(keys) > 1: + raise RegistryError(f"{domain['label']} allows only one value") + values = { + row["key"]: row + for row in conn.execute( + "SELECT * FROM domain_value WHERE domain_id = ?", (domain["id"],) + ) + } + unknown = [k for k in keys if k not in values] + if unknown: + raise RegistryError( + f"unknown {domain['label']} value(s): {', '.join(unknown)};" + " add them under Admin > Domains first" + ) + chosen = {values[k]["id"] for k in keys} + retired = {values[k]["id"] for k in keys if values[k]["retired_at"]} + domain_value_ids = {row["id"] for row in values.values()} + + repo_ids = [] + for name in dict.fromkeys(full_names): + row = conn.execute( + "SELECT id FROM repository WHERE full_name_lower = ?", (name.lower(),) + ).fetchone() + if not row: + raise NotFoundError(f"unknown repository {name!r}") + repo_ids.append(row["id"]) + + changed = 0 + stamp = now_iso() + with conn: + for repo_id in repo_ids: + held = { + row[0] + for row in conn.execute( + "SELECT value_id FROM repository_classification" + " WHERE repository_id = ?", + (repo_id,), + ) + if row[0] in domain_value_ids + } + if mode == "set": + target = chosen + elif mode == "add": + target = held | chosen + else: + target = held - chosen + newly_retired = (target - held) & retired + if newly_retired: + raise RegistryError( + "a retired value cannot be newly assigned; restore it under" + " Admin > Domains first" + ) + if target == held: + continue + for value_id in held - target: + conn.execute( + "DELETE FROM repository_classification" + " WHERE repository_id = ? AND value_id = ?", + (repo_id, value_id), + ) + for value_id in target - held: + conn.execute( + "INSERT INTO repository_classification" + " (repository_id, value_id, assigned_at) VALUES (?, ?, ?)", + (repo_id, value_id, stamp), + ) + changed += 1 + return changed diff --git a/src/spark/registry/export.py b/src/spark/registry/export.py index 49465b7f..648f3bc3 100644 --- a/src/spark/registry/export.py +++ b/src/spark/registry/export.py @@ -9,6 +9,7 @@ from typing import Any, Dict, List from spark.cli_output_layout import source_slug +from spark.registry import domains from spark.registry.store import Registry, now_iso SCHEMA_VERSION = 1 @@ -50,6 +51,7 @@ def build_portfolio(registry: Registry) -> Dict[str, Any]: source are left out of the list but retained in the database. """ sources = registry.list_sources() + classified = domains.classifications(registry) enabled_ids = {s["id"] for s in sources if s["enabled"]} repositories: List[Dict[str, Any]] = [] for repo in registry.list_repositories(include_excluded=False): @@ -60,6 +62,7 @@ def build_portfolio(registry: Registry) -> Dict[str, Any]: for flag in ("is_fork", "is_private", "is_archived"): item[flag] = bool(item[flag]) item["sources"] = [f"{s['type']}:{s['identifier']}" for s in reached_by] + item["classifications"] = classified.get(repo["id"]) repositories.append(item) return { @@ -74,6 +77,19 @@ def build_portfolio(registry: Registry) -> Dict[str, Any]: } for s in sources ], + "domains": [ + { + "key": d["key"], + "label": d["label"], + "multi": d["multi"], + "values": [ + {"key": v["key"], "label": v["label"], "retired": v["retired"]} + for v in d["values"] + ], + } + for d in domains.list_domains(registry, include_retired=True) + if not d["retired"] + ], "repositories": repositories, } diff --git a/src/spark/registry/store.py b/src/spark/registry/store.py index 48374115..26962092 100644 --- a/src/spark/registry/store.py +++ b/src/spark/registry/store.py @@ -1,4 +1,10 @@ -"""Registry operations: sources, repositories and portfolio associations.""" +"""Registry operations: sources, repositories and portfolio associations. + +SIZE JUSTIFICATION (Constitution I): this is the single data-access class the +API, worker and CLI share. Managed lists live in ``catalog``, classification in +``domains``, and tokens in ``connections``; what remains is core record access +plus the Dependabot upserts, which share its transactions. +""" from __future__ import annotations @@ -20,6 +26,15 @@ class RegistryError(ValueError): """Raised for invalid registry input or a missing record.""" +class NotFoundError(RegistryError): + """The record named by an id or repository name does not exist.""" + + +class UnknownNameError(RegistryError): + """A client, project or application name that is not in its managed list + (or is retired). Names are never created as a side effect of assignment.""" + + def inserted_id(cursor: sqlite3.Cursor) -> int: """The row id from an INSERT; sqlite3 types it Optional, but an INSERT sets it.""" if cursor.lastrowid is None: # pragma: no cover - only after a non-INSERT @@ -72,7 +87,7 @@ def add_source( existing = self.find_source(source_type, identifier) if existing: return existing - client_id = self._client_id(client, create=True) if client else None + client_id = self.client_id_for(client) with self.conn: cursor = self.conn.execute( "INSERT INTO source (type, identifier, enabled, client_id, created_at)" @@ -93,7 +108,7 @@ def get_source(self, source_id: int) -> Dict[str, Any]: "SELECT * FROM source WHERE id = ?", (source_id,) ).fetchone() if not row: - raise RegistryError(f"no source with id {source_id}") + raise NotFoundError(f"no source with id {source_id}") return dict(row) def list_sources(self, enabled_only: bool = False) -> List[Dict[str, Any]]: @@ -211,7 +226,7 @@ def set_repository_excluded(self, full_name: str, excluded: bool) -> None: ) self.conn.commit() if cursor.rowcount == 0: - raise RegistryError(f"unknown repository {full_name!r}") + raise NotFoundError(f"unknown repository {full_name!r}") def list_repositories(self, include_excluded: bool = True) -> List[Dict[str, Any]]: sql = ( @@ -248,20 +263,40 @@ def prune_orphans(self) -> int: return cursor.rowcount # -- portfolio ------------------------------------------------------ - def _client_id(self, name: Optional[str], create: bool = False) -> Optional[int]: + def client_id_for( + self, name: Optional[str], *, current: Optional[int] = None + ) -> Optional[int]: + """Id of an active client by name; ``current`` may stay even if retired.""" + return self._resolve("client", name, None, None, current) + + def _resolve( + self, + table: str, + name: Optional[str], + parent_column: Optional[str], + parent_id: Optional[int], + current: Optional[int], + ) -> Optional[int]: + """Look a managed name up; never create it. A retired entry is only + accepted when it is what the record already uses.""" if not name: return None - row = self.conn.execute( - "SELECT id FROM client WHERE name = ?", (name,) - ).fetchone() - if row: - return row[0] - if not create: - raise RegistryError(f"unknown client {name!r}") - with self.conn: - return self.conn.execute( - "INSERT INTO client (name, created_at) VALUES (?, ?)", (name, now_iso()) - ).lastrowid + sql = f"SELECT id, retired_at FROM {table} WHERE name = ?" + params: List[Any] = [name] + if parent_column: + sql += f" AND {parent_column} IS ?" + params.append(parent_id) + row = self.conn.execute(sql, params).fetchone() + if not row: + raise UnknownNameError( + f"unknown {table} {name!r}; add it under Admin > Lists first" + ) + if row["retired_at"] and row["id"] != current: + raise UnknownNameError( + f"{table} {name!r} is retired; restore it under Admin > Lists" + " or choose another" + ) + return row["id"] def associate_repository( self, @@ -271,96 +306,32 @@ def associate_repository( project: Optional[str] = None, application: Optional[str] = None, ) -> None: - """Link a repository to a client/project/application (all optional; - names are created on first use). Unassigned repositories are valid.""" + """Link a repository to an existing client/project/application (all + optional; unassigned is valid). A project without a client is an + internal project. Unknown or retired names are rejected.""" row = self.conn.execute( - "SELECT id FROM repository WHERE full_name_lower = ?", (full_name.lower(),) + "SELECT id, client_id, project_id, application_id FROM repository" + " WHERE full_name_lower = ?", + (full_name.lower(),), ).fetchone() if not row: - raise RegistryError(f"unknown repository {full_name!r}") - client_id = self._client_id(client, create=True) - project_id = application_id = None + raise NotFoundError(f"unknown repository {full_name!r}") + if application and not project: + raise RegistryError("an application belongs to a project; choose one") + client_id = self.client_id_for(client, current=row["client_id"]) + project_id = self._resolve( + "project", project, "client_id", client_id, row["project_id"] + ) + application_id = self._resolve( + "application", application, "project_id", project_id, row["application_id"] + ) with self.conn: - if project: - found = self.conn.execute( - "SELECT id FROM project WHERE name = ? AND client_id IS ?", - (project, client_id), - ).fetchone() - project_id = ( - found[0] - if found - else self.conn.execute( - "INSERT INTO project (client_id, name, created_at)" - " VALUES (?, ?, ?)", - (client_id, project, now_iso()), - ).lastrowid - ) - if application: - found = self.conn.execute( - "SELECT id FROM application WHERE name = ? AND project_id IS ?", - (application, project_id), - ).fetchone() - application_id = ( - found[0] - if found - else self.conn.execute( - "INSERT INTO application" - " (client_id, project_id, name, created_at)" - " VALUES (?, ?, ?, ?)", - (client_id, project_id, application, now_iso()), - ).lastrowid - ) self.conn.execute( "UPDATE repository SET client_id = ?, project_id = ?," " application_id = ? WHERE id = ?", - (client_id, project_id, application_id, row[0]), + (client_id, project_id, application_id, row["id"]), ) - # -- clients, projects, applications ---------------------------------- - def create_client(self, name: str) -> Dict[str, Any]: - name = (name or "").strip() - if not name or len(name) > 120: - raise RegistryError("client name must be 1-120 characters") - return {"id": self._client_id(name, create=True), "name": name} - - def create_project(self, client_id: Optional[int], name: str) -> Dict[str, Any]: - name = (name or "").strip() - if not name or len(name) > 120: - raise RegistryError("project name must be 1-120 characters") - if client_id is not None: - self._require("client", client_id) - found = self.conn.execute( - "SELECT id FROM project WHERE name = ? AND client_id IS ?", - (name, client_id), - ).fetchone() - if found: - return {"id": found[0], "client_id": client_id, "name": name} - with self.conn: - new_id = self.conn.execute( - "INSERT INTO project (client_id, name, created_at) VALUES (?, ?, ?)", - (client_id, name, now_iso()), - ).lastrowid - return {"id": new_id, "client_id": client_id, "name": name} - - def create_application(self, project_id: int, name: str) -> Dict[str, Any]: - name = (name or "").strip() - if not name or len(name) > 120: - raise RegistryError("application name must be 1-120 characters") - project = self._require("project", project_id) - found = self.conn.execute( - "SELECT id FROM application WHERE name = ? AND project_id = ?", - (name, project_id), - ).fetchone() - if found: - return {"id": found[0], "project_id": project_id, "name": name} - with self.conn: - new_id = self.conn.execute( - "INSERT INTO application (client_id, project_id, name, created_at)" - " VALUES (?, ?, ?, ?)", - (project["client_id"], project_id, name, now_iso()), - ).lastrowid - return {"id": new_id, "project_id": project_id, "name": name} - def _require(self, table: str, row_id: int) -> sqlite3.Row: if table not in ("client", "project", "application", "connection"): raise ValueError(table) @@ -368,41 +339,9 @@ def _require(self, table: str, row_id: int) -> sqlite3.Row: f"SELECT * FROM {table} WHERE id = ?", (row_id,) ).fetchone() if not row: - raise RegistryError(f"no {table} with id {row_id}") + raise NotFoundError(f"no {table} with id {row_id}") return row - def portfolio_tree(self) -> List[Dict[str, Any]]: - """Clients with their projects and applications (for pickers).""" - clients = [ - dict(r) - for r in self.conn.execute("SELECT id, name FROM client ORDER BY name") - ] - for client in clients: - client["projects"] = self._projects_for(client["id"]) - internal = self._projects_for(None) - if internal: - clients.insert(0, {"id": None, "name": "Internal", "projects": internal}) - return clients - - def _projects_for(self, client_id: Optional[int]) -> List[Dict[str, Any]]: - projects = [ - dict(r) - for r in self.conn.execute( - "SELECT id, name FROM project WHERE client_id IS ? ORDER BY name", - (client_id,), - ) - ] - for project in projects: - project["applications"] = [ - dict(r) - for r in self.conn.execute( - "SELECT id, name FROM application WHERE project_id = ?" - " ORDER BY name", - (project["id"],), - ) - ] - return projects - # -- source editing --------------------------------------------------- def update_source( self, @@ -412,13 +351,14 @@ def update_source( connection_id: Optional[int] = None, clear_connection: bool = False, ) -> Dict[str, Any]: - self.get_source(source_id) + """``client=""`` clears the client; ``None`` leaves it unchanged.""" + source = self.get_source(source_id) with self.conn: if client is not None: self.conn.execute( "UPDATE source SET client_id = ? WHERE id = ?", ( - self._client_id(client, create=True) if client else None, + self.client_id_for(client, current=source["client_id"]), source_id, ), ) diff --git a/tests/unit/test_api.py b/tests/unit/test_api.py index 84cb0bf7..aec8964e 100644 --- a/tests/unit/test_api.py +++ b/tests/unit/test_api.py @@ -230,6 +230,14 @@ def test_disable_edit_and_remove_a_source_keeps_repositories(admin): source = admin.post( "/api/sources", json={"type": "org", "identifier": "Acme"} ).json() + unknown = admin.patch( + f"/api/sources/{source['id']}", json={"enabled": False, "client": "Contoso"} + ) + assert unknown.status_code == 422 and unknown.json()["detail"]["code"] == ( + "unknown_name" + ) + assert admin.get("/api/sources").json()[0]["enabled"] is True # unchanged + admin.post("/api/clients", json={"name": "Contoso"}) patched = admin.patch( f"/api/sources/{source['id']}", json={"enabled": False, "client": "Contoso"} ) @@ -248,16 +256,24 @@ def test_exclude_and_assign_repositories_and_build_the_portfolio(admin): ).status_code == 200 ) - admin.patch( - "/api/repositories", - json={ - "full_name": "Acme/a", - "assign": True, - "client": "Contoso", - "project": "Website", - "application": "Public site", - }, + assignment = { + "full_name": "Acme/a", + "assign": True, + "client": "Contoso", + "project": "Website", + "application": "Public site", + } + rejected = admin.patch("/api/repositories", json=assignment) + assert rejected.status_code == 422 + assert rejected.json()["detail"]["code"] == "unknown_name" + client = admin.post("/api/clients", json={"name": "Contoso"}).json() + project = admin.post( + f"/api/clients/{client['id']}/projects", json={"name": "Website"} + ).json() + admin.post( + f"/api/projects/{project['id']}/applications", json={"name": "Public site"} ) + assert admin.patch("/api/repositories", json=assignment).status_code == 200 repos = {r["full_name"]: r for r in admin.get("/api/repositories").json()} assert repos["Acme/b"]["excluded"] is True assert repos["Acme/a"]["application"] == "Public site" diff --git a/tests/unit/test_classification.py b/tests/unit/test_classification.py new file mode 100644 index 00000000..8a61bee4 --- /dev/null +++ b/tests/unit/test_classification.py @@ -0,0 +1,351 @@ +"""Managed lists (clients, projects, applications) and classification domains.""" + +import sqlite3 + +import pytest + +from spark.registry import Registry, catalog, domains +from spark.registry.__main__ import main as registry_cli +from spark.registry.db import MIGRATIONS, connect, schema_version +from spark.registry.discovery import run_discovery +from spark.registry.export import build_portfolio +from spark.registry.store import NotFoundError, RegistryError, UnknownNameError +from tests.unit.registry_fakes import FakeGithub, make_repo + +REPOS = ["Acme/a", "Acme/b", "Acme/c"] + + +@pytest.fixture +def registry(tmp_path): + reg = Registry.open(tmp_path / "registry.db") + reg.add_source("org", "Acme") + run_discovery(reg, FakeGithub(orgs={"Acme": [make_repo(n) for n in REPOS]})) + yield reg + reg.close() + + +def held(registry, name): + repos = {r["full_name"]: r for r in registry.list_repositories()} + return domains.classifications(registry).get(repos[name]["id"]) + + +# -- migration ------------------------------------------------------------------ +def _v3_database(path): + """A registry as the previous release left it, with free-text names.""" + conn = sqlite3.connect(path) + for number, script in enumerate(MIGRATIONS[:3]): + conn.executescript(f"BEGIN;\n{script}\nPRAGMA user_version = {number + 1};") + stamp = "2026-11-01T00:00:00+00:00" + conn.executescript(f""" + INSERT INTO client (id, name, created_at) VALUES + (1, 'Contoso', '{stamp}'), (2, 'Contoso Corp', '{stamp}'); + INSERT INTO project (id, client_id, name, created_at) + VALUES (1, 1, 'Website', '{stamp}'); + INSERT INTO application (id, client_id, project_id, name, created_at) + VALUES (1, 1, 1, 'Public site', '{stamp}'); + INSERT INTO source (id, type, identifier, client_id, created_at) + VALUES (1, 'org', 'Acme', 2, '{stamp}'); + INSERT INTO repository (id, full_name, full_name_lower, owner, name, + client_id, project_id, application_id, first_seen_at, last_seen_at) + VALUES (1, 'Acme/a', 'acme/a', 'Acme', 'a', 1, 1, 1, '{stamp}', '{stamp}'); + INSERT INTO repository_source VALUES (1, 1); + """) + conn.commit() + conn.close() + + +def test_migration_keeps_existing_names_and_assignments(tmp_path): + path = tmp_path / "registry.db" + _v3_database(path) + registry = Registry.open(path) + assert schema_version(registry.conn) == len(MIGRATIONS) + assert (tmp_path / "registry.db.pre-v3.bak").exists() + repo = registry.list_repositories()[0] + assert (repo["client"], repo["project"], repo["application"]) == ( + "Contoso", + "Website", + "Public site", + ) + assert registry.get_source(1)["client_id"] == 2 + names = [c["name"] for c in catalog.tree(registry)] + assert names == ["Contoso", "Contoso Corp"] + # Near-duplicates are suggested, never merged on their own. + pair = catalog.duplicates(registry) + assert [(d["kind"], d["a"]["name"], d["b"]["name"]) for d in pair] == [ + ("client", "Contoso", "Contoso Corp") + ] + registry.close() + + +def test_seeded_domains_and_values(): + registry = Registry(connect(":memory:")) + seeded = {d["key"]: d for d in domains.list_domains(registry)} + assert list(seeded) == ["tier", "type", "lifecycle", "stack"] + assert [v["key"] for v in seeded["tier"]["values"]] == [ + "core", + "supporting", + "archive", + ] + assert {k: d["multi"] for k, d in seeded.items()} == { + "tier": False, + "type": False, + "lifecycle": False, + "stack": True, + } + assert len(seeded["type"]["values"]) == 7 + + +# -- managed names -------------------------------------------------------------- +def test_unknown_names_are_rejected_not_created(registry): + with pytest.raises(UnknownNameError, match="unknown client 'Contoso'"): + registry.associate_repository("acme/a", client="Contoso") + with pytest.raises(UnknownNameError): + registry.add_source("user", "Octo", client="Contoso") + with pytest.raises(UnknownNameError): + registry.update_source(1, client="Contoso") + assert catalog.tree(registry) == [] + with pytest.raises(NotFoundError): + registry.associate_repository("no/such") + + +def test_assignment_follows_the_hierarchy(registry): + contoso = catalog.create_client(registry, "Contoso") + fabrikam = catalog.create_client(registry, "Fabrikam") + web = catalog.create_project(registry, contoso["id"], "Website") + catalog.create_application(registry, web["id"], "Public site") + tools = catalog.create_project(registry, None, "Tools") # internal + registry.associate_repository( + "acme/a", client="Contoso", project="Website", application="Public site" + ) + registry.associate_repository("acme/b", project="Tools") + # A project is looked up under the chosen client only. + with pytest.raises(UnknownNameError): + registry.associate_repository("acme/c", client="Fabrikam", project="Website") + with pytest.raises(RegistryError, match="belongs to a project"): + registry.associate_repository("acme/c", application="Public site") + tree = catalog.tree(registry) + assert [c["name"] for c in tree] == ["Internal", "Contoso", "Fabrikam"] + assert tree[0]["projects"][0]["id"] == tools["id"] + assert tree[1]["repository_count"] == 1 and fabrikam["id"] == tree[2]["id"] + + +def test_names_are_unique_per_scope_and_trimmed(registry): + contoso = catalog.create_client(registry, " Contoso ") + assert contoso["name"] == "Contoso" + with pytest.raises(RegistryError, match="already"): + catalog.create_client(registry, "contoso") + other = catalog.create_client(registry, "Fabrikam") + catalog.create_project(registry, contoso["id"], "Website") + catalog.create_project(registry, other["id"], "Website") # other scope: fine + with pytest.raises(RegistryError, match="already"): + catalog.update(registry, "client", other["id"], name="CONTOSO") + for bad in ("", " ", "x" * 121): + with pytest.raises(RegistryError): + catalog.create_client(registry, bad) + + +def test_retired_entries_leave_pickers_but_stay_where_used(registry): + contoso = catalog.create_client(registry, "Contoso") + registry.associate_repository("acme/a", client="Contoso") + catalog.update(registry, "client", contoso["id"], retired=True) + assert catalog.tree(registry) == [] + assert catalog.tree(registry, include_retired=True)[0]["retired"] is True + assert registry.list_repositories()[0]["client"] == "Contoso" + registry.associate_repository("acme/a", client="Contoso") # unchanged: allowed + with pytest.raises(UnknownNameError, match="retired"): + registry.associate_repository("acme/b", client="Contoso") + catalog.update(registry, "client", contoso["id"], retired=False) + registry.associate_repository("acme/b", client="Contoso") + + +def test_merging_clients_moves_everything_and_retires_the_merged_one(registry): + keep = catalog.create_client(registry, "Contoso") + typo = catalog.create_client(registry, "Contosso") + keep_web = catalog.create_project(registry, keep["id"], "Website") + typo_web = catalog.create_project(registry, typo["id"], "website") + catalog.create_application(registry, typo_web["id"], "Shop") + catalog.create_project(registry, typo["id"], "Docs") + registry.update_source(1, client="Contosso") + registry.associate_repository( + "acme/a", client="Contosso", project="website", application="Shop" + ) + registry.associate_repository("acme/b", client="Contosso", project="Docs") + + moved = catalog.merge(registry, "client", typo["id"], keep["id"]) + + assert moved == {"repositories": 2, "sources": 1} + repos = {r["full_name"]: r for r in registry.list_repositories()} + assert (repos["Acme/a"]["client"], repos["Acme/a"]["project"]) == ( + "Contoso", + "Website", + ) + assert repos["Acme/a"]["application"] == "Shop" + assert repos["Acme/b"]["project"] == "Docs" + assert registry.get_source(1)["client_id"] == keep["id"] + tree = catalog.tree(registry) + assert [c["name"] for c in tree] == ["Contoso"] + projects = {p["name"]: p for p in tree[0]["projects"]} + assert set(projects) == {"Docs", "Website"} + assert projects["Website"]["id"] == keep_web["id"] + assert [a["name"] for a in projects["Website"]["applications"]] == ["Shop"] + + +def test_merge_is_refused_across_scopes_and_into_itself(registry): + a = catalog.create_client(registry, "A corp") + b = catalog.create_client(registry, "B corp") + pa = catalog.create_project(registry, a["id"], "Web") + pb = catalog.create_project(registry, b["id"], "Web 2") + with pytest.raises(RegistryError, match="same client"): + catalog.merge(registry, "project", pa["id"], pb["id"]) + with pytest.raises(RegistryError, match="different"): + catalog.merge(registry, "client", a["id"], a["id"]) + catalog.update(registry, "client", b["id"], retired=True) + with pytest.raises(RegistryError, match="retired"): + catalog.merge(registry, "client", a["id"], b["id"]) + with pytest.raises(NotFoundError): + catalog.merge(registry, "client", a["id"], 999) + + +def test_duplicate_suggestions(registry): + for name in ("Acme", "Acme, Inc.", "Northwind Traders", "Northwind Trader", "Beta"): + catalog.create_client(registry, name) + pairs = {(d["a"]["name"], d["b"]["name"]) for d in catalog.duplicates(registry)} + assert pairs == {("Acme", "Acme, Inc."), ("Northwind Traders", "Northwind Trader")} + + +# -- domains ---------------------------------------------------------------------- +def test_single_choice_holds_one_value_and_multi_holds_several(registry): + assert domains.classify(registry, ["acme/a"], "tier", ["core"]) == 1 + with pytest.raises(RegistryError, match="only one"): + domains.classify(registry, ["acme/a"], "tier", ["core", "archive"]) + with pytest.raises(RegistryError, match="single-choice"): + domains.classify(registry, ["acme/a"], "tier", ["archive"], mode="add") + domains.classify(registry, ["acme/a"], "tier", ["archive"]) # replaces + domains.classify(registry, ["acme/a"], "stack", ["python", "node-react"]) + domains.classify(registry, ["acme/a"], "stack", ["dotnet"], mode="add") + domains.classify(registry, ["acme/a"], "stack", ["python"], mode="remove") + assert held(registry, "Acme/a") == { + "tier": ["archive"], + "type": [], + "lifecycle": [], + "stack": ["dotnet", "node-react"], + } + domains.classify(registry, ["acme/a"], "tier", []) # clears + assert held(registry, "Acme/a")["tier"] == [] + + +def test_unknown_values_domains_and_repositories_change_nothing(registry): + with pytest.raises(RegistryError, match="unknown Tier value"): + domains.classify(registry, ["acme/a"], "tier", ["gold"]) + with pytest.raises(NotFoundError): + domains.classify(registry, ["acme/a"], "colour", ["red"]) + with pytest.raises(NotFoundError): + domains.classify(registry, ["acme/a", "no/such"], "tier", ["core"]) + assert held(registry, "Acme/a")["tier"] == [] # the batch was all or nothing + + +def test_bulk_classification_changes_exactly_the_selected(registry): + changed = domains.classify(registry, ["acme/a", "ACME/C"], "type", ["website"]) + assert changed == 2 + assert [held(registry, n)["type"] for n in REPOS] == [["website"], [], ["website"]] + assert domains.classify(registry, ["acme/a"], "type", ["website"]) == 0 + + +def test_retired_values_stay_where_used_but_cannot_be_newly_assigned(registry): + tier = {d["key"]: d for d in domains.list_domains(registry)}["tier"] + archive = next(v for v in tier["values"] if v["key"] == "archive") + domains.classify(registry, ["acme/a"], "tier", ["archive"]) + domains.update_value(registry, archive["id"], retired=True) + listed = {d["key"]: d for d in domains.list_domains(registry)}["tier"] + assert "archive" not in [v["key"] for v in listed["values"]] + assert held(registry, "Acme/a")["tier"] == ["archive"] + domains.classify(registry, ["acme/a"], "tier", ["archive"]) # kept: allowed + with pytest.raises(RegistryError, match="retired"): + domains.classify(registry, ["acme/b"], "tier", ["archive"]) + + +def test_values_in_use_are_retired_not_deleted(registry): + tier = {d["key"]: d for d in domains.list_domains(registry)}["tier"] + core, supporting = tier["values"][0], tier["values"][1] + domains.classify(registry, ["acme/a"], "tier", ["core"]) + with pytest.raises(RegistryError, match="in use"): + domains.delete_value(registry, core["id"]) + with pytest.raises(RegistryError, match="in use"): + domains.delete_domain(registry, tier["id"]) + domains.delete_value(registry, supporting["id"]) + keys = [v["key"] for v in domains.list_domains(registry)[0]["values"]] + assert keys == ["core", "archive"] + + +def test_custom_domains_and_switching_to_single_choice(registry): + hosting = domains.create_domain( + registry, key="Hosting", label="Hosting", multi=True + ) + assert hosting["key"] == "hosting" and hosting["multi"] is True + with pytest.raises(RegistryError, match="already exists"): + domains.create_domain(registry, key="hosting", label="Again") + with pytest.raises(RegistryError, match="key must be"): + domains.create_domain(registry, key="bad key", label="Bad") + for key in ("azure", "pages"): + domains.add_value(registry, hosting["id"], key=key, label=key.title()) + with pytest.raises(RegistryError, match="already has"): + domains.add_value(registry, hosting["id"], key="Azure", label="Dup") + domains.classify(registry, ["acme/a"], "hosting", ["azure", "pages"]) + with pytest.raises(RegistryError, match="several values"): + domains.update_domain(registry, hosting["id"], multi=False) + domains.classify(registry, ["acme/a"], "hosting", ["azure"]) + single = domains.update_domain(registry, hosting["id"], multi=False, label="Host") + assert single["multi"] is False and single["label"] == "Host" + renamed = domains.update_value(registry, single["values"][0]["id"], label="Azure") + assert renamed["key"] == "azure" # keys are stable; labels change freely + domains.update_domain(registry, hosting["id"], retired=True) + assert "hosting" not in held(registry, "Acme/a") + with pytest.raises(RegistryError, match="retired"): + domains.classify(registry, ["acme/b"], "hosting", ["azure"]) + + +def test_export_carries_classifications_and_explicit_unassigned(registry): + domains.classify(registry, ["acme/a"], "stack", ["python"]) + portfolio = build_portfolio(registry) + by_name = {r["full_name"]: r for r in portfolio["repositories"]} + assert by_name["Acme/a"]["classifications"]["stack"] == ["python"] + assert by_name["Acme/b"]["classifications"] == { + "tier": [], + "type": [], + "lifecycle": [], + "stack": [], + } + catalog_keys = [d["key"] for d in portfolio["domains"]] + assert catalog_keys == ["tier", "type", "lifecycle", "stack"] + stack = portfolio["domains"][3] + assert stack["multi"] is True and stack["values"][0]["label"] == ".NET" + + +def test_pruning_a_repository_removes_its_classification(registry): + domains.classify(registry, ["acme/a"], "tier", ["core"]) + registry.remove_source(1) + assert registry.prune_orphans() == 3 + rows = registry.conn.execute("SELECT COUNT(*) FROM repository_classification") + assert rows.fetchone()[0] == 0 + + +# -- CLI -------------------------------------------------------------------------- +def test_cli_rejects_unknown_names_unless_asked_to_create(tmp_path, capsys): + db = str(tmp_path / "cli.db") + seeded = Registry.open(db) + seeded.add_source("org", "Acme") + run_discovery(seeded, FakeGithub(orgs={"Acme": [make_repo("Acme/a")]})) + seeded.close() + assign = ["--db", db, "assign", "Acme/a", "--client", "Contoso"] + assert registry_cli([*assign, "--project", "Web"]) == 2 + assert "unknown client" in capsys.readouterr().err + assert registry_cli([*assign, "--project", "Web", "--create"]) == 0 + assert "created client 'Contoso'" in capsys.readouterr().out + assert registry_cli([*assign, "--project", "web", "--create"]) == 0 # reused + add = ["--db", db, "add", "user", "Octo", "--no-validate", "--client", "Fabrikam"] + assert registry_cli(add) == 2 + assert registry_cli([*add, "--create"]) == 0 + check = Registry.open(db) + assert check.list_repositories()[0]["project"] == "Web" + assert len(catalog.tree(check)[0]["projects"]) == 1 + check.close() diff --git a/tests/unit/test_classification_api.py b/tests/unit/test_classification_api.py new file mode 100644 index 00000000..793708e4 --- /dev/null +++ b/tests/unit/test_classification_api.py @@ -0,0 +1,168 @@ +"""Admin API routes for managed lists and classification domains.""" + +import pytest +from fastapi.testclient import TestClient + +from spark.api import security +from spark.api.app import create_app +from spark.registry import Registry +from spark.registry.secrets import SecretBox, generate_key +from tests.unit.registry_fakes import make_repo +from tests.unit.test_api import PASSWORD, TokenAwareGithub + + +@pytest.fixture +def admin(tmp_path): + db_path = tmp_path / "registry.db" + registry = Registry.open(db_path) + security.create_admin(registry, "admin", PASSWORD) + registry.close() + world = dict(orgs={"Acme": [make_repo("Acme/a"), make_repo("Acme/b")]}) + app = create_app( + db_path, + secret_box=SecretBox(generate_key()), + github_factory=lambda token: TokenAwareGithub(token, **world), + default_token="default-token", + ) + client = TestClient(app, base_url="http://testserver") + signed_in = client.post( + "/api/session", json={"username": "admin", "password": PASSWORD} + ) + client.headers["X-CSRF-Token"] = signed_in.json()["csrf_token"] + client.post("/api/sources", json={"type": "org", "identifier": "Acme"}) + return client + + +def detail(response): + return response.json()["detail"] + + +def test_new_routes_require_sign_in(tmp_path): + app = create_app(tmp_path / "r.db") + client = TestClient(app, base_url="http://testserver") + for method, path in [ + ("get", "/api/portfolio/duplicates"), + ("get", "/api/domains"), + ("post", "/api/domains"), + ("patch", "/api/domains/1"), + ("delete", "/api/domains/1"), + ("post", "/api/domains/1/values"), + ("patch", "/api/domain-values/1"), + ("delete", "/api/domain-values/1"), + ("post", "/api/repositories/classify"), + ("post", "/api/projects"), + ("patch", "/api/clients/1"), + ("post", "/api/clients/1/merge"), + ("patch", "/api/projects/1"), + ("post", "/api/applications/1/merge"), + ]: + assert getattr(client, method)(path).status_code == 401, (method, path) + + +def test_writes_require_the_csrf_token(admin): + del admin.headers["X-CSRF-Token"] + response = admin.post("/api/domains", json={"key": "x", "label": "X"}) + assert response.status_code == 403 + + +def test_list_entries_can_be_renamed_retired_and_merged(admin): + keep = admin.post("/api/clients", json={"name": "Contoso"}).json() + typo = admin.post("/api/clients", json={"name": "Contoso Inc"}).json() + internal = admin.post("/api/projects", json={"name": "Tools"}) + assert internal.status_code == 201 and internal.json()["client_id"] is None + pairs = admin.get("/api/portfolio/duplicates").json() + assert pairs[0]["a"]["id"] == keep["id"] and pairs[0]["b"]["id"] == typo["id"] + + admin.patch("/api/sources/1", json={"client": "Contoso Inc"}) + merged = admin.post( + f"/api/clients/{typo['id']}/merge", json={"into_id": keep["id"]} + ) + assert merged.json() == {"repositories": 0, "sources": 1} + assert admin.get("/api/sources").json()[0]["client"] == "Contoso" + names = [c["name"] for c in admin.get("/api/portfolio").json()] + assert names == ["Internal", "Contoso"] + everything = admin.get("/api/portfolio", params={"include_retired": True}).json() + assert [c["retired"] for c in everything] == [False, False, True] + + renamed = admin.patch(f"/api/clients/{keep['id']}", json={"name": "Contoso Ltd"}) + assert renamed.json()["name"] == "Contoso Ltd" + clash = admin.patch(f"/api/clients/{keep['id']}", json={"name": "contoso inc"}) + assert clash.status_code == 422 and detail(clash)["code"] == "invalid" + retired = admin.patch(f"/api/clients/{keep['id']}", json={"retired": True}) + assert retired.json()["retired"] is True + assert admin.patch("/api/clients/999", json={"name": "x"}).status_code == 404 + same = admin.post(f"/api/clients/{keep['id']}/merge", json={"into_id": keep["id"]}) + assert same.status_code == 422 + + +def test_unknown_client_on_a_new_source_is_rejected_before_saving(admin): + response = admin.post( + "/api/sources", json={"type": "user", "identifier": "Octo", "client": "Nope"} + ) + assert response.status_code == 422 and detail(response)["code"] == "unknown_name" + assert [s["identifier"] for s in admin.get("/api/sources").json()] == ["Acme"] + + +def test_domains_can_be_managed(admin): + seeded = admin.get("/api/domains").json() + assert [d["key"] for d in seeded] == ["tier", "type", "lifecycle", "stack"] + created = admin.post( + "/api/domains", json={"key": "hosting", "label": "Hosting", "multi": True} + ) + assert created.status_code == 201 + domain_id = created.json()["id"] + value = admin.post( + f"/api/domains/{domain_id}/values", json={"key": "azure", "label": "Azure"} + ).json() + assert value["repository_count"] == 0 + edited = admin.patch(f"/api/domain-values/{value['id']}", json={"label": "AZ"}) + assert edited.json()["label"] == "AZ" + bad = admin.post("/api/domains", json={"key": "has space", "label": "X"}) + assert bad.status_code == 422 + assert admin.delete(f"/api/domain-values/{value['id']}").status_code == 204 + retired = admin.patch(f"/api/domains/{domain_id}", json={"retired": True}) + assert retired.json()["retired"] is True + assert "hosting" not in [d["key"] for d in admin.get("/api/domains").json()] + listed = admin.get("/api/domains", params={"include_retired": True}).json() + assert "hosting" in [d["key"] for d in listed] + assert admin.delete(f"/api/domains/{domain_id}").status_code == 204 + assert admin.delete(f"/api/domains/{domain_id}").status_code == 404 + + +def test_repositories_are_classified_singly_and_in_bulk(admin): + bulk = admin.post( + "/api/repositories/classify", + json={"full_names": ["Acme/a", "Acme/b"], "domain": "type", "values": ["api"]}, + ) + assert bulk.json() == {"changed": 2} + admin.post( + "/api/repositories/classify", + json={"full_names": ["Acme/a"], "domain": "stack", "values": ["python"]}, + ) + repos = {r["full_name"]: r for r in admin.get("/api/repositories").json()} + assert repos["Acme/a"]["classifications"] == { + "tier": [], + "type": ["api"], + "lifecycle": [], + "stack": ["python"], + } + assert repos["Acme/b"]["classifications"]["stack"] == [] + two = admin.post( + "/api/repositories/classify", + json={ + "full_names": ["Acme/a"], + "domain": "tier", + "values": ["core", "archive"], + }, + ) + assert two.status_code == 422 + missing = admin.post( + "/api/repositories/classify", + json={"full_names": ["no/such"], "domain": "tier", "values": ["core"]}, + ) + assert missing.status_code == 404 + empty = admin.post( + "/api/repositories/classify", + json={"full_names": [], "domain": "tier", "values": []}, + ) + assert empty.status_code == 422 diff --git a/tests/unit/test_registry.py b/tests/unit/test_registry.py index bd396ae3..ec0a513c 100644 --- a/tests/unit/test_registry.py +++ b/tests/unit/test_registry.py @@ -6,7 +6,7 @@ import pytest from github import GithubException -from spark.registry import Registry, collection_users, seed_users +from spark.registry import Registry, catalog, collection_users, seed_users from spark.registry.db import MIGRATIONS, connect, schema_version from spark.registry.discovery import ( classify_error, @@ -172,6 +172,9 @@ def test_associations_are_optional_and_reflected_in_the_export(registry): gh = FakeGithub(orgs={"Acme": [make_repo("Acme/a"), make_repo("Acme/b")]}) registry.add_source("org", "Acme") run_discovery(registry, gh) + client = catalog.create_client(registry, "Contoso") + project = catalog.create_project(registry, client["id"], "Website") + catalog.create_application(registry, project["id"], "Public site") registry.associate_repository( "acme/a", client="Contoso", project="Website", application="Public site" ) From d7eb4019d785b085c9ac0225459faf63b0b19292 Mon Sep 17 00:00:00 2001 From: Mark Hazleton Date: Sat, 21 Nov 2026 17:40:47 -0600 Subject: [PATCH 2/3] fix(pr-7): address L-01, L-02 - Validate a repository assignment before saving the excluded flag, so a rejected PATCH leaves the repository unchanged. - Keep domain headings to the label; the Rename control sits beside them. Co-Authored-By: Claude Opus 5.5 --- .../src/components/Admin/Admin.module.css | 11 ++++ .../src/components/Admin/DomainsPanel.jsx | 50 ++++++++++++------- frontend/tests/Classification.test.jsx | 11 ++++ src/spark/api/app.py | 6 ++- tests/unit/test_api.py | 12 +++++ 5 files changed, 70 insertions(+), 20 deletions(-) diff --git a/frontend/src/components/Admin/Admin.module.css b/frontend/src/components/Admin/Admin.module.css index 443889db..4db76ba9 100644 --- a/frontend/src/components/Admin/Admin.module.css +++ b/frontend/src/components/Admin/Admin.module.css @@ -229,6 +229,17 @@ border-top: 1px solid var(--color-border); } +.titleRow { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.titleRow h3 { + margin: 0; +} + .srOnly { position: absolute; width: 1px; diff --git a/frontend/src/components/Admin/DomainsPanel.jsx b/frontend/src/components/Admin/DomainsPanel.jsx index e4f9f1b3..85812561 100644 --- a/frontend/src/components/Admin/DomainsPanel.jsx +++ b/frontend/src/components/Admin/DomainsPanel.jsx @@ -79,13 +79,27 @@ NewEntryForm.propTypes = { onAdd: PropTypes.func.isRequired, }; -function Renamable({ id, label, onRename }) { +/** + * A label with a Rename control. With `headingId` the label is rendered as a + * heading and the control sits beside it, so the heading holds only the label. + */ +function Renamable({ id, label, onRename, headingId }) { const [editing, setEditing] = useState(false); const [value, setValue] = useState(label); + const heading = headingId ?

{label}

: null; + const wrap = (content) => + heading ? ( +
+ {heading} + {content} +
+ ) : ( + content + ); if (!editing) { - return ( + return wrap( <> - {label}{" "} + {!heading && {label}}{" "} - + , ); } - return ( + return wrap( { @@ -125,7 +139,7 @@ function Renamable({ id, label, onRename }) { - + , ); } @@ -133,6 +147,7 @@ Renamable.propTypes = { id: PropTypes.string.isRequired, label: PropTypes.string.isRequired, onRename: PropTypes.func.isRequired, + headingId: PropTypes.string, }; /** @@ -212,18 +227,17 @@ export default function DomainsPanel({ onUnauthorized, onChanged }) { className={styles.domain} aria-labelledby={`domain-${domain.id}-title`} > -

- - run( - () => adminApi.editDomain(domain.id, { label }), - `Renamed to ${label}.`, - ) - } - /> -

+ + run( + () => adminApi.editDomain(domain.id, { label }), + `Renamed to ${label}.`, + ) + } + />

Key {domain.key} ·{" "} {domain.multi ? "multi-choice" : "single-choice"} diff --git a/frontend/tests/Classification.test.jsx b/frontend/tests/Classification.test.jsx index 5de69129..04d8cd2b 100644 --- a/frontend/tests/Classification.test.jsx +++ b/frontend/tests/Classification.test.jsx @@ -395,6 +395,17 @@ describe("", () => { ); }); + it("keeps domain headings to the label, with rename beside them", async () => { + const user = userEvent.setup(); + render( {}} />); + const heading = await screen.findByRole("heading", { name: "Tier" }); + expect(screen.getByRole("article", { name: "Tier" })).toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "Rename Tier" })); + const input = screen.getByLabelText("New label for Tier"); + expect(heading).not.toContainElement(input); + expect(screen.getByRole("heading", { name: "Tier" })).toBeInTheDocument(); + }); + it("offers delete only for unused values and retire for all", async () => { render( {}} />); const table = await screen.findByRole("table", { name: "Tier values" }); diff --git a/src/spark/api/app.py b/src/spark/api/app.py index a4c7902e..1e35a9b2 100644 --- a/src/spark/api/app.py +++ b/src/spark/api/app.py @@ -337,8 +337,8 @@ def edit_repository( registry: Registry = Depends(get_registry), ) -> Dict[str, bool]: try: - if body.excluded is not None: - registry.set_repository_excluded(body.full_name, body.excluded) + # The assignment is validated (and rejected) before anything is + # written, so a refused request leaves the repository unchanged. if body.assign: registry.associate_repository( body.full_name, @@ -346,6 +346,8 @@ def edit_repository( project=body.project or None, application=body.application or None, ) + if body.excluded is not None: + registry.set_repository_excluded(body.full_name, body.excluded) except RegistryError as error: raise http_error(error) from error return {"ok": True} diff --git a/tests/unit/test_api.py b/tests/unit/test_api.py index aec8964e..575e4d74 100644 --- a/tests/unit/test_api.py +++ b/tests/unit/test_api.py @@ -266,6 +266,18 @@ def test_exclude_and_assign_repositories_and_build_the_portfolio(admin): rejected = admin.patch("/api/repositories", json=assignment) assert rejected.status_code == 422 assert rejected.json()["detail"]["code"] == "unknown_name" + combined = admin.patch( + "/api/repositories", + json={ + "full_name": "acme/a", + "excluded": True, + "assign": True, + "client": "Nope", + }, + ) + assert combined.status_code == 422 + repos = {r["full_name"]: r for r in admin.get("/api/repositories").json()} + assert repos["Acme/a"]["excluded"] is False # rejected request changed nothing client = admin.post("/api/clients", json={"name": "Contoso"}).json() project = admin.post( f"/api/clients/{client['id']}/projects", json={"name": "Website"} From 97f6d3a79c25e59232c9fcfccb4512ff3a371c29 Mon Sep 17 00:00:00 2001 From: Mark Hazleton Date: Sat, 21 Nov 2026 17:41:29 -0600 Subject: [PATCH 3/3] =?UTF-8?q?review(pr-7):=20rev=204=20=E2=80=94=202=20f?= =?UTF-8?q?ixed,=200=20remaining?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit L-01 and L-02 remediated in d7eb401 and awaiting independent verification. Co-Authored-By: Claude Opus 5.5 --- .devspark.work/pr-review/pr-7.md | 293 +++++++++++++++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100644 .devspark.work/pr-review/pr-7.md diff --git a/.devspark.work/pr-review/pr-7.md b/.devspark.work/pr-review/pr-7.md new file mode 100644 index 00000000..28cdfe03 --- /dev/null +++ b/.devspark.work/pr-review/pr-7.md @@ -0,0 +1,293 @@ +--- +pr: 7 +devspark_version: 9.6.0 +reviewed_commit: 62933a48d8811aaf43c0719e4ee40372b5b72a46 +revision: 4 +findings: &id001 + critical: 0 + high: 0 + medium: 0 + low: 2 + con: 0 +historical_findings: *id001 +current_findings: + critical: 0 + high: 0 + medium: 0 + low: 2 +current_state_counts: + open: 0 + remediated: 0 + awaiting-verification: 2 + reopened: 0 + resolved: 0 +unresolved_blockers: 0 +recommendation: approve +gate_status: pass +max_severity: low +risk_rating: high +risk_score: 8 +risk_escalated: false +review_state: + format_version: 1 + findings: + - finding_id: L-01 + aliases: [] + severity: low + category: correctness + blocking: false + description: PATCH /api/repositories commits an `excluded` change before validating + the assignment names, so a request that carries both and is rejected for an + unknown or retired name still changes the repository. The same ordering was + fixed for sources in this PR; this PR makes the assignment step reject far more + input than before (unknown names used to be created). + expected_outcome: A rejected repository PATCH leaves the repository unchanged, + matching edit_source. + evidence: + - src/spark/api/app.py:340-348 — `set_repository_excluded(...)` runs before `associate_repository(...)`, + which now raises UnknownNameError for unknown/retired names + - 'Consumer trace: the admin UI sends `excluded` and `assign` in separate requests + (RepositoriesPanel.jsx), so no current caller combines them; unconfirmed risk, + Low' + recommended_action: 'Resolve the client/project/application before writing: validate + the assignment first (for example call associate_repository before set_repository_excluded, + or resolve the names up front as edit_source does), and add a test that a combined + PATCH with an unknown client leaves `excluded` unchanged.' + execution_mode: manual + status: awaiting-verification + outcome: '' + provenance: + kind: native + location: src/spark/api/app.py:340 + remediation: + correction_commit: d7eb4019d785b085c9ac0225459faf63b0b19292 + author_context: Claude Code session that authored the PR (same session as the + review) + explanation: 'edit_repository now calls associate_repository, which resolves + and rejects unknown or retired names, before set_repository_excluded, so a + rejected combined PATCH writes nothing. Regression test: a PATCH with excluded=true + and an unknown client returns 422 and leaves excluded false.' + author_validation: './run-validation.ps1 exit 0 at d7eb4019d785b085c9ac0225459faf63b0b19292: + black, flake8, mypy (76 files), pytest 572 passed, vitest 169 passed, build, + audits.' + proof_obligation: A distinct reviewer confirms that a combined excluded+assign + PATCH that fails validation leaves the repository unchanged, and that the + valid combined path still applies both changes. + verification: null + disposition: null + reopen_reason: null + - finding_id: L-02 + aliases: [] + severity: low + category: accessibility + blocking: false + description: Each domain's

contains the Rename button, and while renaming + it contains a
with an input. A form is not permitted inside a heading + (headings allow phrasing content only), and the heading's accessible name becomes + 'Tier Rename Tier', which also names the
through aria-labelledby. + expected_outcome: Domain headings contain only the domain label; the rename control + sits beside the heading. + evidence: + - frontend/src/components/Admin/DomainsPanel.jsx:215-226 — `

` + - frontend/src/components/Admin/DomainsPanel.jsx:92 — Rename button `aria-label={`Rename + ${label}`}` rendered inside the heading + recommended_action: Render the label alone in the

and place Renamable's button/form + after it (for example a header row div containing the h3 and the control), keeping + aria-labelledby pointed at the h3. + execution_mode: manual + status: awaiting-verification + outcome: '' + provenance: + kind: native + location: frontend/src/components/Admin/DomainsPanel.jsx:215 + remediation: + correction_commit: d7eb4019d785b085c9ac0225459faf63b0b19292 + author_context: Claude Code session that authored the PR (same session as the + review) + explanation: 'Renamable takes a headingId; the h3 now holds only the domain + label and the Rename button or rename form renders beside it in a title row. + The article stays labelled by the h3. Regression test: the heading and article + are named exactly ''Tier'' and the rename input is not inside the heading.' + author_validation: './run-validation.ps1 exit 0 at d7eb4019d785b085c9ac0225459faf63b0b19292: + black, flake8, mypy (76 files), pytest 572 passed, vitest 169 passed, build, + audits.' + proof_obligation: A distinct reviewer confirms that each domain heading's accessible + name is the label alone, both before and while renaming, and that no form + sits inside a heading. + verification: null + disposition: null + reopen_reason: null + conditions: [] + last_change: + operation: remediate-and-submit + affected: + - L-02 + event_fingerprint: 8633007bc3088c024a30850c3ef2dad9361dbd7867617ebfa37acc74c271349c + actor_role: '' + actor_context: '' + explanation: '' +--- +# Pull Request Review: feat(registry): managed lists and classification domains + +- **PR**: #7 — 001-work-ps-023-classification-domains → main — @markhazleton — OPEN +- **Reviewed Commit**: 62933a48d8811aaf43c0719e4ee40372b5b72a46 +- **Review Date**: 2026-11-21 21:39:28 UTC (last updated 2026-11-21 21:39:28 UTC) +- **Constitution Version**: 1.2.0 + +## Revision Log + +| Rev | Commit | Date | Critical | High | Medium | Low | CON | Test Command | Result | +|-----|--------|------|----------|------|--------|-----|-----|--------------|--------| +| 1 | 62933a4 | 2026-11-21 | 0 | 0 | 0 | 2 | 0 | reused: CI `validate` run 44951807850 on 62933a4; local `./run-validation.ps1` | pass | + +## Test Evidence + +- reused: GitHub Actions `validate` (run 44951807850, job 136991190205) on commit 62933a4 — pass in 1m34s. It runs `run-validation.ps1`: pip check, black, flake8, mypy, pytest, config validate, pip-audit, npm ci, lint, format check, vitest with coverage, build, npm audit. +- reused: local `./run-validation.ps1` on the same tree before commit — exit 0; pytest 572 passed, vitest 168 passed, pip-audit and npm audit clean. No rerun was triggered: the reviewed commit is the one CI validated. + +## Stats + +| Metric | Value | +|--------|-------| +| Files changed | 26 | +| Commits | 1 | +| Lines | +3842 −325 | +| Tiers (P0/P1/P2/P3) | 2 / 17 / 6 / 1 | +| Risk | high (8) — p0_files, large_diff; Knowledge absent (live) | + +## Executive Summary + +**Overall Assessment**: A sound, well-tested change. Managed lists and domains are enforced in the store, so the API, the CLI and the UI all apply the same rules, and the migration keeps existing data. Two Low, nonblocking findings. Knowledge status is `absent` (`.knowledge/` holds no claims), so file tiers came from path patterns alone. I reviewed `db.py` (schema), `store.py` (data access) and `catalog_routes.py`/`app.py` (routes) at P0 depth although the script placed them in P1. **Independence:** this review was produced by the same agent session that wrote the change, so it is not an independent review; a human or separate reviewer should still read it before merging. + +- Constitution: PASS (6 applicable principles evaluated) · Durable delta: PASS (0 open PRD findings) +- Security: 0 issues · Quality: 2 recommendations · Testing: PASS · Docs: PASS +- Constitution Improvements: 0 CON findings + + +## Action Items + +### Immediate Actions (Blocking) + +- None found. + +### Recommended Improvements + +- [ ] **L-01** [awaiting-verification] — PATCH /api/repositories commits an `excluded` change before validating the assignment names, so a request that carries both and is rejected for an unknown or retired name still changes the repository. The same ordering was fixed for sources in this PR; this PR makes the assignment step reject far more input than before (unknown names used to be created). +- [ ] **L-02** [awaiting-verification] — Each domain's

contains the Rename button, and while renaming it contains a with an input. A form is not permitted inside a heading (headings allow phrasing content only), and the heading's accessible name becomes 'Tier Rename Tier', which also names the
through aria-labelledby. + +### Constitution Improvements + +- None. + + +## Findings Detail + +| ID | Status | Severity | Blocking | Issue | Expected outcome | Evidence | +| --- | --- | --- | --- | --- | --- | --- | +| L-01 | Pending verification | low | No | PATCH /api/repositories commits an `excluded` change before validating the assignment names, so a request that carries both and is rejected for an unknown or retired name still changes the repository. The same ordering was fixed for sources in this PR; this PR makes the assignment step reject far more input than before (unknown names used to be created). | A rejected repository PATCH leaves the repository unchanged, matching edit_source. | src/spark/api/app.py:340-348 — `set_repository_excluded(...)` runs before `associate_repository(...)`, which now raises UnknownNameError for unknown/retired names; Consumer trace: the admin UI sends `excluded` and `assign` in separate requests (RepositoriesPanel.jsx), so no current caller combines them; unconfirmed risk, Low | +| L-02 | Pending verification | low | No | Each domain's

contains the Rename button, and while renaming it contains a with an input. A form is not permitted inside a heading (headings allow phrasing content only), and the heading's accessible name becomes 'Tier Rename Tier', which also names the
through aria-labelledby. | Domain headings contain only the domain label; the rename control sits beside the heading. | frontend/src/components/Admin/DomainsPanel.jsx:215-226 — `

`; frontend/src/components/Admin/DomainsPanel.jsx:92 — Rename button `aria-label={`Rename ${label}`}` rendered inside the heading | + + +## Constitution Alignment Details + +**Passing**: 6 of 6 applicable principles — I Single Responsibility (new modules all under 500 LOC; `store.py` at 521 now carries the required size justification), II Data Privacy (no private data; classifications are administrator-entered and exported only to the self-hosted data root), III Fail Fast, Fail Loud (unknown/retired names and refused deletes return messages that say what to do), V Accessibility First (labelled controls, fieldsets for multi-choice, existing colour tokens), VII Self-Hosted Mode (every new route requires a session, writes require CSRF; covered by tests), Governance (no new dependencies). IV and VI not applicable. + +## Testing + +**Status**: ADEQUATE — new pytest and vitest suites cover the new behavior, including a migration from the previous schema; CI passed on the reviewed commit. + +| File | Changes | Type | +|------|---------|------| +| frontend/tests/Classification.test.jsx | +426 -0 | Added | +| frontend/tests/SourcesView.test.jsx | +46 -1 | Modified | +| tests/unit/test_api.py | +25 -9 | Modified | +| tests/unit/test_classification.py | +351 -0 | Added | +| tests/unit/test_classification_api.py | +168 -0 | Added | +| tests/unit/test_registry.py | +4 -1 | Modified | + +No tests were removed. Two existing tests changed expectations to match the intended behavior (unknown names are now rejected): `test_disable_edit_and_remove_a_source_keeps_repositories` and `test_exclude_and_assign_repositories_and_build_the_portfolio` — justified; they now also assert the rejection. + +## Changed Files + +| File | Tier | Changes | Type | +|------|------|---------|------| +| frontend/src/components/Admin/RepositoriesPanel.jsx | P0 | +212 -118 | Modified | +| frontend/src/components/Admin/RepositoryEditor.jsx | P0 | +184 -0 | Added | +| frontend/src/components/Admin/Admin.module.css | P1 | +106 -0 | Modified | +| frontend/src/components/Admin/BulkClassify.jsx | P1 | +109 -0 | Added | +| frontend/src/components/Admin/DomainsPanel.jsx | P1 | +373 -0 | Added | +| frontend/src/components/Admin/ListEntry.jsx | P1 | +146 -0 | Added | +| frontend/src/components/Admin/ListsPanel.jsx | P1 | +253 -0 | Added | +| frontend/src/components/Admin/SourcesPanel.jsx | P1 | +22 -3 | Modified | +| frontend/src/components/Admin/SourcesView.jsx | P1 | +19 -2 | Modified | +| frontend/src/components/Admin/portfolioOptions.js | P1 | +84 -0 | Added | +| frontend/src/services/adminApi.js | P1 | +29 -1 | Modified | +| src/spark/api/app.py | P1 | +17 -54 | Modified | +| src/spark/api/catalog_routes.py | P1 | +245 -0 | Added | +| src/spark/registry/__main__.py | P1 | +47 -2 | Modified | +| src/spark/registry/catalog.py | P1 | +356 -0 | Added | +| src/spark/registry/db.py | P1 | +70 -0 | Modified | +| src/spark/registry/domains.py | P1 | +446 -0 | Added | +| src/spark/registry/export.py | P1 | +16 -0 | Modified | +| src/spark/registry/store.py | P1 | +72 -132 | Modified | +| frontend/tests/Classification.test.jsx | P2 | +426 -0 | Added | +| frontend/tests/SourcesView.test.jsx | P2 | +46 -1 | Modified | +| tests/unit/test_api.py | P2 | +25 -9 | Modified | +| tests/unit/test_classification.py | P2 | +351 -0 | Added | +| tests/unit/test_classification_api.py | P2 | +168 -0 | Added | +| tests/unit/test_registry.py | P2 | +4 -1 | Modified | +| .documentation/guides/DOCKER_DEPLOYMENT.md | P3 | +16 -2 | Modified | + +## Behavioral Changes + +| Change | Before | After | Intentional? | Risk | +|--------|--------|-------|-------------|------| +| Assigning an unknown client/project/application (`PATCH /api/repositories`, `POST`/`PATCH /api/sources`, CLI `add`/`assign`) | Name created on first use | 422 `unknown_name` (CLI exit 2; `--create` restores the old behavior on purpose) | Yes (PR description) | Scripts that relied on implicit creation must create names first or pass `--create` | +| `POST /api/clients` and the project/application create routes with an existing name | Returned the existing entry (idempotent) | 422 `invalid` ("already an existing client here") | Yes (names are unique per scope) | No in-repo caller relied on idempotency | +| `Registry.create_client/create_project/create_application/portfolio_tree` | Methods on `Registry` | Functions in `spark.registry.catalog` | Yes (refactor) | Only `app.py` called them; updated | +| `GET /api/portfolio`, `GET /api/repositories`, `portfolio.json` | — | Additive fields: `retired`, usage counts, `classifications`, `domains` | Yes | Additive; `schema_version` stays 1 | +| `PATCH /api/sources/{id}` with an invalid client | `enabled` change saved, then failed | Nothing saved; 422 | Yes (fix) | None | + +## Deployment & Handoff Notes + +### Deployment Notes + +- Migration 4 runs on first start against the server registry; the existing pre-migration copy (`registry.db.pre-v3.bak`) is written automatically. After deploy, the administrator should check the Lists tab for existing clients and suggested duplicates (already listed in the PR description). + +### Handoff Notes + +- DevSpark tooling — owned by the DevSpark framework — `.devspark/scripts/bash/get-pr-context.sh` emits invalid JSON when the PR body has CRLF line endings (it splits the string on `\r`); the PowerShell script works. Not a defect of this PR. + +### Observations + +- Bulk selection is kept after an apply and across filter changes, so a later bulk action can include rows the current filter hides; the "N selected" count states this. It matches "changes exactly the selected repositories"; clearing the selection after a successful apply would be a reasonable follow-up, not a defect. +- Saving the repository editor issues one assignment request and one classify request per changed domain; a failure partway leaves earlier requests applied. The panel reports the error and reloads, so the screen shows what was saved. Acceptable for a single administrator. +- After merging a client whose project matches a same-named project under the target, the retired duplicate application rows keep a `client_id` that no longer matches their retired project's client. They are retired and unused, so nothing reads the mismatch. +- Classifications are exported to `portfolio.json` only, not to per-source `repositories.json`; the PR description states this exclusion. + + +## Approval Decision + +**Recommendation**: APPROVE — derived from current blockers and applicable review conditions. + +*This local recommendation does not cast a hosted approval vote or authorize merge.* + + +--- + +*Re-review after fixes: `/devspark-pr-review #7 re-review`. Address findings with `/devspark-address-pr-review 7`; commit the review file on its own.* + +--- + + +## Current Review State + +- Historical unique findings: 2 +- Current unresolved findings by severity: {'critical': 0, 'high': 0, 'medium': 0, 'low': 2} +- Current lifecycle state counts: {'open': 0, 'remediated': 0, 'awaiting-verification': 2, 'reopened': 0, 'resolved': 0} +- Unresolved blockers: 0 +- Pending independent verification: 2 +- Review conditions: pass +- Local recommendation: approve +