Make main the lean product a site receives

main was 16 days and 259 commits behind the line the product is actually built
on, at contract 0.30.0 against 0.35.0, with no per-PC credential code at all. It
was neither current nor curated - just stale. This brings it forward and, at the
same time, makes it mean something: main is what a receiving site installs, and
nothing else.

WHAT IT CARRIES. Twelve plugins - backups, computers, endpoints, guides,
knowledgebase, machines, network, notifications, printers, slides, tools,
warranty - plus applications, which is manifest-less core and always ships. The
only manifest dependency inside that set is endpoints on computers, and both are
in it, so the closure is self-contained.

WHAT IT DOES NOT. employees, geenforce, measuringtools, printedparts and usb
stay on the site line. So do the Windows installer tree, the VM rehearsal
helpers, the agent tooling config, one site's data loader, the internal audit
and findings records, and the planner spreadsheet. 1,135 tracked files against
1,438.

A REMOVAL THAT BREAKS THE APP IS NOT A REMOVAL, and two nearly shipped:

deploy/site-profile-universal.json still named all seventeen plugins. It is the
file docs/DEPLOY.md tells a site to provision from, so a fresh install would
have failed at `flask plugin apply-profile` with PluginError - the first thing a
receiving site does, broken by the branch meant to serve them. It now names the
twelve that exist, and its comment says the two must agree.

agent/ was never refreshed. Whoever populated this branch copied shopdb/,
plugins/, frontend/ and tests/ from the site line and left the agent tree at its
September state: 22 C# and PowerShell sources missing, including AgentCredentials,
EnrollmentService, AgentHttpFactory and the fleet-alert client, plus one file the
site line had deleted still present. The old tree is internally consistent, so it
compiles, and nothing in CI builds it - every gate was green over a server that
speaks enrollment and per-PC credentials to a bundled agent source that cannot.
Resynced whole.

DECISIONS THIS ENCODES, rather than defers:

- The plugin-authoring lab builds printedparts, whose manifest depends on
  employees, so it could not stay. The lab remains on the site line and main
  ships no build-along tutorial. That is a real loss for an adopting developer
  and is recorded here rather than discovered later.
- Recognition, Training and Recertification notifications are no longer seeded.
  Each splits one notification into a card per employee and renders a photo,
  which needs a plugin this branch does not bundle. Seeding them would offer an
  author a type that cannot resolve anybody. A site that installs employees gets
  them from that plugin's own seed.
- Windows/IIS is documented as the legacy path throughout, and the README leads
  with Docker, because that is what a receiving site gets.

The API description is regenerated for THIS branch - 347 paths and 483
operations, down from 415 and 573 - so the published contract describes what is
here rather than what the site line serves. docs/CONFIG.md lost the two
measuring-tool label keys the code no longer declares, which two lanes had
decided opposite ways.

Suite: 3124 passed, 6 skipped. Naming and style gates pass. The docs gates run
rather than skip, and every index line count is derived from the file it names.
This commit is contained in:
cproudlock
2026-09-19 11:24:40 -04:00
parent cb3975049c
commit 534f179ee6
675 changed files with 115759 additions and 60239 deletions

View File

@@ -1,4 +1,17 @@
"""Base plugin class that all plugins must inherit from."""
"""Base plugin class that all plugins must inherit from.
One rule that is not expressible as a method signature, so it lives here where
a plugin author reads it: A PLUGIN MUST NOT HOLD A DB SESSION ACROSS EXTERNAL
I/O. Finish with the database, then make the HTTP call / run the subprocess /
touch the share, then open a fresh session to write the result. Under gevent a
slow external call does not block its worker, but it does pin one of that
worker's pooled database connections for its whole duration, and enough
concurrent greenlets on such a path drain the pool and stall every other
request in the process - the whole site, every plugin, with the CPU idle and
MySQL healthy. See CONTRIBUTING.md ("A plugin must not hold a DB session across
external I/O") for the shape to write, and docker-compose.yml for how the pool
relates to the worker count and to MySQL max_connections.
"""
from abc import ABC, abstractmethod
from typing import List, Dict, Optional, Type
@@ -6,6 +19,41 @@ from dataclasses import dataclass, field
from flask import Flask, Blueprint
# Settings hubs whose Vue page actually draws plugin-contributed tabs: it asks
# /api/plugins/settings-routes, keeps the routes whose `hub` matches its own id,
# and registers them with router.addRoute(). Every other hub renders its own
# tabs and nothing else, so a route naming one would be returned by the API and
# never drawn - a tab the author declared correctly that simply does not exist
# for the user. Hubs are added here only when their .vue file gains that code;
# tests/test_core/test_plugin_settings_hubs.py fails if the two drift apart.
SETTINGS_HUBS_WITH_PLUGIN_TABS = ('model-catalog',)
def renderable_settings_routes(plugin_name: str, routes: Optional[List[Dict]],
logger) -> List[Dict]:
"""The subset of a plugin's declared settings routes that a hub can draw.
Anything naming a hub outside SETTINGS_HUBS_WITH_PLUGIN_TABS is dropped and
logged as an error naming the plugin, the hub and the supported set. The
declaration is not a crash - the plugin's API, models and pages are all
fine - so this refuses the dead tab rather than the plugin. The hard stop
lives in the test suite, where the author still has a chance to fix it.
"""
kept = []
for route in routes or []:
hub = route.get('hub')
if hub in SETTINGS_HUBS_WITH_PLUGIN_TABS:
kept.append(route)
continue
logger.error(
"Plugin %s declares settings route '%s' for hub '%s'. No settings "
"hub page registers plugin tabs for that hub, so the tab would "
"never render; dropping it. Hubs that support plugin tabs: %s",
plugin_name, route.get('name'), hub,
', '.join(SETTINGS_HUBS_WITH_PLUGIN_TABS))
return kept
@dataclass
class PluginMeta:
"""Plugin metadata container."""
@@ -16,7 +64,8 @@ class PluginMeta:
author: str = ""
dependencies: List[str] = field(default_factory=list)
# Default to the current pre-1.0 contract range; tighten when 1.0 lands
core_version: str = ">=0.2.0,<1.0.0"
# 0.20.0: added get_asset_type_descriptor hook (additive, backward-compatible)
core_version: str = ">=0.20.0,<1.0.0"
api_prefix: str = None
def __post_init__(self):
@@ -78,9 +127,9 @@ class BasePlugin(ABC):
"""Transparency note shown when a site enables this plugin.
Return None for plugins that need no special setup. For plugins that
create extra tables (e.g. a self-hosted directory or USB tables), return:
create extra tables (a revision history, an events log), return:
{
'tables': ['directoryemployees', ...], # created in the shopdb DB
'tables': ['backuprevisions', ...], # created in the shopdb DB
'note': 'Plain-language what/why.',
'docs': 'plugins/<name>/README.md', # where the schema lives
}
@@ -128,6 +177,56 @@ class BasePlugin(ABC):
"""
return []
def get_settings_routes(self) -> List[Dict]:
"""Frontend routes this plugin adds to settings pages.
Returns a list of route configurations for the plugin's settings pages.
Each route is a dict with:
hub - settings hub to attach to; ONLY a hub named in
SETTINGS_HUBS_WITH_PLUGIN_TABS (top of this module) draws
plugin tabs. A route for any other hub is dropped by
/api/plugins/settings-routes with an error in the log.
path - route path relative to hub (e.g. 'operatingsystems')
name - unique route name (e.g. 'model-catalog-os')
tab - tab label shown in hub UI (e.g. 'Operating Systems')
component- path to the Vue component AS IT EXISTS IN THE BUILD, i.e.
relative to frontend/src, which for a plugin means
'.plugins-staged/<name>/views/<Component>.vue' - the copy
scripts/stage-frontend.mjs makes of plugins/<name>/frontend
Example:
return [{
'hub': 'model-catalog',
'path': 'operatingsystems',
'name': 'model-catalog-os',
'tab': 'Operating Systems',
'component': '.plugins-staged/computers/views/OperatingSystemsList.vue'
}]
Three constraints the shape of this hook does not show, so read them
before you rely on it (ADR-019, "Constraints as implemented"):
1. Declare a hub only if it is in SETTINGS_HUBS_WITH_PLUGIN_TABS. Today
that is 'model-catalog' alone. The other hubs have no code to draw
your tab, so the route is accepted and dropped.
2. Route the page yourself as well, in plugins/<name>/frontend/
routes.js, and treat THAT as the real route. The hub interpolates
`component` into a dynamic import with no static file extension,
which Vite will not rewrite, so the tab loads under `npm run dev`
and 404s in a production build. A page reachable only through the
tab is a page nobody can open at a site. Your frontend also has to
be staged into the build (SITE_PLUGINS decides that), so enabling a
plugin whose UI was never staged needs a frontend rebuild.
3. The tab is not a link you can hand out. The hub registers the route
when it mounts, so the URL resolves only for someone who has already
been through the parent hub in that page load. Do not link to it
from an email, a doc, or another page, and do not expect a refresh
on it to land anywhere.
Return [] (default) if the plugin adds no settings pages.
"""
return []
def get_settings_defaults(self) -> List[Dict]:
"""Declare the Setting rows this plugin owns.
@@ -211,6 +310,27 @@ class BasePlugin(ABC):
f"implement apply_collector_payload"
)
def resolve_agent_credential(self, secret: str) -> Optional[int]:
"""Asset id for an active per-PC agent credential, else None.
Optional (contract 0.33.0). A plugin that issues endpoint credentials
answers here so the generic collector can accept them on any schema
declaring 'acceptsagentcredential'. Called via
shopdb.api.resolve_agent_credential, which asks enabled plugins and
takes the first non-None answer.
"""
return None
def agent_shared_key_refused(self, hostname: str) -> bool:
"""True when the shared collector key may not report for this hostname.
Optional (contract 0.33.0). True when the shared key is switched off or
the hostname's asset holds an active per-PC credential. Called via
shopdb.api.agent_shared_key_refused, which is True if any enabled
plugin says so.
"""
return False
def on_install(self, app: Flask) -> None:
"""Called when plugin is installed via CLI."""
pass
@@ -418,6 +538,11 @@ class BasePlugin(ABC):
Consumed by GET /api/pluginui/map-overlays. Disabled plugins are
skipped; a broken plugin is isolated in prod, re-raised in dev/test.
No bundled plugin implements this, so the dict above IS the whole
specification - there is no shipped example to copy. Core's side is
exercised against a stub in tests/test_core/test_pluginui.py, which is
also the shortest worked example of a declaration.
"""
return []
@@ -438,5 +563,48 @@ class BasePlugin(ABC):
Consumed by GET /api/pluginui/asset-presentation. Disabled plugins are
skipped; a broken plugin is isolated in prod, re-raised in dev/test.
No bundled plugin implements this either; same note as get_map_overlays
above. With nothing declaring one, the route returns [] and core falls
back to its legacy id-keyed route map in shopdb/core/api/search.py.
"""
return []
def get_asset_type_descriptor(self) -> Optional[Dict]:
"""Return subtype management descriptor for this plugin's asset type.
Declares how to CRUD the plugin's subtype table (printertypes,
machinetypes, etc.) so core can render a generic CRUD UI without
importing the plugin's models or views. Return None if the plugin
has no subtype table.
Contract (all keys required if returning non-None):
{
'assettype': str, # matches assettypes.assettype
'subtype_endpoint': str, # API path WITHOUT /api prefix (e.g., '/printers/types')
'subtype_id_field': str, # PK field name (e.g., 'printertypeid')
'subtype_label_field': str, # Display name field (e.g., 'printertype')
'subtype_description_field': str, # Description field
'subtype_color_field': str, # Color field for map markers
'optional_tabs': List[str], # Plugin-specific tabs (e.g., ['supplies'])
'edit_permission': str, # Required permission (e.g., 'printers.manage')
}
The endpoint must support:
- GET (list) ?active=true/false for pagination
- GET /{id} for single record
- POST (create)
- PUT /{id} (update)
- DELETE /{id}
Payload fields:
- {subtype_label_field}: required string
- {subtype_description_field}: optional text
- {subtype_color_field}: optional string (CSS color)
- isactive: optional boolean (default True)
Consumed by GET /api/pluginui/asset-type-descriptors. Disabled
plugins are skipped; a broken plugin is isolated in prod, re-raised
in dev/test.
"""
return None