Files
pages/docs/design/platform-extension-architecture.md
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

169 lines
7.7 KiB
Markdown

# Platform Extension Architecture
## Purpose
This document keeps current implementation choices from closing off planned
collaboration, federation, high-availability, content, security, and storage
features. It defines extension boundaries, not permission to bypass existing
identity or authorization rules.
## Non-negotiable identity boundaries
Future features attach to stable identities:
| Feature data | Stable attachment |
| --- | --- |
| semantic navigation | `(domain_uuid, path)` binding |
| content history | Page UUID and immutable Revision UUID |
| payload | Document SHA-256 |
| inline comment | Page UUID + Revision UUID + range/context anchor |
| thread, like, view, quality | Page UUID, optionally Revision UUID |
| City service | Campus/Domain/Zone/Spot UUID |
| notification | event UUID + recipient Principal UUID |
| share | delegated capability ID, never a copied Page |
Comments, likes, counters, inbox state, quality scores, and diary metadata must
not be inserted into canonical Page HTML as hidden mutable state. Renaming a
Path must not detach them. Creating a Revision must not rewrite their history.
## Required platform contracts
### Event and outbox contract
Every canonical mutation emits a typed event in the same transaction as its
state change. An event has an instance UUID, Domain UUID, monotonic Domain
sequence, event type/version, actor, target typed address, authorization-safe
summary, payload hash, timestamp, and idempotency key. Consumers maintain
their own checkpoint. Notifications, feeds, view aggregation, federation,
search, DR, webhooks, and quality automation consume events rather than adding
callbacks to every write handler.
The scheduler owns retries, leases, priority, backoff, dead letters, logs, and
resource quotas. Foreground Page reads and writes always outrank extension
jobs. Delivery is at least once; consumers must be idempotent.
### Authorization contract
Every new endpoint declares a typed policy target and operation. Effective
permissions can be explained and enumerated without exposing inaccessible
objects. Anonymous access is an explicit positive grant to an anonymous
Principal class. A share token produces a caveat-limited Principal and never
becomes a normal login session.
Cross-Domain policy sharing uses signed, sequenced records with an authoritative
origin. It may inherit identities, groups, Roles, and selected positive grants;
it never imports local secrets or silently grants access because Domains share
a Campus. Revocation and origin loss are explicit states.
### Projection and conversion contract
Viewer, editor, print, preview, transpiler, diagram, widget, and export are
projections of an immutable Revision. Adapter selection uses MIME, filename,
declared capability, Domain policy, and bounded-delivery needs. Adapter output
does not become identity.
Conversions record source format, compiler/provider ID and version, options,
warnings, source map when available, output MIME, and output Document hash.
External renderers receive bounded content or one-use retrieval capabilities,
not database or unrestricted network access.
Widgets are registered providers. Document content may request a provider and
resource ID, but may not supply executable JavaScript. Rendering uses a
sandboxed iframe or sanitized server projection with explicit CSP, consent,
origin allowlist, timeout, and privacy policy.
### Document Store contract
The canonical interface is content-addressed and supports:
```text
Stat(sha256)
Open(sha256) / ReadAt(sha256, offset, length)
PutIfAbsent(expected_sha256, stream)
Verify(sha256)
DeleteUnreferenced(sha256, retention proof)
```
Filesystem and S3 implementations obey the same contract. Bucket/key URLs are
placement data and never appear in Revision identity. Metadata databases,
credentials, signing keys, sessions, and comments do not belong in this store.
### Extension manifest contract
An extension declares stable ID, type, version, PagesWiki compatibility range,
entry point, MIME/extensions, requested capabilities, outbound hosts, resource
limits, configuration schema, migrations, health probe, and signature. Types
include projection, editor, transpiler, diagram, widget, notification,
inspection, storage, search, and theme.
Install, upgrade, disable, and rollback are explicit administrator operations.
An unavailable extension degrades to a safe built-in projection; it cannot make
canonical Page content unreadable or prevent raw immutable retrieval.
## Collaboration data model direction
- `page_activity_events` are append-only canonical facts.
- `principal_recent_views` is private derived state with retention controls.
- `page_metric_buckets` stores aggregated counts, not raw IP history forever.
- `page_reactions` has `(domain_uuid, page_uuid, principal_uuid, reaction)`
identity and an audit event.
- `quality_assessments` records rubric/version and human or machine provenance.
- `comment_threads` attach to Page or Revision; `comment_anchors` retain range,
quoted context hash, and rebase/orphan state.
- `notifications` reference events and store recipient delivery/read state;
notification text is rendered at read time with current authorization.
Deletion and retention are explicit. A user losing access must stop seeing
notification details even if an older notification row remains.
## Federation and disaster recovery direction
Controller desired state is a signed, monotonic manifest journal. DR replicates
the journal, encrypted signing-key material under a documented recovery policy,
and last-known-good snapshots. Promotion creates a new auditable epoch and
fences the former leader. Managed instances pin permitted controller identities
and reject sequence rollback or concurrent epochs.
Page Documents, metadata, event logs, and controller desired state have separate
backup/replication policies. A Campus manifest is not a database backup.
## Load balancing and HA constraints
Application nodes should become disposable after canonical state is externalized:
- bearer/session validation keys and revocation state are shared or replicated;
- background jobs use leases and idempotency keys;
- caches are disposable and version-keyed;
- uploads stream to canonical storage and do not depend on a later request
reaching the same node;
- WebSockets support drain/reconnect;
- proxy headers are trusted only from configured proxies.
SQLite remains valid for one writable application node and local replicas or
backups. Concurrent writers must use a metadata backend designed for it or a
fenced leader; a writable SQLite file on NFS is prohibited.
## Security and privacy constraints
- External feeds, widgets, diagram services, and scanners use per-provider
outbound allowlists, DNS/IP rebinding defenses, size/time limits, and logs.
- Malware inspection is asynchronous but policy can quarantine download and
adapter access until a required clean verdict exists.
- View history and popularity avoid retaining unnecessary personal data.
- Comments, reactions, shares, and notifications are covered by export,
retention, moderation, abuse, and audit policy.
- Theme packages supply CSS tokens/assets, never privileged script.
## Compatibility gates for current work
Before merging a feature, tests must show that it:
1. preserves Page UUID, Revision UUID, Document hash, and Domain Path semantics;
2. declares authorization targets and anonymous/share behavior;
3. remains bounded for payload, rows, recursion, time, and concurrency;
4. emits versioned events for canonical mutations;
5. tolerates retry and duplicate delivery;
6. degrades safely when an extension or remote service is unavailable;
7. supports migration rollback and mixed-version federation where applicable;
8. does not assume process-local state in an HA-targeted code path.